System Design · 03. Data & Storage · 12 min · Advanced

Consensus & Leaders

How a group of machines agrees on one leader and one order of writes.

In short

A leader needs votes from a majority of all nodes (3 of 5), so two leaders can never exist in the same term. Terms and heartbeats detect a dead leader, and a new election takes about 155–305 ms.

A write is committed when a majority holds it, so it survives any minority of crashes. Real systems that do this for you: etcd, Consul, ZooKeeper, Kafka's KRaft, and Paxos-based stores such as Spanner.

Key ideas

  • Consensus means a group of nodes agreeing on one value, such as who the leader is, even when some of them fail. (step 1)
  • A majority is the smallest group that any other majority must overlap with. That overlap is what makes agreement safe. (step 3)
  • Consensus is not only about electing a leader: it is also how the group agrees on the order of every command. (step 7)

Good to know

  • This is the idea behind Raft and Paxos. Raft is the easier one to learn, and etcd, Consul and Kafka's KRaft use it. (step 4)
  • Each follower picks a random timeout, so two nodes rarely become candidates at the same instant. If they do, the vote splits and a new term starts. (step 5)
  • A committed entry is safe because any future leader needs a majority, and that majority must include a node that has the entry. (step 8)
  • Use 3 for small clusters and 5 when you want to survive two failures. More than 7 makes every write slower for little gain. (step 10)

Watch out

  • A node cannot tell "the leader died" from "I cannot reach the leader". The rule must not depend on that guess. (step 2)
  • Too short a timeout causes needless elections on a slow network; too long means longer downtime after a real crash. (step 6)
  • While there is no leader, writes pause. Reads from followers may still work but can be old. (step 9)
Clientn1n2n4n3leadern5

Key numbers

Working leaders
1
Votes to win
3 of 5
Crashes survived
2
Failover time
155–305 ms

Terms

Leader
The one node that puts all writes in order while the others follow it.
Split brain
Two parts of a cluster each believe they have a leader and accept conflicting writes.
Quorum (majority)
More than half of all nodes; any two quorums share at least one node.
Term
An election number; each node votes once per term and the higher term wins.
Candidate
A node that has timed out, raised its term and is asking for votes.
Heartbeat
A small periodic message from the leader that tells followers it is alive.
Election timeout
How long a follower waits without a heartbeat before starting an election, chosen at random.
Replicated log
An ordered list of commands that every node applies in the same order.
Commit
An entry is committed once a majority of nodes has stored it, so it cannot be lost.
Raft
A consensus algorithm built on terms, majority votes and a replicated log; used by etcd and Consul.
Failover
Switching to a new leader after the old one crashes.