Home›Learn›Consensus and leaders
Course · Stay upLesson 23 of 330 read

Consensus and leaders

After a failover, how does everyone agree on the new primary?

One failover with Patroni and etcd, animated, and the same idea in five other systems.

Press Play, or step with the arrows.

High availability needs one decision made reliably: which node is the primary now. If two nodes both believe it, both take writes and the data splits. That is the problem consensus solves.

How each system picks a leader

Go deeper
SystemWho decidesDefault timing
PostgreSQL + PatroniA leader key in etcd, Consul or ZooKeeper, with a TTLttl 30 s, loop_wait 10 s
MongoDB replica setThe members vote among themselves (a Raft-based protocol)electionTimeoutMillis 10 s, heartbeats every 2 s
MySQL InnoDB ClusterGroup Replication: members agree on every transaction (Paxos based)A member is expelled after it stops responding
Redis SentinelA quorum of Sentinels agrees the primary is down, then one Sentinel leads the failoverdown-after-milliseconds, 30 s in the example config
CassandraNo leader: any replica takes writes; lightweight transactions use Paxos per partition (one partition key)n/a
etcd, Consul, ZooKeeperRaft or Zab among their own membersTheir own election timeouts

Two rules hold everywhere. A leader needs a majority, so three nodes survive one failure and five survive two. And a leader that loses the majority must stop acting as leader on its own, because the others cannot stop it. That step, self-demotion when the lease cannot be renewed, is what prevents split brain. True fencing, a token or STONITH that blocks the old leader's writes, is a separate, stronger mechanism.

patronictl -c /etc/patroni.yml list
# Member  Host  Role     State      TL  Lag in MB
# pg2     ...   Leader   running     2
# pg1     ...   Replica  streaming   2          0
// MongoDB: who is primary, and the election term
rs.status().members.map(m => [m.name, m.stateStr])
rs.status().term
Connected

Where this shows up

The same mechanism, replication and failover, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 3 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. Why does Patroni wait for the leader key to expire before promoting?

2. Two replicas try to take the leader key at the same moment. What happens?

3. A five-node cluster can lose how many nodes and still elect a leader?

Part 1 of 4 · Learn · 23 pagesAll pages

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.