Topic 13.7
Leader Election
In one line
Exactly one node acts as leader at any time, others follow — via leases, fencing, and a consensus-safe tiebreaker.
Think of it like this
A group of coworkers stuck in a lift picking one person to press the emergency button, using a clear rule (like 'whoever has the lowest employee ID') so there's never a situation where two people both think they're in charge, or nobody is.
Key ideas
- 01
Why leaders: single writer/coordinator simplifies ordering (partitioning), locks, and scheduler triggers.
- 02
Leases: the leader holds a lease with a TTL; it must renew — a crashed leader loses the lease and a new one takes over.
- 03
Election mechanisms: etcd/Zookeeper (linearizable lock + session), Redis SETNX (weaker), or Raft itself.
- 04
Fencing tokens: every leader term carries a monotonic token; resources reject operations from a stale leader-term (the slow-leader bug).
- 05
Split brain: without fencing, two leaders can both write — fencing + lease is what makes 'exactly one' honest.
- 06
Interviews: you design leader election for a job scheduler (12.24), a config authority, or a queue sequencer.
Java / Spring map
- →
LeaderLatch (Curator against Zookeeper); or a lease in Redis with a fencing token check in the resource.
Code & diagrams
The moment a leader disappears, the cluster must agree on ONE replacement — not zero, not two.
Explain without notes
Node A stalls 12s past its lease, resumes, and tries to keep scheduling. What stops the double scheduling?
Practice
Design the scheduler leader: election, lease renewal, fencing token check on execution.
Trade-offs
- ↔
Leadership centralizes the tricky part (single owner, easy reasoning) at a failover+consensus cost.
Run it in production
You've designed it. Now build, operate, and break the same idea hands-on in the DevOps courses:
Completion checklist
I can design leader election with lease + fencing and name the split-brain that it prevents.