Distributed patterns and operations

Leader election

Choose one owner for a job, replace it automatically when it fails, and make a node that wrongly believes it is still leader harmless.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

Some work must have exactly one owner. A scheduler that fires the monthly invoice run. The primary in a replicated database, the one node allowed to accept writes. The controller that assigns shards to workers. If nobody owns the job, it does not happen. If two nodes own it, invoices go out twice, or two primaries accept conflicting writes.

The simplest design is a single instance. It is correct, and it is a single point of failure: when that machine dies at 2 a.m., invoices stop until someone wakes up and starts another.

So you run three instances and need them to agree on which one is in charge. The first idea is to let them watch each other: each standby pings the leader and takes over if the pings stop. This handles crashes and fails on network faults. When the link between two nodes breaks, each one hears silence and concludes that the other is dead. The standby promotes itself while the old leader carries on. Two leaders at once is called split brain.

It happens to careful teams. In October 2018 a 43-second loss of connectivity between two of GitHub’s sites led its automated failover to promote MySQL primaries in a second data centre. Each site ended up holding writes that the other did not have, and restoring consistency left the service degraded for just over 24 hours.

Leader election is the problem of choosing one owner automatically, replacing it when it fails, and making sure that a node which wrongly believes it is the owner can do no damage. The third part is the one people forget.

Why a majority fixes split brain

Two nodes cannot tell a dead peer from an unreachable one, and no cleverer ping changes that. The way out is to require a majority, also called a quorum, to agree on the leader. With three voters a leader needs two votes, and with five it needs three. When the network splits, at most one side contains a majority, so at most one side can elect anyone.

The minority side has no leader and stops doing the leader’s work. That is the price: you give up availability on that side to keep a single owner, which is the consistency choice described in CAP and PACELC.

This is why coordination clusters have odd sizes. Three nodes tolerate one failure and five tolerate two. Four tolerate only one, the same as three.

Getting majority voting right through crashes, restarts and lost messages is what consensus algorithms such as Raft do. The consensus lesson covers terms, votes and log replication in detail, and the simulator below shows the election part.

Raft leader election

Open full screen
AFollowerterm 0BFollowerterm 0CFollowerterm 0DFollowerterm 0EFollowerterm 0

Break things

Leader
none
Term
0
Votes to win
3 of 5
Clock
0 ms

Press Start. The amber ring around each follower is its election timeout, reset by every heartbeat from the leader. Crash the leader and watch the first follower to time out ask for votes. Crash three nodes and nobody can reach a majority.

Simplified for clarity: messages arrive instantly and logs are left out. Real Raft also refuses to vote for a candidate whose log is behind the voter's.

What just happened

