Consensus lets a group of machines agree on a value, or on an ordered log of values, even when some of them crash. It is how a cluster of three or five servers behaves like one reliable machine. Paxos (Lamport) is the classic algorithm; Raft (Ongaro and Ousterhout, 2014) was designed to be understandable and now powers etcd, Consul, CockroachDB and Kafka's KRaft. This lesson covers why consensus is hard, how majorities make it possible, and exactly how Raft elects leaders and replicates its log safely.
Think of it like
A committee that keeps minutes
A chairperson proposes each entry for the minutes, and an entry becomes official once a majority of members have copied it into their notebooks. If the chair disappears, members wait a random amount of time before nominating themselves, so they rarely all stand at once. A new chair needs a majority of votes, and nobody votes for a candidate whose notebook is missing entries they already have. That is Raft.
Replicated state machines
If several servers start in the same state and apply the same deterministic commands in the same order, they end in the same state. So making a fault-tolerant key-value store, lock service or metadata store reduces to one problem: agreeing on the order of commands in a replicated log. That is what consensus provides.
- Safety
- Nothing bad ever happens: two servers never decide different values for the same log slot, regardless of crashes, delays or message loss.
- Liveness
- Something good eventually happens: the cluster makes progress and commands get committed.
- Crash fault
- A node stops or restarts. Raft and Paxos tolerate these. They do not tolerate Byzantine (malicious or corrupted) nodes; that needs BFT protocols such as PBFT.
Press play to see a command travel through a five-node Raft cluster, and use the simulation above to crash leaders and watch elections happen.
Why consensus is hard: FLP
Fischer, Lynch and Paterson proved in 1985 that in a fully asynchronous system (no upper bound on message delay), no deterministic algorithm can guarantee that consensus always terminates if even one process may crash. The root cause: you can't tell a crashed node from a slow one.
Majority quorums
| Cluster size | Majority | Failures tolerated |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 6 | 4 | 2 |
| 7 | 4 | 3 |
Paxos in brief
- 1
Prepare(n)
A proposer picks a unique proposal number
n(higher than any it has seen) and sendsPrepare(n)to the acceptors. - 2
Promise
An acceptor that hasn't promised anything higher promises to ignore proposals numbered below
n, and replies with the highest-numbered proposal it has already accepted, if any. - 3
Accept(n, v)
With promises from a majority, the proposer sends
Accept(n, v). The valuevmust be the value of the highest-numbered proposal reported in the promises; only if none was reported may it use its own value. - 4
Accepted
An acceptor accepts unless it has since promised a higher number. Once a majority accepts the same proposal,
vis chosen and learners are told.
Single-decree Paxos decides one value. Multi-Paxos decides a log by electing a stable leader that skips phase 1 for subsequent slots, reaching one round trip per entry, just like Raft. Paxos is famously hard to turn into a complete system (Google's "Paxos Made Live" paper describes the gaps); it underpins Chubby, Spanner and Megastore. ZooKeeper uses ZAB, a closely related atomic broadcast protocol.
Raft in depth
Roles and terms
- Follower
- Passive: responds to RPCs from leaders and candidates. Becomes a candidate if it hears nothing before its election timeout.
- Candidate
- Increments the term, votes for itself and asks everyone else for votes.
- Leader
- Handles all client requests, appends entries to its log, replicates them and sends periodic heartbeats.
- Term
- A monotonically increasing number that acts as a logical clock. Each term has at most one leader. Any node that sees a higher term updates its own and steps down to follower; messages with a stale term are rejected.
Leader election with randomized timeouts
- 1
Timeout
A follower's election timer expires without a heartbeat. It increments
currentTerm, becomes a candidate and votes for itself. - 2
Request votes
It sends
RequestVote(term, lastLogIndex, lastLogTerm)to every other node. - 3
Vote
Each node grants at most one vote per term, first come first served, and only to a candidate whose log is at least as up to date as its own.
- 4
Win
With votes from a majority, the candidate becomes leader and starts sending heartbeats.
- 5
Lose or split
If it hears from a leader with an equal or higher term, it steps down. If nobody wins (a split vote), timers expire again with fresh random values and a new term begins.
Log replication and the commit index
Each log entry holds a command and the term in which the leader created it. AppendEntries includes prevLogIndex and prevLogTerm; a follower rejects the RPC if its log has no entry at that index with that term. The leader then backs up (decrements nextIndex for that follower) and retries until the logs agree, after which the follower's conflicting suffix is overwritten with the leader's entries.
| Node | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| Leader (term 3) | 1 | 1 | 1 | 2 | 3 | 3 | 3 |
| Follower A | 1 | 1 | 1 | 2 | 3 | 3 | |
| Follower B | 1 | 1 | 1 | 2 | 2 | 2 |
The leader's commit index is the highest index stored on a majority. Committed entries are applied to the state machine in order, and followers learn the commit index from subsequent AppendEntries calls.
Safety properties
- Election safety: at most one leader per term, because each node votes once per term and two majorities overlap.
- Log matching: if two logs contain an entry with the same index and term, the logs are identical up to that index. A leader creates at most one entry per index per term, and the consistency check enforces the rest.
- Leader completeness: a committed entry appears in the log of every future leader. The election restriction guarantees this: voters compare last log term (higher wins), then last log index (longer wins), and refuse less up-to-date candidates. Any winner needs a majority, which overlaps the majority holding every committed entry.
- State machine safety: no two nodes ever apply different commands at the same index.
Membership changes
Switching a cluster directly from configuration C_old to C_new is unsafe: during the transition, a majority of the old and a majority of the new could be disjoint and elect two leaders. Raft offers joint consensus (a transitional configuration in which decisions need majorities of both C_old and C_new) and the simpler single-server changes (add or remove one node at a time, so any old and new majorities overlap). etcd also adds new members as non-voting learners until they have caught up.
Linearizable reads
A leader that was partitioned away may not know it was replaced, so answering reads from local state can return stale data. Options: send the read through the log (slow but simple); ReadIndex, where the leader records its commit index, confirms it is still leader with one heartbeat round to a majority, then answers once that index is applied; or lease reads, which skip the round trip but rely on bounded clock drift.
Raft vs Paxos
| Aspect | Multi-Paxos | Raft |
|---|---|---|
| Design goal | Minimal, provably correct core | Understandability and a complete specification |
| Leader | An optimization | Required: all writes flow through it |
| Log | Slots decided independently; holes allowed | Contiguous; no holes |
| Who can lead | Any proposer with a higher ballot (catches up during phase 1) | Only a candidate with an up-to-date log |
| Membership changes | Not part of the basic protocol | Joint consensus or single-server changes |
| Used in | Chubby, Spanner, Megastore | etcd, Consul, CockroachDB, TiKV, Kafka KRaft, RabbitMQ quorum queues |
Where consensus is used
- etcd stores all Kubernetes cluster state; every
kubectl applyends up as a Raft log entry. - Consul servers replicate the service catalog and KV store with Raft (membership itself uses gossip; see Heartbeats & Gossip Protocols).
- CockroachDB, TiKV, YugabyteDB split data into ranges and run one Raft group per range ("multi-Raft") so consensus scales horizontally.
- Kafka KRaft replaces ZooKeeper with a Raft-based metadata quorum inside Kafka; Kafka 4.0 removed ZooKeeper mode entirely.
- ZooKeeper (ZAB) and Spanner (Paxos) are the long-standing alternatives.
Typical voters
3 or 5
tolerate 1 or 2 failures
Commit latency
1 RTT
leader to a majority, plus fsync
etcd election timeout
1 s
default; heartbeat 100 ms
Throughput limit
1 leader
shard into many groups to scale
Implementation
The two rules that carry most of Raft's safety: the election restriction and committing only current-term entries by counting.
from dataclasses import dataclass, field
@dataclass
class Entry:
term: int
command: str
@dataclass
class Node:
current_term: int = 0
voted_for: int | None = None
log: list[Entry] = field(default_factory=lambda: [Entry(0, "")]) # sentinel at index 0
def last_index(self) -> int:
return len(self.log) - 1
def last_term(self) -> int:
return self.log[-1].term
def handle_request_vote(self, term: int, candidate: int,
last_index: int, last_term: int) -> tuple[int, bool]:
if term < self.current_term:
return self.current_term, False
if term > self.current_term:
self.current_term, self.voted_for = term, None
# Compare (last term, last index) lexicographically: the election restriction
up_to_date = (last_term, last_index) >= (self.last_term(), self.last_index())
if self.voted_for in (None, candidate) and up_to_date:
self.voted_for = candidate # persist before replying
return self.current_term, True
return self.current_term, False
def advance_commit_index(self, match_index: list[int], commit_index: int) -> int:
for idx in range(self.last_index(), commit_index, -1):
if self.log[idx].term != self.current_term:
break # only count replicas of current-term entries
if sum(1 for m in match_index if m >= idx) > len(match_index) // 2:
return idx
return commit_indexKey takeaways
- Consensus agrees on an ordered log; deterministic replicas applying that log form a replicated state machine.
- FLP: no deterministic protocol guarantees termination in a fully asynchronous system with one crash, so real protocols keep safety always and use timeouts for liveness.
- 2f + 1 nodes tolerate f failures because any two majorities intersect.
- Paxos: prepare/promise, then accept/accepted, and a proposer must adopt the highest accepted value it hears.
- Raft: randomized elections, one vote per term, the election restriction, and commit by majority replication of current-term entries.
- Use consensus stores (etcd, ZooKeeper, Consul) for small critical state; shard into many Raft groups to scale data.
Common pitfalls
- Running an even number of voters, which adds latency without adding fault tolerance.
- Serving reads from a leader's local state without ReadIndex or leases, returning stale data after a silent partition.
- Applying entries before they are committed, so a new leader can roll them back after clients saw them.
- Setting the election timeout close to the heartbeat interval or to typical GC pauses, causing election storms.
- Changing membership by swapping many nodes at once instead of one at a time or via joint consensus.
Interview tips
- Explain the election restriction and why it guarantees new leaders hold every committed entry.
- Know the quorum math cold: 3 nodes tolerate 1 failure, 5 tolerate 2, and 4 is no better than 3.
- Mention where consensus appears in your design (leader election, shard maps, locks) and which product provides it.
Real-world applications
- Kubernetes control plane state in etcd.
- Distributed SQL databases replicating each range with Raft.
- Kafka metadata management with KRaft.
- Distributed locks and leader election via ZooKeeper, etcd or Consul sessions.
Test yourself
How many node failures can a 5-node Raft cluster tolerate while still committing writes?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.