Sub topic 3
Election Timeouts, Split Votes, and Pre-Vote
This chapter assumes you know nodes, RPCs, network partitions, and append-only logs. It focuses on Raft’s operational edge cases.
Election timeouts and split votes
A follower starts an election when it receives no heartbeat before its election timeout. It increments its term, becomes a candidate, votes for itself, and sends RequestVote RPCs.
Timeouts are randomized. Each server chooses a value from a range, such as 150–300 milliseconds. Usually one candidate starts first and receives a majority before other servers time out.
import random
def new_election_timeout():
return random.uniform(0.150, 0.300)A split vote occurs when several candidates start together. Each receives some votes, but no candidate gets a majority. Candidates wait for another randomized timeout and try again. The timeout range should be much longer than normal heartbeat and network round-trip times.
Pre-vote
Pre-vote reduces disruption from an isolated server. Before increasing its term, a follower asks whether peers would vote for it. If it cannot contact a majority, it remains in its current term. This prevents a disconnected server from repeatedly raising the term and forcing a healthy leader to step down after it reconnects.
Persistence before replying
A server must durably write currentTerm, votedFor, and log entries before replying to an RPC that depends on them. After a crash, replaying this state prevents a server from voting twice in one term or forgetting an accepted log entry.
Clients and linearizable reads
Clients should attach a unique request ID. The leader records completed IDs and results, so a retry after a lost response does not execute the command twice. A linearizable read reflects the latest completed write. A leader can establish this with a quorum check, such as a read index, rather than trusting an old local state.
Snapshots and log compaction
A snapshot stores the state-machine state plus metadata about the last included log index and term. The server can delete older log entries. If a follower is far behind, the leader sends the snapshot instead of every missing entry.
Changing membership safely
Raft uses joint consensus when changing membership. During the transition, an entry must be accepted by a majority of both the old and new configurations. This prevents two incompatible groups from each forming a leader.
Exercise
Why does randomized election timing reduce, but not eliminate, split votes?
Show answer
It makes simultaneous timeouts unlikely, but delays, partitions, or unlucky choices can still cause multiple candidates to start together.