Raft Consensus
Agree on one sequence of operations despite node crashes, delayed messages, and network partitions.
Elect → Propose → Replicate → Majority → Commit → Apply
refresher
Raft elects one leader to order commands. The leader appends each command to its log, replicates it to followers, and marks it committed after a majority stores it. Every healthy node eventually applies the same committed log in the same order.
What problem does Raft solve?
Copies alone do not establish authority. If several replicas accept competing writes, which sequence survives? Raft gives a cluster one durable, ordered history even as leaders fail and messages arrive late.
How it works
- Elect — followers time out, become candidates, increment the term, and request votes.
- Propose — the elected leader receives a client command and appends a log entry.
- Replicate — the leader sends the entry to followers using
AppendEntries. - Commit — after a majority acknowledges, the entry becomes committed.
- Apply — each node applies committed entries to its state machine in order.
Run an election
Raft election playground
Advance terms, remove authority, and isolate a minority. Watch which nodes can participate in a majority election.
Key trade-offs
| Choice | What you gain | What it costs |
|---|---|---|
| 3-node cluster | Tolerates one failure with low coordination cost | No progress after two failures |
| 5-node cluster | Tolerates two failures | More infrastructure and replication traffic |
| Synchronous majority | Committed history survives leader failure | Write latency includes quorum round trips |
What happens if?
The leader crashes before majority acknowledgement
The entry is uncommitted. A future leader may overwrite it. The client must retry because it cannot know whether the command survived.
The leader commits, then crashes before replying
The command is durable, but the client sees a timeout. A retry can execute the command twice unless the API uses an idempotency key or request identity.
A minority is isolated
It may continue reading local state if policy allows, but it cannot elect a leader or commit new entries. Safety is preserved by sacrificing progress in the minority.
Real systems
Raft appears in etcd, Consul, TiKV, CockroachDB ranges, and many control planes. It is best for relatively small consensus groups coordinating metadata or replicated state—not for broadcasting every event to thousands of nodes.
Staff+ interview modeWhy can an acknowledged client request still need idempotency?Show answer
The server may commit the request and fail before the response reaches the client. The client observes an ambiguous timeout and retries. Consensus protects the log’s order; idempotency protects the business operation from duplicate intent.