Sub topic 8
Election timeouts, split votes, and pre-vote
This chapter assumes you know the three Raft roles (follower, candidate, leader), how terms work, and how RequestVote and heartbeat AppendEntries calls behave. It covers the timing that decides when elections start, why elections sometimes fail to produce a leader, and how pre-vote stops a disconnected server from disrupting a healthy cluster.
Two timers, one inequality
Raft uses two time values.
- The heartbeat interval is how often a leader sends
AppendEntriesto each follower, with or without new entries. - The election timeout is how long a follower or candidate waits without hearing from a valid leader before it starts an election.
The Raft paper summarizes the constraint as broadcastTime << electionTimeout << MTBF. Broadcast time is the time to send RPCs to every server and get replies, including the disk write each server performs before replying. MTBF is the mean time between failures of a single server. The first inequality keeps healthy leaders from being mistaken for dead ones. The second keeps the cluster from spending its life in elections.
A common starting point is a heartbeat of 50 ms and an election timeout of 150 to 300 ms. A follower can then miss two heartbeats, from a dropped packet or a slow moment, before it gives up on the leader.
Randomized timeouts
If every follower used the same timeout, they would all become candidates at the same instant after a leader crash. Each would vote for itself, and no one would reach a majority. Raft avoids this by drawing each timeout at random.
import random
def new_election_timeout():
# Randomized per server and per reset, so servers rarely time out together.
# The range must be well above the heartbeat interval and the network round trip.
return random.uniform(0.150, 0.300) # secondsTwo details are easy to get wrong.
- Draw a fresh value on every reset. A server that keeps its first random value for life can lose to the same rival every time.
- Reset the timer only on events that show a viable leader exists. Those events are receiving
AppendEntriesfrom a leader whose term is at least yours, granting a vote, and starting your own election. RejectedRequestVotecalls and staleAppendEntriescalls must not reset it. If they did, a noisy stale server could keep followers from ever timing out.
After a leader crashes, the first server to time out usually wins. It has a head start of one random gap over the others. Its RequestVote messages arrive before the other timers expire, and those servers reset their timers when they grant the vote.
How a split vote happens
A split vote occurs when two or more candidates start an election in the same term and the votes divide so that nobody gets a majority. Each server grants at most one vote per term. A candidate has already voted for itself, so it rejects other candidates in that term.
Consider four live servers out of five, with the fifth crashed. A majority of five is three votes. S1 and S2 time out within a millisecond of each other.
Nothing unsafe has happened. No leader exists in term 5, which is allowed. The cost is availability. When the candidates' timers expire, each one increments its term to 6 and tries again. Because the new timeouts are random, the two candidates are unlikely to collide a second time. Each additional round resolves with high probability, so the expected delay is small.
Measuring how often timeouts collide
The first two timeouts to fire matter most. If the second one fires less than one message delay after the first, that server becomes a candidate before it hears the first candidate's request. The following script estimates how often that collision happens for a given range.
import random
def collision_probability(servers, low, high, latency, trials=100_000):
"""Fraction of trials where the second timeout fires within `latency`
seconds of the first, so two candidates run in the same term."""
collisions = 0
for _ in range(trials):
timeouts = sorted(random.uniform(low, high) for _ in range(servers))
if timeouts[1] - timeouts[0] < latency:
collisions += 1
return collisions / trials
if __name__ == "__main__":
latency = 0.005 # 5 ms one-way delay
for low, high in [(0.150, 0.300), (0.150, 0.165)]:
p = collision_probability(5, low, high, latency)
print(f"range {low:.3f}-{high:.3f} s: {p:.1%} of trials collide")For five servers and a 5 ms delay, the closed form is 1 - (1 - latency/width)^5. That gives about 16% for the 150 ms wide range and about 87% for the 15 ms wide range. Your simulated numbers should be close to those values.
A collision is a necessary condition for a split vote, not a guarantee of one. Even so, the numbers show that the width of the range matters more than its absolute values.
Choosing timeout values
| Setting | Too low | Too high |
|---|---|---|
| Election timeout lower bound | Followers time out during normal jitter, such as a slow disk or a garbage-collection pause, and start needless elections | The cluster stays leaderless for longer after a real crash |
| Election timeout range width | Candidates collide often and split votes repeat | Slow recovery in unlucky draws |
| Heartbeat interval | Extra network and CPU load | Followers miss the leader's signal and time out |
Practical rules:
- Keep the election timeout at several times the heartbeat interval, so a single lost message does not trigger an election.
- Set the lower bound above the time for a network round trip plus one disk flush. Servers write state to disk before replying, so slow storage extends the real round trip.
- Make the range at least as wide as the lower bound. A range of
[T, 2T]is the common choice. - Measure on your real network. Cross-region clusters need values that are an order of magnitude larger than a single-datacenter setup.
The disruptive server problem
Standard Raft has a weakness involving partitions. Suppose S3 loses its connection to the rest of a three-server cluster. The leader and S2 keep working. S3 hears no heartbeats, so its timer expires, it increments its term, and it becomes a candidate. It cannot win, because it cannot reach anyone. Its timer expires again and the term goes up again. After a minute it may be in term 400, while the healthy cluster is still in term 5.
When the partition heals, S3 sends a message carrying term 400. The leader sees a higher term, steps down, and becomes a follower, as the term rules require. S3's log is stale, so it will not win the election that follows. The cluster still went through an unnecessary leader change and a window with no leader.
Pre-vote
Pre-vote is an extension described in Diego Ongaro's Raft dissertation. It adds a trial round before a real election. A server that times out does not increment its term. It sends a PreVote request that carries the term it would use, which is current_term + 1. It only starts a real election if a majority says they would grant the vote.
flowchart TD
A[Election timeout fires] --> B[Send PreVote with current_term + 1, term unchanged]
B --> C{Majority would vote yes?}
C -- No --> D[Reset timer and stay follower]
C -- Yes --> E[Increment term, vote for self, persist]
E --> F[Send real RequestVote]A pre-vote receiver changes nothing about its own state: not its term, not voted_for, and not its election timer. It answers yes only if both conditions hold.
- The candidate's log is at least as up to date as the receiver's log, using the same comparison as
RequestVote. - The receiver has not heard from a current leader within the minimum election timeout.
def handle_pre_vote(s, req):
# req.term is the term the candidate WOULD use, its current_term + 1.
# Nothing here changes current_term, voted_for, or the election timer.
if req.term < s.current_term:
return (s.current_term, False)
last_index = len(s.log) - 1
last_term = s.log[last_index].term
candidate_up_to_date = (req.last_log_term, req.last_log_index) >= (last_term, last_index)
heard_from_leader = s.time_since_leader_contact() < s.min_election_timeout
return (s.current_term, candidate_up_to_date and not heard_from_leader)
def on_election_timeout(s):
if s.role == "leader":
return
if not s.pre_vote_succeeds(): # asks peers using term = current_term + 1
s.reset_election_timer()
return
s.current_term += 1
s.voted_for = s.id
s.role = "candidate"
s.persist() # term and vote must be durable before sending
s.reset_election_timer()
s.send_request_vote_to_all()In the partition example, S3 sends pre-votes that nobody answers, so its term stays at 5 the whole time. When it reconnects, the leader and S2 refuse the pre-vote because they have recent leader contact. S3 receives the next heartbeat and rejoins quietly. If S3 had been fully reconnected and the leader really had died, S2 would stop hearing from the leader, and S3's log might be current enough for the pre-vote to pass. Pre-vote only blocks elections that would be disruptive.
Implementations often pair pre-vote with check quorum. A leader steps down if it has not heard from a majority within an election timeout. This stops a partitioned old leader from believing it is still in charge. Etcd and several other production Raft libraries ship both as options.
Common errors
- Seeding every server's random generator identically, so all timeouts match.
- Resetting the election timer on any incoming message, including rejected votes.
- Forgetting to persist
current_termandvoted_forwhen starting an election, which allows a restarted server to vote twice in a term. - Counting pre-vote replies from servers that changed their own term while handling them.
- Choosing timeouts in a test cluster and reusing them across regions or slow disks.
Exercise
A five-server cluster uses an election timeout range of 150 to 160 ms and a 5 ms one-way network delay. After each leader crash, elections often take several rounds. Give two reasons the range is a poor choice and a better setting.
Show answer
The range is only 10 ms wide, so several servers usually time out within one network delay of each other and become candidates in the same term, which causes repeated split votes. The lower bound is also not much higher than a typical heartbeat plus a round trip and disk flush, so even healthy followers may time out during a brief pause. A better setting is a range such as 150 to 300 ms with a heartbeat of about 50 ms, which makes collisions rare and tolerates a couple of missed heartbeats.
Exercise
A follower is partitioned for ten minutes and then rejoins. Without pre-vote, what happens to the healthy leader on reconnection, and why does pre-vote prevent it?
Show answer
Without pre-vote, the isolated follower incremented its term every time its timer expired, so it holds a much higher term than the leader. When its message arrives, the leader sees the higher term and steps down, forcing a new election even though the isolated server's stale log cannot win it. With pre-vote, the follower never increments its term because its pre-vote requests fail to reach a majority. Once reconnected, the other servers have heard from the leader recently and refuse its pre-vote. Its term stays the same, so the leader is not disturbed.