Platform Engineering · Lesson 140

PostgreSQL High Availability: Replication, Patroni and CloudNativePG Failover, and Connection Pooling

A PostgreSQL primary with streaming replicas is not highly available by itself: something has to notice the primary is gone, choose a replica, promote it, stop the old primary from coming back as a second primary, and move every client to the new one. Patroni does that on virtual machines and Kubernetes, CloudNativePG does it as a Kubernetes operator, and a connection pooler such as PgBouncer keeps the reconnect from becoming its own outage. This lesson follows one failover three ways, a planned switchover, a lost primary with asynchronous replication, and a reconnect storm, and shows where the seconds, the lost transactions, and the connection limits come from.

Difficulty: Advanced · Know this first: Lesson 139, Lesson 30, Lesson 44

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar splits a failover from the primary failing to a fully redundant cluster, in seconds. It is a worked example, not a measurement. In an unplanned failover the leader lock's expiry dominates the outage; the reconnect can dominate it instead when nothing pools the connections.

Try it: will the reconnect fit?

After a failover every app pod opens its pool again. Set the pods, the pool size per pod, the server's max_connections, and whether a pooler sits in between.

client connections = pods × pool size · server connections = client connections, or the pooler's server pool (80 here) · keep 20 percent of max_connections free for admin, replication, and migrations

1,200client connections
1,200server connections
nofits with 20% spare

Too many clients: the reconnect fails until pools back off

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

PostgreSQL HA grows in four levels: first replicas and what failover means, then running Patroni or CloudNativePG, then tuning data loss, failover time, and pooling, and finally designing for the RPO and RTO the business actually needs.

Basic — A primary, replicas, and a failover

At the basic level you know the parts. One primary takes writes. Replicas stream its WAL and can serve reads. Failover promotes a replica when the primary is lost; switchover does it on purpose.

Terms: WAL, streaming replication, replication lag, synchronous and asynchronous commit, RPO (data you can lose), RTO (time without writes), split brain.

Where it breaks: a replica alone is not HA. Without something to detect, promote, and fence, a failed primary is an outage until a person acts.

Try it: Basic

What is split brain in a database cluster?

Now do it: Run pg_ha.py in Go deeper and read the three numbers it prints: failover time, data at risk, and connections.

Intermediate — Run Patroni or CloudNativePG

At the intermediate level you run a three-member cluster.

  • Patroni on VMs or Kubernetes: a DCS (etcd, Consul, or Kubernetes), a REST API per member, and HAProxy or a Service that sends writes to the leader.
  • CloudNativePG on Kubernetes: a Cluster resource with instances, storage, and backups; -rw, -ro, and -r services; switchover with its kubectl plugin.
  • Backups with continuous WAL archiving to object storage, and a restore tested on a schedule.

Troubleshooting: patronictl list or kubectl cnpg status for roles and lag; pg_stat_replication on the primary.

Try it: Intermediate

In CloudNativePG, which service should an application use for writes?

Now do it: Apply the Cluster in Go deeper to a test cluster with CloudNativePG installed and run a switchover with its plugin. Time the write pause.

Advanced — Data loss, failover time, and pooling

At the advanced level you tune the trade-offs.

  • RPO: synchronous standbys (quorum-based, such as ANY 1 (r1, r2)) for zero loss; decide what happens when no standby answers: block writes, or fall back to async.
  • RTO: Patroni's ttl and loop_wait, CloudNativePG's failover delay; shorter is faster and more likely to fail over on a blip.
  • Pooling: PgBouncer (or CloudNativePG's Pooler resource) in transaction mode, server pools sized to what the CPU can run, and app pools sized so pods × pool fits.
  • Fencing: Patroni's watchdog; never run two members that each believe they hold the lock.

Failure scenarios: replication slots for a dead replica filling the primary's disk with WAL; a long-running query on a replica conflicting with replay; a pooler in transaction mode breaking session-level features such as advisory locks held across statements.

Try it: Advanced

The primary's disk fills with WAL although every replica is caught up. What is a common cause?

Now do it: Run SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) FROM pg_replication_slots; on a test primary.

