Leader Election in Distributed Systems
Learn how failure detection, quorum-based elections, leases, and fencing tokens affect safety and stale writes in distributed systems.
Leader election selects a coordinator, but a timeout only signals suspicion that the current leader may be unavailable. Safe coordination depends on protocol rules, quorum assumptions, and how the protected resource validates writes. This guide compares simple elections, leases, and consensus, then shows how fencing tokens reject writes from a paused former leader.
Leader Election in Distributed Systems
Introduction
In distributed systems, some protocols use a coordinator to sequence operations or make decisions. Leader election chooses that coordinator while nodes can crash, pause, or lose contact across a network partition.
An election timeout cannot tell a crashed process from a slow one. Two processes can temporarily believe they are leader, so the protocol and the system that accepts writes must decide which one has authority.
Core concepts
Many distributed protocols use a leader to sequence updates to a replicated log. Followers accept entries under the protocol’s term and commit rules; a leader title by itself does not make writes safe.
If the leader stops responding, the cluster needs to recover without accepting conflicting committed histories. Consensus protocols protect their replicated state with rules such as terms, voting, and quorum commits. An external database or storage service does not automatically inherit those protections.
Basic approaches
Highest node ID
In a simple priority election, nodes can prefer the highest ID among the members they can contact. That is a selection rule, not a safety guarantee: a partition can leave two groups with different views of membership, and an old leader can keep running.
Randomized delays can reduce simultaneous election attempts. Raft also randomizes election timeouts, but its safety comes from term-based voting, log checks, and majority rules, not from node IDs.
IDs are typically configured in a membership list. Every participant needs the same membership view for a priority rule to select the same candidate. A total order on IDs cannot resolve a network partition on its own.
Do not confuse this rule with Raft. In Raft, a timeout makes a follower suspect that the leader is unavailable. The follower increments its term, votes for itself, and requests votes. Servers vote at most once per term, and a candidate needs votes from a majority plus an up-to-date log to win. Randomized timeouts help resolve split votes; they do not establish correctness by themselves. See the Raft paper for the election and safety rules.
There is no timeout that works as proof of death in an asynchronous network. A shorter timeout can improve recovery after a crash, but it also increases false suspicions when messages are delayed or a process is paused. Tune timeouts against measured latency and the protocol’s documented requirements rather than assuming a fixed maximum network delay.
Bully algorithm
The bully algorithm works straightforwardly: when a node suspects the leader is down, it sends election messages to every node with a higher ID. If none reply within a timeout, it announces itself as leader. The name fits because the highest-ID node always wins, no matter who started the election.
The algorithm then moves up the ID list. A node that receives an election message from a lower-ID peer replies with OK and starts its own election. The node that receives no OK responses from higher-ID nodes wins and broadcasts a coordinator message to all lower-ID nodes.
The algorithm assumes a synchronous network: nodes need a useful bound on message delay to distinguish an unavailable peer from a slow one. A private cluster can still see long scheduler pauses or network disruptions, so it does not remove that assumption.
Message complexity is O(n^2) in the worst case. If nodes initiate elections in descending ID order, each one sends messages to all higher-ID nodes before failing. For small clusters this is fine. At scale, the overhead becomes a problem, which is why consensus-based approaches dominate in production systems.
Bully algorithm sequence diagram
In the bully algorithm, the highest-ID node always wins by forcing younger nodes out of elections:
sequenceDiagram
participant N1 as Node 1 (ID=1)
participant N3 as Node 3 (ID=3)
participant N5 as Node 5 (ID=5)
participant N7 as Node 7 (ID=7)
Note over N1,N7: Node 7 (current leader) crashes
N1->>N3: ELECTION
N3->>N5: ELECTION
N5->>N7: ELECTION
Note over N7: No response — Node 7 is down
N5->>N1: OK(ID=5)
N5->>N3: OK(ID=5)
Note over N5,N1: N3 and N1 acknowledge N5
N5->>N1: COORDINATOR(ID=5)
N5->>N3: COORDINATOR(ID=5)
Note over N5,N1: N5 becomes leader
Leader election algorithm comparison
| Algorithm | Time Complexity | Message Complexity | Assumptions | Best For |
|---|---|---|---|---|
| Highest-ID | Depends on detection | Varies | Shared membership view | Priority selection only |
| Bully | O(n) worst case | O(n^2) worst case | Timely message delivery | Small teaching examples |
| Lease-based | Lease-expiry delay | Implementation-specific | Lease service and expiry assumptions | Temporary ownership |
| Consensus-based | Timeout plus election | Protocol-specific | Fixed membership and majority quorum | Replicated durable state |
| Algorithm | Safety boundary | What happens without it |
|---|---|---|
| Highest-ID | None unless writes are fenced | A partition can leave multiple active leaders |
| Bully | Assumes participants can communicate | A delayed response can look like a failed node |
| Lease-based | Lease service plus resource-side checks | An expired holder may keep running |
| Consensus-based | Majority and protocol commit rules | Minority cannot commit new entries |
Lease-based leadership
A more sophisticated approach uses leases. Rather than claiming leadership forever, a node holds leadership for a fixed period (the lease). To renew leadership, it must successfully extend the lease before it expires.
sequenceDiagram
participant L as Leader
participant F1 as Follower 1
participant F2 as Follower 2
rect rgb(40, 60, 40)
Note over L,F2: Leadership with Lease
L->>F1: Heartbeat + Extend Lease
L->>F2: Heartbeat + Extend Lease
F1-->>L: ACK
F2-->>L: ACK
Note over L: Lease valid for next 10s
end
rect rgb(80, 40, 40)
Note over L,F2: Lease Expires
L-xF1: Heartbeat (fails)
L-xF2: Heartbeat (fails)
Note over F1: Lease expired, starts election
end
Leases provide a form of eventual leader detection. If the leader fails to extend its lease (because it crashed or is network-partitioned), other nodes will notice after the lease expires and initiate an election.
Lease expiry helps the coordinator decide when another candidate may take over. It does not stop a paused or partitioned former holder from resuming and sending a delayed write to another service. Clock and process pauses make this possible even when both clients use the same lease duration. The protected resource must reject stale owners, or the operation must be safe to repeat and reconcile.
One common defense is a fencing token: each successful ownership grant gets a strictly increasing number. The storage service remembers the greatest token it has accepted and rejects writes with a lower token. The token only protects the resource if that resource checks it. Google’s Chubby paper describes sequencers containing a lock generation number that a recipient server validates. etcd also documents that lease ownership alone does not guarantee mutual exclusion for an external resource; its lease guidance explains the need to validate operations.
Consensus-based election
Consensus protocols such as Raft use elections as part of agreeing on a replicated history. In Raft, a candidate wins a term by receiving a majority of votes, subject to log freshness rules. The quorum intersection and log rules protect committed entries; a minority partition cannot commit new entries. This does not automatically fence writes to an unrelated external system.
Failure detection and election safety
Failure detection answers, “Have I heard from the leader recently?” It does not answer, “Has the leader stopped?” Heartbeat timeouts are suspicions. Network delay, a long process pause, or a partition can all look like a crash.
Heartbeats: A leader periodically contacts followers. If a follower misses the protocol’s timeout, it may start an election. That lets the cluster recover, but it does not revoke the old process’s ability to execute code.
Terms or epochs: A consensus group can reject stale protocol messages after a newer term is established. This protects the group’s own state machine. For writes to an external database, pass a fencing token and make the database validate it; a process cannot be trusted to stop itself after losing contact with the election service.
Practical considerations
In practice, durable leader election should usually come from an established consensus-backed coordination service, such as etcd or ZooKeeper. Their election primitives manage leadership within the coordination system; your application still needs to handle lease loss and protect any external resource it writes.
A custom election protocol has to handle simultaneous elections, network partitions, and reordered messages. Those cases are easy to miss. My post on Distributed Transactions discusses coordination when a workflow spans multiple services.
Timeout selection guidance
Picking election timeouts is a balancing act. Set them too short and you get spurious elections from transient network hiccups. Set them too long and you maximize downtime during an actual failure.
There is no universal election-timeout value. Start with the coordination system’s documented defaults, then measure heartbeat delays, scheduler pauses, and network latency under expected load. A short timeout can cause avoidable elections; a long timeout delays failover. Raft uses randomized timeout ranges to reduce split votes, but application choices should follow the deployed implementation’s guidance rather than copy a number from another cluster.
Randomized timeouts reduce the chance that several candidates start together. They improve liveness after a suspected failure; quorum and protocol rules provide election safety. The Raft paper describes both the timeout and majority-vote behavior.
Relationship to consensus
Leader election chooses a coordinator; consensus decides which values become part of a replicated history. Raft specifies both election and log-replication rules. Paxos is a separate family of protocols, and its phases should not be described as Raft election phases. The Raft Consensus Algorithm post goes into more detail.
Quick recap checklist
- Leader election designates one node as coordinator across a distributed system
- The bully algorithm selects by ID under its communication assumptions; it does not protect writes to an external resource
- Ring-based approaches circulate tokens; O(n) with fewer messages than bully
- A lease can expire while its former holder is paused; fence writes at the resource that receives them
- A consensus protocol protects its replicated log through terms, voting, and quorum rules
- A majority quorum can commit while a minority partition cannot; this does not fence unrelated services
- Randomized timeouts reduce the chance that candidates start together
- Terms reject stale protocol messages inside a consensus group, not arbitrary writes to an external database
- For durable coordination, start with an established consensus-backed service and validate its guarantees against your workload
Production failure scenarios
Scenario 1: etcd leader failure during peak traffic
When an etcd leader fails, the cluster uses its timeout-based failure detector to elect a replacement. It can take about an election timeout, and the cluster cannot process writes during the election. A client request may time out without the client knowing whether it committed, so retries should be idempotent or check the operation’s result. The etcd failure guide describes these behaviors.
Scenario 2: ZooKeeper lease expiration during network jitter
A client that cannot reach ZooKeeper may pause long enough for its session to expire. The client can resume and still have queued work, even though ZooKeeper has already removed its ephemeral session state and another client may hold leadership. Handle session expiration as loss of ownership, reconnect, and reacquire before continuing. Any external writes still need resource-side fencing; a session event cannot retract a delayed request already sent elsewhere. See the ZooKeeper session documentation.
Scenario 3: Cassandra gossip-based election during split
Cassandra does not elect one leader for ordinary writes. Gossip helps nodes track cluster membership and detect failures; each request’s coordinator contacts replicas, and the selected consistency level determines how many acknowledgments it needs. QUORUM counts replicas for the keyspace, while LOCAL_QUORUM requires a quorum in the coordinator’s local data center. During a partition, one local quorum may be reachable while another is not. See Apache Cassandra’s failure-detection guarantees and consistency-level overview.
Scenario 4: Redis Sentinel false positive election
Sentinel decides that a primary is down from missed replies, so network delay or a long process pause can trigger a failover even if the old primary is still running. A configured quorum marks the primary objectively down; a majority of Sentinels must then authorize one Sentinel to perform failover. A client isolated with the old primary may still write to it during the partition. When the partition heals, Sentinel reconfigures the old primary as a replica, and those divergent writes can be discarded. Redis recommends at least three Sentinels on independent machines for a robust deployment. See the Sentinel quorum and partition behavior.
Split brain and quorum
The fundamental challenge is that a partition or long pause can leave an old process running after a new leader takes over. A timeout alone cannot prevent both processes from attempting work.
sequenceDiagram
participant A as Leader A (token 41)
participant C as Coordination service
participant B as Leader B (token 42)
participant S as Storage service
A->>C: Holds lease
Note over A: Process pauses; lease renewal stops
C->>B: Lease expires; B wins leadership
B->>S: Write with token 42
S-->>B: Accept; highest token is now 42
A->>S: Delayed write with token 41
S-->>A: Reject stale token
If storage does not compare fencing tokens, A’s delayed write may be accepted after B has taken over. The token must be attached to every protected write, and the resource must store and enforce the highest accepted value.
In a Raft-style consensus group, a candidate needs a majority in the current term, and only a majority can commit new entries. The Raft paper describes the election-safety property and majority requirement; etcd’s glossary defines quorum as a member majority. This assumes the group has a consistent membership configuration and clients treat only committed results as durable. A quorum does not protect writes made directly to another service.
If the system uses quorum-based replication such as Raft, a minority partition cannot commit new log entries. That protects the replicated state from two conflicting committed histories, but it does not stop an isolated old leader from attempting side effects against an external service.
If the system relies on a single leader without quorum guarantees (like primary-backup replication without a quorum), split brain can cause data divergence. One partition might apply writes that the other partition does not know about.
Understanding these trade-offs connects to the CAP Theorem. A system that keeps accepting writes on both sides of a partition may need to reconcile divergent updates afterward.
Interview questions
- Leader election designates a single node as coordinator across a set of distributed nodes
- Needed because many protocols assume a single coordinator to sequence operations, avoid conflicts, and make decisions
- Without it, multiple nodes could concurrently attempt to coordinate, leading to split brain or data divergence
- The challenge: nodes can crash, networks can partition, and messages can be delayed or reordered
- Nodes form a logical ring; each knows its successor
- When the leader drops, a token walks the ring collecting node IDs
- Highest-ID collector becomes leader and announces the win around the ring
- O(n) time and O(n) messages—same complexity as bully but fewer messages in practice
- A delay or partition can leave an old process working after another node wins leadership
- A consensus quorum prevents two conflicting committed histories inside its replicated log
- A fencing token must also be checked by any external database or storage service
- Leader election picks a node; consensus agrees on a value—different problems
- Raft uses terms, majority voting, and log-freshness checks to elect a leader for its replicated log
- Paxos is a separate consensus protocol family; its phases are not Raft election phases
- Consensus protects the replicated state, while external side effects need their own validation
- Leader crashes and every node whose timeout fires at roughly the same moment tries to become leader
- Result: burst of election messages, network congestion, possible delays in recovery
- Randomized timeout ranges reduce the chance that candidates start an election together
- They improve recovery after a suspicion; majority voting provides Raft's election safety
- Leader holds the role for a fixed duration (the lease) rather than indefinitely
- Must renew before expiration or loses leadership automatically
- If the leader crashes or gets partitioned, the lease expires and others start a new election
- A lease service can transfer ownership after expiry, but a paused former holder can still resume
- For writes to another service, attach a fencing token and have that service reject stale values
- Nodes start as followers; if no heartbeat arrives within election_timeout, they become candidates
- Candidate increments its term, votes for itself, and sends RequestVote to every other node
- A candidate needs a majority and an up-to-date log; randomized timeouts reduce repeated split votes
- A higher term makes a server step down within the Raft group, not at an unrelated database
- The specific timeout range depends on the deployed implementation and network conditions
- Too aggressive: transient network hiccups trigger spurious elections, wasting resources
- Too lenient: real failures sit undetected while the system limps along
- Heartbeats are the standard: leader sends periodic pings; miss N in a row and a follower starts an election
- Terms help consensus participants reject stale protocol messages; they do not revoke an external process's access
- Quorum systems (Paxos/Raft): writes to the minority partition fail to reach consensus—data stays safe but that partition can't make progress
- Primary-backup without quorum: split brain becomes possible since each partition applies writes independently
- The core tension is availability versus consistency, straight out of CAP
- Quorum gives stronger guarantees but needs a majority of nodes up at all times
- Standard ring circulates a token collecting all IDs; Chang and Roberts optimizes this by forwarding only the highest ID seen
- The highest-ID in the ring wins—token circulates at most once instead of potentially many times
- More efficient when IDs are uniformly distributed; still assumes reliable delivery and synchronous communication
- Binary consensus resolves a single bit: should this value be 0 or 1?
- Multi-Paxos uses binary consensus as a building block for deciding each log entry
- Leader election can be expressed as repeated binary decisions: should node X be leader? Y? Z?
- Those repeated decisions ultimately establish a total order—essentially the sequence of proposals a leader makes
- Start with the coordination service's documented timeout and heartbeat settings
- Measure network latency and process pauses under expected load
- Short timeouts speed recovery but can cause false suspicions; longer timeouts delay failover
- No timeout proves that a remote process has stopped
- When several nodes coordinate durable state and the system must preserve one committed history
- When a majority quorum is available and minority partitions can stop making progress
- When the team wants an established election implementation instead of a custom protocol
- External storage still needs fencing or conditional writes to reject a stale leader
- In Raft, a higher term makes servers reject stale protocol messages and step down from old leadership
- This protects the Raft group's log and state machine
- An unrelated database cannot see that term unless the application passes a token to it
- Use a fencing token or conditional write for that external resource
- Lease-based election can transfer ownership after expiry, but a paused old holder may still try to act
- Consensus-based protocols need a majority to elect a leader and commit new entries; a minority cannot make progress
- Use resource-side fencing when either approach controls writes outside its own coordination system
Further reading
- Raft Consensus Algorithm - In-depth coverage of Raft’s leader election and log replication
- CAP Theorem - Understanding how consistency and availability trade-offs affect leader election design
- Distributed Transactions - How leader election interacts with two-phase commit and Saga patterns
- etcd Documentation - Production-grade coordination service using Raft
- ZooKeeper Internals - Original leader election implementation and use cases
Conclusion
Leader election is one part of coordination. Failure detection helps a system react when communication stops, while protocol rules and resource-side checks determine whether a new leader can safely act. Leases help transfer ownership; fencing protects writes from a former holder that wakes up late.
Decision guide
- No durable shared writes? A simple election may be enough for best-effort work that can be repeated or discarded.
- Several nodes coordinate durable state? Use a proven consensus-backed service such as etcd or ZooKeeper. Follow its documented election and quorum rules instead of implementing a custom protocol.
- The leader writes to an external database, object store, or device? Add a monotonically increasing fencing token or conditional write that the destination itself validates. A lease or leadership watch alone is not a write fence.
- Can the destination not enforce ownership? Make operations idempotent and design reconciliation for overlapping or delayed work; do not assume the old process has stopped.
For etcd, the election API exposes a leader key revision that can be checked transactionally inside etcd. For an external destination, pass an ownership generation with each write and have the destination reject older generations. See the etcd election API reference and Google’s Chubby sequencer design.
Category
Related Posts
ZooKeeper 3.9.7: Choosing a Coordination Service
Choose ZooKeeper or another coordination service, then run a ZooKeeper 3.9.7 leader-election lab and observe how losing quorum affects writes.
The FLP Impossibility Result
The FLP result shows that deterministic consensus cannot guarantee termination in a fully asynchronous message-passing system with one possible crash failure.
Paxos Consensus Algorithm
Paxos is a family of consensus algorithms for achieving agreement in distributed systems despite failures, pioneered by Leslie Lamport.