SysDesignAtlas

Leader Election

When you need a leader, how election works, split brain and fencing, and the designs that avoid needing a single leader in the first place.

HLDMedium10 min readleader-electioncoordinationsplit-brain
Confidence

#Why elect a leader

A leader is a designated node that performs a role no one else may perform simultaneously:

  • Accepting writes in a primary-replica database, so ordering is unambiguous.
  • Running a scheduled job exactly once across a fleet, not once per instance.
  • Owning a partition — one consumer per Kafka partition, one worker per shard.
  • Coordinating — assigning work, driving a rebalance, managing cluster membership.

The leader's real value is serialisation — forcing things into a single order. Once one node makes all the decisions, a hard distributed problem becomes an ordinary single-machine one: no locks between machines, no conflicting versions, no agreement needed per operation. That's an enormous simplification, and it's why the pattern is everywhere.

The cost is equally clear: the leader is a bottleneck for throughput, a single point of failure, and an availability gap during every election.

#How election works

Election is consensus — the cluster must agree on one value ("who is leader"), and disagreement is catastrophic. Three practical approaches:

#1. Consensus-backed (etcd, ZooKeeper, Consul)

The standard production answer. Candidates race to create a key with a lease; exactly one wins.

   etcd:  PUT /leader = node-A  if not exists,  lease 10s
          → winner renews the lease every ~3s
          → if it stops renewing, the key expires and
            others compete for it

