Question presented to candidate:
"What is leader election in a distributed system? Why do so many systems want a single leader, how does a group of servers agree on one, and what goes wrong when the network misbehaves?"
What a strong answer should cover:
Why a leader: one node orders writes, assigns work or owns a resource, which avoids conflicts; examples such as a database primary, the Kafka controller (KRaft) or a Kubernetes controller-manager
The two properties: safety (at most one leader per term) and liveness (a leader is eventually elected); FLP-style limits mean liveness relies on timeouts
The Raft-style mechanism: heartbeats, election timeouts, candidates asking for votes, one vote per node per term, majority wins, higher term always wins
Split votes and why timeouts are randomized; how timeout ranges trade failover speed against repeated elections
The stale leader problem: a paused or partitioned old leader still thinks it leads; majority commits stop it inside the cluster, fencing tokens stop it at external resources
The practical options: built-in consensus (Raft, Paxos, ZAB), a coordination service (etcd, ZooKeeper, Kubernetes Leases) or a database lease, and why the bully algorithm is not partition-safe
Code / implementation expected: Optional โ the election rules in pseudocode, or a small simulation; the example simulates a five-node Raft-style election with a crash, a partition and fencing.
leader-election
2
Try it yourself
Sketch your approach before you read the solution. That is what the interview tests.
Stuck? Get a hint.
A short nudge toward the approach. It will not give the answer away.
3
Solution
Target Audience: Engineers who know what a server, a network and a replica are; consensus is introduced from scratch, and every term is defined as it appears.
Difficulty: Hard
Verified with: Node 22.22, Python 3.12, Go 1.24 and Java 21 (all four print identical output).
How to read this doc: Every idea is explained in plain language first, then tagged with ๐ Interview term: so you also learn the exact words an interviewer expects. Election times, vote counts and failure behaviour come from the example program; the Verified section quotes its full output.
1. Why This Even Matters โ A Story First
Five friends share one holiday budget in a group chat. If everybody books things on their own, two people book the same hotel and nobody books the flights. So they agree that one person, the organiser, makes all bookings, and the others send requests to the organiser