Search

Search papers and lessons

Leader Election

Level 3 · 11 min read

Leader election makes a group of machines pick exactly one coordinator, even when messages are late and machines crash, and the old coordinator is shut out once a new one is chosen.

On this page

  • Colour = topic mix
  • Distributed systems
  • Discrete math
  • Networking
  • Programming languages
  • ReadReady to readNot yet

TL;DR

In a group of machines, one machine often has to coordinate the others: accept writes, hand out work, or own a resource. Leader election is the procedure that picks that one machine and makes sure that no two machines can both win the role in the same term. The hard part is that a silent machine might be dead or only slow, so the group needs a rule that stays safe even when a leader it has replaced is still running.

Builds on: Asynchronous Message Passing, Quorum · Leads to: Distributed Consensus, State Machine-based replication, and the coordination systems built on it

Where it's used

Coordination services. Apache ZooKeeper's core service elects a leader among its replicas, and the leader orders every update the cluster accepts. Clients rely on there being one leader at a time, so the election rule decides whether the service can ever disagree with itself. See the ZooKeeper paper.

Database primaries. A replicated database often has one primary that takes writes while the others follow. etcd, the key-value store behind Kubernetes, runs the Raft protocol, and Raft's first job in every term is electing a leader by majority vote before that leader can write.

Lock services. Google's Chubby lock service keeps a small set of replicas, and one of them holds the master lock. The replica holding the lock is the master, and the others take over only when the lock is released or its lease expires. The Chubby paper describes that lease rule in detail.

Controllers in container platforms. A Kubernetes controller may run as several replicas for safety, and the replicas compete for a Lease object. The one that holds an unexpired lease acts, and the others wait until it expires. The lease period is measured in seconds, which is why failover is not instant.

How it works

Every node knows the list of all nodes. A node that is not the leader can only learn it is alone by waiting. Here is a tiny instance with three nodes, A, B and C. A majority of three is two. A term is a numbered election round; terms only go up. Each node votes at most once per term.

sequenceDiagram
  participant A
  participant B
  participant C
  Note over A: term 1, leader (votes from A and B)
  Note over A: link to B and C fails
  Note over B: no heartbeat for 3 units
  B->>B: start term 2, vote for self
  B->>C: vote request term 2
  C-->>B: vote granted
  Note over B: 2 of 3 votes, leader in term 2
  Note over A: term 1, only reaches itself
  B->>A: heartbeat term 2 after heal
  Note over A: sees higher term, steps down
  1. Start. A is the leader of term 1. It got votes from itself and B, which is a majority of three. A sends B and C a heartbeat every second, and they reset their timers each time one arrives. Check: A holds two of three votes, so the term-1 leadership is valid.
  2. Failure. The network link between A and the other two fails. A is still running and still believes it is leader. Check: from B's point of view, A has stopped answering. From A's point of view, B and C have stopped answering. Neither can tell which side is broken.
  3. Timeout. B hears no heartbeat for 3 time units, its election timeout. It increases its term to 2, votes for itself, and asks C for a vote. Check: B has one of the two votes it needs, so it is not yet a leader.
  4. Vote. C has not voted in term 2, so it grants B's request. B now has two votes out of three, a majority. Check: C's single vote was the only one B needed beyond its own. B is leader in term 2.
  5. Stale write. Meanwhile A, still in term 1, tries to write. It needs acknowledgements from a majority, which means at least one other node. Neither B nor C accepts a term-1 write, so A's write fails. Check: A is the leader only in its own mind; no majority accepts its term.
  6. Heal. The link comes back. B's heartbeat with term 2 reaches A. A sees a higher term than its own, steps down, and becomes a follower. Check: at the end, only B is leader, and only in term 2.

The rule that keeps this safe is step 4 together with step 5: a leader must hold a majority in its term, and each node votes once per term. Silence alone never makes a node the leader. It only starts an election.

The math

Let the group have nn nodes. A majority is any set of more than half of them:

majority size=⌊n2⌋+1\text{majority size} = \left\lfloor \frac{n}{2} \right\rfloor + 1

For n=3n = 3 this is 2. For n=5n = 5 it is 3.

Why two leaders in one term cannot happen. Take two majorities M1M_1 and M2M_2 in the same group of nn nodes. Their sizes add to more than nn:

∣M1∣+∣M2∣≥2(⌊n2⌋+1)>n|M_1| + |M_2| \ge 2\left(\left\lfloor \frac{n}{2} \right\rfloor + 1\right) > n

so they share at least one node. That shared node votes once per term, so it cannot have voted for both leaders in the same term. Two leaders in one term would need two disjoint majorities, and that is impossible.

Terms order the leaders. Each term tt is a whole number, and a node that sees a message with a larger term moves to that term and steps down. This is why the leader in step 6 yields to B: 2 is greater than 1.

Timeouts are guesses. A node starts an election after a randomised timeout TT with no heartbeat. If every node waited the same fixed time, several might start at once and split the votes. Randomisation makes a single starter likely, but never certain, so the algorithm must still handle a tie by waiting and trying again in a later term.

Simpler rule, for contrast. In the bully algorithm, the highest-numbered live node is the leader: a node that notices the leader is silent sends election messages to every higher ID, and if none answers, it declares itself leader. The rule is simple, but it has no majority step, so it can produce two leaders when the network splits.

Worked examples

Example
Example 1: three nodes, who can lead

Three nodes, A, B and C. A majority is 2.

  1. Write down the votes in term 5: A votes for B, B votes for B, C votes for A.
  2. Count the votes for B: 2 (from A and B). Count the votes for A: 1 (from C).
  3. Compare each with the majority of 2. B has 2 and wins. A has 1 and does not.
  4. Interpretation: B is the only candidate with a majority, so B is the only possible leader in term 5.
