Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Systems · Consensus

Elect a Leader.

Consensus sounds abstract until you watch it happen. In Raft, every node is one of three roles — follower, candidate, or leader — and a single leader per term makes all the decisions. It stays leader by sending periodic heartbeats that reset everyone’s randomized election timer. When a follower’s timer runs out (it hasn’t heard from a leader), it becomes a candidate, bumps the term, votes for itself, and asks the rest for votes; whoever collects a majority wins and becomes leader. The randomized timers make split votes rare and self-correcting. Run the cluster, then kill the leader and watch a fresh election.

strong-leader consensus · majority vote (⌊n/2⌋+1) · randomized timers avoid split votes
term

A logical clock. Each election starts a new, higher term; one leader per term.

roles

Follower (waits), candidate (seeking votes), leader (sends heartbeats).

election timer

A randomized countdown; if it hits zero without a heartbeat, the node runs for leader.

majority

A candidate needs votes from more than half the nodes to become leader.

raft.js — followers, candidates, one leader
Ready
Five nodes start as followers with random election timers. Step advances time: when a timer hits zero, that node becomes a candidate and asks for votes. A majority makes it leader. Auto to run it live.
0
term
–
leader
0
elections

How it works

The whole protocol turns on two randomized timers and one rule: majority wins. Each follower waits a random election timeout (say 150–300 ticks). Because the timeouts differ, one node almost always times out first, becomes a candidate alone, and wins cleanly — this randomization is Raft’s elegant fix for split votes. A candidate votes for itself and requests votes; each node grants at most one vote per term, to the first qualifying candidate it hears. Collect a majority and you’re leader; then send heartbeats (empty log-append messages) fast enough to reset every follower’s timer before it expires, which is how a healthy leader stays in power. If two candidates do split the vote in the same term, nobody wins, the term ends with no leader, and fresh random timeouts break the tie on the next round.

1

Followers wait on a random timer

Every node begins as a follower with its own randomized election timeout. A heartbeat from a leader resets this timer; silence lets it count down.

2

Timeout → candidate, request votes

When a follower’s timer expires, it becomes a candidate, increments the term, votes for itself, and asks every other node for a vote for this term.

3

Majority → leader, then heartbeat

Each node grants at most one vote per term. A candidate that collects a majority becomes leader and immediately starts sending heartbeats to reset followers and suppress new elections.

✓

Leader fails → new election

If the leader crashes or is partitioned away, its heartbeats stop, a follower times out, and the cycle repeats at a higher term — automatically restoring a single leader.

Roles
follower/candidate/leader
Vote needed
majority
Split votes
random timers fix them
Used in
etcd, Consul, TiKV

The code

# Raft leader election, per node (simplified) on election_timeout: # no heartbeat heard in time state = CANDIDATE term += 1 votes = {self} # vote for yourself for peer in others: request_vote(peer, term) # ask for their vote on request_vote(candidate, term): if term >= my_term and not_voted_this_term: grant_vote(candidate) # at most one vote per term on majority_votes: state = LEADER while leader: send_heartbeats() # reset followers' timers

The picture: the shortest timer wins

timers start at tick 0 tick 9: term 1 n0 · 9runs out: candidate n1 · 12grants vote, resets n2 · 14 n3 · 11 n4 · 15 votes 5need 3 of 5n0 leads dashed: time a vote reset before it ran out
The lab hides its timers. This is what they do. Each node draws a random timeout, and the first to run out (n0, at tick 9) campaigns alone. Its RequestVote reaches the others while they still have time left, shown dashed, so each one votes for it and resets its timer instead of becoming a candidate too. A split vote needs two timers to run out before either candidate’s request arrives. The wider the random range, the rarer that gets.

Worked example: an election, a crash and a split vote

This follows the lab’s rules on five nodes, with timer values picked from its 8–15 tick range. The majority is ⌊5/2⌋ + 1 = 3, and it stays 3 after a node dies, because it counts the configured cluster, not the nodes still alive.

TickWhat happensTermVotesResult
0Five followers, timers 9, 12, 14, 11, 150—no leader
1–8Timers count down, no heartbeats0—waiting
9n0 runs out: term + 1, votes for itself, sends RequestVote11 + 4 = 5n0 leader
10–12Heartbeats reset n1–n4 every tick1—term holds
after 12Kill n0. Survivors draw timers n1 10, n2 8, n3 13, n4 81—no leader
20n2 and n4 run out in the same tick and both campaign2n2: 1 + 1, n4: 1 + 1split: 2 < 3
20Everyone draws new timers: n1 12, n2 11, n3 8, n4 142—retry
28n3 runs out alone and campaigns31 + 3 = 4n3 leader

Three elections, final term 3. Tick 20 is the split vote. n1 and n3 each have one vote for term 2 and give it to different candidates, so 2 + 2 can never reach 3. The way out is not cleverness but fresh randomness: on the next round one timer (n3’s 8) is clearly shortest. Kill a second leader and the 3 remaining nodes can still elect one, since 3 ≥ 3. Kill a third and no candidate can ever reach 3 votes, so the cluster stops accepting writes rather than risk two leaders.

