Module 5 · Distributed systemsLesson 48 of 888 minAdvanced
Consensus algorithms
Consensus lets a group of machines agree on a value, or an order of events, even when some of them crash.
Watch writes get committed once 3 of 5 nodes have them. Crash one follower, then another: writes still work. Crash a third and see them stop.
Many things in a distributed system need everyone to agree: who is the leader, what order writes happened in, whether a lock is held. Consensus algorithms make that possible despite crashes and lost messages.
The core idea: majorities
A decision counts only when a majority of nodes has accepted it. Any two majorities share at least one node. So if one majority has accepted "x = 1", no other majority can accept a conflicting "x = 2" without that shared node noticing.
That gives a simple rule for size:
| Nodes | Majority | Failures survived |
|---|---|---|
| 3 | 2 | 1 |
| 5 | 3 | 2 |
| 7 | 4 | 3 |
Even numbers don't help: 4 nodes need 3 for a majority and still survive only 1 failure.
Raft, in brief
Raft is the easiest consensus algorithm to understand, and it's used in etcd, Consul and CockroachDB:
- One node is the leader. All writes go to it.
- The leader appends each write to its log and sends it to followers.
- When a majority has it, the entry is committed and applied.
- If the leader dies, a new one is elected (next lesson).
Where you meet consensus
You rarely implement it yourself. You use systems built on it:
- etcd and ZooKeeper: configuration, service discovery, leader election and locks.
- Kubernetes: stores all cluster state in etcd.
- Distributed SQL (Spanner, CockroachDB): each shard is replicated by consensus.
- Kafka (KRaft): keeps cluster metadata in a Raft log.
The cost
Every write waits for a majority round trip. Across data centres that's real latency, and if a majority is unreachable, the system stops accepting writes. That's the CP side of CAP, chosen on purpose.