The primary just died. Who promotes a replica, and how do you make sure the old one never comes back as a second primary?
PostgreSQL ships with replication, but not with failover. Something outside the database has to notice the primary is gone, pick the best replica, promote it, and point the app at it. Patroni is the most common way to do that.
Every server fails eventually: a disk, a kernel panic, a zone outage, or just the patch you have to install on Tuesday. With one database, each of those is an outage for every customer at once. High availability turns them into a few seconds that most users never notice.
Revenue and trust. Checkout, login, payments: when the database is down, the whole product is down, and nothing in the app can work around it.
Two numbers. RTO: how fast writes work again, seconds instead of the 15 to 30 minutes a manual failover takes. RPO: how much confirmed data a failure can lose, ideally zero.
The quiet win. With a spare node, patches, upgrades and hardware swaps become rolling switchovers during the day, not maintenance windows at night.
A backup. A bad DELETE reaches every replica in milliseconds. You still need backups and point-in-time recovery.
| Availability target | Downtime allowed per year | Per month | What it takes |
|---|---|---|---|
| 99.9% ("three nines") | 8.8 hours | 43.8 minutes | One server and good backups can almost do it, if nothing big breaks. |
| 99.99% ("four nines") | 52.6 minutes | 4.4 minutes | Automatic failover. One manual 3 a.m. failover uses most of the year. |
| 99.999% ("five nines") | 5.3 minutes | 26 seconds | Automatic failover in seconds, and maintenance with no downtime at all. |
The arithmetic is why teams automate: a single manual failover at 3 a.m. can spend a whole year of a 99.99% budget.
Nobody configures a thousand clusters by hand. At that scale, high availability is a product the database team runs, with the same few parts everywhere:
Each cluster is a file in Git: size, version, replicas, settings. Terraform, Ansible or a Kubernetes operator turns the file into servers, and a pull request is how anything changes.
The same Patroni (or orchestrator, or Group Replication) setup on every cluster, so a failover at 3 a.m. behaves exactly like the one you tested.
Consul, etcd or a proxy layer tells every app where the primary is right now. Failover updates one record, not a thousand config files.
Rolling patches and upgrades one node, then one cluster, at a time. Rate limits so a bad network day cannot trigger a hundred failovers at once.
Scheduled switchovers and game days that kill a primary on purpose, restore tests from backup, and dashboards that show every cluster's role, lag and last failover.
The common incidents are scripted and safe to run; the rare ones page a person with the evidence already gathered. That is the idea behind the DBA agent on this site.
Step through it: how a team patches a cluster with no downtime.
Now let us look at how one PostgreSQL cluster does it, starting with how it was done before tools like Patroni existed.
PostgreSQL 9.0 (2010) added streaming replication: a standby receives the WAL as it is written and replays it. 9.1 added synchronous replication. But the database never decides on its own to promote a standby. That was always a person, or a script.
pg_last_wal_replay_lsn() on each one and choose the one furthest ahead.pg_ctl promote, or SELECT pg_promote(); since PostgreSQL 12. Before 12 this was a trigger file named in recovery.conf.pg_basebackup, or pg_rewind (since 9.5) to rewind it to the point where the histories split.Expect 15 to 30 minutes at 3 a.m., done well. Done badly, it is split brain and lost orders. Tools like repmgr and Pgpool-II scripted parts of it. Patroni, released by Zalando in 2015, took a different approach: let a consensus store decide who the leader is, so two nodes can never both believe it.
Step through it:
A replica is only useful if something promotes it fast and safely. A script that promotes on a timeout can promote while the old primary is still alive behind a network split, and then both take writes.
Patroni is a small Python agent that runs next to every PostgreSQL server and controls it: it starts, stops, promotes and demotes PostgreSQL itself. The agents agree on who is the leader through a distributed configuration store (DCS), usually a three-node etcd cluster. The leader holds a key in etcd with a time to live. Only the holder of that key may run as primary.
loop_wait (10 s). The key lives for ttl (30 s).maximum_lag_on_failover (1 MB of WAL) behind./primary, sees the new answer, and sends new connections there.For your app: typically 30 to 45 seconds without writes, up to about 50, with no person involved.
watchdog: mode: required, Linux /dev/watchdog) so a hung Patroni resets its host. If etcd itself goes down, every primary demotes, unless you turn on failsafe_mode.synchronous_mode: on makes Patroni promote only a synchronous standby. If no standby can be synchronous, the primary keeps writing unprotected; synchronous_mode_strict: on blocks writes instead.loop_wait + 2 × retry_timeout ≤ ttl. Shorter timers mean faster failover and more false alarms.Step through it:
Running on Kubernetes? See PostgreSQL on Kubernetes with CloudNativePG, which does failover without Patroni. Running hundreds of clusters? See how a team runs 1,000 databases.
Put etcd on three separate machines or zones, so losing one keeps a majority. Two PostgreSQL nodes work, three give you a spare after a failover. HAProxy checks Patroni's REST API on port 8008, not PostgreSQL itself.
etcdctl endpoint health --cluster.pip install "patroni[etcd3]" or your distribution's package). Do not run initdb yourself: Patroni bootstraps the first node and clones the others./etc/patroni.yml on each node. Only name and the addresses change between nodes.scope: orders # cluster name, the same on every node
name: pg1 # unique per node
restapi:
listen: 0.0.0.0:8008
connect_address: 10.0.0.11:8008
etcd3:
hosts: 10.0.0.21:2379,10.0.0.22:2379,10.0.0.23:2379
bootstrap:
dcs: # stored in etcd, shared by all nodes
ttl: 30
loop_wait: 10
retry_timeout: 10
maximum_lag_on_failover: 1048576
synchronous_mode: on
postgresql:
use_pg_rewind: true
parameters:
wal_level: replica
wal_log_hints: "on" # pg_rewind needs this or data checksums
max_wal_senders: 10
max_replication_slots: 10
postgresql:
listen: 0.0.0.0:5432
connect_address: 10.0.0.11:5432
data_dir: /var/lib/postgresql/18/main
bin_dir: /usr/lib/postgresql/18/bin
authentication:
superuser: { username: postgres, password: change-me }
replication: { username: replicator, password: change-me }
systemctl start patroni), then pg2 and pg3. The first one to start initializes the cluster and takes the key; the others clone it with pg_basebackup.patronictl -c /etc/patroni.yml list shows one Leader, the Sync Standby and the lag of each replica.listen orders_write bind *:5000 option httpchk GET /primary http-check expect status 200 default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions server pg1 10.0.0.11:5432 check port 8008 server pg2 10.0.0.12:5432 check port 8008 server pg3 10.0.0.13:5432 check port 8008 listen orders_read bind *:5001 option httpchk GET /replica http-check expect status 200 default-server inter 3s fall 3 rise 2 server pg1 10.0.0.11:5432 check port 8008 server pg2 10.0.0.12:5432 check port 8008 server pg3 10.0.0.13:5432 check port 8008
The app connects to HAProxy on 5000 for writes and 5001 for reads. /primary answers 200 only on the leader, so HAProxy never sends a write to a replica.
/primary answer 200 on pg2. Writes resume.pg_rewind, and starts it as a replica of pg2.A planned switchover is much faster, because the leader hands over on purpose: patronictl switchover --leader pg1 --candidate pg2. Use it for upgrades and maintenance.
| Failure | What happens | What you do |
|---|---|---|
| Primary host dies | Failover in typically 30 to 45 s, up to about 50. | Nothing. Check patronictl list afterwards. |
| Network cut between the primary and etcd | The primary cannot renew its key and demotes itself. A replica on the majority side takes over. | Nothing. That is the fencing working. |
| etcd loses its majority | Nobody can hold the key. The primary demotes to read-only, unless failsafe_mode is on and all members can still reach each other. | Fix etcd first. Keep etcd on separate hosts from the databases. |
| Every replica is too far behind | No replica is within maximum_lag_on_failover, so nobody is promoted. | Decide by hand: patronictl failover --candidate pg3 promotes it and accepts the data loss. |
| You need to work on a node without a failover | Patroni would react to a stopped PostgreSQL. | patronictl pause, do the work, patronictl resume. |
| A replica is broken or very far behind | It keeps streaming, or stays stuck. | patronictl reinit orders pg3 re-clones it. |
Step through it:
patronictl -c /etc/patroni.yml list # leader, sync standby, lag, timeline curl -s http://10.0.0.11:8008/patroni # this node's state as JSON etcdctl endpoint health --cluster # is the DCS healthy
SELECT application_name, state, sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_behind
FROM pg_stat_replication;
Alert on: no leader, more than one leader (should be impossible; check your timers), a replica behind by more than maximum_lag_on_failover, and etcd members down. Page playbooks: no leader, or the primary went read-only, failovers that should not happen.
How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.