Consensus and leader election¶
What you'll be able to do¶
- Explain why replicated systems need consensus, and how it prevents split brain.
- Compute how many failures an n-node cluster survives, and say why two nodes and even sizes do not help.
- Trace a Raft election, a commit and a partition, and explain what fencing tokens protect against a stale lock holder, and what they do not.
The problem: agreeing despite failures¶
In replication a follower is promoted when the leader dies. If every node decides alone when that happens, a network hiccup can leave two nodes each believing they lead. Both accept writes and data diverges: split brain.
Consensus is a protocol by which nodes agree on one value, or one ordered sequence of values, despite crashes and delayed or lost messages. Agree on a sequence and you get a replicated log: nodes that start from the same state and apply the same commands in the same order to a deterministic state machine reach the same state. Clock reads, unseeded randomness or model inference inside the apply step can break this. It also gives leader election, locks and configuration stores.
A cut-off node may still believe it is leader. It cannot commit new log entries without a majority, but its belief can still cause stale reads or unsafe external side effects unless those operations confirm leadership or use fencing.
A safety property says nothing bad ever happens (two nodes never decide different values). A liveness property says something good eventually happens (a value is eventually decided).
What is and is not possible¶
The FLP result (Fischer, Lynch and Paterson, 1985) says that in a fully asynchronous system, where a slow node looks like a dead one, no deterministic protocol can guarantee that consensus terminates if even one node may crash. Real systems use timeouts to suspect failures and randomness to break ties, which gives liveness in practice once the network behaves for long enough. They never trade away safety: a misfiring timeout may stall the cluster but must not make it decide two things. "May pause, must not lie."
Quorums: why majorities work¶
A majority of n nodes has n // 2 + 1 members. Two majorities together have at least n + 1 members, but only n nodes exist, so they share a node. Through that node a later majority can learn of an earlier decision. Overlap alone is not enough: the protocol also needs rules about who may win and when something counts as decided.
def majority(n): return n // 2 + 1
for n in (2, 3, 4, 5, 6, 7):
print(n, majority(n), n - majority(n))
| Nodes n | Majority | Failures tolerated |
|---|---|---|
| 2 | 2 | 0 |
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 6 | 4 | 2 |
| 7 | 4 | 3 |
To tolerate f failures you need 2f+1 nodes: 5 = 2·2 + 1 gives f = 2. Consequences:
- Two nodes are not fault tolerant. The majority of 2 is 2, so either failure stops progress; you doubled what can break.
- Even sizes do not help. Four nodes tolerate one failure, like three, with an extra machine. A 2-2 split leaves neither side a majority.
- Each extra failure costs two more nodes, so 3 or 5 is typical.
Raft at intuition level¶
Raft was designed to be understandable. Paxos, Multi-Paxos, ZAB and Viewstamped Replication are siblings. The Raft visualization shows the steps below.
Roles and terms¶
Each node is a follower, candidate or leader. Time is cut into numbered terms, a logical clock (compare unique IDs). A node seeing a higher term adopts it and, if leading, steps down.
Elections¶
A follower hearing no heartbeat before its election timeout becomes a candidate: it increments its term, votes for itself and sends RequestVote. A node grants a vote only if:
- The candidate's term is not older than its own.
- It has not voted for a different candidate in that term.
- The candidate's log is at least as up to date: compare the last entry's term first, then length. As
(last term, last index),(2, 1) >= (1, 5)is true.
A majority of votes makes the candidate leader, and it sends heartbeats. By rule 2 two candidates cannot both win a term: their majorities would share a node that voted once. Timeouts are randomized, so one node usually fires first; a split vote just means another term. Nodes persist term, vote and log before replying.
Log replication¶
The leader appends the command to its log and sends AppendEntries, naming the entry just before the new ones. A follower lacking it refuses, and the leader backs up and resends, so logs converge.
A leader can commit an entry from its current term once a majority stores it; the leader then applies it and answers. Committing that entry also commits all preceding entries. An older-term entry on a majority is not necessarily committed yet: a node lacking it, but ending in a newer-term entry, could still win an election and overwrite it. The election restriction (rule 3), log matching (the previous-entry check) and this current-term commit rule together give leader completeness: every later leader holds every committed entry.
Partitions¶
Locks, leases and fencing tokens¶
A lease is a lock that expires, so a dead holder cannot block everyone forever. The trap: expiry is judged by clocks, while the holder can pause (garbage collection, a stalled VM) past its lease without knowing, then resume and write. Checking "do I still hold it?" first does not help; the pause can come right after the check.
The fix is a fencing token: a number that increases with every grant. The holder sends it with every write, and the resource atomically rejects any token lower than the highest it has recorded, whatever the holder's clock says.
The limit: storage rejects A's token only after it has recorded a newer one. Until it sees B's 34, A's late write with 33 is accepted. So before relying on exclusivity (say, before reading data it will rewrite), B should raise the resource's token floor to 34, or the resource must validate the current grant atomically with each write.
Where the resource cannot check tokens, a conditional write (compare-and-set on a version) can reject a writer whose view is out of date. Leases assume clocks tick at roughly the same rate, not that they show the same time. A lock with no check at the resource is an efficiency tool, not a correctness tool.
Where you meet it, and what it costs¶
Use systems built on consensus rather than writing your own: persistence, membership changes and snapshots hide subtle bugs. ZooKeeper shows how locks, leader election and fencing tokens are built on such a service.
| System | Role |
|---|---|
| etcd, Consul (Raft), ZooKeeper (ZAB) | Small strongly consistent stores for config, membership, locks, leader election |
| Kubernetes | State in etcd; scheduler and controller-manager replicas elect one active instance with leases |
| Replicated databases, Kafka's controller | Leader election; see failover |
A 5-node commit waits for two follower acks, so latency is set by the second-fastest follower. With illustrative round trips of 1, 1, 2 and 2 ms that is about 1 ms plus disk sync; with followers at 1, 70, 70 and 120 ms across regions, about 70 ms. One leader orders all writes, so more nodes add fault tolerance, not write throughput.
Reads trade freshness for cost. A linearizable read reflects every write that completed before it began. The read index is the leader's commit index when the read arrives.
| Read path | Result | Cost |
|---|---|---|
| Leader read after a current-term commit, quorum confirmation, and applying through the read index | Linearizable | Quorum round trip (possibly batched) plus apply wait |
| Same, with a lease replacing the per-read quorum round trip | Linearizable only if clock drift stays in bound | Fast, clock assumption |
| Plain local read on a follower | May be stale | Cheap, scales out |
For AI engineers
Your training jobs may run on a control plane built on this. If a Kubernetes cluster loses its etcd quorum, API writes and control-plane changes generally stop; already running containers usually continue until another dependency fails.
For one active pipeline scheduler, use leader election, not "two replicas and hope". Failover may still execute a job again (a crash after the work, before completion is recorded), so use a durable job claim and idempotent effects. A latest checkpoint pointer written by two workers after a pause can regress to an older model; give each writer a generation number as a fencing token and use conditional writes.
A model registry may keep the small "which version is production" pointer in a coordination service, with the weights in object storage.
Common mistakes¶
- Running two nodes "for high availability": either failure stops a majority-based cluster.
- A lock with no expiry (a dead holder blocks everyone) or no fencing (a paused holder overwrites newer work).
- Assuming a new lock grant alone shuts out the old holder. The resource must have seen the new token.
- Assuming clocks agree. Leases need bounded drift; timestamps from different machines are not an ordering.
- Treating a single Redis
SET ... NXlock, or any cache, as a correct lock for safety-critical work. - Implementing consensus yourself instead of using etcd, ZooKeeper or Consul.
Check yourself¶
A 5-node cluster splits 2 | 3. A client writes "x" to the old leader on the 2 side. What happens, and what is true after healing?
Only the 2 side can store "x", so it cannot commit and the client gets no success. The 3 side elects a new leader in a higher term; after healing, the old leader steps down and "x" is overwritten by the new leader's log.
Why must a node refuse a candidate whose log is behind its own, even if the candidate's term is higher?
A committed entry is on a majority, so some voter in any later majority holds it. Ignoring log freshness could elect a candidate lacking it and lose a committed write.
A lock holder pauses 40 seconds with a 30 second lease and no fencing. Describe the failure and the fix.
The lease expires, another client takes the lock, then the first resumes and overwrites newer data. Issue an increasing token per grant and have the resource reject lower ones. The new holder presents its token to the resource before relying on exclusivity.
Your election timeout is shorter than normal network jitter. Do you lose safety or liveness?
Liveness. Nodes keep suspecting a healthy leader and starting elections, so progress stalls, but safety holds.
Lab¶
In code/consensus/, complete a small deterministic model of election and replication (a teaching model, not Raft). You implement majority, fault_tolerance, the vote rules, elections, and the current-term commit rule. Tests then cut the cluster: a minority leader cannot commit, a stale leader steps down, and logs converge. Finally, FencedResource must reject a paused client's stale token once it has seen a newer one. Run: cd code/consensus && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- Raft visualization to watch elections and replication.
- Kleppmann's Cambridge distributed systems course and MIT 6.824.
- Interactive: Designed to Scale: consensus, CAP
- Timeouts and retries for timeouts that drive elections.