Algorithms · Safety nets

Raft leader election

How Kubernetes’ database picks a leader. Five servers must agree who’s in charge, with nobody in charge to ask. Random alarm clocks settle it.

The problem

Kubernetes keeps its cluster state (what should be running, and where) in etcd. If that one database dies, the whole cluster is flying blind. So etcd runs on several servers that must always agree on one story.

Agreement is easiest when one server, the leader, is in charge and the others copy it. But servers crash. The moment the leader vanishes, the survivors must pick a new one, with no boss to tell them how.

The obvious way

Give every follower the same rule: "if you hear nothing from the leader for 150 ms, start an election." It sounds fair, and it fails. All followers lose the leader at the same moment, so they all time out at the same moment, and each one votes for itself. Nobody reaches a majority, so they all wait 150 ms and do exactly the same thing again. Forever.

The clever idea

Picture a silent classroom where the teacher walks out. Everyone waits, and whoever can't stand the silence first says "I'll lead, any objections?" The others, still waiting, just say yes. That works because people get restless at different moments.

Raft, by Diego Ongaro and John Ousterhout, builds that in on purpose. Each server picks a random election timeout, and the paper's example range is 150-300 ms. Usually one server times out first, asks for votes, and wins before anyone else wakes up.

How the code does it

The leader (server 0) is dead, so four survivors remain, but a win still needs 3 of the original 5. Each term, every survivor draws a timeout. Then each one looks at the earliest request it would hear. If it arrives (5 ms after the sender's timeout) before the server's own timer fires, it votes for the sender. Otherwise it has become a candidate and votes for itself.

With fixed timeouts, all four timers fire together, no request arrives early enough, and every server votes for itself: four candidates with one vote each, never a majority. With random timeouts, one server is almost always first by more than 5 ms, so the other three vote for it and it wins in term 1. The bars from the final show call make the gap obvious. Fixed hits the 10-term cap on every run, because it never recovers, so that bar is a lower bound.

Trade-offs

Randomness is not a guarantee, only good odds, so splits can still happen and cost a wasted term. The timeout range also has to be wider than the message delay, or servers collide. And while no leader exists, the cluster cannot accept writes. Raft chooses safety over availability: if fewer than a majority of servers can talk, it waits instead of risking two leaders.

Where else you'll see it

Any system that needs a trusted leader across several machines uses the same pattern. The real implementation behind etcd lives in the open-source Go library at github.com/etcd-io/raft. After this simulation, its election code should look much less mysterious.

With 5 servers and the leader dead, why do fixed 150 ms timeouts get stuck?

  • Everyone votes for themselves, so no one gets 3 votes
  • Messages take too long to arrive
  • The dead leader still holds the vote
Show the answer

Everyone votes for themselves, so no one gets 3 votes. All timers fire together, so no request arrives before a server's own timer does. Four candidates each get one vote, and a majority needs 3.

Change it and see
  • Change DELAY from 5 to 50
  • Change randint range to 150, 155
  • Set MAX_TERMS to 3
  • Raise ALIVE to include server 0

The code

Python, with what each line means beside it. It compares the clever way with every server starting an election at the same fixed time.

import randomBring in random numbers
from collections import CounterBring in a vote counter
ALIVE, MAJORITY, DELAY, MAX_TERMS = [1, 2, 3, 4], 3, 5, 10Four survivors, need 3 of 5, 5 ms messages
def election(pick, say=0):Define one election, given a timeout recipe
for term in range(1, MAX_TERMS + 1):Try term after term, up to a limit
timeout = {s: pick() for s in ALIVE}Every survivor draws its own timeout
votes = {}Start with an empty ballot box
for me in ALIVE:Go through each server's point of view
arrives, who = min((timeout[c] + DELAY, c) for c in ALIVE if c != me)Find the earliest request it would hear
votes[me] = who if arrives < timeout[me] else meVote for it if it arrives first, else self
leader, count = Counter(votes.values()).most_common(1)[0]Find the top candidate and their votes
if term <= say:If we should narrate this term
print(f"term {term}: timeouts {list(timeout.values())} -> server {leader} has {count} vote(s)")Print timeouts and the top candidate
if count >= MAJORITY:If someone has a majority
return termThat term wins, report it
return MAX_TERMSNobody won, give up at the limit
fixed = lambda: 150Fixed recipe: always 150
randomized = lambda: random.randint(150, 300)Random recipe: pick 150 to 300
random.seed(4)Make the demo repeatable
print("Fixed timeouts, first 2 terms:")Announce the fixed run
election(fixed, say=2)Run it, narrating two terms
print("Randomized timeouts:")Announce the random run
election(randomized, say=3)Run it, narrating up to three terms
fixed_avg = sum(election(fixed) for _ in range(200)) / 200Average terms over 200 fixed elections
random_avg = sum(election(randomized) for _ in range(200)) / 200Average terms over 200 random elections
show([fixed_avg, random_avg], "avg terms to elect a leader: fixed (left) vs random (right)")Draw both averages as bars

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on safety nets