Trade-offs: cluster size and timeouts

In this table, Time is who must answer before a write commits or a candidate wins (always a majority, leader included), and Space is how many nodes can fail with the cluster still working.

CaseTimeSpaceWhy
N = 11 of 10 failuresNo consensus needed and no fault tolerance. Fine for development only.
N = 32 of 31 failureThe usual minimum. The leader plus one follower commits.
N = 43 of 41 failureOne more copy, no more tolerance, and every commit waits for an extra ack.
N = 53 of 52 failuresSurvives one planned restart and one unplanned crash at the same time.
N = 74 of 73 failuresMore safety, but each heartbeat round is 6 messages, and commits wait on more peers.
Election timeoutFailover takes about one timeout plus an election—Too short, and a GC pause or slow link starts a needless election. Too long, and a dead leader goes unnoticed. The Raft paper asks for broadcast time ≪ election timeout ≪ time between failures, and suggests 150–300 ms.

Messages grow linearly: a heartbeat round and an election each cost N − 1 messages from one node. That is why clusters stay at 3 or 5, and systems that need many replicas run many small Raft groups instead of one big one.

Common mistakes

  • Miscounting the majority

    It is ⌊N/2⌋ + 1: 2 of 3, 3 of 5. The look-alike ⌈N/2⌉ + 1 is an easy slip: it gives 4 for N = 5 and is only right for even N. Also count against the configured size, never just the nodes that happen to be alive. Otherwise two halves of a partition can each elect a leader.

  • Granting a vote without checking the log

    The code above checks only the term. Real Raft also refuses a candidate whose log is less up to date than the voter’s, comparing the last entry’s term and then its index. Skip that check and a leader can be elected without a committed entry, and then overwrite it.

  • Not persisting the term and the vote

    currentTerm and votedFor must reach disk before the reply goes out. A node that crashes, restarts and forgets its vote can vote twice in one term, and then two leaders exist.

  • Serving reads from a leader that might be stale

    A leader cut off in a minority partition still believes it leads until it hears a higher term. Reading its local state can return stale data. Confirm leadership with a majority first (ReadIndex), or use time-bounded leases that rely on clocks not drifting too far.

  • Letting a rejoining node disrupt a healthy leader

    A node isolated for a while keeps timing out and raising its term. When it reconnects, that higher term forces the healthy leader to step down. The PreVote extension has a node first check that it could win before it raises its term.

Where this shows up in production

  • Kubernetes, through etcd

    Every Kubernetes cluster keeps its state in etcd, a Raft-replicated key-value store. That is why control planes come in 3s and 5s, and why losing a majority of etcd members freezes changes to the cluster while workloads that are already running carry on.

  • Databases with many small groups

    CockroachDB and TiKV split data into ranges or regions and run a separate Raft group for each, so leadership and load spread across machines instead of one leader carrying all the writes.

  • Kafka without ZooKeeper

    Kafka’s KRaft mode replaced ZooKeeper with a Raft-based quorum of controllers for cluster metadata. ZooKeeper itself uses a different protocol, ZAB, which also uses majority quorums.

  • The interview angle

    Expect “why 5 nodes and not 4?” (same majority logic as above), “what happens in a 2 | 3 partition?” (only the side with 3 can elect and commit), and “how do you avoid split votes?” (randomized timeouts, then the term check). Strong answers also mention the log check on votes, which the page’s simplified code leaves out.

Quick check

1. How many votes does a candidate need to become leader?

2. How does Raft avoid endless split votes?

3. What keeps a healthy leader in power?

FAQ

What is Raft?

A consensus algorithm keeping a cluster in agreement on a replicated log, designed to be easier to understand than Paxos. It uses a strong leader — one elected per term handling all requests and replication — and decomposes consensus into leader election, log replication, and safety, with randomized timeouts to avoid split votes.

What is a term in Raft?

Raft’s logical clock — a monotonically increasing number starting with each election, with at most one leader per term. Terms detect stale leaders and messages: an older-term message is rejected, and learning of a newer term makes a node step down to follower.

How does Raft handle a network partition?

If a partition cuts the leader off from a majority, the majority side elects a new leader at a higher term and keeps progressing; the old leader on the minority side can’t commit (no majority) and steps down once it sees the higher term when the partition heals. Only the majority side ever progresses.

How does Raft compare to Paxos?

Both give the same consensus guarantees, but Raft was designed for understandability: a single strong leader and a clear decomposition (election, replication, safety), versus Paxos’s more abstract, leaderless formulation. Raft is simpler to implement correctly, so etcd, Consul, and TiKV use it.

Keep going

Finished this one? 0 / 61 Labs done
NextThe Quorum Dial Next on the “Agreement between machines” ladder · rung 2 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs