Skip to content

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.

17 min read0/4 questions

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:

NodesMajorityFailures tolerated
110
220
321
431
532
743

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.

Predict the outputPython

How many node failures can a majority-quorum cluster survive for each size?

print([(n - 1) // 2 for n in [3, 4, 5, 6]])
Need a nudge? Hints walk you through it.

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:

  1. 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).
  2. 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.
  3. 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.
  4. 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.

A Raft cluster loses its leader
n1: followern1followern2: leader, term 1n2leader, term 1n3: followern3followern4: followern4followern5: followern5followerheartbeatheartbeatheartbeatheartbeatvote?vote?

Term 1. n2 is leader. It sends heartbeats (and new log entries) to all four followers, which keeps resetting their election timers.

1/6

Now run a small simulation of the vote rules, including a node with a stale log and a network split.

Pythonraft_election.py
import random random.seed(7) class Node: def __init__(self, name): self.name = name self.term = 0 self.voted_for = None self.log = [] # the term of each entry self.alive = True def last(self): return (self.log[-1] if self.log else 0, len(self.log)) def request_vote(self, cand, term, cand_last): if term > self.term: # newer term: step down, forget old vote self.term, self.voted_for = term, None up_to_date = cand_last >= self.last() # compare (last term, length) if term == self.term and self.voted_for in (None, cand) and up_to_date: self.voted_for = cand return True return False def stand(cand, nodes, can_reach): cand.term += 1 cand.voted_for = cand.name votes = 1 + sum( peer.request_vote(cand.name, cand.term, cand.last()) for peer in nodes if peer is not cand and peer.alive and can_reach(cand, peer) ) need = len(nodes) // 2 + 1 # a majority of the WHOLE cluster won = votes >= need print(f" {cand.name} term {cand.term}: {votes}/{len(nodes)} votes, needs {need} -> {'LEADER' if won else 'lost'}") return won def election(nodes, can_reach, first=None, candidates=None): live = [n for n in (candidates or nodes) if n.alive] timeout = {n.name: random.randint(150, 300) for n in live} order = sorted(live, key=lambda n: timeout[n.name]) if first: # force a node to time out first order.remove(first) order.insert(0, first) for cand in order: if stand(cand, nodes, can_reach): return cand.name return None nodes = {f"n{i}": Node(f"n{i}") for i in range(1, 6)}cluster = list(nodes.values())anyone = lambda a, b: True print("1. Fresh cluster")leader = election(cluster, anyone) for n in cluster: # 3 entries reach every node except n5 if n.name != "n5": n.log = [nodes[leader].term] * 3 print("2. Leader crashes, n5 (behind) times out first")nodes[leader].alive = Falseleader = election(cluster, anyone, first=nodes["n5"]) print("3. Network splits {n1, n2} | {n3, n4, n5}")side = {"n1": 0, "n2": 0, "n3": 1, "n4": 1, "n5": 1}split = lambda a, b: side[a.name] == side[b.name]nodes["n4"].alive = True # the crashed node is backmajority = [nodes["n3"], nodes["n4"], nodes["n5"]]print(" majority side elects:", election(cluster, split, candidates=majority) or "no leader") old = nodes["n2"] # still thinks it leads term 3acks = 1 + sum(1 for p in cluster if p is not old and split(old, p))print(f" old leader n2 tries a write: {acks}/5 acks -> {'committed' if acks >= 3 else 'NOT committed'}")
Output
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 it in order5 steps

Put the steps of a Raft leader change in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

A paused lock holder, stopped by a fencing token
Worker 1Lock serviceWorker 2Storageacquire leasegranted, token 33GC pause, 30sacquire leasegranted, token 34write, token 34write, token 33rejected: 33 is older than 34

acquire lease

1/8
Pythonfencing.py
class LockService: """Hands out a lease plus a token that only ever goes up.""" def __init__(self): self.token = 0 self.holder = None def acquire(self, who): self.token += 1 self.holder = who return self.token class Storage: def __init__(self, check_tokens): self.check_tokens = check_tokens self.highest = 0 self.data = None def write(self, who, token, value): if self.check_tokens and token < self.highest: print(f" REJECT {who}: token {token} is older than {self.highest}") return self.highest = max(self.highest, token) self.data = value print(f" ok {who} wrote {value!r} with token {token}") for check in (False, True): print("storage checks tokens:", check) locks, disk = LockService(), Storage(check) t1 = locks.acquire("worker-1") # worker-1 gets the lock... # ...then freezes in a 30s GC pause. Its lease expires. t2 = locks.acquire("worker-2") # worker-2 gets the lock disk.write("worker-2", t2, "invoice v2") disk.write("worker-1", t1, "invoice v1") # worker-1 wakes, still thinks it holds the lock print(" final:", disk.data)
Output
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 Lease objects 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'), or SELECT ... FOR UPDATE SKIP LOCKED often solves "only one worker processes this job" more simply.
Quick check
A nightly billing job must never charge a customer twice, and two pods run it. A teammate proposes a Redis lock with SET NX PX 60000. What is the main problem?
Need a nudge? A hint rules out a wrong answer.

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 the pairs0/5 matched

Match each system to how it reaches agreement.

Choose an item, then its match on the other side.

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.

Key terms
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.