Command Palette

Search for a command to run...

PHASE 13Advanced ~7 min· topic 7 of 13

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.

0/13 · 0%

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

  1. 01

    Why leaders: single writer/coordinator simplifies ordering (partitioning), locks, and scheduler triggers.

  2. 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.

  3. 03

    Election mechanisms: etcd/Zookeeper (linearizable lock + session), Redis SETNX (weaker), or Raft itself.

  4. 04

    Fencing tokens: every leader term carries a monotonic token; resources reject operations from a stale leader-term (the slow-leader bug).

  5. 05

    Split brain: without fencing, two leaders can both write — fencing + lease is what makes 'exactly one' honest.

  6. 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

LeaderElectionFlowdiagram

The moment a leader disappears, the cluster must agree on ONE replacement — not zero, not two.

Rendering diagram…

Explain without notes

01

Node A stalls 12s past its lease, resumes, and tries to keep scheduling. What stops the double scheduling?

Practice

01

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

Completion checklist

  • I can design leader election with lease + fencing and name the split-brain that it prevents.

Back to phase