System Design · Concept Library · Free article
Raft and Leader Election: Agreeing on One Leader When the Network Lies
Raft keeps a group of servers to at most one leader per term by holding an election only a strict majority can win. Two majorities always share a server, so a split network cannot crown two winners, and a returning old leader steps down when it sees a newer term.
Leader election by consensus lets a group of replicas agree on one — and only one — leader, even when the network is dropping messages and machines are dying, by refusing to crown anyone who cannot win a strict majority of the votes. A lone failover controller that promotes a follower the instant a heartbeat goes quiet is dangerously naive: a brief network blip makes it crown a second leader while the first is still alive and writing, and now two leaders accept conflicting writes — split-brain. The fix is to stop appointing leaders and start electing them. Each replica group runs a term (a numbered round, the logical clock of the system); a follower whose election timer fires becomes a candidate, asks the group to vote, and may only become leader if more than half the group votes for it. That single rule — a majority — is the one thing a network split cannot subvert: only one side of any partition can ever hold more than half the copies, so two leaders become mathematically impossible, and a candidate is only allowed to win if its log is at least as up to date as the voters (so a new leader is guaranteed to hold every committed write). Raft is the modern, deliberately learnable version of this idea (Paxos is its older, subtler cousin), and it runs underneath etcd, Consul, CockroachDB, and Kafka. The cost is real — every leader change and every committed write pays a coordination round trip — which is why consensus belongs on your metadata and locks, not on your hottest data path.
For forty seconds, Shard 4 had two leaders
The page fires at 02:11: a 40-second network blip has cut Shard 4’s leader off from the little controller that watches it. That controller had one job — notice when a leader goes quiet and promote a follower to replace it — and it did exactly that: it saw silence, assumed the leader was dead, and crowned a follower in Tokyo. There was only one problem. The old leader in Virginia never actually died. It was just briefly unreachable, and the whole time, it kept happily accepting writes from US users. So for forty seconds Shard 4 had two leaders, on two continents, each certain it was in charge, each writing different values to the same accounts.
When the network healed, the damage was already on disk: about 14,000 writes that conflict, two histories for the same rows and no honest way to say which is true. This is the wound the failover chapter left open on purpose. It gave you a follower that keeps your data alive and a controller that promotes it when the leader dies — but it deliberately refused to answer the one question that turns out to matter most: who is allowed to decide a leader is dead, and how do you stop two nodes from both believing they won? This page is that answer. By the end, a network can tear the cluster clean in half and you will still have exactly one leader — provably, every time.
Stop appointing leaders. Make the replicas vote.
The bug last night was not a bad controller — it was the idea of a controller. Any single watcher can be fooled, because over a network you genuinely cannot tell a machine that has died from one that is merely slow or cut off: both look identical, which is silence. A lone observer forced to guess will, sooner or later, guess wrong and crown a second leader. You cannot fix that by making the observer smarter. You fix it by never letting one voice decide.
So flip the machinery around. Instead of an outsider appointing a leader, the replicas themselves elect one — and a candidate may only take the crown if more than half of the group votes for it. That number, more-than-half, is not an arbitrary threshold; it is the single magic ingredient of the whole design. Picture the group split by a broken cable into two islands. At most one island can hold more than half the members — a pie can only be cut so that one piece is the bigger half. So at most one island can ever elect a leader; the other, unable to reach a majority, is forced to stand down. Two leaders stop being a risk you mitigate and become an outcome the arithmetic forbids.
Three roles, and a number that keeps time
Here is the machine in the smallest number of moving parts that works. At any instant every server in the group is playing exactly one of three roles. A follower is passive: it sits quietly, applies what the leader sends, and answers votes — the resting state of almost everyone almost always. A candidate is a follower that got tired of waiting and is now campaigning for votes. A leader is the one server that won a majority and is now taking all the writes and sending out regular heartbeats to say still here, still me. There is at most one leader at a time, and everyone else is a follower behind it.
So what actually starts an election? This is the hinge the whole protocol turns on, so let’s go slowly. Every follower keeps a private countdown running — its election timeout — picture a kitchen timer wound to a couple hundred milliseconds. The leader’s job, besides taking writes, is to send a steady drumbeat of heartbeats to every follower, and here is the trick that makes the whole thing tick: every heartbeat that arrives winds that follower’s timer back to full. While the drumbeat keeps coming, no timer ever reaches zero, so everyone stays a calm follower. The heartbeat means "still alive, still me"; the timer is a dead-man’s switch waiting for that signal to stop.
An election is triggered by silence — nothing more. The moment a follower’s timer drains all the way to zero without a heartbeat winding it back, that follower gives up on the leader and starts campaigning. Notice it cannot actually tell a dead leader from one that is merely slow or briefly unreachable — from the outside both look identical: the drumbeat just stopped. Here’s the subtle part that makes it work in practice. If every follower used the same timeout, they would all give up at the same instant; so each rolls a slightly random timeout. When a leader dies, that randomness means one follower’s timer hits zero a hair before the others — it campaigns first, votes for itself, and asks the rest to vote for it. And when a follower agrees to vote, that message winds its own timer back too, so it won’t launch a rival campaign. The usual result: one candidate pulls ahead and wins before anyone else has even woken up. Once in a while two wake together and split the vote so nobody reaches a majority — then the round simply repeats, and a later section shows how that tie breaks itself almost immediately. So elections are the exception, not a constant churn: a healthy cluster holds one clean election when a leader dies, and then goes quiet again.
The second idea is subtler and it is the one that makes the whole thing safe without a shared clock: the term. A term is just a number that only ever goes up — round 1, round 2, round 3 — and every election starts a new one. Think of it as the group’s logical calendar: not wall-clock time (which nobody trusts across machines), but a strictly increasing count of "eras," where each era has at most one leader. Every message a server sends stamps its current term on it, and there is exactly one rule to remember: if you ever see a term higher than your own, you immediately step down to follower and adopt it. That one line is how a stale leader — say, our Virginia node waking up from its blip — discovers it has been deposed: the first message it hears carries a newer term, and it quietly abdicates. Terms are how the cluster fences the past without anyone having to agree on the time.
Watch the whole thing once, end to end — the steady drumbeat, the silence that trips one follower’s stopwatch, the quick vote, and the old leader that comes back only to step down. Step through it and keep an eye on each follower’s election-timeout bar: full (green) means a heartbeat just reset it; empty (red) means it’s about to campaign.
The interactive version of this example is available when JavaScript loads.
The election, from timeout to crown
Zoom into the moment a leader dies. Its followers were each counting down a private election timeout — a stopwatch that resets every time a heartbeat arrives. With the leader gone, no heartbeats arrive, and eventually one follower’s stopwatch hits zero. That follower does four things in a breath: it increments the term (a new era begins), switches to candidate, votes for itself, and sends RequestVote to everyone else, asking for their vote in this new term.
Each other server, on receiving that RequestVote, applies a simple test: have I already voted in this term, and is this candidate’s log at least as current as mine? If it hasn’t voted yet and the candidate is current, it grants the vote — one vote per server per term, no take-backs. The candidate tallies replies. The instant its own vote plus the granted votes cross a majority, it becomes leader and immediately fires off heartbeats — which reset everyone else’s stopwatch and shut down any competing campaigns before they start. A leader that wins fast keeps the peace precisely by being loud and prompt.
The election, as a checklist
- Silence. A follower’s election timeout elapses with no heartbeat from a leader.
- Campaign. It increments the term, becomes a candidate, votes for itself, and sends
RequestVoteto all peers. - Vote. Each peer grants its single vote for that term only if it hasn’t already voted and the candidate’s log is at least as up to date as its own.
- Win. The moment the candidate holds a strict majority (its own vote included), it becomes leader.
- Assert. The new leader sends heartbeats (
AppendEntries), resetting every follower’s timer and quelling rival candidates. - Or retry. If nobody wins before the timers fire again, a new term opens and the whole thing repeats — the case the next section is about.
What if everyone campaigns at once?
There’s an obvious way for this to jam. Suppose the leader dies and several followers hit zero at the same instant. They all become candidates in the same term, they all vote for themselves, and each asks the others for a vote — but every server has already spent its one vote on itself. Nobody reaches a majority. The term ends with no winner, so a new term opens… and if the timers are still synchronized, the exact same standoff repeats. This is a split vote, and a naive design can stall in it indefinitely, re-running elections while the shard serves nothing.
The fix is almost cheeky in how simple it is: make every server’s election timeout a little bit random. Instead of all waiting, say, exactly 200 ms, each waits a random amount in a window — the Raft paper suggests something like 150–300 ms. Now the stopwatches almost never hit zero together. One follower’s timer fires first, it campaigns alone for a moment, and it collects a majority and starts heartbeating before anyone else even wakes up to run. On the rare occasion two do tie, the next round re-randomizes and the tie breaks almost immediately. A pinch of randomness turns a deadlock into a race with a near-certain quick winner — no coordinator, no cleverness, just staggered alarm clocks.
Feel the difference directly. Turn randomized timeouts off and watch the candidates collide, term after term, crowning nobody; turn them on and watch one pull ahead and win almost instantly:
The interactive version of this example is available when JavaScript loads.
Not just any winner — only a caught-up one
A majority stops two leaders from existing. But it doesn’t, by itself, stop the wrong leader from being chosen — and there is a very wrong choice available. Imagine a follower that had fallen behind and was missing the last few committed writes. If it happened to win an election, it would become the new source of truth while lacking data the cluster had already promised was safe. Those writes would silently vanish. A majority alone doesn’t prevent this; we need one more rule.
That rule is the vote restriction hiding in the checklist above: a server refuses its vote to any candidate whose log is less up to date than its own. "Up to date" has a precise meaning — compare the term of each log’s last entry first, then its length — but the plain version is: you cannot lead if you’re behind. Now chain it to the majority. A committed write, by definition, lives on a majority of the group. Any winning candidate also needs a majority to vote for it. Those two majorities must overlap in at least one server — and that shared server holds the committed write and would refuse to vote for anyone missing it. So every possible winner already has every committed write. The overlap that forbids two leaders is the very same overlap that guarantees the one leader we do get is complete.
How big should the group be? (and why odd)
We keep saying "a majority," so let’s make it exact and put a number on what it buys. For a group of N servers, a majority — the quorum — is ⌊N/2⌋ + 1: for 3 that’s 2, for 5 that’s 3, for 7 that’s 4. As long as a quorum of servers is alive and can talk, the group can elect a leader and keep committing writes. The moment it can’t reach a quorum, it stops — deliberately — rather than risk acting on a minority. So the real question when you size a cluster is: how many simultaneous failures do I want to survive and keep serving?
The answer falls straight out of the quorum. A group of N tolerates ⌊(N−1)/2⌋ failures and still functions: 3 servers survive 1 death, 5 survive 2, 7 survive 3. Now the part that trips people up — why odd sizes. Compare 5 and 6. Five tolerates two failures. Six also tolerates only two (a quorum of 6 is 4, so losing 3 breaks it), yet it costs you an extra machine that can fail and an extra vote to gather on every decision. An even size gives you a bigger quorum without buying any more fault tolerance — strictly more cost, strictly no gain. Odd is not a superstition; it’s the efficient frontier. Slide N around and watch the quorum and the fault tolerance move:
The interactive version of this example is available when JavaScript loads.
Tear the cluster in half
Everything so far has been rehearsal for the event that started this chapter: a network partition — a cut cable that splits the group into two islands that are each alive and working but can no longer hear each other. Last night that cut gave Shard 4 two leaders. Watch how a majority rule refuses to let it happen again. When the split lands, each island counts itself. Only the island holding a majority of the whole group can elect or keep a leader; the smaller island, unable to reach a quorum no matter how it votes, is forced to stand down — it stops accepting writes rather than crown a rival. Two islands, at most one majority, at most one leader. The arithmetic that felt abstract two sections ago is now the thing standing between you and a forked database.
And the returning old leader — the exact zombie from last night? Say the split stranded the old leader on the minority side. It still thinks it’s in charge, but it can’t reach a majority to commit anything, so its writes simply never succeed. When the network heals, its first contact carries a term lower than the majority side’s new leader, and by the golden rule it steps down to follower on the spot. It deposes itself. (Guaranteeing a partitioned old leader can’t corrupt shared storage during the split — before it learns it lost — is the job of fencing, which the failover page owns; here the point is narrower and deeper: a minority can never win an election in the first place.
You might be circling a sharper worry now — and it’s exactly the right one to have. The majority side gets to elect a leader, but what if the node it picks had fallen behind? Suppose servers 1, 2, and 3 hold the latest committed writes while 4 and 5 were lagging, and the split strands server 1 with the two laggards on the majority side. Couldn’t 4 or 5 grab the crown and silently drop committed data? No — and the reason is the vote restriction from a few sections back. A winner needs a full majority; on that side the only majority available includes server 1; and server 1, holding writes the laggards lack, refuses to vote for a candidate behind its own log. So 4 and 5 simply can’t gather the votes — the only node that can is one as current as server 1. Say the rule once, generally: the majority that elects a leader always overlaps the majority that stored the committed writes, and that one shared server vetoes any incomplete candidate. The winning side is guaranteed to crown a complete leader, never a lossy one. (And notice the trap: a node being slow to send its heartbeat only decides who campaigns first — it never lets a behind node actually win.)
There’s one number doing all the quiet work in that story, and it’s worth saying out loud because it’s the exact spot most people stumble: a majority always means a majority of the whole cluster — 3 of 5 — never a majority of whoever a node can currently reach. Watch it bite. On an island of S3, S4, and S5, the laggard S4 can nominate itself and S5 will gladly vote for it — they’re equally behind, so no refusal there — but that’s only 2 votes, and a win needs 3. The single remaining vote S4 could ask for belongs to S3, which refuses (S4 is behind it). So S4 freezes at 2 of 5 and can never win, no matter how many rounds it retries. The fresh node S3, by contrast, collects S4’s and S5’s votes too (its log isn’t behind theirs), reaches 3 of 5, and leads. And this very same fixed denominator is why the minority side stands down at all: with only 2 of 5 reachable it cannot conjure a third vote from thin air. Flip the rule to "a majority of whoever I can see" and both sides of a split could elect a leader — which is precisely the split-brain we came here to kill. The denominator is the whole safety. Drag the cut and watch the tallies: every count is out of 5.
The interactive version of this example is available when JavaScript loads.
A write is safe once a majority has it
Leaders don’t just get elected; they do a job — they take writes and keep the followers’ copies in step. The mechanism is the same AppendEntries call that carries heartbeats, now carrying actual entries. A client’s write lands on the leader, which appends it to its own log first and then ships it to the followers. Here is the word that matters: an entry is committed — truly safe, acknowledged to the client — only once a majority of the group has stored it. Not when the leader has it. When a majority does. Only then does the leader tell the client "done," and only committed entries ever get applied.
This is where Leader Completeness earns its keep. Because a committed entry lives on a majority, and any future leader also won a majority, and two majorities overlap — every future leader already has every committed write. So when a leader dies mid-stream, the entries that had reached a majority are safe: the next leader has them. The entries that had not yet reached a majority were never committed, never acknowledged, and may simply vanish when the old leader is replaced — which is exactly why clients must retry writes idempotently (an idempotency key makes the retry harmless). Kill the leader mid-flight and watch which entries survive:
The interactive version of this example is available when JavaScript loads.
It always stays safe. It doesn’t always make progress.
There are two different promises a system like this can make, and it’s worth being precise about which one Raft keeps absolutely and which one it keeps only usually. Safety is "nothing bad ever happens" — never two leaders in a term, never a committed write lost. Raft keeps safety come what may: no amount of dropped messages, dead nodes, or clock weirdness can produce two leaders or erase committed data. Liveness is "something good eventually happens" — an election finishes, a write commits. That one, Raft can only promise when the network behaves.
This isn’t a shortcoming of Raft; it’s a law of the universe it lives in. A classic result (the FLP impossibility) proves that in a fully asynchronous network where messages can be arbitrarily delayed, no algorithm can guarantee it always both stays correct and always finishes — you can have guaranteed safety or guaranteed termination, not both. Raft, sensibly, picks safety and buys practical liveness with timing: the broadcastTime ≪ electionTimeout ≪ MTBF relationship from earlier is that bargain. When the network is healthy the timers do their job and elections finish in milliseconds; when it’s truly partitioned the minority side simply waits — stalled, but never wrong. If you remember one line: a consensus system under stress gets slow or unavailable; it does not get incorrect. That’s the trade it was designed to make.
When "on a majority" isn’t enough
This whole page has leaned on one rule: a write is safe — committed — once a majority of the group has stored it. That rule is right. But it carries one asterisk, and it’s the asterisk almost everyone misses, so we’ll take it slowly and it’ll click. The asterisk is only about old writes — the ones a leader was still copying out when it died. For a leader’s own fresh writes, "on a majority means safe" really is the whole story. For a write it inherited from a dead predecessor, being on a majority turns out not to be enough on its own. Let’s see exactly why, one small step at a time.
First, hold on to one fact — it’s the single thing that makes the trap possible. When two servers both want to lead, the winner is the one whose log is more up to date, and the very first thing "up to date" compares is the term stamped on their last write. A write stamped term 3 outranks a write stamped term 2 — even if the term-2 write is sitting on more machines. So a newer-stamped write can beat an older one that, by a simple headcount, looks perfectly safe. Keep that in your pocket. Now the story.
- Term 2. Leader A writes entry X into slot 7 and copies it to just one other server — only a couple of machines, a minority — then it crashes, before X ever reaches a majority or gets announced as safe.
- Term 3. With A gone, node E wins the next election. The servers that voted for E happen to be ones that never received X, so E has no idea X exists. E writes its own entry Y into that same slot 7 — a different value, freshly stamped term 3 — but then E also crashes, before copying Y anywhere.
- Term 4. A comes back and wins again. It picks up where it left off and finishes copying its old term-2 X onto a majority. Look at the board now: X really is on more than half the servers.
- The trap springs. If A looks at that majority and thinks "X is on most servers, so X is committed for good" — it is wrong. Suppose A crashes once more. E can run again and E can win, because E’s slot-7 entry Y is stamped term 3, which outranks A’s term-2 X in the up-to-date check. The moment E leads, it overwrites slot 7 with Y everywhere — and the X we just called "committed" is gone. A write we promised was permanent got erased. That is the one thing that must never happen.
Sit with what just went wrong. Being on a majority made X look safe while it was still quietly overwritable — the headcount lied, because a higher-term rival (E, with its term-3 Y) was still lurking with a claim to the same slot. Counting copies isn’t wrong; it just isn’t the whole test for a write you inherited from an earlier term.
The fix is a small, careful change to when a leader is allowed to call an old entry committed. A leader may count copies to commit an entry only when that entry belongs to its own current term. It is not allowed to count copies for an entry it inherited from an older term. Those inherited entries still become safe — but only indirectly, by riding underneath a fresh entry the current leader commits on top of them.
Watch how that one change closes the trap. When A returns as the term-4 leader, it must not trust the headcount on the old term-2 X. Instead it writes a brand-new term-4 entry and works to get that onto a majority. The instant a term-4 entry is on a majority, something quietly decisive happens: any rival like E, which is missing that term-4 entry, is now behind — and can never win an election again. With E permanently locked out, nothing can overwrite slot 7, so X — sitting just below the term-4 entry — is finally, truly safe. Think of the fresh entry as a lid: once the leader seals a write of its own term on top, everything beneath it is sealed too.
This one is far easier to watch than to read, so step through it. Run it once on the naive rule and watch a "committed" X get erased four terms later; then flip to the Raft rule and watch the term-4 lid make X untouchable. The five logs update slot by slot as each term plays out:
The interactive version of this example is available when JavaScript loads.
The flaky node that keeps forcing elections
Here’s a gentler but genuinely annoying failure — worth knowing because it looks like the system misbehaving when it’s really just being too eager. Picture a node with a one-way network problem: it can still shout to everyone, but it has stopped hearing the leader’s heartbeats. From its point of view the leader has gone silent, so it does the dutiful thing — times out, bumps its term, and starts campaigning. But nothing was actually wrong: the leader is alive and well. The campaign still forces that healthy leader to step down (a higher term always wins), an election churns for no reason, and then the flaky node’s trouble flares again and the whole pointless cycle repeats. One slightly-broken node can keep an entire healthy cluster in a constant state of re-election.
Two small guards stop this. The first is Pre-Vote: before a candidate actually raises the term and disturbs anyone, it runs a dry run — it quietly asks the group "if I ran, would you vote for me?" without changing any numbers. If a healthy leader is still heartbeating the majority, the others answer no, and the twitchy node backs off having disrupted nothing. The second is check-quorum: a leader keeps an ear out for its followers, and if it stops hearing back from a majority, it steps down on its own rather than clinging to a title it can no longer back up. Together they make elections happen when leadership is genuinely in doubt — not every time a single node has a bad minute.
Measuring an election — and debugging a flapping leader
Most write-ups stop at the algorithm. In production, what you actually live with is a handful of signals, and knowing which one is lying to you is the whole skill. A healthy consensus group is boring: the leader never changes, the term number sits still, and writes commit in about a round trip. When it stops being boring, these are the dials that tell you why.
| Signal | Healthy | What a bad value is telling you |
|---|---|---|
| Leader changes / min | ≈ 0 in steady state | Elections firing repeatedly (flapping) — timeouts too tight, GC pauses, or a slow disk stalling the leader’s heartbeats. |
| Term number | Flat between real failures | Every bump is an election; a fast-climbing term is a cluster that can’t hold a leader. |
| Election latency | Tens to a few hundred ms | Long elections are downtime — often an oversized group or slow peers. |
| Commit latency (proposal→commit) | ≈ one RTT + one fsync | Rising: a slow disk fsync, a lagging follower dragging the majority, or network latency. |
| WAL fsync p99 | < 10 ms (sub-ms on SSD) | A slow disk stalls the leader so it misses heartbeats and triggers needless elections (etcd targets p99 < 10 ms). |
| Peer round-trip time | Well under the heartbeat interval | If RTT approaches the election timeout, expect false failovers. |
When a cluster won’t hold a leader — term climbing, leader changes/min never settling — the cause is almost never Raft itself; it’s the machine underneath breaking the timing bargain. The usual suspects, roughly in order: election timeouts set too aggressively for the real network (a 50 ms timeout on a link with 40 ms of jitter will false-alarm forever); a stop-the-world GC pause freezing the leader long enough to look dead; a slow or saturated disk whose fsync stalls the leader so it can’t heartbeat in time; and CPU starvation from noisy neighbours. The counter-intuitive fix is almost always to loosen the timing, not tighten it — and to fix the disk.
What consensus costs — and when not to use it
Consensus is not free, and the bill comes due on every committed write. To commit, the leader has to land the entry on a majority — at least one network round trip to the fastest-enough followers — and durably fsync it to disk. That sets a floor no tuning removes: commit latency ≥ one round trip to a majority + one disk sync (sub-millisecond on SSD, ~10 ms on spinning rust, plus an in-datacenter RTT of a few hundred microseconds). And you can’t grow your way out: every member you add enlarges the majority each write must wait for, so a 7-node group commits slower than a 3-node one. Consensus buys correctness and pays in latency and a hard cap on how big one group can usefully get.
Which tells you exactly where not to put it: never on your hottest, highest-volume data path. Hatch does not run its 12 TB of links through one Raft group — it shards the data across many independent replica groups, each holding its own election for its own slice, so consensus ever only coordinates a shard, never the whole world. And for workloads that prize availability and throughput over strict global ordering — a cart, a feed, a session store — you often skip single-leader consensus entirely and reach for leaderless, eventually-consistent replication (the Dynamo and Cassandra style), trading a crisp order for staying up during a partition. Whether that trade is even yours to make is the CAP question, and how you tune "how many copies is enough" on the leaderless side is the read/write quorums story.
Adding and removing members without a second leader
One last sharp edge: the group isn’t frozen for all time — machines get replaced, and sometimes you need to grow from three nodes to five. You cannot just edit everyone’s config and restart, and the reason is the exact hazard this whole page has circled. If some nodes adopt the new membership while others still believe the old one, there’s a window where the old set and the new set can each assemble their own majority — two disjoint majorities, two leaders, split-brain, smuggled back in by a config change.
So Raft changes membership through a controlled handoff, not a swap. The general method is joint consensus: a brief transitional configuration that requires agreement from a majority of both the old and the new sets at once, so there is never an instant where the two can act independently. The simpler and far more common method is to change one server at a time — add or remove a single member per step — because a single-node change can never split the group into two disjoint majorities (the old and new majorities always overlap by at least one). Either way the invariant is the one you already trust: at every moment, any two majorities must share a member.
Raft, Paxos, ZAB — and who runs what
Raft didn’t invent consensus; it made it teachable. The underlying problem — get a group of unreliable machines to agree on one ordered log, tolerating a minority failing — has a whole family of solutions, and they are all equivalent in what they guarantee. They differ mostly in how they’re presented and which corners they bother to specify.
| Algorithm | Origin / claim to fame | Where you meet it |
|---|---|---|
| Paxos (single-decree) | Lamport, 1998 — the original; proves agreement on one value, and is famously subtle | The theoretical bedrock; rarely implemented raw |
| Multi-Paxos | Paxos chained to agree on a log; leader election left underspecified | Google Chubby, Spanner, Megastore |
| Raft | Ongaro & Ousterhout, 2014 — built for understandability; fully specifies election + log | etcd, Consul, CockroachDB, TiKV, Kafka (KRaft) |
| ZAB | ZooKeeper Atomic Broadcast — leader-based total-order broadcast | Apache ZooKeeper |
| Viewstamped Replication | Oki & Liskov, 1988 — leader-based replication, a close Raft cousin | The academic ancestor; ideas reused widely |
The comparison interviewers reach for is Paxos versus Raft. Single-decree Paxos agrees on a single value; to run a replicated log you chain it into Multi-Paxos, and the messy, under-described part — how you choose and keep a stable leader — is exactly what Raft nails down. That’s Raft’s real contribution: not more power (the two are equally capable and equally safe), but a decomposition — leader election, log replication, safety — that a person can hold in their head and implement without a doctorate. (A pointed 2020 paper, Paxos vs Raft: have we reached consensus on distributed consensus?, argues the two are algorithmically closer than folklore admits — much of the daylight is presentation.) Learn Raft to understand the machine; know the name Paxos so the older systems don’t surprise you.
Once you can see it, consensus is everywhere a system needs a single, always-consistent source of truth. etcd holds all of Kubernetes’ cluster state; Consul and ZooKeeper run service discovery and coordination; CockroachDB, TiKV/TiDB, and YugabyteDB put a Raft group under every shard so each slice keeps one consistent leader; Kafka replaced its ZooKeeper dependency with a self-hosted Raft (KRaft) for its own metadata; MongoDB’s replica-set elections are Raft-like. The tell never changes — find the part of a system that must never have two masters, and you’ll find a majority vote holding it together.
The election, in about fifteen lines
You will almost never write this yourself — you’ll run a battle-tested library (etcd’s raft, raft-rs, Dragonboat). But the whole election really is this small, and seeing the two rules in code is what makes them stick. Here it is as pseudocode, split into the timer that starts an election and the handler that answers one.
Every server, on its election timer:
- If it has heard no heartbeat for longer than its randomized
electionTimeout, it starts an election. - Start one:
currentTerm += 1, becomecandidate, vote for self (votedFor = me,votes = 1), and sendRequestVote(term, candidateId, lastLogIndex, lastLogTerm)to every peer. - The instant
votesreaches a majority of the whole cluster, becomeleaderand start sendingAppendEntriesheartbeats immediately. - Re-roll
electionTimeout = random(150ms, 300ms)each round, so a split vote breaks itself on the next try.
Every server, on receiving a RequestVote:
- Reject a stale caller: if the request’s
termis behind mycurrentTerm, replyvoteGranted: false(and tell it my term). - Step down to a newer term: if the request’s
termis ahead of mine, adopt it, becomefollower, and clearvotedFor. - The safety check — is the caller at least as up to date as me?
upToDate = (their lastLogTerm is ahead of mine) OR (same lastLogTerm AND their lastLogIndex ≥ mine). - Grant at most one vote per term, only to a current-enough candidate: if
votedForis empty or already this candidate,AND upToDate, then setvotedFor = candidateId, reset the election timer, and replyvoteGranted: true.
Pitfalls
- Committing an inherited entry on headcount alone. The Figure-8 trap: an old-term entry on a majority can still be overwritten. Commit by counting only current-term entries; seal the rest with a lid.
- Election timeouts tuned for speed. Too tight, and a routine GC pause or network blip looks like a dead leader and triggers a needless failover. Leave headroom above your real RTT and worst-case pause.
- Even-sized clusters. Four or six buy a bigger quorum with no extra fault tolerance over three or five. Always odd.
- Consensus on the hot data path. Every committed write pays a majority round-trip plus an fsync — a floor no tuning removes. Don’t put your highest-volume writes behind one group.
- Big-bang membership changes. Swapping every node’s config at once can briefly create two disjoint majorities and two leaders. Change one node at a time, or use joint consensus.
- Leader-local reads. A deposed-but-unaware leader will happily serve stale data. Use ReadIndex or a lease for linearizable reads, or document that reads can be stale.
- Forgetting idempotent retries. A write that was never committed can be lost on a leader change; a blind client retry can then double-apply it. Use an idempotency key.
- Trusting Raft to fence external state. Raft keeps its own log consistent, but a partitioned old leader can still poke shared storage before it learns it lost. Fencing tokens (see failover) guard that boundary.
Best practices
- Use a proven library, don’t hand-roll. etcd’s
raft, TiKV’sraft-rs, Dragonboat — consensus is exactly the code you want boring and well-tested. - Size odd: 3 or 5. Three for a single availability zone, five spread across zones for real resilience; seven only when you must, never more.
- Tune the timers as a ratio (heartbeat ≈ election ÷ 5 to ÷ 10) and leave generous headroom; watch
leader changes/min, term churn, and WAL fsync p99. - Keep the group small; scale by multiplying groups. Shard the data across many independent Raft groups, each with its own leader — never grow one giant group.
- Consensus for the control plane, cheaper replication for bulk data. Metadata, membership, config, locks, and leadership belong in a group; your 12 TB of rows do not.
- Turn on Pre-Vote and check-quorum so a flaky node can’t keep disrupting a healthy leader, and a leader that loses its majority steps down on its own.
- Be explicit about reads. Use ReadIndex or a leader lease when you need linearizable reads; otherwise say plainly that a read may be slightly stale.
- Change membership one node at a time, and let the cluster fully catch up before the next step.
From intern to principal, the questions you’ll get
- What does leader election actually solve? (intern)
- It picks one server as the single source of truth for ordering writes, so the group agrees on one history and never forks as members fail. Without one agreed leader, two nodes can take conflicting writes — split-brain.
- What are the three roles, and what is a "term"? (SDE1)
- Follower (passive, waits for heartbeats), candidate (timed out, campaigning), leader (takes writes, heartbeats). A term is a monotonically increasing number — a logical clock — with at most one leader; any server that sees a higher term steps down and adopts it.
- Why are election timeouts randomized? (SDE2)
- If every follower used the same timeout they’d all campaign at once, each vote for itself, and split the vote forever. Randomizing makes one time out first and win before the others start — and re-randomizing each round breaks any tie fast.
- How does a majority prevent two leaders during a partition? (SDE2 → SDE3)
- A winner needs a majority of the whole cluster, and two majorities of the same group must overlap — so only one side of any split can gather one. The minority side can’t reach it and stands down. At most one leader, always.
- A leader dies mid-write — what happens to the in-flight writes? (SDE3)
- Writes that had reached a majority (committed) survive: the next leader is guaranteed to have them. Writes that hadn’t were never acknowledged and may be dropped — so clients must retry idempotently (an idempotency key makes the retry safe).
- How is a new leader guaranteed to hold every committed write? (SDE3 → staff)
- The up-to-date vote restriction: a server won’t vote for a candidate whose log is behind its own. A committed write is on a majority; the winner also won a majority; the two overlap on a server that holds the write and would refuse an incomplete candidate. So every possible winner is complete — Leader Completeness.
- Why odd cluster sizes — why 5 and not 6? (senior)
- Fault tolerance is ⌊(N−1)/2⌋. Five and six both tolerate two failures, but six needs a bigger quorum (4 vs 3) on every write and adds one more thing that can break — strictly more cost, no more resilience.
- Why can’t a leader just answer reads from its own memory? (senior → staff)
- It might be a deposed leader that hasn’t learned it lost, so it could serve stale data. Confirm leadership first: a ReadIndex round-trip to a majority, or a time-bounded leader lease (which trades the round-trip for a dependence on bounded clock drift).
- Explain the current-term commit rule — the Figure-8 hazard. (staff)
- A leader may commit an entry by counting replicas only if it’s from the leader’s own term; entries inherited from older terms commit only indirectly, once a current-term entry is committed above them. Otherwise a majority-replicated old entry can still be overwritten by a higher-term rival, and a "committed" write is lost.
- Raft vs Paxos — why does industry mostly reach for Raft? (staff → principal)
- They’re equally safe and equally capable. Raft’s edge is understandability: it decomposes into leader election, log replication, and safety, and fully specifies leader election and log structure that Paxos leaves vague — so it’s far easier to implement correctly.
- When would you NOT use consensus? (principal)
- When you don’t need one global order. Consensus puts a majority round-trip plus an fsync on every write and caps group size, so keep it off the hot, high-volume data path — use it for metadata, membership, config, locks, and leadership, and use cheaper (often leaderless, eventually-consistent) replication for bulk data.
- How do you change membership without risking two leaders? (principal)
- Never swap every config at once — that can create two disjoint majorities. Add or remove one node at a time (majorities always overlap), or use joint consensus (a transitional config needing a majority of both the old and new sets). Let the cluster settle between steps.
- The meta question: how would you make consensus faster, or scale it out? (principal)
- Faster: batch and pipeline log entries, put the log on fast SSDs (the fsync is on the critical path), and keep followers close. Scale: don’t grow one group — shard the data across many independent Raft groups, each with its own leader, and keep each group small (3–5). Consensus scales by multiplication, not by bigger groups.
Make the copies vote
Nearby: Database Failover (the naive promoter this replaces, and the fencing that stops a returning zombie), Leader–Follower Replication (the replica set that now votes), and Consistent Hashing (the ring each replica group sits on). The two ideas this page deliberately handed off are its closest siblings: Read/Write Quorums turns "how many copies is enough" into a rule (W + R > N), and the CAP theorem is the deeper law behind the minority side going dark. And notice the wound left wide open: this majority lives inside one region today. The moment a group’s voters are spread across continents, every election and every committed write has to cross an ocean before it counts — and that cross-continent tax is exactly where the journey heads next.
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.