Lesson 15 of 38Distributed systems
Consensus and Leader Election
Why picking one leader is hard, how majority quorums and Raft prevent split brain, and why safe distributed locks need fencing tokens.
You can now store data and give every row a safe ID. This unit is about what goes wrong when several machines must agree. Your Postgres primary stops answering health checks at 3 a.m. The failover tool promotes a replica. Ten seconds later the old primary, which was only stuck on a slow disk, comes back and keeps accepting writes from app servers that still point at it. You now have two primaries and two diverging copies of the orders table. This is split brain, and avoiding it is the job of consensus: getting a group of machines to agree on one value, such as "who is the leader right now", even when some of them crash or the network misbehaves. You will almost never implement consensus yourself, but you use it every day through etcd, ZooKeeper, Kafka, and your database's failover, and senior interviews expect you to explain how it works and where it breaks.
Why this is hard
On one machine, agreeing is trivial. Across machines, three facts make it hard:
- The network is unreliable. Messages get delayed, dropped, duplicated, or delivered out of order. A network partition can split a cluster into groups that cannot talk to each other but can each still talk to some clients.
- Processes pause. A garbage collector stops the world for 20 seconds. A VM is live-migrated. A container is throttled. The process does not know it was frozen; from its point of view, time jumped.
- There is no global clock. Each machine's clock drifts and can be stepped by NTP, as you saw in Generating Unique IDs. You cannot order events across machines by timestamp alone.
Put together, they give the core problem: a timeout cannot tell "dead" from "slow". When node A stops hearing from node B, B might have crashed, might be paused, or might be fine with a broken link between them. Every failover system has to act without knowing which.
Split brain and majority quorums
The fix for split brain is a rule: an action needs a majority of the whole cluster, not a majority of the nodes you can currently reach. A majority of N is floor(N/2) + 1, so 2 of 3, or 3 of 5.
The logic is simple and worth saying in an interview: any two majorities overlap in at least one node. If 3 of 5 nodes voted for leader A in some term, any other group of 3 contains at least one of those voters, and that voter will not vote for a second leader in the same term. So there can be at most one leader per term. During a partition, the side with the majority can keep working. The minority side cannot elect anyone and cannot commit writes. It is unavailable, which is the CP choice from the Consistency and CAP lesson.
This also explains cluster sizes:
| Nodes | Majority | Failures tolerated |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 7 | 4 | 3 |
A 2-node cluster is worse than one node: it needs both to agree, so either failure stops it. Even sizes add a machine without adding tolerance. That is why etcd, ZooKeeper, and Consul clusters run 3 or 5 voting members. Going beyond 5 or 7 makes every write wait for more acknowledgements, so large systems shard their data into many small consensus groups instead.
How many node failures can a majority-quorum cluster survive for each size?
print([(n - 1) // 2 for n in [3, 4, 5, 6]])
Raft at a glance
Raft (Ongaro and Ousterhout, 2014) is the consensus algorithm most modern systems use, designed to be easier to understand than Paxos. etcd, Consul, CockroachDB, TiKV, and Kafka's KRaft controllers all run it. You do not need the full paper; you need the shape.
Every node is in one of three states: follower, candidate, or leader. Time is divided into numbered terms, and each term has at most one leader.
Electing a leader:
- Followers expect regular heartbeats from the leader. Each follower has an election timeout, randomized (the paper suggests 150 to 300 ms; etcd defaults to a 100 ms heartbeat and a 1 second election timeout).
- If the timeout passes with no heartbeat, the follower becomes a candidate, increments the term, votes for itself, and asks every other node for its vote.
- Each node votes for at most one candidate per term, and only for a candidate whose log is at least as up to date as its own. This rule is what stops a node that missed recent writes from becoming leader and erasing them.
- A candidate with votes from a majority becomes leader and starts sending heartbeats. Anyone who sees a higher term steps down to follower.
The randomized timeouts matter. If every follower timed out at the same moment, they would all vote for themselves, split the vote, and try again forever. Randomness makes one node usually time out first and win before the others start.
Replicating the log: clients send writes only to the leader. The leader appends the entry to its log and sends it to the followers. Once a majority have stored it, the entry is committed: the leader applies it, replies to the client, and tells followers to apply it too. A committed entry survives any later election, because every possible future majority includes a node that has it, and only such nodes can win.
Step through an election, a crash, and a re-election in a five-node cluster.
Term 1. n2 is leader. It sends heartbeats (and new log entries) to all four followers, which keeps resetting their election timers.
Now run a small simulation of the vote rules, including a node with a stale log and a network split.
Press Run (⌘ Enter) to see what happens.Two things to notice. n5 timed out first but lost, because its log was missing committed entries, so the up-to-date rule protected those writes. And during the split, the old leader n2 still believes it is leader, but it can only reach 2 of 5 nodes, so nothing it accepts gets committed. Being leader is not enough; every commit needs a majority.
The subtle parts of Raft that interviewers sometimes probe
Committing old entries. A new leader does not mark entries from earlier terms as committed just because they now sit on a majority. It commits an entry from its own term, and everything before that entry becomes committed with it. Without this rule, an entry could be counted as committed and later overwritten (Figure 8 in the paper shows the exact scenario).
Reads are not free. A leader that was partitioned away might not know it has been replaced, so reading from it can return stale data. To serve a linearizable read, the leader first confirms it still has a majority (a round of heartbeats, the "ReadIndex" approach) or relies on a time-based lease, which assumes bounded clock drift. etcd does linearizable reads by default and offers cheaper serializable reads that may be stale.
Membership changes. Adding or removing nodes while the cluster runs needs care, because the old and new configurations could each form their own majority. Raft adds one server at a time, or uses a joint consensus phase.
Put the steps of a Raft leader change in order.
- Tap the steps below in the right order.
Leases and fencing tokens
Leader election and distributed locks are the same problem: one process at a time may do something. Systems implement both with a lease, a lock that expires unless renewed. If the holder crashes, the lease runs out and someone else can take over. That is better than a lock held forever by a dead process.
But leases have a trap, described clearly in Martin Kleppmann's 2016 critique of the Redlock algorithm. A process can acquire a lease, then pause (GC, swap, a stopped VM) for longer than the lease. The lease expires, a second process acquires it and starts writing, and then the first process wakes up still believing it holds the lock. Checking "do I still hold the lock?" right before writing does not help, because the pause can happen between the check and the write.
The fix is a fencing token: every time the lock service grants a lease, it also hands out a number that only goes up. The client includes the token with every write, and the storage rejects any write with a token lower than the highest it has seen. The paused process wakes up with token 33, the storage has already seen 34, and the stale write is refused. The protection lives in the resource, not in the client's beliefs.
acquire lease
Press Run (⌘ Enter) to see what happens.Where do tokens come from in practice? etcd gives every key a revision number that increases on each change, and ZooKeeper has transaction ids and sequential nodes. In a database you can use the same idea as optimistic concurrency: UPDATE ... WHERE id = ? AND version = ?. Raft's term number is a fencing token too: nodes reject messages from a leader with an old term.
Distributed locks in practice
Before reaching for a lock, ask what happens if two holders overlap. If the answer is "some duplicate work" (two workers send the same daily report), you want a lock for efficiency. If the answer is "corrupted data or money lost", you need it for correctness, and then you need fencing or a design that does not depend on the lock.
- Redis
SET lock:report <random-id> NX PX 30000: sets the key only if it does not exist, with a 30-second expiry. Release it only if the value still matches your random id (with a small Lua script), so you never delete someone else's lock. Fine for efficiency. Not safe for correctness: there is no fencing token, and a Redis failover with asynchronous replication can lose the key so two clients both hold it. - Postgres advisory locks (
pg_try_advisory_lock(42)): handy when the protected work is in the same database. A session-level lock is released when the connection drops. Watch out for connection poolers in transaction mode, which can hand your session to someone else. - etcd or ZooKeeper leases: built on consensus, so a granted lease really is exclusive within the cluster, and you get revision numbers to use as fencing tokens. This is what Kubernetes controllers use for leader election (through
Leaseobjects stored in etcd), and what Patroni uses to decide which Postgres node is primary. - Avoid needing one at all: a unique constraint, a conditional write (
WHERE status = 'pending'), orSELECT ... FOR UPDATE SKIP LOCKEDoften solves "only one worker processes this job" more simply.
SET NX PX 60000. What is the main problem?Where you meet consensus
You will rarely see the word Raft in application code, but consensus sits under a lot of what you deploy:
- Kubernetes stores all cluster state in etcd (Raft). Lose etcd quorum and the control plane stops, though running pods keep running.
- Kafka used ZooKeeper for metadata for years. Kafka 4.0 (2025) removed ZooKeeper entirely; the controllers now run their own Raft-based quorum called KRaft.
- ZooKeeper itself uses its own protocol, Zab, which is similar in spirit to Raft and Paxos.
- Consul and HashiCorp Vault (with integrated storage) use Raft.
- CockroachDB and TiKV split data into ranges and run a separate Raft group per range. Google Spanner does the same with Paxos groups per split. This is how they shard while keeping each piece strongly consistent.
- MongoDB replica sets elect primaries with a Raft-inspired protocol.
The rule seniors repeat: never implement consensus yourself. The algorithms are short on paper; correct implementations take years of testing against partitions, pauses, and disk failures.
Match each system to how it reaches agreement.
Two names to recognize
FLP impossibility (Fischer, Lynch, and Paterson, 1985) proves that in a fully asynchronous system, where messages can take arbitrarily long, no deterministic algorithm can guarantee consensus will finish if even one process may crash. Real systems get around it by using timeouts: they assume the network is usually timely, stay safe (never two leaders) always, and only promise progress when timing behaves. That is exactly the Raft trade: safety from majorities and terms, liveness from timeouts.
Byzantine faults are nodes that lie or send conflicting messages, through bugs or malice, rather than just crashing. Raft and Paxos assume nodes are honest and only crash; they need 2f + 1 nodes to survive f failures. Byzantine fault tolerance needs 3f + 1 and is far more expensive. You meet it in blockchains and some aerospace systems, not inside a company's own data center, where machines are trusted.
- consensus
- Getting a group of nodes to agree on a value, such as the leader or the next log entry, despite crashes and network faults.
- split brain
- Two nodes both acting as leader and accepting writes, so the data diverges.
- majority quorum
- floor(N/2) + 1 nodes. Any two majorities overlap, which is what makes decisions safe.
- term
- A numbered period in Raft with at most one leader. Higher terms override lower ones.
- election timeout
- How long a Raft follower waits without a heartbeat before starting an election. Randomized to avoid split votes.
- lease
- A lock or leadership grant that expires unless renewed, so a crashed holder cannot keep it forever.
- fencing token
- A number that increases with each lock grant. Storage rejects writes carrying an older token than it has seen.