Example
Example 2: five nodes split by a partition

Five nodes, numbered 1 to 5. A majority is ⌊5/2⌋+1=3\lfloor 5/2\rfloor+1 = 3. The network splits into a group {1, 2} and a group {3, 4, 5}.

  1. The group {1, 2} has two nodes. It can get at most 2 votes, which is less than 3. So it cannot elect a leader.
  2. The group {3, 4, 5} has three nodes. If all three vote for node 3, it gets 3 votes, which is a majority. Node 3 is leader.
  3. Node 1 and node 2 can still run elections, but every one of their elections fails, so they have no leader and their writes are refused. This is the cost of safety: the minority side stops.
  4. Interpretation: during a split only the majority side keeps working, and at most one side can ever have a leader.
Example
Example 3: a lease-based lock with a realistic failover gap

A leader renews a lease every 5 seconds, and the lease lasts 10 seconds. A renews at times 0, 5 and 10. It crashes at time 12. Standby B may take over only after the last lease expires.

  1. The last renewal was at time 10, so the lease runs until 10+10=2010+10=20.
  2. A crashed at time 12. It cannot renew, so the lease will not be extended.
  3. B must wait until the lease expires at time 20 before it may act. Between 12 and 20 there is no leader.
  4. Interpretation: the gap is the lease length minus the time since the last renewal. The lease is a safety tool: it means that A cannot still be acting when B starts, as long as the clocks agree roughly.
  5. Try it: if A renewed every 2 seconds with a 10-second lease, and crashed at time 12, when would B take over? Answer: 20. A renews at 0, 2, 4, ..., 10, and crashes just before its renewal at 12, so the last renewal is at 10 and the lease expires at 10+10=2010+10=20. Renewing more often does not help here; a shorter lease does.

Common mistakes and tradeoffs

It is tempting to think a missing heartbeat means the leader has died. In fact it means only that the leader has been silent for a while. A slow or partitioned leader looks the same from outside, so a correct rule must never let silence alone grant the role.

It is tempting to think that the highest-numbered live node is always a safe choice. In fact a rule that picks the highest ID with no majority can end with two leaders when the network splits. Majority voting, with one vote per term, is what prevents that.

It is tempting to think that once a leader is elected, the others can stop checking it. In fact the old leader may keep running for a while after it has been replaced. The usual fix is a fencing token: each new leader gets a larger number, and the resource it writes to, such as a storage server, rejects any request carrying a smaller number. The stale leader's writes then fail even though it still believes it leads.

Tradeoffs. Leader-based designs are simple to reason about: one node orders the work, and writes have a clear order. The cost is a short unavailable window during failover, and a minority partition that cannot make progress. Leaderless designs avoid the election entirely but spread the ordering problem elsewhere. Byzantine faults, where nodes lie rather than crash, need a different design, covered in Byzantine Fault Tolerance; the rules here assume nodes fail by stopping.

History

The first ring-based election methods were published in the late 1970s. Chang and Roberts described an election on a ring of machines in which the largest ID wins, and Garcia-Molina's bully algorithm followed in 1982, adding messages to any higher ID. Both assumed that a silent node was dead, which is not safe on a real network, so they worked well in theory and caused trouble in practice. Majority-vote protocols such as Paxos, which Lamport described in the late 1980s and published in 1998, showed how to keep safety even when nodes cannot tell slow from dead. The Raft protocol, published in 2014, set out leader election with terms and majorities in a form that engineers could implement, and it is now common in database and coordination systems. Google's Chubby paper in 2006 showed a lock service that picked one master safely and gave the rest of its industry a practical pattern.

Recap

  • A leader is one node that coordinates others. Election picks it, and safety means no two nodes hold the role in the same term.
  • Silence proves nothing. A timeout only starts an election; it never makes a node the leader.
  • A majority of nn nodes is ⌊n/2⌋+1\lfloor n/2\rfloor+1. Two majorities always share a node, and each node votes once per term, so two leaders cannot be elected in one term.
  • A stale leader is stopped by terms, which are checked by the nodes it talks to, and by fencing tokens at the resource.
  • Next, read Distributed Consensus, which generalises election to agreeing on any value, and State Machine replication, which uses a leader to order the log.

Check yourself

QuestionA group of seven nodes uses majority voting. What is the smallest number of votes a leader needs, and why can two leaders not both win in the same term?Show answer

The majority of 7 is ⌊7/2⌋+1=4\lfloor 7/2\rfloor+1=4. Two sets of 4 out of 7 nodes must share at least one node, since 4+4=8>74+4=8>7. That shared node votes once per term, so it cannot give its vote to both candidates. Hence two leaders cannot both win the same term.

QuestionIn the three-node example, B has a majority in term 2. What stops A from acting as leader after the link heals?Show answer

A is still in term 1. When it receives B's heartbeat with term 2, it sees a higher term, steps down to follower, and accepts only the term-2 leader. Its old term-1 leadership carries no authority, because no majority will accept term-1 writes.

QuestionWhy is a missing heartbeat not enough to prove that a leader has crashed?Show answer

A heartbeat can be delayed or lost on a slow or partitioned link, and the leader can still be running. From the other nodes' side, a crashed leader and a silent but healthy one look the same. So a safe rule must check for a majority before it accepts a new leader.

QuestionA team wants failover to take under a second, with leases of 10 seconds. Give one change that helps and one risk it creates.Show answer

A shorter lease, or a faster renewal with a shorter expiry, shrinks the gap after a crash. The risk is more false failovers: a short lease expires during a brief network hiccup while the leader is still running, which is why fencing tokens are still needed for the resource.

Sources