Video in progress
How does a consensus algorithm like Raft work, and why does a cluster usually have 3 or 5 nodes?
In Raft, one leader appends writes to its log and sends them to the followers; once a majority (a quorum) confirms a write, it's committed. Thanks to the majority rule, 3 nodes survive one failure and 5 nodes survive two; an even number doesn't add fault tolerance.
📖 Answer
etcd, Consul, Kafka's KRaft mode — they all run on Raft or a similar algorithm.
The main ideas:
Leader election. Every node starts as a follower. If no heartbeat arrives from the leader for a set time (randomized, say 150–300 ms), the node makes itself a candidate, increments the term number and asks for votes. The one that gets a majority of votes becomes the leader. The randomized timeout makes it less likely that two candidates appear at once.
Log replication. The client sends a write to the leader. The leader appends it to its log and sends it to the followers. Once a majority confirms they've stored it, the write is committed and the client gets "OK".
The safety part: a node votes only if the candidate's log is at least as up to date as its own — so a node that doesn't know about a committed write can't become leader. Messages from a leader in an old term are rejected — that's how split brain is prevented.
Now, why 3 or 5:
| Nodes | Quorum | Survives |
|---|---|---|
| 3 | 2 | 1 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
4 nodes survive no more than 3 do, but the quorum is larger — writes are slower. More than 7 is rare: every write waits on more nodes.
Placement matters too: put the 3 nodes in three zones. If you put them in two zones (2+1), when the zone with 2 nodes goes down, the quorum is lost.
The cost: every write takes at least one network round trip, and if the quorum is lost the cluster stops accepting writes — that isn't a bug, it's the C choice in CAP. That's why consensus is used not for all the data, but for metadata, configuration and leader election.
Sign up to mark studied questions and save your progress.