ZooKeeper does it slightly differently. Each candidate creates an entry that is sequential (automatically numbered in arrival order) and ephemeral (deleted the moment that candidate's connection drops). Lowest number wins. Each loser watches only the entry immediately ahead of it, rather than all of them — otherwise every change wakes the entire fleet at once. Because the entry disappears on disconnect, there's no expiry time to guess at.

Either version is safe for the same reason: the underlying store answers as if it were a single copy, so two nodes cannot both be told they won.

#2. Built into the protocol (Raft)

As covered in Consensus: randomized election timeouts, terms, and majority votes, with the log-completeness rule preventing an out-of-date node from winning.

#3. Simple algorithms (mostly of academic interest)

Bully — the highest-ID reachable node wins; it announces itself and others yield. Simple, chatty, and prone to repeated elections when the network is flaky.

Ring — election messages circulate around a logical ring accumulating IDs. Elegant, fragile in practice.

Both assume reliable failure detection — that every node can tell for sure whether another node is dead. That doesn't exist: a slow or cut-off node looks exactly like a dead one, so two nodes can each conclude "the leader is gone, it's me now". Real systems use consensus.

#Split brain

The defining failure. Two nodes each believe they are leader, usually because of a partition rather than a crash.

   Before:   [A=leader]  B  C  |  D  E

   Partition splits the cluster:
     Left  {A, B, C} — A is still leader, has majority ✓
     Right {D, E}    — sees no leader, tries to elect one

   With majority quorum: D and E can only get 2 of 5 votes
                         → NO leader elected → safe ✓

   WITHOUT quorum (e.g. "highest ID wins"): E declares
                         itself leader → TWO LEADERS → divergence ✗

Prevention layers, and a strong answer names more than one:

1. Majority quorum. Only a partition containing more than half the nodes can elect. Since two disjoint majorities can't exist, two leaders can't be elected. This is why cluster sizes are odd — a 4-node cluster split 2/2 leaves neither half with a majority, so nobody can elect a leader and the whole cluster stalls.

2. Fencing tokens. Quorum prevents electing a second leader, but it doesn't stop the old leader from acting. A node that was partitioned may not yet know it lost leadership and can keep writing.

The fix: every election produces an epoch — a number that goes up by one each time a new leader is chosen. The leader attaches its epoch to every write (this number is the "fencing token"), and storage remembers the highest epoch it has seen.

   A is leader with epoch 7, gets partitioned (doesn't know it)
   B is elected leader with epoch 8
   B writes to storage → storage records max_epoch = 8
   A writes with epoch 7 → storage REJECTS (7 < 8) ✓

The resource (the storage being written to) enforces this, not the election service. Without that check, election alone cannot guarantee that only one leader's writes get through. Same mechanism as in distributed locks — and naming it in a leader-election discussion is a distinctly senior move.

3. Lease self-fencing. The leader holds a lease (say, 10 s) and must keep renewing it. If a renewal fails, the leader stops acting immediately — it doesn't wait for the lease to run out. Pick numbers so the old leader always gives up first: for example, it stops after 6 s without a successful renewal, while nobody else can take over until the full 10 s lease expires. That gap closes most of the two-leader window without needing the storage to check anything. (Not all of it — a long garbage-collection pause can freeze the leader past both deadlines, which is why fencing tokens are still the stronger guarantee.)

4. STONITH ("Shoot The Other Node In The Head"). Forcibly power off or network-isolate the old leader. Brutal, effective, used in systems where correctness matters more than anything else.

#The availability gap

Every failover has a window where there is no leader and writes are rejected:

   leader dies
      │  detection (heartbeat timeout)     ~5-30s
      │  election                          ~0.1-1s
      │  new leader initializes, catches up ~1-10s
      ▼
   writes resume                    TOTAL: seconds to a minute

Detection dominates. Everything else is fast. And the timeout is an unavoidable tradeoff:

  • Too short — a leader that's merely busy (slow to send heartbeats under heavy load) gets declared dead. These spurious failovers are themselves an outage, and each switch risks losing writes the old leader hadn't replicated yet.
  • Too long — a leader that really has died leaves you without writes for minutes.

Typical values: 5–15 s for databases where a false failover is expensive, 1–3 s where failover is cheap and quick.

#Doing without a leader

Often the better design. Volunteer these:

1. Partition ownership. Instead of one leader for everything, assign each shard an owner. Losing one owner affects one shard, and throughput scales with shard count. The blast radius — how much of the system breaks when one piece fails — shrinks from everything to 1/N.

   ONE LEADER               PARTITIONED OWNERSHIP
   all writes → A           shard 1 → A    shard 4 → A
   (bottleneck,             shard 2 → B    shard 5 → B
    full outage             shard 3 → C    shard 6 → C
    on failure)             (blast radius = 1/N)

This is how Kafka consumer groups, sharded databases, and cell-based architectures work. It's the single most useful alternative to global leadership.

2. Leaderless replication. Quorums — any node serves any request, conflicts resolved after the fact. No election, no failover gap, at the cost of weaker consistency.

3. Make the work idempotent and let everyone do it. If a scheduled job is idempotent, running it on all N instances is wasteful but correct. For cheap jobs this beats the complexity of election outright — and saying so is a good instinct.

4. Deterministic assignment. Hash the task to an instance: hash("nightly-report") % 3 = 1, so instance 1 runs it. No coordination at all, as long as every instance agrees on the list of instances. Degrades gracefully — while an instance is joining or leaving, two instances may briefly disagree on the list, so a task runs twice or not at all for a moment. That's a duplicate or a brief gap, not corruption.

#Practical checklist

If you propose leader election in an interview, be ready for these:

  • How is the leader elected? Consensus store or Raft — not "highest ID."
  • How long until failure is detected? Give a number and justify it.
  • What happens to in-flight work? Does the new leader resume it, restart it, or drop it?
  • How do you prevent the old leader from acting? Fencing tokens. This is the question the rest of the design has to answer.
  • What's unavailable during election? Be specific — usually writes, while reads continue from replicas.
  • Do you actually need one? The best answer is often partitioned ownership instead.

#The common mistake

Using a leader for the data path rather than the control path.

Routing every user request through an elected leader makes it your throughput ceiling and your blast radius. The right pattern, as with consensus generally:

   CONTROL PLANE (leader, consensus)
     who owns what · membership · config · rebalancing
     → tiny volume, rarely changes, needs to be unambiguous
                    │
   DATA PLANE (no leader on the hot path)
     actual reads and writes, routed directly to the owning shard
     → huge volume, scales horizontally

Keep the leader in charge of decisions, not traffic. That framing answers most leader-election design questions correctly on its own.

#Check yourself

What does a leader really buy you, and what does it cost?Show answer
Serialisation: one node orders all decisions, turning a distributed problem into a single-machine one. Costs: a throughput bottleneck, a single point of failure, and a gap during every election.
How does election with etcd or ZooKeeper work?Show answer
Candidates race to create a key with a lease (etcd) or an ephemeral sequential node (ZooKeeper, lowest number wins, each watching only its predecessor). The store is linearizable, so two nodes can't both win.
How does a majority quorum prevent two leaders being elected?Show answer
Only a partition with more than half the nodes can elect, and two disjoint majorities can't exist. It's also why clusters have odd sizes.
Why isn't quorum election enough to guarantee a single writer?Show answer
The old leader may not know it lost and keep writing. Fencing tokens fix this: each new leader has a higher epoch, and storage rejects writes from older epochs.
What dominates the failover gap, and why tune it conservatively?Show answer
Failure detection — 5–30 s of heartbeat timeout — dominates. Spurious failovers risk losing unreplicated writes, reset connection pools and cold-start caches, so systems that flap are less available than ones that fail over slowly.
Name three ways to avoid needing a single global leader.Show answer
Partitioned ownership (an owner per shard, so blast radius is 1/N); leaderless replication with quorums; making jobs idempotent so every instance can run them; or hashing tasks to instances.
What's the common leader-election design mistake?Show answer
Putting the leader on the data path. Keep it on the control path — membership, ownership, config — and route actual reads and writes straight to the owning shard.

#What to carry forward

  • A leader serialises decisions — simple, but a bottleneck and a failover gap.
  • Elect through a consensus store or Raft with majority quorums, never "highest ID wins".
  • Election doesn't stop an old leader acting: fence at the resource with epoch numbers.
  • Failure detection dominates failover time; tune conservatively, because flapping costs availability.
  • Prefer partitioned ownership, and keep leaders on the control path, not the data path.
00:00
/ 10m