What it is
Leader election picks exactly one node in a group to do something that must not happen twice at once: run a scheduler, own a shard, be the database primary, accept writes for a partition. The others stand by and take over when the leader fails. Most systems do not run their own election protocol; they use a coordination service (etcd, ZooKeeper, Consul, or a Kubernetes Lease object stored in etcd) and a lease on a key.
Why it exists
Many jobs are easiest to get right with a single actor: one instance sends the nightly emails, one node assigns work, one primary orders writes. Running them on a single fixed machine makes that machine a single point of failure. Leader election keeps the single-actor simplicity while letting any node take over, without a human deciding who is in charge.
How it works
Campaign. Every candidate tries an atomic "create this key if it does not exist" on the coordinator. In etcd that is a transaction comparing the key's create revision with 0; in ZooKeeper each candidate creates an ephemeral sequential znode and the lowest sequence number wins. The coordinator serialises these requests, so exactly one succeeds. The losers watch the key (or, in ZooKeeper, the znode just before theirs, avoiding a herd of notifications).
Lease. The key is attached to a lease with a time-to-live. The leader keeps it alive with periodic renewals (etcd LeaseKeepAlive, ZooKeeper session heartbeats, a Kubernetes Lease object's renewTime). If renewals stop because the leader crashed, hung or lost the network, the coordinator deletes the key when the TTL runs out, watchers are notified and campaign again. Failover therefore takes roughly one TTL plus a campaign round trip.
Split brain. The lease expires at the coordinator. The old leader learns nothing unless it can talk to the coordinator. A partitioned leader, a process stuck in a long GC pause, or a VM frozen during live migration can all keep acting after another node has been elected. If the old leader can still reach the shared resource, two leaders write at once.
Step down on your own timer. A leader should stop acting when it has not managed to renew within a renew deadline shorter than the TTL, measured with a monotonic clock from when it sent its last successful renewal. Kubernetes' client-go leader election uses this structure; its widely used defaults are a 15 s lease duration, a 10 s renew deadline and a 2 s retry period. The difference between deadline and TTL absorbs clock-rate differences between machines. It does not protect against a pause after the leader checked its deadline.
Fencing tokens. Each successful election produces a number that only grows: the election key's revision in etcd, the zxid or znode sequence number in ZooKeeper, a term or epoch elsewhere. The leader attaches it to every write, and the resource keeps the highest token it has seen and rejects lower ones (a conditional update such as UPDATE … WHERE fence_token <= :token, an object-store precondition, or a storage system with built-in epochs). A deposed leader's writes then fail no matter how late they arrive. Older infrastructure achieves the same with STONITH ("shoot the other node in the head"): power off the old leader before the new one starts.
The coordinator needs consensus. etcd replicates with Raft, ZooKeeper with ZAB, Consul with Raft. Their members agree on who holds the key, so a crashed or partitioned coordinator member cannot hand the key to two candidates. A single Redis instance or a single database row gives no such guarantee once that node fails over.
When to use it
- A singleton job or controller in a horizontally scaled service (schedulers, Kubernetes controllers, cron-like workers).
- Choosing a primary among replicas when the database does not do it itself.
- Assigning ownership of partitions or shards to one worker at a time.
When not to
- When the work can safely run more than once: make it idempotent and run it everywhere, or let a queue hand each item to one consumer.
- When a database transaction or a unique constraint can enforce the rule directly.
- When the system already elects leaders internally (Raft-based databases, Kafka partition leadership): do not add a second election on top.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Short lease TTL | Fast failover | More renewal traffic; false failovers when a healthy leader is briefly slow or paused |
| Long lease TTL | Stable leadership | Longer outage when the leader really dies |
| Step-down deadline | Fewer overlaps without changing the resource | Still timing-dependent; a gap with no leader between deadline and expiry |
| Fencing tokens | Safety at the resource regardless of timing | The resource must support conditional writes or token checks |
| Coordination service | Proven consensus, watches, leases | Another critical cluster to run (or a managed one to depend on) |
Alternatives
- The database's own mechanism: an advisory lock held on a session, or a conditional update on a leadership row with a version number that doubles as a fencing token.
- Consensus inside the system (embedding Raft) when the leader's state should itself be replicated, as databases do.
- Static assignment with manual failover, for systems where a few minutes of downtime are acceptable and automation is riskier than humans.
- Leaderless designs: idempotent work spread over all instances, partitioned by consistent hashing or a queue.
Failure modes
- Split brain from partitions, GC pauses, VM freezes or clock jumps when the resource does not check fencing tokens.
- Flapping leadership when TTLs are close to normal renewal latency, or when the leader is overloaded and renewals queue behind other work. Renew on a dedicated thread or event loop that is not blocked by the job itself.
- Coordinator outage: no renewals succeed, every leader steps down, and nothing leads until it is back. Size and spread the coordinator cluster accordingly.
- Thundering herd: every candidate wakes up on the same watch event. ZooKeeper's recipe of watching only the predecessor node avoids it.
- Work that is not resumable: the new leader must be able to tell what the old one finished; keep progress in the shared store, guarded by the token.
In production
Use a library rather than raw primitives: client-go's leaderelection package, etcd's concurrency package (Election, Session), Apache Curator's LeaderLatch/LeaderSelector for ZooKeeper, Consul sessions. Expose who leads and the leadership age as metrics, alert on frequent changes, and test failover by killing and pausing the leader (kill -STOP simulates a GC pause well). Pass the fencing token down to every write the leader makes, not just the first one.
Common misconceptions
- "When the lease expires, the old leader stops." It stops only if it notices, and partitions or pauses can prevent that.
- "Checking that I still hold the lease right before writing is enough." A pause or network delay between the check and the write breaks it; only the resource can make the final check.
- "A Redis key with a TTL is a leader election." It works until the Redis node fails over or a client pauses; without fencing it is a best-effort optimisation.
- "Shorter TTLs are always better." They trade false failovers for faster real ones.
Interview angle
When a design needs a singleton (a scheduler, a primary), say how you would elect it: a lease on etcd/ZooKeeper or a Kubernetes Lease, with failover time about one TTL. Then raise split brain on your own: partitions and pauses can leave the old leader active, so the leader steps down before its lease can expire elsewhere and every write carries a fencing token that the resource checks. That chain of reasoning is what interviewers look for.
Model assumptions
This lesson is a scripted illustration, not a simulation: the simulator has no lease, watch or fencing model, so every campaign, renewal, watch notification and write is a packet placed by hand and lease and token state appears as annotations. Time is compressed so a lease fits on screen: a 600 ms TTL, renewals every 200 ms, a 450 ms renew deadline, 30 ms one-way between an instance and the coordinator or storage, 10 ms between coordinator members and about 1 ms of processing. Real leases are measured in seconds. The token values (57, 63) stand for etcd revisions and are illustrative.