SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

Leader Election

How a group picks one machine to lead, and picks a new one when it fails.

⏱ 13 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Leader election is how a group of machines picks exactly one of them to be in charge of a job, and picks a new one if that machine fails.

  • Some jobs must be done by one machine at a time: taking writes, running a scheduler, or sending a daily report.
  • Machines vote, or race for a lock, and the winner becomes the leader. The others are followers on standby.
  • The hard part is never having two leaders at once, even when the network breaks.

02Concept: What is it?

In a single program, "who is in charge" is easy: there is only one. In a group of servers, each server can only see the others through a network, and the network can be slow or broken. A server cannot tell "the leader is dead" apart from "the leader is just slow or cut off".

A leader election algorithm gives the group clear rules so that all running servers agree on one leader. Followers watch the leader using heartbeats. When the heartbeats stop for too long, the followers start a new election.

A good election has two promises. Safety: at most one leader at a time. Liveness: if enough machines are working, a leader is eventually chosen. Because of the limits of networks, an exact guarantee of both at once is impossible in theory (the FLP result), so real systems use timeouts and majorities.

The life of a leader
👑Leader workssends heartbeats
→↓leader crashes
🤫Heartbeats stopfollowers notice
→↓timeout
🗳️Electionvote or race
→↓winner
👑New leadertakes over
Elections are rare. Most of the time the cluster is just leader plus followers.
🧠Two leaders is worse than none
With no leader, the system pauses for a moment. With two leaders (split brain), both accept writes and the data can be damaged. Good designs prefer a short pause over two leaders.

03Real-Life Example

🍵Choosing a Team Captain on a Bus
A school team is on a bus trip. They need one captain to talk to the coach. Each pupil can only shout to the others, and sometimes the bus is so noisy that shouts are missed. The rule: the captain stands up and waves every few seconds. If nobody sees a wave for a while, a pupil says "I will do it, who agrees?". A new captain counts only if more than half of the whole team agrees. If the bus splits into two rooms, only the room with more than half can choose a captain. The smaller room waits quietly.
Team on the bus
Leader election
The captain
The leader
The waves every few seconds
Heartbeats
No wave for a while
Election timeout
Saying "I will do it, who agrees?"
A candidate asks for votes
More than half of the whole team must agree
Quorum (majority)
The small room waits quietly
The minority side makes no leader
The old captain returns and sits down
A stepped-down old leader becomes a follower
Election by majority vote
🙋Candidateasks for votes
→↓vote?
🖥️Server 2yes
🖥️Server 3yes
🖥️Server 4no reply
→↓3 of 5 incl. itself
👑Leader

04Why Do We Need It?

🧭One decision maker
One node orders the writes, so the copies do not disagree.
🛡️Automatic recovery
When the leader dies, a new one takes over in seconds with nobody paged.
🔁No duplicate work
A cron job or a consumer runs on one node, not on every node.
🧱Simple design
One leader is easier to reason about than all nodes writing at once.
⚖️Avoid split brain
A majority rule keeps two leaders from existing together.
📈High availability
Standby machines are ready, so a single failure is not an outage.
Many systems are simpler and safer with one leader. Election is how you keep exactly one, even as machines come and go.

05Where Do We Use It?

🗄️Database replication
One primary takes writes and replicas copy it. Failover picks a new primary.
📨Kafka partitions
Each partition has one leader broker that handles reads and writes for it.
☸️Kubernetes
The controller manager and the scheduler run on several nodes but only one is active, chosen by a lease.
⏰Scheduled jobs
A nightly report must run once, on one node.
🧮Distributed stores
etcd, ZooKeeper, Consul and Raft-based systems all elect a leader.
🎮Game or room servers
One server owns the state of a game room.

06Types / Parts / How It Works

Common ways to elect a leader

Three families
Bully algorithm
🔢Highest id wins
⚠️Splits the brain on partitions
Majority vote (Raft, Paxos)
🗳️Need more than half
🛡️Safe on partitions
Lock or lease in a store
🔐Take a key in etcd, ZooKeeper, Redis
⏳Renew before it expires
Pick by how much safety and how much simplicity you need.
MethodHow it worksGood and bad
BullyA node that notices the leader is gone asks all higher ids. The highest running id winsSimple and quick. A network split can create two leaders. Many messages
RingNodes pass an election message around a ring, collecting ids. The biggest id winsFewer messages. Slow, and a broken link breaks the ring
Raft style voteRandom timeouts, a candidate asks for votes, a majority wins in a numbered termSafe and well tested. Needs a majority alive
Paxos basedLeader chosen through Paxos rounds (as in Multi-Paxos)Very safe. Harder to build
Lock or lease (ZooKeeper, etcd, Consul)All nodes try to create the same key with a lease. The one that succeeds leads, and renews the leaseEasy to add to an app. You depend on the store and on clock-safe leases
Static or by handAn operator picks the leaderSimplest. Slow recovery and a human in the loop

Ideas used by every method

IdeaWhat it isWhy it matters
HeartbeatA regular I am alive messageHow followers notice a dead leader
TimeoutHow long to wait before starting an electionShort is fast but jumpy. Long is calm but slow
Term or epochA number that goes up with each new leaderLets everyone ignore a stale old leader
QuorumMore than half of all nodesTwo groups can never both have a quorum
LeaseA leadership that expires unless renewedA stuck leader loses power on its own
VisualizerBully vs majority vote: crash nodes and split the networkCrash the top node and see who wins. Then split the network in the middle. Bully makes two leaders. The majority vote lets only one side lead, or none.
How is the leader chosen?

Click a node to crash or restore it. The old leader was S7. In the majority mode the lowest running id fires its timer first in this demo.

Leaders
1
should be exactly 1
Messages
41
for this election
Nodes up
6 / 7
majority = 4
S6 wins because it has the highest id among the running nodes. 6 node(s) started an election and 41 messages were sent.

07How to Use It / Steps / Implementation

Doing leader election in practice

  1. 1
    Do not write it yourself if you can avoid it
    Use a tested tool: etcd, ZooKeeper, Consul, or the Kubernetes Lease API. Or use a database that already has failover.
  2. 2
    Use a majority-based system
    Run the store as 3 or 5 nodes with Raft or ZooKeeper (ZAB), so a split cannot give two leaders.
  3. 3
    Use a lease with a time limit
    The leader holds the key with a time-to-live and renews it often (for example every third of the TTL).
  4. 4
    Stop work when the lease cannot be renewed
    If the leader cannot renew, it must stop acting as leader right away, before the lease runs out.
  5. 5
    Attach a term (fencing token)
    Every action carries the term number of the leader. Storage rejects actions with an older term, so a stale leader cannot do damage.
  6. 6
    Tune timeouts
    The timeout should be several times the heartbeat interval and the normal network delay. Test a slow network.
  7. 7
    Make followers ready
    Standby nodes should be warm, with data and connections ready, so takeover is quick.
  8. 8
    Test failure on purpose
    Kill the leader, freeze it, and cut the network in a test. Check that there is never more than one active leader.
💡Do you need an election at all?
If the work can be done safely by many nodes (idempotent jobs, partitioned work), skip the leader. Fewer leaders means fewer things that can go wrong.
⚠️A paused leader does not know it is paused
A garbage collection pause or a frozen VM can make a leader stop for longer than its lease. When it wakes up it still thinks it is leader. Use fencing tokens so the storage can say no.

08Key Terms to Know

TermMeaning in easy words
Leader (primary, master)The one node currently in charge of a job
Follower (replica, standby)A node that waits and can take over
CandidateA node that wants to become leader and is asking for votes
ElectionThe process of choosing a leader
HeartbeatA small regular message that shows a node is alive
Election timeoutHow long to wait without a heartbeat before starting an election
QuorumMore than half of all nodes. Two groups cannot both have one
Term / epochA counter that rises with every new leader
LeaseA leadership or lock that ends by itself unless renewed
Fencing tokenA rising number that lets storage reject writes from an old leader
FailoverSwitching the work from a failed leader to a new one

09Pros, Cons and Trade-offs

✅ Pros
  • Automatic recovery from a leader failure
  • One writer makes ordering and consistency simple
  • Standby nodes remove the single point of failure
  • Mature tools exist (etcd, ZooKeeper, Consul)
  • Clear model for jobs that must run once
⚠️ Cons
  • A short pause while the new leader is chosen
  • Split brain if the design has no majority or fencing
  • The leader can become a bottleneck
  • Timeout tuning is hard (false alarms or slow recovery)
  • Extra moving parts to run and monitor

Trade-offs

ChoiceWe gainWe lose
Short timeoutFast failoverFalse elections when the network is slow or the leader is busy
Long timeoutStable leadershipA longer outage when the leader really fails
Majority voteSafety on partitionsNo leader when a majority is lost
Bully (highest id)Very simpleTwo leaders possible on a network split
Lease in an external storeEasy to add to an appA new dependency, and risk if clocks or pauses are wrong
No leader (all nodes work)No election and no bottleneckNeeds conflict-free work or extra coordination

10Common Problems and Mistakes

Common mistakes

  1. No majority rule. A network split gives each side its own leader.
  2. Trusting a leader that is only slow. A paused old leader wakes up and writes. Without fencing tokens, it damages data.
  3. Lease and timeout too close. A leader that renews at the last moment loses leadership on a small delay.
  4. Relying on clock time. Servers' clocks drift. Use monotonic timers for the local wait and a store's lease for the truth.
  5. Even number of nodes. Four nodes tolerate no more failures than three, and a 2 and 2 split gives nobody a majority.
  6. Leader doing too much. One node becomes the bottleneck. Use it to coordinate, not to carry all the traffic.
  7. Never testing failover. It works on paper, then fails in the real outage.

Things to watch

🧠Split brain
Two nodes both act as leader. Prevent with quorum and fencing.
🌀Flapping
Leadership moves back and forth because of a flaky network or a heavy load.
⏳Slow failover
A long timeout means a long outage. Measure real failover time.
🗳️Election storm
Many nodes start elections together. Random delays reduce it.

11Real-World Examples

🐘PostgreSQL with Patroni
Patroni uses etcd or Consul to pick one primary and promote a replica on failure.
🐒ZooKeeper
Used for years by Hadoop, HBase and Kafka (older versions) to choose leaders.
☸️Kubernetes controllers
Several copies run, and one holds a Lease object and is the active leader.
🍃MongoDB replica sets
Members hold elections, and a majority vote picks the primary.
📨Kafka
A controller and a leader per partition. Newer versions use KRaft.
🔴Redis Sentinel
Sentinels agree that the master is down and promote a replica.
📝Note
Product behaviour and defaults change between versions. Check the documentation for the version you run.
Mini case: database failover
🗄️Primarycrashes
→↓lease expires
🔐etcd3 nodes, majority
→↓grants lease
🗄️Replica becomes primaryterm + 1
Old leader Source of truth New leader
One safe primary at all times.

12Related Topics to Read Next

Raft→

A complete election and replication algorithm built on majority votes.

Consensus Algorithms→

Leader election is a special case of reaching agreement.

Heartbeats→

How followers know when to start an election.

Split Brain Problem→

The disaster a good election prevents.

Distributed Locks→

Another way to make sure only one node does a job.

Network Partitions→

The reason a node cannot tell dead from cut off.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: the group agrees on exactly one leader, and replaces it when it fails.
  • ✔Detect: heartbeats, and a timeout when they stop.
  • ✔Safe method: a vote that needs more than half of all nodes (Raft, Paxos, ZooKeeper).
  • ✔Bully: highest id wins. Simple, but can give two leaders on a split.
  • ✔Lease: a leadership with a time limit. The leader must keep renewing it.
  • ✔Fencing token: a rising number so storage can reject a stale leader.
  • ✔Use: an odd number of nodes (3 or 5), in different failure zones.
  • ✔One line: “Pick one leader by majority, and make sure an old leader can never do harm.”
← Previous
Raft
Next →
ZooKeeper and etcd