Leader election in system design interviews
Leader election is how a group of servers agrees that exactly one of them is in charge of something, such as accepting writes, assigning work or running a scheduled job, and how they pick a replacement when that one stops responding. In interviews the hard part is not the vote itself but the edge cases: a leader that is slow rather than dead, a network split into two halves, and an old leader that wakes up still thinking it is in charge.
By Evin JohnPublished 9 min read
1. What leader election solves
Many jobs are easier with one decision-maker. A database replica set takes writes on one node so that every follower applies them in the same order. A cron-style scheduler should fire each job once, not once per server. In many message brokers, each partition has one leader replica that takes its writes. In each case several machines are capable of the role, so the system needs a rule for choosing one, a way to notice when it fails and a way to hand the role over without ending up with two.
Election is a special case of consensus: the nodes must agree on one value (who leads for this round) even when some of them crash or messages are lost. That link explains why the well-known solutions all reuse majority voting.
2. Why interviewers care
The phrase "the leader handles writes" appears in most designs with replication, and it hides several assumptions. Interviewers probe them to see whether you understand failover: how long the system is unavailable for writes, whether acknowledged data can be lost, and what stops a split network from producing two leaders that both accept writes. For a job scheduler the same probe becomes "what stops a job from running twice?".
3. Detecting that the leader is gone
Followers learn the leader is alive from heartbeats: small periodic messages, or the normal replication traffic. If none arrives within a timeout, a follower assumes the leader is dead and starts an election. The timeout is a trade-off you should be ready to state.
| Timeout | Good | Bad |
|---|---|---|
| Short (sub-second to a couple of seconds) | Fast failover, short write outage | A garbage-collection pause or a slow network triggers needless elections, and frequent elections are their own outage |
| Long (tens of seconds) | Few false alarms | A real crash leaves the system without a leader for longer |
No timeout is perfect, because in an asynchronous network a slow node and a dead node look the same from outside. Design as if a deposed leader may still be running and may still try to act. That assumption drives most of what follows.
4. The algorithms, briefly
| Approach | How the leader is chosen | Weakness |
|---|---|---|
| Bully algorithm | Every node has an ID; a node that suspects the leader messages all higher IDs, and the highest live ID wins | Assumes reliable failure detection; a partition can produce a leader on each side |
| Ring election | An election message circulates around a logical ring collecting live IDs; the highest becomes leader | Slow on large rings and fragile when ring members fail mid-election |
| Majority vote with terms (Raft-style) | A follower whose timeout expires increments the term, votes for itself and asks the others; a node grants at most one vote per term; a majority wins | Needs a majority to be reachable; the minority side cannot elect anyone |
| Lease from a coordination service | Candidates race to create a key or lock with a time-to-live; the holder leads while it keeps renewing | Depends on the service's own correctness and on fencing for slow holders |
The Raft paper (Ongaro and Ousterhout) describes the majority approach in a form that is easy to explain aloud. Time is divided into numbered terms. Each follower waits a randomized election timeout, often quoted in the range of 150 to 300 milliseconds in the paper's examples, so that usually one node times out first and wins before others start competing. A candidate needs votes from a majority of the cluster, and each node votes once per term, so two candidates cannot both win the same term. Raft adds one more rule interviewers like: a node refuses to vote for a candidate whose log is behind its own, so a newly elected leader already has every committed entry.
class Node:
def __init__(self, nid):
self.id, self.term, self.voted_for = nid, 0, None
def request_vote(self, term, candidate):
if term > self.term: # newer term: forget the old vote
self.term, self.voted_for = term, None
if term == self.term and self.voted_for in (None, candidate):
self.voted_for = candidate
return True
return False
class Storage:
"""Accepts writes only from the newest term it has seen."""
def __init__(self):
self.highest_term = 0
def write(self, term, value):
if term < self.highest_term:
return f"rejected {value!r} from stale term {term}"
self.highest_term = term
return f"stored {value!r} at term {term}"
s = Storage()
print(s.write(2, "from new leader")) # stored 'from new leader' at term 2
print(s.write(1, "from old leader waking up")) # rejected ... from stale term 1We checked the vote rule with 2,000 randomized runs: in a five-node cluster, two candidates start the same term and each of the other three nodes receives both vote requests in a random order. One candidate or the other won every run (1,029 and 971 times) and no run produced two winners. That is the majority argument in action: two majorities of five always share at least one voter, and that voter only votes once per term.
5. Using a coordination service instead
Application teams rarely implement Raft. They borrow a store that already runs consensus and build election on top of it.
- ZooKeeper-style ephemeral sequential nodes. Each candidate creates a node under an election path; the service numbers them and deletes a node when its session expires. The lowest number leads. Each other candidate watches only the node just ahead of it, so a leader's death wakes one successor rather than the whole herd.
- etcd or Consul-style leases. A candidate writes a leader key attached to a lease with a time-to-live, using a create-if-absent transaction. The holder renews the lease while healthy; if it stops, the key disappears and another candidate can claim it. Client libraries for these stores offer election helpers built this way.
- A database row as a lease. For modest needs, a row with leader_id and expires_at, claimed with a conditional update, works fine. Its availability is the database's availability.
- Kubernetes leases. Controllers running several replicas commonly elect one active instance through a Lease object in the cluster's API, which is itself backed by etcd.
6. Split brain and the stale leader
Split brain means two nodes act as leader at once. Majority rules stop it inside the election: in a five-node cluster split three and two, only the side with three can elect anyone, and the two-node side stops accepting writes. That is why clusters use odd sizes (three tolerates one failure, five tolerates two) and why a two-node cluster cannot fail over safely on its own.
Elections do not stop the second case: a leader that paused for twenty seconds (a long garbage collection, a frozen virtual machine), lost its lease meanwhile and then resumes mid-write without knowing it was replaced. The cure is to make the leader's term number travel with every write it sends, and to have the storage or downstream service remember the highest term it has accepted and refuse anything older. The term then acts as a fencing number. A lease on its own cannot do this, because the paused process does not know time has passed. (Fencing with tokens is the same idea applied to locks; the consistency guide mentions it for job claims.)
- Old leader A
- Leads in term 4
- Pauses
- Resumes; writes with term 4
- Sees term 5; steps down
- Cluster
- Heartbeats stop
- B wins votes for term 5
- Storage
- Accepts B's write (term 5)
- Rejects A's write (term 4 < 5)
7. What failover costs
- A write gap. From the leader's death until a new leader is elected and clients find it, writes fail or queue. Detection timeout plus election time plus client rediscovery is the number to estimate.
- Possible data loss with asynchronous replication. If the old leader acknowledged writes that never reached the follower that took over, those writes are gone. Synchronous replication to at least one follower, or a consensus log, closes this at a latency cost.
- A thundering reconnect. Every client discovers the new leader at once. Jittered retries help.
- The leader as a bottleneck. One node takes all the writes for its scope. If that is too much, split the scope: one leader per shard or per partition, which is how many partitioned systems spread the load.
8. When you do not need a leader
Leaderless replication, as in Dynamo-style stores, lets any replica take writes and reconciles later, trading a single order for availability. Work distribution can often use partitioned ownership (consistent hashing of job IDs to workers) or a queue where each message goes to one consumer, so no leader is needed to assign work. And if a job is idempotent, running it twice in a rare failover may be acceptable, which removes the need for a strict single runner.
9. How it shows up in common prompts
| Prompt | What the leader owns | The question to expect |
|---|---|---|
| Job scheduler | Firing due jobs, or assigning shards of the schedule | How do you stop a job firing twice during failover? |
| Sharding | Writes for each shard's replica group | What happens to writes on a shard while its leader fails over? |
| Rate limiter | Usually nothing: counters live in a shared store | Why not elect a leader to count? Because it becomes the bottleneck |
| Collaborative editor | Ordering edits for one document on one server | How do you move a document's session when its server dies? |
10. Interview questions on leader election
| Question | Core of a good answer |
|---|---|
| How do followers know the leader died? | Heartbeats and a timeout, which is only a suspicion |
| Why does Raft randomize election timeouts? | So one node usually starts first and wins before others split the vote |
| Why can't two leaders win the same term? | Each node votes once per term and any two majorities overlap |
| A network splits a five-node cluster 3 and 2. What happens? | The three-node side elects or keeps a leader; the two-node side cannot and stops writes |
| Why run three or five nodes, not four? | Four tolerates one failure, like three, while needing a larger majority |
| The old leader was only paused. How do you stop its writes? | Tag writes with the term; downstream rejects lower terms |
| Would you implement election yourself? | No: use a coordination service or a database lease, then fence |
| How long is the system unavailable during failover? | Timeout plus election plus client rediscovery, with an estimate |
11. Mistakes to avoid
- Treating a timeout as proof of death. It is a guess; the old leader may still act.
- Leases with no fencing. A paused holder can resume after its lease expired and corrupt data.
- Even-sized clusters, or two nodes with automatic failover. Without a majority, a split either stops both sides or crowns two leaders.
- One global leader for everything. It caps write throughput; elect per shard or per partition.
- Ignoring replication mode. Failover with asynchronous replication can drop acknowledged writes; say whether that is acceptable.
12. How to talk about it in the interview
- Say what the leader owns and why one owner helps here.
- Name the mechanism you would use, usually a coordination service or a consensus-replicated store, rather than describing a homemade protocol.
- State the failover time and the data-loss window in numbers.
- Close with the stale-leader case and how terms or fencing handle it.
Fictional example
- Interviewer
- You run three instances of the nightly billing report service for availability. How do you make sure only one generates the report?
- Candidate
- They elect a leader through the etcd cluster we already run: each instance tries to create a leader key bound to a ten-second lease, and whoever succeeds keeps renewing it. Only the leader starts the report.
- Interviewer
- What if the leader freezes for a minute and then continues?
- Candidate
- Its lease expires and another instance takes over with a higher revision number from etcd. Each report run writes its output with that number, and the report table rejects a write carrying an older one, so the frozen instance cannot overwrite the new run. The report step is also idempotent per billing date, so a rerun replaces the same rows.
Talking through failover with Natively
Failover answers sound fine in your head and fall apart when spoken, usually at the paused-leader question. Run the scenario as a timed mock with a peer and let Natively transcribe it on your computer. During the call you can ask it for a suggested answer or for follow-up questions the interviewer might ask next; if you capture a screenshot of the timeline you sketched, it can explain or critique what it shows. Reading the transcript afterwards is the honest check: did you give a failover time, or only say "another node takes over"?
Questions people ask
What is leader election in distributed systems?
It is the process by which a group of servers agrees that exactly one of them holds a role, such as accepting writes or running scheduled jobs, and picks a replacement when that server stops responding. It is a form of consensus, so practical solutions rely on majority votes or on a coordination service that already runs consensus.
How does Raft elect a leader?
A follower that hears no heartbeat within a randomized timeout increments the term number, votes for itself and asks the others for votes. Each node votes at most once per term and refuses candidates whose log is behind its own. The candidate that gathers a majority becomes leader for that term.
What is split brain and how do you prevent it?
Split brain is two nodes acting as leader at the same time, usually after a network partition. Requiring a majority to elect a leader means only one side of a split can have one. A leader that was merely paused is handled by tagging its writes with its term and having storage reject older terms.
Should I implement leader election myself in an interview design?
Usually not. Say you would use a coordination service such as ZooKeeper, etcd or Consul, or a lease row in a strongly consistent database, then explain how its leases work and how you fence writes from a stale leader. Interviewers care more about the failure cases than about the algorithm's code.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
