Course contents

08. Distributed Systems Lesson 8 of 10

Leader Election

Elect a single leader with leases on a coordination service, see how partitions cause split brain, and stop stale leaders with fencing tokens.

14 minAdvanced8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Candidates atomically create a key only if it does not exist; the winner leads, the others watch the key.
  • Leadership is a lease: the leader renews it, and when renewals stop the key expires and others take over.
  • Failover takes about one lease TTL; shorter TTLs fail over faster but misfire on slow, healthy leaders.
  • A lease expiring at the coordinator does not stop the old leader: partitions and pauses create split brain.
  • Leaders should step down before the lease can expire elsewhere, and resources should reject stale leaders by fencing token.
  • The coordinator itself must be a consensus-backed cluster, or the election is not safe.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. Three instances, one job: who leads?

    Three instances of a service can all run the nightly billing job, but it must run once. They elect a leader through a coordination service, here etcd (ZooKeeper and Consul work the same way).

    Each instance tries to create the key /election/billing only if it does not exist yet, attached to a lease. The coordinator handles these one at a time: Instance 1’s request arrives first and wins; Instances 2 and 3 are told the key exists and start watching it. Instance 1 is leader and starts writing to storage.

    Scripted illustration: packets and annotations show the protocol, nothing is simulated.

    Scene: All three instances ask the coordinator to create the election key. Instance 1’s request arrives first and succeeds; Instances 2 and 3 are refused and watch the key. Instance 1 then writes to storage.

    Key idea: Leader election = an atomic “create if absent” on a strongly consistent store, with everyone else watching the key.

  2. 2. Leadership is a lease, renewed while alive

    The key is tied to a lease with a time-to-live (TTL): 600 ms in this compressed picture, seconds in real systems. The leader renews it every 200 ms. Each renewal resets the TTL, and between renewals the leader does its work.

    The lease is what makes failover automatic: if the leader stops renewing, for whatever reason, the coordinator deletes the key when the TTL runs out and the others can take over. No human has to decide that the leader is dead.

    Scripted illustration.

    Scene: Instance 1 renews its lease with the coordinator every 200 ms and, in between, writes to storage.

    Key idea: A lease turns “the leader is alive” into “the leader renewed within the TTL”, which a coordinator can check on its own.

  3. 3. The leader dies: the lease expires

    Instance 1 crashes right after a renewal. Nothing happens at first: the coordinator cannot know yet whether it is dead or just slow. When the 600 ms TTL runs out without a renewal, the coordinator deletes the key and notifies the watchers.

    Instances 2 and 3 both campaign again. Instance 2’s request is first, so it becomes leader at 692 ms and resumes the writes.

    The job had no leader for about one TTL. That is the price of leases: a shorter TTL means faster failover but more renewals and more false failovers when a healthy leader is briefly slow.

    Scripted illustration.

    Scene: Instance 1 is down. After 600 ms without a renewal the coordinator deletes the key and notifies Instances 2 and 3. Both campaign; Instance 2 wins and writes to storage.

    Key idea: Failover time ≈ the lease TTL. Short TTLs fail over faster but misfire on slow, healthy leaders.

  4. 4. A partition: two leaders at once

    Instance 1 is back as a follower. Now Instance 2, the leader, is partitioned from the coordinator but can still reach storage. Its renewals are lost. At 600 ms its lease expires, the coordinator notifies the watchers, and Instance 3 becomes leader at 692 ms.

    Instance 2 never hears any of this: the expiry notice cannot reach it either. Its code only stops leading when the coordinator tells it so, so it keeps working. At 730 ms its write lands in storage, right after Instance 3’s. Two instances both believe they lead and both write: split brain.

    Scripted illustration.

    Scene: Instance 2 is cut off from the coordinator. Its lease expires at 600 ms, Instance 3 wins the new election and writes to storage, but Instance 2 keeps writing too: storage accepts writes from both.

    Key idea: A lease expiring at the coordinator does not stop the old leader. Something on the leader’s side, or at the resource, has to.

  5. 5. First defence: step down on your own clock

    Same partition, better client. Instance 2 measures time since its last successful renewal with a monotonic clock, counting from when it *sent* that renewal. If it cannot renew within a renew deadline of 450 ms, shorter than the 600 ms TTL, it steps down and stops writing. Kubernetes’ leader election works this way (renew deadline below lease duration).

    Now its last write is at 100 ms; Instance 3 starts at 723 ms. Between 450 and 692 ms nobody leads: that gap is the safety margin for clocks running at slightly different rates.

    This relies on timing: if Instance 2 is paused (a long GC, a frozen VM) right after it checked, it can still write late. Hence the next step.

    Scripted illustration.

    Scene: Instance 2 is still cut off, but stops writing when it fails to renew within 450 ms. Instance 3 becomes leader after the lease expires; storage only ever sees one writer at a time.

    Key idea: Stop leading before the lease can expire elsewhere (renew deadline < TTL). It helps, but a paused process can still act late.

  6. 6. Let storage reject the old leader

    Every lease grant comes with a number that only ever grows: a fencing token. In etcd the election key’s revision works (Instance 2 got 57, Instance 3 gets 63); in ZooKeeper, the znode’s sequence number or zxid. The leader sends its token with every write, and storage remembers the highest token it has seen and rejects anything lower.

    Instance 2 checks its deadline at 440 ms: still fine. Then it pauses for 300 ms. Meanwhile Instance 3 leads and writes with token 63. When Instance 2 wakes up and sends its write with token 57, storage refuses it. The old leader cannot do harm, whatever its clock or its pauses.

    The resource has to cooperate: a conditional write (… WHERE fence_token <= 57), a version check, or a storage API that accepts a token. Scripted illustration.

    Scene: Instance 2 writes with token 57, then pauses. Instance 3 becomes leader and writes with token 63. When Instance 2 resumes and writes with token 57, storage rejects the write because it has already seen 63.

    Key idea: Fencing tokens move the final check to the resource: writes from a deposed leader carry an older token and are rejected.

  7. 7. The coordinator is a consensus cluster

    Why trust the coordinator? Because it is not one machine. etcd runs as three or five members that replicate every change with Raft; ZooKeeper uses ZAB. When Instance 1 campaigns again, its “create if absent” goes to the etcd leader, which replicates it to a majority before answering “key held by Instance 3, revision 63”.

    That is what makes the election safe: two instances can never both create the key, even if a coordinator member crashes or is partitioned. Lease expiry is decided by the etcd leader; if that leader changes, etcd extends outstanding leases rather than expiring them early.

    Build leader election on such a service (or on a Kubernetes Lease object, which lives in etcd), not on a single Redis or database row without fencing. Scripted illustration.

    Scene: The coordinator is a three-member etcd cluster. Instance 1’s campaign request reaches the etcd leader, which replicates it to the other two members and, once a majority has it, answers that the key is held by Instance 3.

    Key idea: An election is only as safe as the store behind it: use a consensus-backed coordinator and fencing tokens.

  8. 8. What to remember about leader election

    Elect a leader with an atomic create-if-absent on a consensus-backed store, tied to a lease. Failover takes about one lease TTL.

    A lease expiring at the coordinator does not stop the old leader: partitions and pauses create two leaders. Make the leader step down before its lease can expire elsewhere, and make the resource reject stale leaders with fencing tokens.

    Scene: Three service instances with Instance 3 as leader, a three-member etcd cluster and the storage they write to.

    Key idea: Lease for liveness, consensus for uniqueness, fencing tokens for safety at the resource.