Module 5 · Distributed systemsLesson 49 of 887 minAdvanced
Leader election
Many systems let one node lead. When it dies, the others must notice and pick exactly one new leader.
Watch the bars under the followers fill up and reset with each heartbeat. Crash the leader and see who times out first and wins the vote.
Having one leader makes many problems simple: it decides the order of writes, hands out work, or holds a lock. The hard part is replacing it safely.
How Raft elects a leader
- The leader sends heartbeats to followers every so often.
- Each follower has an election timeout, randomly chosen, like 150 to 300 ms in real systems.
- If a follower hears nothing before its timeout, it becomes a candidate: it increases the term number, votes for itself, and asks others for votes.
- Each node votes for at most one candidate per term.
- A candidate with a majority becomes the new leader and starts sending heartbeats.
Avoiding two leaders (split brain)
The worst outcome is two nodes both acting as leader, accepting conflicting writes. Safeguards:
- Majority votes: only one candidate can get a majority in a term.
- Terms: an old leader that comes back from a pause sees a higher term and steps down. Its stale messages are rejected.
- Fencing tokens: resources reject commands with an old term or token (see the next lesson).
The trade-off in timeouts
- Short timeouts: fast failover, but a slow network or a long garbage-collection pause can trigger needless elections.
- Long timeouts: fewer false alarms, but longer outages when the leader really dies.
In practice
Use a tool that does this for you: etcd, ZooKeeper or Consul offer leader election as a feature. Kubernetes controllers use "leases" stored in the cluster for the same purpose. Rolling your own election on a database row or a Redis key is a common source of split-brain bugs.