Skip to content

Leader election: when to use it and how it works

Leader election is how a group of machines with no leader picks exactly one of themselves to coordinate the rest, and picks again when that one fails. Reach for it only when the work needs tight coordination or a single source of truth for writes, because it adds complexity and a new way to fail. This page covers when to use it, how two well-known approaches work, what else can do the job and four checked problems.

Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.

Book your first hour ($250)

What a leader is for

Most services scale by adding machines that each answer whatever requests reach them, and for that no leader is needed. Some work needs one machine in charge: handing out pieces of a large job and gathering the answers, deciding which node owns which task, or accepting every write to a record so that readers never see two conflicting versions. In those cases the cluster keeps one node as leader and the others as followers, and an election is the procedure that chooses the leader when the cluster starts and again whenever the leader stops responding.

Typically each node is in one of three states: leader, follower or candidate. The leader sends a regular heartbeat, a small message that says it is alive. A follower that stops hearing heartbeats for long enough turns candidate and asks the others for support.

When it fits and when it does not

Use it or not
SituationLeader election?Reason
Nodes are interchangeable and each can serve requests aloneNoThere is nothing to coordinate, so a leader is only a single point of failure
One job must be divided among nodes and the results combinedYesSomeone has to assign the pieces and assemble the answer
Many writes to shared data must give every reader the latest versionYes, or use a store that does it for youThe leader is the one place that defines the latest state
Two nodes sometimes touch the same recordOften a lock or a version check is simplerSee the alternatives below

The costs are real. A badly built election can produce two leaders at once or none at all. With one machine in charge, all the traffic for its job funnels through it, and followers do what it says even when it is wrong. And a cluster that must all follow one leader is harder to update a few machines at a time or to run experiments on. Use election only when the need for coordination or strong consistency is clear and no alternative fits.

Two approaches you may be asked to describe

The bully approach

Every node has a unique number and knows everyone else’s. When a node finds the leader missing, it sends an election message to every node with a higher number. If none of them answers, it declares itself leader and tells the rest. If one answers, that node takes over the election in the same way. The highest-numbered live node always ends up the winner, which is simple to explain. The weaknesses are the number of messages, which grows with the square of the cluster as Problem 3 shows, and that a high-numbered node that keeps crashing and returning takes leadership back each time and forces a new election.

The Raft approach

Raft is a consensus algorithm designed to be easier to understand than earlier ones. Time is divided into numbered terms. A follower that hears no heartbeat before its timeout adds one to the term, becomes a candidate and asks for votes. A candidate that gathers votes from a majority of the cluster becomes the leader for that term, and a candidate that sees a higher term steps down. The timeouts are randomized so that nodes seldom start at the same moment, and if votes split, the nodes simply try again. The Raft paper, In Search of an Understandable Consensus Algorithm, describes the election in just these terms and adds that each server votes for at most one candidate in a term. The Raft project’s own page says consensus algorithms typically make progress while any majority of servers is available, so that a cluster of 5 servers keeps working if 2 fail, and that with more failures they stop making progress but never return a wrong result.

The majority rule is the key idea. Two candidates cannot both collect more than half the votes, so there is at most one leader per term. Problems 1 and 2 turn it into counts. The rule also explains why clusters use odd sizes: a cluster of 2f + 1 tolerates f failures, and adding a node to make an even number adds cost without letting the cluster survive one more failure.

Other well-known options are Paxos, an older consensus protocol, and ZooKeeper’s atomic broadcast, which a shared coordination service uses internally. The usual advice is to use one of these through an existing library or service and not to write an election yourself, since the details are easy to get wrong. Google’s site reliability book gives the topic its own chapter, Managing Critical State: Distributed Consensus for Reliability, which signals how deep it goes.

Safety and liveness

Two promises matter. Safety means there is never more than one leader. Liveness means an election eventually finishes. When messages can be delayed without limit, no algorithm can promise both at once, and real systems keep safety and accept that an election may take a few rounds. Say this sentence in an interview and you have shown you understand the trade.

Ways to coordinate without a leader

Alternatives to an election
ApproachHow it worksWatch for
Optimistic lockingRead a record with its version number, change it, and write back only if the version is unchanged; otherwise retryMany retries when contention is high
Pessimistic lockingTake a lock, change the record, release the lockDeadlocks and locks that are never released
Idempotent requestsGive each request an id so that a repeat has no further effectThe id has to be stored and checked
A workflow engineA central service holds the steps and the state and assigns the workThe engine is a dependency of its own

A note on who needs this. Our system design for interns guide found no system design round named in our program records, and a first internship interview is mostly coding, your projects and behavioral questions. This page is for students who are curious, who have a design question in a course or a project, or who are looking ahead to a new-graduate loop. If a recruiter says there will be a design round, ask what scale it expects and prepare for that.

Practice problems

These problems are our own, written for this site. Every answer is recomputed when the site is built, and a wrong answer would stop the build. Try each before you open the steps. Read how the problems are checked.

Problem 1. A cluster has 7 nodes. A candidate becomes leader only when it holds votes from a majority of all 7 nodes, counting its own vote. What is the fewest votes that win? Give an integer.

Show the answer and the working

Answer: 4

  1. A majority of 7 is more than half of 7, which is more than 3.5.
  2. The smallest whole number above 3.5 is 4.
  3. Two candidates cannot both reach 4 votes, because 4 + 4 = 8 is more than the 7 nodes that exist. That is why a majority rule gives at most one leader in a term.

Problem 2. A cluster must still be able to elect a leader after any 3 nodes fail, which means the surviving nodes must be a majority of the original cluster. What is the smallest cluster that meets this? Give an integer.

Show the answer and the working

Answer: 7

  1. With n nodes and 3 failures, n - 3 nodes survive, and they must be more than n / 2.
  2. Try n = 6: 3 survive, which is exactly half of 6, not more than half.
  3. Try n = 7: 4 survive, which is more than 3.5.
  4. So 7 is the smallest. In general a cluster of 2f + 1 nodes tolerates f failures.

Problem 3. Nodes have ids 1 to 9 and node 9, the leader, has failed. Node 4 notices and starts an election by sending an election message to every node with a higher id, dead or alive. Every live node that receives such a message starts one election of its own and sends an election message to every node with a higher id. Ignoring replies, how many election messages are sent in all? Give an integer.

Show the answer and the working

Answer: 15

  1. Node 4 sends to 5, 6, 7, 8 and 9: 5 messages.
  2. Nodes 5, 6, 7 and 8 each start an election. Node 5 sends to 6 to 9: 4 messages. Node 6 sends 3, node 7 sends 2 and node 8 sends 1.
  3. The total is 5 + 4 + 3 + 2 + 1 = 15.
  4. The cost grows with the square of the cluster, which is one reason large clusters use other algorithms.

Problem 4. The leader sends a heartbeat every 150 milliseconds. A follower starts an election when it has missed 3 heartbeats in a row. The leader sends a heartbeat at time 0 and crashes immediately afterward. At what time, in milliseconds, does the follower start an election? Give an integer.

Show the answer and the working

Answer: 450

  1. The heartbeats that should arrive are due at 150, 300 and 450 milliseconds.
  2. The follower has missed three in a row when the third one fails to arrive, at 450 ms.
  3. A shorter timeout finds a crash sooner but also fires on a slow network, so real systems add a random delay to the timeout so that followers do not all start at once.

Questions

What is split brain?

Split brain is a failure in which two nodes both believe they are the leader and act at the same time. A majority rule prevents it, because two candidates cannot both hold more than half of the votes.

Why do clusters use an odd number of nodes?

With a majority rule, 2f + 1 nodes tolerate f failures, and a sixth node adds cost without letting the cluster survive more failures than five do.

Do I need to implement an election algorithm in an interview?

Almost never. The usual advice is to use an existing coordination service or library and to explain when you would need one. Being able to say what a leader is for and what can go wrong is the useful part.

How a session helps

In a session George can work a small design question with you aloud, ask where each of your numbers came from and mark where a failure mode was left unsaid. You say each design in your own words; nothing here is written for you to recite. See the packages page for the sessions and book a session when you have a date to work toward.

Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.

Start with one hour

  • Your first purchase is refundable for unused time within 7 days. Nothing renews. Refund terms