Why you need consensus, and when to use it
Some questions need one answer that every machine agrees on, even when machines crash and the network drops messages: who is the leader, who holds this lock, what is the current configuration. If two machines each believe they are the leader, both accept writes and the data diverges. This is called split brain.
Consensus is the family of algorithms (Paxos, Raft and others) that let a group of nodes agree on a value so long as a majority can still talk to each other. Coordination is what you build on top: leader election, distributed locks, configuration and service discovery. It gives you two things interviewers always ask about:
- Consistency: at most one leader or lock holder at a time, and every node sees the same decisions in the same order.
- Availability through failover: when the leader dies, the survivors elect a new one without a human.
Use it when:
- Exactly one node must do a job: run the scheduler, own a partition, be the database primary.
- Several nodes must agree on shared state, such as cluster membership or configuration.
- You need a lock across machines that is released automatically if the holder dies.
Skip it, or use something else, when:
- A single database row or a
SELECT ... FOR UPDATEis enough to guard the job. - Two nodes doing the same work is harmless, because the work is idempotent.
- You would run your own cluster for one small lock. Use the coordination service your platform already has.
- The data can be repaired later, so eventual consistency is acceptable.
Try it
Run a five-node cluster, then break it. The rule decides who is allowed to be leader.
Leader election
Step 1 of 3 · Press Space to play, arrow keys to stepInitial state. Five nodes, N1 is the leader of term 1. Followers reset a timer on every heartbeat.
- tick:
- 0
- leaders:
- 1
- highest term:
- 1
- writes committed:
- 0
- conflicting writes:
- 0
- messages:
- 0
1 tick = one step. A write is committed only when a majority (3 of 5) confirm it.
Things to try:
- Run the Raft-style rule with no failure. The leader confirms a write with a majority and commits it.
- Make the leader crash. A follower's timer runs out first, it asks for votes, and a majority makes it leader of a higher term.
- Choose Network split with the Raft-style rule, then with the naive rule. Only the three-node side can elect a leader in the first case. In the second, both sides have a leader and the writes conflict.
- Watch the leaders counter. With the Raft-style rule it briefly shows 2 during the split, because the old leader N1 does not yet know it was replaced. That is safe: N1's write stays pending (it cannot reach 3 nodes) and is discarded once N1 sees the higher term. The conflicting writes counter stays at 0. With the naive rule both leaders commit, and that counter rises. The messages counter is the number of vote, heartbeat and confirmation messages sent so far.
Consensus building blocks
| Building block | How it works | Good when | Weakness |
|---|---|---|---|
| Leader election | Nodes vote, and a candidate needs a majority. Each leader has a numbered term | One node must coordinate writes | Writes pause during an election |
| Replicated log (Raft, Paxos) | The leader appends entries and commits them once a majority store them | Replicating state in the same order everywhere | Every write waits for a majority round trip |
| Leases | A node holds a role for a time limit and must renew it | Locks and leadership that must expire if the holder dies | Clocks and pauses can let two holders overlap briefly |
| Fencing tokens | Each lock grant carries an increasing number, and the resource rejects older ones | Protecting a resource from a lock holder that was paused | The resource must check the token |
| Coordination service (etcd, ZooKeeper) | A small consensus cluster that other systems use for locks, election and configuration | You want these features without writing consensus yourself | Another cluster to run and keep healthy |
Majority rule vs naive failover
- Majority rule: a node can lead only if more than half the cluster agrees. Two leaders in the same term would need two disjoint majorities, which cannot exist. An old leader on the minority side may still believe it leads for a while, but it cannot get a majority to confirm a write, so nothing it accepts is ever committed. The price is that the smaller side of a split stops accepting writes, which gives up availability for consistency.
- Naive failover ("I heard nothing, so I am the leader") stays available on both sides of a split, and then produces two leaders. It is fine only when you can merge or discard one side's work.
This is the trade-off in the CAP theorem. When the network splits, consensus systems choose consistency over availability on the minority side.
How a leader election works
A short version of Raft. The majority has a name, a quorum: the smallest group that is allowed to decide (3 of 5):
- Every follower has a random election timer. A heartbeat from the leader resets it.
- If the timer runs out, the follower becomes a candidate, adds one to the term, votes for itself and asks the others for votes.
- Each node votes once per term. A candidate with a majority becomes leader.
- If votes split, nobody wins, the timers run out again, and the random delays make a clean result likely next time.
- A node that sees a higher term steps down at once. That is how an old leader, back after a split, learns it is no longer leader.
- A node only votes for a candidate whose log is at least as up to date as its own, so a new leader always holds every entry that was already committed.
Numbers to keep in mind (illustrative defaults, all configurable): the Raft paper suggests election timeouts of 150 to 300 ms, and etcd's defaults are a 100 ms heartbeat and a 1000 ms election timeout. The timeout must be several times the network round trip, or healthy leaders get replaced for no reason. Each committed write costs at least one round trip to a majority, so cross-region clusters pay that latency on every write. Reads served by a leader that has not checked it is still the leader can be stale, so systems that need fresh reads confirm leadership first.
The leader then confirms every write with a majority before it counts as committed.
Coordination services vs the alternatives
| Concern | etcd / ZooKeeper | A database row lock | Redis lock |
|---|---|---|---|
| Survives a node failure without losing the lock | Yes | Only with a replicated database | Not guaranteed |
| Lock is freed if the holder dies | Yes, with a lease or ephemeral node | With a timeout you build | With an expiry |
| Safe against a paused holder | With fencing tokens | With a version column | Not by itself |
| Extra system to run | A small cluster | None | A cache you may already run |
| Best for | Leadership, configuration, strict locks | Simple jobs with one database | Efficiency locks where a rare double run is harmless |
A coordination service wins when correctness depends on one holder. A database row or a Redis lock is enough when a duplicate run is harmless.
Avoiding a new single point of failure
The coordination cluster is now critical for everyone who uses it. Run three or five nodes, never two or four: an odd number gives the same fault tolerance as the next even number with one machine fewer (three tolerate one failure, five tolerate two). Spread them across failure zones, keep the data small, and make clients cope with it being briefly unreachable. You accept slower writes, since each one needs a majority, and an operational burden.
Common mistakes
- Running two or four nodes. You pay for more machines and tolerate no more failures than with one fewer.
- Locks without expiry. A crashed holder blocks everyone for ever. Use a lease or an ephemeral node.
- Trusting a lock after a pause. A garbage collection pause can outlast the lease, so use a fencing token.
- Putting big or busy data in the coordination service. It is for small, important facts, not for your application data.
- Checking the time to decide who is leader. Clocks drift. Timers are fine for noticing that a leader may have failed, but who is allowed to lead must come from terms and majorities, and who is allowed to write must be backed by fencing tokens.
- Ignoring the minority side. Decide what a node does when it cannot reach a majority: stop writing.
How to talk about consensus in an interview
- Say what you need: one leader, or one lock holder, at a time.
- Say you would use etcd or ZooKeeper rather than write consensus yourself, and explain that a majority is why a split cannot create two leaders.
- Mention leases that expire, terms, and fencing tokens unprompted.
- Name the trade-off: consistency over availability, so the minority side stops and writes cost a majority round trip.