Press Start to begin the first election.

    Crash the leader and watch a follower time out, raise the term and collect votes. Then partition the cluster and check that the side without a majority never elects a leader.

    Electing through a coordination store

    You rarely implement consensus yourself. You run a small consensus-backed store and let your services use it as the referee. The store does the voting among its own nodes, and your service only has to win a race to write one key.

    • etcd. Each candidate creates a lease with a time to live, say 10 seconds, and then tries to write the leader key in a transaction that succeeds only if the key does not exist. The winner keeps its lease alive with heartbeats. The others watch the key and try again when it disappears.
    • ZooKeeper. Each candidate creates an ephemeral sequential znode under an election path, and the lowest sequence number is the leader. Each other candidate watches only the node just ahead of it, so one failure wakes one candidate and not all of them. An ephemeral node is removed when its creator’s session expires.
    • Kubernetes. Controllers elect a leader by updating a Lease object through the API server, which stores it in etcd. The control plane components default to a 15 second lease duration, a 10 second renew deadline and a 2 second retry period.
    Leader election with a lease, a partition and an epoch check4 components: etcd, Scheduler A, Scheduler B, Job database. Connections: Scheduler A to etcd (campaign, renew); Scheduler B to etcd (campaign, watch); Scheduler A to Job database (write + epoch); Scheduler B to Job database (write + epoch).etcdleader key with a leaseScheduler AScheduler BJob databasechecks the epochcampaign, renewcampaign, watchwrite + epochwrite + epoch

    Step 1 of 8

    Two copies of a job scheduler run for availability, but only one may fire jobs. Each tries to create the same key in etcd, attached to a lease that lasts 10 seconds. etcd is a consensus-backed store, so it gives one answer.

    Read the steps as text
    1. Two copies of a job scheduler run for availability, but only one may fire jobs. Each tries to create the same key in etcd, attached to a lease that lasts 10 seconds. etcd is a consensus-backed store, so it gives one answer.
    2. Scheduler A's request is applied first, so A is the leader, and it takes the revision number of its key, 7, as its epoch. Scheduler B is told the key already exists and starts watching it.
    3. A keeps its lease alive with a heartbeat every few seconds and fires jobs, stamping each write with epoch 7. As long as the heartbeats arrive, the key stays and B stays on standby.
    4. A network fault cuts A off from etcd. A is still running and can still reach the job database, but its heartbeats no longer arrive.
    5. Ten seconds pass with no renewal, so etcd expires the lease and deletes the key. B's watch fires, B creates the key, and it becomes leader with a higher epoch, 8.
    6. A has not stepped down yet. Perhaps its own timer runs slightly slow, or it was paused. For a moment two processes both believe they are the leader, which is exactly the split brain that election was supposed to prevent.
    7. Both schedulers fire the same job. The job database has already seen epoch 8 from B, so it accepts B's write and rejects A's write, which carries epoch 7.
    8. A sees the rejection, or its failed renewals, and steps down. The store guarantees one leader per epoch. It cannot guarantee that an old leader knows it has been replaced, so whatever the leader writes to must check the epoch.
    Leader election with a lease, a partition and an epoch check

    Leases, heartbeats and failover time

    Leadership held this way is a lease: it lasts until a deadline and has to be renewed. It is the same mechanism as a distributed lock, held for a long time.

    Failover time is roughly the lease duration plus the time the new leader needs to start work. A 10 second lease means about 10 seconds without a leader after a crash. Shorten it and you fail over faster, but a brief garbage collection pause or network stall now deposes a healthy leader, and frequent needless elections are an outage of their own. Values from a few seconds to a few tens of seconds are typical.

    A leader should also give up before the store gives its place away. That is the purpose of the renew deadline in Kubernetes: a leader that has failed to renew for 10 seconds stops acting, 5 seconds before the 15 second lease lets another candidate in.

    What “at most one leader” really means

    This is the subtle part, and the part that senior interviews probe.

    A consensus-backed store can guarantee that at most one leader is chosen per term, where the term (also called an epoch or generation) is a counter that rises at every election. That guarantee does not depend on clocks.

    It cannot guarantee that at most one process believes it is the leader at a given instant. The old leader’s belief lasts until its own timer says the lease has expired, and the store’s view changes when the store’s timer says so. Those are two clocks on two machines. If the old leader’s clock runs slow, or the process is frozen for 20 seconds in the middle of its work, it acts as leader after a successor has been chosen. Safety margins make this unlikely. They cannot make it impossible, because a pause can fall after any check.

    So the design rule is to assume that two nodes may briefly believe they lead, and to make that harmless:

    • Fencing. The leader attaches its term to everything it sends, and receivers reject anything older than the newest term they have seen. Kafka does this with a controller epoch, and Raft carries the term in every message.
    • Go through the log. In Raft a leader cannot commit a write until a majority has acknowledged it. A deposed leader on the wrong side of a partition can accept requests and never commit them. It can still return stale reads unless reads confirm leadership too.
    • Idempotent work. If the leader’s job is to trigger tasks, give each task a deterministic key such as invoice-run-2026-11, so that a second trigger does nothing.

    The bully algorithm

    Older textbooks, and some interviewers, mention the bully algorithm, published by Hector Garcia-Molina in 1982. Every node has a numeric id. A node that notices the leader is silent sends an election message to every node with a higher id. If none replies, it announces itself as leader. If one replies, that node takes over the election. The live node with the highest id always wins, which gives the algorithm its name.

    It is easy to explain, and it assumes that a timeout reliably means a node is dead. In a network partition each side runs the algorithm and each elects a leader. It is better at showing why majorities are needed than at running a production system.

    When to use a leader, and when not to

    Choose election when work truly needs a single owner that makes ordered decisions: a replication primary, a scheduler, a controller making cluster-wide assignments.

    Avoid it when there is a cheaper way to get “once”:

    • stateless workers pulling from a queue, with idempotent handlers
    • a unique constraint in a database, such as one invoice run per month
    • a leader per shard in place of one global leader, as Kafka does per partition, so that a failure affects a fraction of the data

    A single global leader is also a throughput ceiling, because everything it owns flows through one machine.

    In the interview

    Leader election appears whenever your design says “the primary”, “the scheduler” or “the coordinator”. Expect the follow-up: what happens if that node dies, and what happens if it only looks dead?

    A strong answer takes about a minute. Say that you would elect through etcd or ZooKeeper and not write your own protocol, that leadership is a lease renewed by heartbeats, and that failover takes about one lease duration. Then make the point that separates senior answers: the store guarantees one leader per term, but an old leader can keep acting until it finds out, so every write the leader makes carries its epoch and the receiver rejects stale ones. Finish by saying whether the job needs a leader at all.

    Key takeaways

    • Some work needs exactly one owner: a replication primary, a scheduler, a controller that assigns shards.
    • Two nodes that watch each other cannot tell a dead peer from an unreachable one, which leads to split brain.
    • Requiring a majority to choose the leader means at most one side of a network partition can elect one.
    • In practice you elect through a consensus-backed store such as etcd or ZooKeeper, and hold leadership as a lease renewed by heartbeats.
    • A store can guarantee one leader per term. It cannot guarantee that an old leader knows it has been replaced.
    • Attach the term or epoch to everything the leader sends, and have receivers reject older ones.
    • Shorter leases fail over faster and depose healthy leaders more often.

    Try it

    Check yourself

    1. Two database nodes monitor each other with heartbeats. The standby promotes itself if it hears nothing for five seconds. The network link between them fails while both stay up and both can still reach clients. What happens?
    2. A five-node cluster that elects leaders by majority is split by a network fault into groups of three and two. Which statement is true?
    3. A leader holds a 10 second lease. It freezes for 30 seconds in a long pause, during which a new leader is elected. It then wakes and sends a write to a storage service. What reliably stops that write?
    4. A team shortens its leader lease from 15 seconds to 2 seconds to speed up failover. What is the most likely side effect?
    5. A cluster of six nodes uses the bully algorithm. A partition splits it into nodes 1 to 3 and nodes 4 to 6. What is the result?

    0 of 5 answered

    Flashcards

    These 6 cards are in your review deck. Tap a card to see the answer.

    What is split brain?

    Two nodes both acting as leader at once, usually after a network fault makes each think the other is dead. Both accept work, and their state diverges.

    Why does requiring a majority prevent two leaders in one term?

    Two groups cannot both contain more than half of the voters. After a partition at most one side can win an election, and the other side has no leader.

    How does leader election work with ZooKeeper?

    Each candidate creates an ephemeral sequential znode. The lowest sequence number leads, and each other candidate watches the node just ahead of it. A node is removed when its creator's session expires.

    What decides failover time with lease-based election?

    Mostly the lease duration: a successor cannot take over until the old lease expires. Shorter leases fail over faster and cause more false elections.

    What can "at most one leader" guarantee, and what can it not?

    A consensus store guarantees one leader per term or epoch. It cannot guarantee that only one process believes it is leader at a given moment, because a paused or slow old leader has not found out yet.

    How do you make a stale leader harmless?

    Attach the leader's term or epoch to every request and have receivers reject anything older than the newest they have seen. Make the leader's work idempotent as well.

    Review the deck