Master — Design for the RPO and RTO the business needs

At the master level you start from the business numbers and work back to the design.

  • RPO zero, RTO under a minute, one region: three members across zones, one synchronous standby by quorum, a pooler, and apps with safe retries.
  • Region loss: a replica cluster in another region (asynchronous, so an RPO of seconds), promoted by a runbook or a tested automation.
  • Point-in-time recovery: WAL archives and base backups to restore to before a bad migration or a deleted table, which replication cannot undo.
  • Capacity: connections, WAL volume, replica apply speed, and backup duration as the database grows.
  • Managed services (RDS, Cloud SQL, Azure Database) give you most of this; know their failover time and RPO, and test them too.

Trade-off: synchronous replication buys zero data loss with commit latency and a dependency on standbys; asynchronous buys speed with a small, real loss window. Make the choice per database, in writing.

Try it: Master

A developer runs DELETE without WHERE on production. Replication copies it to every replica in milliseconds. What recovers the data?

Now do it: Write down your database's RPO and RTO targets and the last time a restore was tested. If there is no date, schedule one.

Go deeper

Three numbers decide how a failover goes: how long until a replica takes over, how much committed data could be lost, and whether every client can reconnect. This script computes all three. Standard library only; python3 pg_ha.py.

Failover time, data at risk, and connections

# pg_ha.py - failover time, data at risk, and the connection arithmetic around a PostgreSQL cluster

# 1. How long until a replica takes over? (Patroni defaults: ttl 30 s, loop_wait 10 s)
ttl, loop_wait = 30, 10
print(f"the leader key expires at most {ttl} s after the last renewal, and replicas check every {loop_wait} s:"
      f" a dead primary is replaced within about {ttl + loop_wait} s, plus a few seconds to promote")

# 2. What does asynchronous replication put at risk on a crash?
commits_per_s, lag_s = 1_500, 0.4
print(f"async replica {lag_s} s behind at {commits_per_s:,} commits/s -> about {commits_per_s * lag_s:.0f} "
      f"committed transactions lost if the primary dies now (synchronous_commit=on with a sync standby: 0)")

# 3. Will the database survive every app pod reconnecting at once?
max_connections = 500
for pods, pool, pooler in [(20, 10, False), (60, 20, False), (60, 20, True)]:
    asked = pods * pool
    server_side = 80 if pooler else asked          # PgBouncer in transaction mode: 80 real connections
    ok = server_side <= max_connections * 0.8      # keep 20% for admin, replication and migrations
    print(f"{pods} pods x {pool} = {asked:>5} client connections"
          f"{' through PgBouncer' if pooler else ''} -> {server_side:>5} on the server: "
          f"{'fits' if ok else 'too many clients: FATAL at reconnect'}")
$ python3 pg_ha.py
the leader key expires at most 30 s after the last renewal, and replicas check every 10 s: a dead primary is replaced within about 40 s, plus a few seconds to promote
async replica 0.4 s behind at 1,500 commits/s -> about 600 committed transactions lost if the primary dies now (synchronous_commit=on with a sync standby: 0)
20 pods x 10 =   200 client connections ->   200 on the server: fits
60 pods x 20 =  1200 client connections ->  1200 on the server: too many clients: FATAL at reconnect
60 pods x 20 =  1200 client connections through PgBouncer ->    80 on the server: fits

Read it like this: with Patroni's defaults, writes are down for up to about forty seconds after a crash; an asynchronous replica 0.4 seconds behind loses about 600 transactions at 1,500 commits a second; and sixty pods with 20 connections each need a pooler to fit a 500-connection server with room to spare.

A CloudNativePG cluster with a synchronous standby, backups, and a pooler

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: shop-db
  namespace: data
