Skip to the guide

Leader election

AdvancedConcept3 pages

Many jobs need exactly one worker in charge at a time: one scheduler firing timed jobs, one database leader taking writes, one process owning a partition. Leader election picks that one, replaces it when it dies, and must never let two act at once. Interviewers want to hear what you'd elect it with, how long a handover takes, and what stops an old leader that doesn't know it's been replaced.

The night supervisor

A factory runs a night shift with one supervisor. At the security desk there's a logbook: "Ana in charge until 02:00". Ana must come back and extend her entry before it runs out. If she doesn't, the guard waits until 02:00 has passed before letting the next person sign in. Ana has a rule of her own: if she hasn't extended by 01:50, she stops giving orders, since she might have dozed off without noticing.

  • Ana → the leader, and her orders → the jobs it fires
  • the guard → the store that judges expiry
  • the next person to sign in → a standby
  • the logbook at the desk → a lease in a coordination service (etcd, ZooKeeper, Consul, or a Kubernetes Lease object)
  • "until 02:00" → the lease duration
  • coming back to extend → renewing the lease
  • waiting until 02:00 has passed → a successor takes over only after the old lease has expired
  • stopping at 01:50 → the leader gives up before its lease can run out