Video in progress

The Postgres primary server went down. How do you build automatic failover, and what data can be lost?

Usually a tool like Patroni manages leader election through etcd/Consul and promotes the most advanced replica to primary. With asynchronous replication the last commits can be lost (RPO > 0); to prevent split brain, the old primary must be stopped with fencing.

📖 Answer

I start with two numbers: RPO (how much data we're ready to lose) and RTO (how long we're ready to be down). The architecture follows from them.

A typical setup:

[app] -> [HAProxy / DNS / Patroni REST check] -> primary
                                               -> replica1 (sync)
                                               -> replica2 (async)
Patroni on every node + an etcd cluster (3 or 5 nodes)

Patroni holds the leader key in etcd with a TTL. If the primary can't renew the key, the replica that is furthest ahead in WAL is promoted. If the old primary comes back, without the key it makes itself read-only or joins as a replica using pg_rewind.

Data loss:

  • Async: the primary confirmed a commit, but the WAL hadn't reached a replica, so those transactions are lost. The client already got an "OK".
  • Sync (synchronous_commit = on + quorum): a confirmed commit is on at least one replica's disk. The cost: network latency on every commit, and writes stop if the sync replica is lost (in Patroni, synchronous_mode controls this).

Split brain is the most dangerous case: the network splits, and the old primary is still accepting writes while the new one does too. The protection: a DCS quorum, killing the old primary with a watchdog (softdog), and directing clients only to the leader endpoint.

The application side has to be ready too: a failover takes 10-30 seconds. Hikari connections get dropped, so you need retries (for idempotent operations), a short connection-timeout, and multiple hosts in the JDBC URL with targetServerType=primary. And most importantly, test failover regularly. A failover that has never been tested is a failover that doesn't work.