spec:
  instances: 3
  storage:
    size: 200Gi
  postgresql:
    parameters:
      max_connections: "500"
      max_slot_wal_keep_size: "20GB"
    synchronous:
      method: any
      number: 1
  backup:
    barmanObjectStore:
      destinationPath: s3://db-backups/shop-db
      s3Credentials:
        accessKeyId:
          name: backup-creds
          key: ACCESS_KEY_ID
        secretAccessKey:
          name: backup-creds
          key: ACCESS_SECRET_KEY
    retentionPolicy: "14d"
---
apiVersion: postgresql.cnpg.io/v1
kind: Pooler
metadata:
  name: shop-db-pooler-rw
  namespace: data
spec:
  cluster:
    name: shop-db
  instances: 2
  type: rw
  pgbouncer:
    poolMode: transaction
    parameters:
      max_client_conn: "2000"
      default_pool_size: "80"

Field names follow CloudNativePG's postgresql.cnpg.io/v1 API and the manifests parse as YAML; newer CloudNativePG releases move backups to a plugin, so check the documentation for your version. Apps connect to shop-db-pooler-rw; try a switchover with kubectl cnpg promote shop-db shop-db-2 on a test cluster and watch the pause.

The same checks with Patroni

patronictl -c /etc/patroni.yml list                 # roles, state, lag per member
patronictl -c /etc/patroni.yml switchover --leader pg-1 --candidate pg-2
psql -c "SELECT application_name, state, sync_state, replay_lag FROM pg_stat_replication;"
psql -c "SHOW max_connections;"

One time it broke

This is a composite of a failure pattern that keeps repeating; the numbers are illustrative. An e-commerce database ran Patroni with asynchronous replicas and no pooler.

Timeline

  • Black Friday 11:40The primary's host fails. Patroni promotes a replica 34 seconds later, as designed.
  • 11:41180 application pods reconnect with 10 connections each against max_connections of 800. Most get "too many clients"; checkout fails for two more minutes while pools retry.
  • Next dayReconciliation finds 212 paid orders with no order record: they committed on the old primary in the last 0.3 seconds and never reached the replica.

What changed after

PgBouncer went in front of the database with 120 server connections; the orders database moved to one synchronous standby by quorum, accepting about 1 ms more per commit; and the payment flow gained an idempotency key so a retried payment can be matched to its order. The failover had worked; the design around it had not been decided on purpose.

If you remember nothing else

Design exercise

Design the PostgreSQL layer for a payments service on Kubernetes that must lose no committed payment, recover writes within a minute in one region, and survive a region outage within an hour.

Clarifying questions to ask

Is zero data loss required for every table, or only payments? How much commit latency can the service afford? How many app pods and connections at peak? How fast is WAL generated? Who runs the region failover, and has it been rehearsed?

Rough sizing

Say 2,000 commits a second at peak, 40 app pods, 300 GB of data growing 20 GB a month, 50 GB of WAL a day, and three zones.

Shape of the answer

CloudNativePG with three instances across zones, one synchronous standby by quorum, a PgBouncer pooler in transaction mode with 100 server connections, WAL archiving and daily base backups to object storage with 14 days of point-in-time recovery, a replica cluster in a second region, alerts on lag, slot size, connections, and backup age, and a quarterly failover and restore drill.

Trade-offs to name

Synchronous standbys remove data loss and add about a network round trip per commit; quorum across two standbys keeps writes going if one is slow. A pooler absorbs storms and breaks session-level features in transaction mode. A cross-region replica bounds region-loss RPO to seconds and adds a manual or automated promotion that must be practised.

Saved on this device, in this browser.
Next in this series · Lesson 141
MongoDB in Production: Replica Sets, Write Concern, Shard Keys, and Kubernetes Operators

MongoDB keeps every document in a replica set: one primary takes writes, secondaries copy its oplog, and a majority of voting members elects a new primary when the old one disappears.

Go to Lesson 141 →

Or browse the full course from the Lessons index.