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
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.
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
Too many clients: the reconnect fails until pools back off
Three questions. No score is saved anywhere — this is just you against the material.
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.
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.
At the intermediate level you run a three-member cluster.
Cluster resource with instances, storage, and backups; -rw, -ro, and -r services; switchover with its kubectl plugin.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.
At the advanced level you tune the trade-offs.
ANY 1 (r1, r2)) for zero loss; decide what happens when no standby answers: block writes, or fall back to async.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.
At the master level you start from the business numbers and work back to the design.
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.
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.
# 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.
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.
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;"
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.
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.
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.
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?
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.
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.
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.