Failover, split brain and fencing
Detecting a dead primary is a guess, promoting a replica is easy, and making sure the old primary stops writing is the whole job
A Postgres primary managed by an HA agent stops responding for 45 seconds: its VM was frozen by the hypervisor during a live migration. The agent on a replica waits for the 30 s leader lease to expire and promotes it. Then the old primary's VM resumes, with its client connections still open. With no fencing, what happens next?
The replication chapter ended with a promoted replica and a killed primary that, if restarted, would have been a second writable primary with a different history. That is what this chapter is about. Failover has five steps: detect that the primary is gone, choose a replica, promote it, move clients to it, and make sure the old primary cannot write. The first four are configuration. The fifth, fencing, is the one that decides whether your failover loses data, and it is the one most setups skip.
The tool here is Patroni, the most widely used Postgres HA manager, and the lab runs a three-node Patroni cluster you can break. The mechanisms are general: MySQL’s Orchestrator, pg_auto_failover, cloud managed failover and Kubernetes operators all make the same decisions with different names.
Detection is a timeout, not a fact
From outside, a crashed host, a hung disk, a paused VM, a 40-second stop-the-world pause in some process, and a broken network link all look identical: heartbeats stop arriving. No observer can tell them apart, which is the core of the failure models lesson. The only tool is a timeout, and a timeout is a decision to act as if the node were dead, not evidence that it is.
That puts a dial in front of you. A short timeout fails over quickly when the primary really is dead, and promotes needlessly when it is merely slow, which gives you more failovers, each with its window of client errors and its risk of split brain. A long timeout means fewer false alarms and longer outages. Patroni’s defaults sit at about half a minute:
| setting | default | meaning |
|---|---|---|
ttl |
30 s | lifetime of the leader key; failover cannot start before it expires |
loop_wait |
10 s | the HA loop runs this often; the leader renews its key each loop |
retry_timeout |
10 s | how long DCS and Postgres calls are retried before the leader gives up and demotes |
maximum_lag_on_failover |
1 MB (common setting) | a replica further behind than this is not a candidate |
Because the leader renews every loop_wait, the key has between 20 and 30 seconds left when the primary dies. Replicas watch the key and react when it expires, promotion takes a second or two, and the router needs a couple of health checks to notice. Expect 25 to 40 seconds of failed writes for an unplanned failover with these defaults, and a few seconds for a planned switchover, where the leader hands the key over instead of letting it expire. The lab measures both. Lowering ttl to 10 s is possible and common on reliable networks; below that, a long GC pause in Patroni itself or a slow etcd fsync starts causing failovers.
The retry_timeout matters at the other end. A Patroni leader that cannot renew its key for retry_timeout demotes its own Postgres before the key expires (the docs require loop_wait + 2 × retry_timeout <= ttl for this to work). That self-demotion is the first fence, and it only works when the Patroni process is alive to perform it.
Who decides: a lease in a consensus store
If each node decided on its own, a partition would let both sides elect themselves. So the decision lives in a distributed configuration store (DCS): etcd, Consul, ZooKeeper or the Kubernetes API, each a replicated state machine built on a consensus protocol like the one in the Raft lesson. The store gives Patroni one primitive that matters: compare-and-set on a key with a TTL. Whoever holds /service/<scope>/leader is the primary.
That key is a lease. It has the property every lease has and the leases and fencing lesson makes you prove: it tells the holder it was the leader when it last renewed, and nothing about now. A process that pauses for longer than the TTL wakes up believing it still holds a lease that expired, and acts on it before checking. Postgres does not check at all. It commits whatever its connections send. The lease decides who should be primary; fencing is what stops the one who should not.
The store has to survive the failures it adjudicates, so it needs its own quorum: three members tolerate one failure, five tolerate two. Run it on separate failure domains from the databases or at least spread across them; a DCS in one zone makes that zone’s loss a cluster outage. Two-node “primary plus witness” setups are this same design with a quorum of one witness, and they inherit its weakness when the witness sits with one side of the partition.
Choosing and promoting a replica
When the key expires, every healthy replica races to take it, but Patroni first checks that a candidate is fit: it must be within maximum_lag_on_failover bytes of the last known primary position, must not carry the nofailover tag, and with synchronous_mode: true it must be the synchronous standby, the only node guaranteed to have every acknowledged commit. Among eligible replicas, the one with the most WAL wins.
Promotion itself is pg_promote() or pg_ctl promote: the replica finishes replaying what it has, stops recovery, and starts a new timeline. The timeline id increments (1 to 2), a history file 00000002.history records the LSN where timeline 2 branched from timeline 1, and from then on the new primary’s WAL file names carry the new timeline. Timelines are how Postgres represents a fork in history, and they are how you can tell, later, that two nodes disagree: two primaries that both think they are on timeline 2, or one on 1 and one on 2 past the branch point, have diverged.
The other replicas follow the new leader. If they were behind the promoted node they stream the difference. If one was ahead (it had received WAL the promoted node had not, which async replication allows), it has diverged too and must be rewound.
How split brain happens
Two writable primaries with diverging histories is split brain, and the split brain lesson shows it on a toy cluster. In Postgres clusters it arrives in a few recurring ways:
- A paused primary. VM migration, a frozen hypervisor, a stuck storage controller, SIGSTOP. The lease expires, a replica is promoted, the old primary resumes with open connections and commits until its agent runs again.
- The agent dies, the database does not. Patroni crashes or is killed, and Postgres, its child, keeps running as primary. Nothing renews the key, a replica is promoted, and every client connected directly to the old primary keeps writing. The lab produces this one.
- A partition between the primary and the DCS but not the clients. The primary’s Patroni cannot renew, demotes after
retry_timeout, and is safe. With a tool that does not self-demote, as at GitHub, both sides of the partition keep serving. - Humans. Restarting the old primary’s VM after a failover without telling the HA tool, with a recovery configuration that makes it start as primary. Lab step 7 of the replication chapter was this.
- Stale routing. A client library that cached the old primary’s IP, a DNS TTL of five minutes, a connection pool that does not drop connections on failover.
Each of these needs the same answer: something that prevents the old primary from completing writes, independent of whether the old primary’s own software is healthy.
Fencing: stop the old primary from writing
There are four layers, and production clusters use more than one because each covers a different failure.
Self-demotion. The agent demotes its own database when it cannot renew the lease. It covers partitions and DCS loss. It does not cover the agent being dead or paused, because the agent is the one who has to act.
A watchdog. Linux exposes /dev/watchdog (hardware, or the softdog module). Once opened, the kernel resets the machine if nobody writes to the device within the timeout. Patroni arms it before promoting and pings it every loop; the timeout is ttl - safety_margin (5 s by default), so if Patroni dies or hangs, the node reboots before the leader key expires and before any replica can be promoted. watchdog: mode: required makes a node refuse leadership if the watchdog cannot be opened. This is the fence for the agent-dies case, and it is the one the lab cannot use, because containers share the host’s kernel.
Routing. Clients reach the primary only through something that asks the DCS-backed agent who the primary is: HAProxy health-checking Patroni’s REST API (GET /primary answers 200 only on the lock holder), PgBouncer reconfigured by a callback, a Kubernetes service whose endpoint Patroni updates, or libpq’s multi-host connection strings with target_session_attrs=read-write, which try each host and keep the first one that accepts writes (useless when two do). Routing fences new connections. It does not fence connections that are already open, which is why HAProxy’s on-marked-down shutdown-sessions exists, nor any client that connects directly.
Synchronous replication as a fence. If the old primary requires a synchronous standby to acknowledge every commit, and that standby has since been promoted or now follows the new primary, the old primary’s commits hang. They are written locally but never acknowledged, so no client is told “success” for a write that will be discarded. Patroni’s synchronous_mode also restricts promotion to the synchronous standby. Together they turn split brain from “both sides accept writes” into “the old side blocks”, which is the outcome you want. It costs the commit latency from the previous chapter.
Outside Postgres, the strongest form is the fencing token from Kleppmann’s distributed-locking post: every lease grant carries a number that only increases, and the storage rejects writes with an older number. Shared-storage databases do this (Aurora’s storage layer rejects writes from a stale writer epoch), and you can do it in application tables when a job must run on one node at a time. Postgres replication itself has no token, which is why its fences are all outside the database.
The oldest form, STONITH (“shoot the other node in the head”), powers off the old primary through an out-of-band interface (IPMI, a cloud API call that stops the instance) before promoting. Pacemaker clusters use it. It works when the fencing path is independent of the network that failed.
Rejoining: pg_rewind and the writes it throws away
After a failover, the old primary may have WAL the new primary never saw: async commits that were not shipped, or writes accepted during a split brain. It cannot follow the new primary from there, because their histories diverge at the timeline branch point.
pg_rewind repairs this by finding the branch point from the timeline history, copying from the new primary every block that changed on either side since then, and setting the node up to replay from the branch. It needs wal_log_hints = on or data checksums, and is much faster than a fresh base backup on a large database. Patroni runs it automatically with use_pg_rewind: true.
Be clear about what it does: every transaction the old primary committed after the branch point is gone. Clients were told those commits succeeded. If you need them, extract them before rewinding (pg_waldump on the old primary’s WAL past the branch LSN, or a copy of the data directory) and reconcile by hand, which is what GitHub spent a day doing.
When the referee fails
If the primary cannot reach the DCS, Patroni demotes it after retry_timeout, which is correct during a partition and absurd when etcd itself is down: a healthy primary with healthy replicas turns read-only because the referee left. Patroni 3.0 added failsafe mode (failsafe_mode: true): when the DCS is unreachable, the leader keeps running only if it can reach every other member through their REST APIs and they confirm they have not seen another leader. If any member is unreachable, it demotes as before. That narrows the outage to “DCS down and a node down at once”.
What clients see
During failover every in-flight transaction on the old primary fails, and every commit that was in progress has an unknown outcome: the client sent COMMIT and the connection died. It may have committed on the old primary and replicated, committed and not replicated (lost), or not committed. Retrying blindly can double-charge; not retrying can lose an order. Only an idempotency key the database can check (a unique constraint on a client-generated request id) makes the retry safe, which the idempotency lesson builds. Clients also need reconnect logic with backoff, and pools that validate connections after errors rather than handing out dead ones.
The lab stack
labs/databases/patroni.yaml is a separate compose project, atlas-patroni, that does not touch the shop. It builds one image from labs/databases/patroni/Dockerfile (Postgres 17 plus Patroni 4.1.5) and runs three etcd members, three Patroni nodes pg1 to pg3 configured by patroni/patroni.yml (ttl 30, loop_wait 10, retry_timeout 10, use_pg_rewind, watchdog off), HAProxy with patroni/haproxy.cfg (port 5500 for the primary, 5501 for replicas, 7070 for its stats page), and a client container that runs patroni/writer.sh. Patroni runs as a child of a shell rather than as the container’s main process, so killing Patroni leaves its Postgres running, the agent-dies case from above. The superuser is postgres with password atlas.
In each terminal:
cd labs/databases
export COMPOSE_FILE=patroni.yamlpatronictl below is shorthand for docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml; run it from any node whose Patroni is alive.
1. Start the cluster and find the leader.
docker compose up -d --build
sleep 30
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml list
curl -s -o /dev/null -w "pg1 /primary: %{http_code}\n" localhost:8008/primary
curl -s -o /dev/null -w "pg2 /primary: %{http_code}\n" localhost:8009/primary
curl -s -o /dev/null -w "pg3 /primary: %{http_code}\n" localhost:8010/primaryLeader in state running, two Replica in state streaming, all on TL 1 with zero lag. Which node won the bootstrap race varies; the rest of the lab says “the leader” and you substitute its name. Exactly one of the curls prints 200 and the others 503: that is the health check HAProxy uses, and http://localhost:7070 shows one server up in the primary section.2. Start a writer.
In terminal 2:
docker compose exec client bash /etc/patroni/writer.sh14:02:11.204 57 pg1: time, new id, the node that took the write. Leave it running for the rest of the lab; its timestamps are your measurement.3. Unplanned failover: kill the leader’s whole container.
In terminal 1, with the leader’s name (here pg1):
docker compose kill pg1
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml list
sleep 40
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml listserver closed the connection unexpectedly or could not connect to server while HAProxy has no healthy primary) for 25 to 40 seconds, then ids resume on another node. Subtract the timestamps to get your failover time; most of it is the leader key’s remaining TTL. The second list shows a new leader on TL 2 and the third node streaming from it. pg1 is missing from the list once its member key expires.4. Rejoin the old primary.
docker compose start pg1
sleep 20
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml list
docker compose logs pg1 --since 1m | grep -iE "rewind|following|replica|demot" | headReplica, streaming, on TL 2. Its log shows Patroni discovering a leader that is not itself and starting Postgres as a replica of it, with a pg_rewind run if pg1 had WAL beyond the branch point. No human decided anything; that is the value of a DCS.5. Planned switchover.
Move leadership back to pg1 (replace pg2 with the current leader):
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml switchover --leader pg2 --candidate pg1 --force6. Split brain: kill Patroni, not Postgres.
pg1 is the leader. Kill only its Patroni process; its Postgres keeps running as a primary:
docker compose exec pg1 pkill -KILL -f /opt/patroni/bin/patroni
docker compose exec pg1 psql -U postgres -Atc "SELECT pg_is_in_recovery()"Wait until the writer’s ids come from another node (25 to 40 seconds), then write to pg1 directly, as an application with a hard-coded host or an old pooled connection would:
docker compose exec pg1 psql -U postgres -c "INSERT INTO ticks (note) VALUES ('split brain: written to pg1') RETURNING id"
for n in pg1 pg2 pg3; do
echo -n "$n: "; docker compose exec $n psql -U postgres -Atc \
"SELECT pg_is_in_recovery(), count(*), max(id), count(*) FILTER (WHERE note LIKE 'split%') FROM ticks"
done
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml listpg_is_in_recovery is f on pg1 straight after the kill: Postgres does not know its agent died. HAProxy marks pg1 down within about four seconds because its REST API stopped answering, so the writer fails until the new leader is promoted. The direct INSERT on pg1 succeeds and returns an id. The loop then shows two nodes with f: pg1 and the new leader, each with a different count and max(id), and only pg1 has the split-brain row. patronictl list shows only two members; the DCS believes the cluster is healthy. With no watchdog, nothing will stop pg1.7. Rejoin, and watch the write disappear.
Start Patroni on pg1 again, sending its log to the container’s output:
docker compose exec -d pg1 bash -c 'exec /opt/patroni/bin/patroni /etc/patroni/patroni.yml >> /proc/1/fd/1 2>&1'
sleep 30
docker compose logs pg1 --since 1m | grep -iE "demot|rewind|lock" | head
docker compose exec pg1 psql -U postgres -Atc "SELECT pg_is_in_recovery(), count(*) FILTER (WHERE note LIKE 'split%') FROM ticks"
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml listpg_rewind against the new leader. pg1 is back as a streaming replica on the new timeline, and the split-brain row is gone: count is 0. A client was told that INSERT succeeded. This is the reconciliation GitHub did by hand for a day, done silently by a tool in a second.8. Fence with synchronous mode, and repeat.
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml edit-config -s synchronous_mode=true --force
sleep 15
docker compose exec pg2 patronictl -c /etc/patroni/patroni.yml listNote the leader’s name (here pg2), kill its Patroni, and wait for the writer to move to the node that was Sync Standby:
docker compose exec pg2 pkill -KILL -f /opt/patroni/bin/patroni
docker compose exec pg2 psql -U postgres -c "SHOW synchronous_standby_names"
docker compose exec pg2 psql -U postgres -c "INSERT INTO ticks (note) VALUES ('split brain, fenced') RETURNING id"Wait ten seconds, press Ctrl-C, and restart Patroni on the old leader as in step 7.
list shows one member as Sync Standby. After the kill, the writer moves to exactly that node, because in synchronous mode only it may be promoted. synchronous_standby_names on the old leader still names the standby that has since become leader. The direct INSERT hangs, and Ctrl-C prints canceling wait for synchronous replication and The transaction has already committed locally, but might not have been replicated. The client got an error, not a success. When Patroni rewinds the node, that row disappears, and no one was promised it.docker compose pause etcd2 etcd3 to leave etcd without a quorum, and restart the writer. Within retry_timeout plus one loop (10 to 20 seconds) the leader’s Patroni gives up renewing its key and demotes its own healthy Postgres; curl localhost:8008/primary, :8009 and :8010 all return 503 and every write fails, although all three databases are running. Unpause with docker compose unpause etcd2 etcd3 and a leader returns. Now run patronictl edit-config -s failsafe_mode=true --force and pause the two etcd members again: the leader stays primary, because it can reach both other members’ REST APIs. Then also docker compose stop one replica and watch it demote anyway: failsafe needs every member to answer. Finish with docker compose down -v and unset COMPOSE_FILE.You run a three-node Patroni cluster on VMs in one cloud region, one node per zone, async replication, etcd on three small separate VMs. Commit latency matters (p99 budget 15 ms, cross-zone round trip 1.5 ms). After reading this chapter, your lead asks for one change this quarter that most reduces the chance of a split brain losing acknowledged writes. Which do you make?
- DOC Patroni documentation
Read 'Dynamic configuration settings' for ttl, loop_wait, retry_timeout and synchronous_mode, 'Watchdog support' for the self-fence, and 'DCS Failsafe Mode' for what happens when etcd goes away. The REST API page lists every health endpoint a router can use.
- POST How to do distributed locking Martin Kleppmann, 2016
The clearest argument for why a lease alone cannot guarantee one writer and why the storage must check a fencing token. Written about Redis locks; every sentence applies to a primary holding a leader key.
- POST October 21 post-incident analysis GitHub, 2018
The incident in the Why, in detail: a 43-second partition, a cross-coast promotion, and a day of reconciling two histories. Read it for what an HA tool optimising for availability does to consistency.
- POST Jepsen: PostgreSQL 12.3 Kyle Kingsbury, 2020
Jepsen's method applied to Postgres: a workload, injected faults, and a checker that finds anomalies the developers' own tests missed. Read it for how to test a database's promises rather than trust them; the Jepsen-style chapter later in this module builds on it.
- DOC PostgreSQL 17: pg_rewind
What pg_rewind copies, what it requires (wal_log_hints or checksums), and the warning that it discards the target's divergent changes. Short and worth reading before you rely on automatic rejoin.
- BOOK Designing Data-Intensive Applications, chapter 8: The Trouble with Distributed Systems Martin Kleppmann, 2017
Unreliable networks, clocks and process pauses are the theory behind 'detection is a timeout'; the section on leases and fencing tokens is the theory behind this chapter's fencing layers. Read: chapter 8, sections 'Unreliable Networks', 'Process Pauses' and 'Knowledge, Truth, and Lies'.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.