Consensus — Raft & Paxos
How a group of unreliable machines agrees on one value, Raft explained well enough to whiteboard, and why you should almost never implement it yourself.
#The problem
Get N machines to agree on a value, given that machines crash, messages are lost, delayed, and reordered, and no one has a reliable clock.
The guarantees a consensus protocol provides:
- Agreement — no two nodes decide different values.
- Validity — the decided value was proposed by someone.
- Termination — nodes eventually decide (given enough working nodes).
FLP impossibility (named after Fischer, Lynch and Paterson, who proved it in 1985) says you cannot have all three at once — not "nobody has managed it yet", but provably never, in a network where messages can be arbitrarily delayed and even one machine might crash. The reason is that you can never distinguish a dead machine from a very slow one, so any algorithm must either risk waiting forever or risk deciding wrongly.
Real protocols get around it by assuming the network is eventually well-behaved for long enough to finish a decision. They promise safety always — two nodes never disagree — and liveness eventually — progress happens once the network cooperates. In an interview, saying this out loud ("safe always, live eventually") shows you understand what consensus can and can't promise.
#Why it matters
Consensus is the foundation under everything that must be unambiguous:
- Leader election — who is the primary?
- Configuration and membership — which nodes are in the cluster?
- Distributed locks with real safety.
- Replicated state machines — the general form, and the one worth understanding. Start several copies of the same program from the same starting point, feed them the identical list of commands in the identical order, and they must all end up in the identical state. So agreeing on the order of a list is enough to keep a whole cluster in step.
The last one is the key insight: consensus on an ordered log gives you a fault-tolerant version of any deterministic service.
#Raft
Designed for understandability, and it succeeded — Raft is what etcd, Consul, TiKV, and CockroachDB use. It decomposes into three pieces.
#Leader election
Each node is a follower, a candidate, or the leader. Time is divided into terms: not clock time, just a counter that goes up by one every time an election is held. Terms are how a node recognises stale information — anything stamped with an older term than the one it knows about is out of date and gets ignored.
follower ──timeout, no heartbeat──► candidate
│ requests votes
┌───────────────────────────┤
│ majority votes │ sees higher term
▼ ▼
leader ──────────────────► follower
│ sends heartbeats
└── stays leader while heartbeats succeed- Followers expect heartbeats from the leader. If none arrives within a randomized election timeout (typically 150–300 ms), a follower becomes a candidate.
- The candidate increments the term, votes for itself, and requests votes.
- Each node votes at most once per term, and only for a candidate whose log is at least as up to date as its own.
- A candidate winning a majority becomes leader.
Two details that matter and that interviewers probe:
Randomized timeouts prevent split votes. If every node timed out simultaneously, they'd all become candidates, split the vote, and repeat forever. Randomization means one node almost always times out first.
The "at least as up to date" rule guarantees safety: a candidate missing committed entries cannot win, because a majority of nodes have those entries and will refuse to vote for it. This is what makes leader election safe rather than merely convenient.
#Log replication
client → LEADER
│ 1. append to own log (uncommitted)
│ 2. AppendEntries to all followers
▼
┌──────────┼──────────┐
F1 F2 F3
│ ack │ ack │ (slow/down)
└──────────┴──────────┘
│ 3. majority acked → entry is COMMITTED
│ 4. apply to state machine, reply to client
│ 5. followers learn commit index from next heartbeat
▼
client gets responseOnly the leader accepts writes. An entry is committed once a majority has it — at that point it is durable even if the leader dies immediately. Here's why: to become the next leader, a node needs votes from a majority. Any two majorities of the same cluster share at least one node (with 5 nodes, two groups of 3 must overlap). That shared node has the entry and refuses to vote for a candidate without it — so any future leader must have it.
The Log Matching Property keeps logs consistent. Each AppendEntries message says "here is entry 8, and the entry before it was entry 7 from term 3". A follower whose entry 7 doesn't match rejects the request. The leader then retries one step further back (entry 6, then 5, …) until it finds the last entry both logs agree on. Everything the follower has after that point is wrong, so the leader overwrites it with its own entries. The result: follower logs always end up identical to the leader's.
#Safety
The critical rule: a leader only commits entries from its own term directly. Suppose a new leader finds an old entry from a previous leader that reached a majority but was never marked committed. It may not declare that entry committed just by counting copies. Entries from previous terms become committed indirectly, when a current-term entry above them commits. Without this restriction, a specific sequence of failures can cause a committed entry to be overwritten — a subtle bug that Raft's authors identified explicitly. You don't need to reproduce the derivation from memory, but knowing the rule exists is what stops you assuming safety you don't have.
#Paxos
The original, and notoriously harder to follow. Two phases:
- Prepare(n) — a proposer picks a proposal number
nand asks acceptors to promise not to accept anything numbered lower. Acceptors reply with the highest-numbered value they've already accepted. - Accept(n, v) — the proposer sends the value. If it learned of any previously accepted value in phase 1, it must propose that value instead of its own — this is the rule that guarantees agreement.
Basic Paxos decides one value. Running both phases for every log entry would be slow, so Multi-Paxos spreads the cost: elect a stable leader, run phase 1 once, then skip it for every following entry. You get a replicated log — essentially the same shape as Raft.
Raft vs Paxos in one line: they solve the same problem with the same quorum math. Raft is a complete recipe — one strong leader, everything built around the log — that you can implement as written. Paxos is a more general algorithm that leaves gaps (leader choice, log management, membership changes) every implementer fills differently. That's why new systems pick Raft.
Variants worth naming:
- Fast Paxos — fewer round trips per decision, at the price of needing larger quorums.
- EPaxos — no single leader. Commands that don't affect each other (say, writes to different keys, which give the same result in either order) can commit in any order, so a client can use its nearest replica. Good for clusters spread across regions.
- Flexible Paxos — the observation that the phase-1 quorum and phase-2 quorum only need to overlap each other; they don't both have to be majorities.
#Quorums and cluster size
Consensus needs a majority: ⌊N/2⌋ + 1.
| Nodes | Majority | Failures tolerated |
|---|---|---|
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 7 | 4 | 3 |
Note 3 and 4 tolerate the same number of failures. Even-sized clusters give you nothing extra — they just add a node that must be maintained and coordinated with. This is why you always see 3, 5, or 7.
More nodes ≠ better. Every write needs a majority ack, so the leader waits for the median node. In a 5-node cluster, a write finishes when the 3rd-fastest node replies — the two slowest don't matter, but the middle one does. Larger clusters mean more messages and slower commits. 5 is the standard choice — tolerates two failures (so you can lose one node and still survive another during maintenance) without excessive coordination cost.
#The costs
- Write latency — at least one round trip to a majority. In-region, a few ms. Cross-region, 100 ms+, irreducibly. This is the PACELC "else latency" cost made concrete: even when nothing is failing, strong consistency costs you latency.
- Throughput is bounded by the leader. Every write must pass through one node, so the cluster can't handle more writes than that one machine can. You scale by sharding into many independent Raft groups — one per partition — which is exactly what Spanner, CockroachDB, and TiKV do.
- Minority unavailability. A partitioned minority cannot serve writes, or linearizable reads, at all. Consensus systems are firmly CP: during a partition they choose consistency and refuse requests rather than risk wrong answers.
- Read cost. A leader that has been cut off may not know a new leader exists, so it could serve stale data. A linearizable (always up-to-date) read therefore technically requires confirming you're still leader first. Two optimizations:
- Leader leases — followers promise not to elect anyone else for a fixed time (say, 10 s). Within that window the leader can answer reads locally and fast. This depends on clocks on different machines not drifting too far apart.
- ReadIndex — before answering, the leader sends one heartbeat round to a majority to confirm it's still in charge. Cheaper than writing a full log entry for each read.
#Where to use consensus — and where not to
Use it for small, critical, low-write-volume state: cluster membership, shard assignment, feature flags, leader election, service discovery, distributed locks that must actually be safe.
Don't use it for bulk data. It's a coordination tool, not a storage engine. Routing every user write through a single Raft group is a common design error — you've reduced your write throughput to one machine's and added round trips.
The standard architecture puts consensus in the control plane and keeps it out of the data plane. The control plane is the part of the system that makes decisions about the system (which node owns which shard, who's in the cluster). The data plane is the part that serves actual user requests.
┌──────────── control plane ────────────┐
│ etcd (Raft): who owns which shard, │ small, critical,
│ cluster membership, config │ rarely written
└───────────────────┬───────────────────┘
│ read (cached aggressively)
┌───────────────────▼───────────────────┐
│ data plane: sharded storage nodes │ huge, hot,
│ serving the actual reads and writes │ no consensus
└───────────────────────────────────────┘Note that each shard may still run its own Raft group for its replicas — the point is that consensus is scoped per-shard, so total write throughput scales with shard count rather than being capped by a single group.
#Check yourself
What does FLP impossibility say, and how do real protocols live with it?Show answer
Why is "consensus on an ordered log" so powerful?Show answer
Why does Raft use randomised election timeouts?Show answer
What stops a Raft candidate that's missing committed entries from becoming leader?Show answer
When is a Raft log entry committed, and why is it then safe?Show answer
A cluster of 4 tolerates how many failures, compared with 3 and 5?Show answer
How do systems scale write throughput when Raft funnels writes through one leader?Show answer
What should and shouldn't go through consensus?Show answer
#What to carry forward
- Consensus lets unreliable machines agree on one ordered log: safe always, live once the network behaves.
- Raft: randomised elections, majority votes for up-to-date candidates, entries committed once on a majority.
- Use 3, 5 or 7 nodes — 5 is standard; even sizes add nothing.
- Writes cost a majority round trip and funnel through the leader — scale by running many groups.
- Use etcd or ZooKeeper rather than implementing it, and keep consensus to small control-plane state.