Leader election is the first subproblem in the Raft consensus algorithm. In this chapter, we outline candidate transitions, voting rules, split-vote mitigation, and state variables.
Candidate State Transitions
Raft nodes start in the Follower state. If a follower receives no heartbeat from the current leader within a randomized election timeout, it enters the Candidate state and triggers an election:
- Increment local term counter (
currentTerm). - Vote for itself.
- Reset the election timer.
- Send a
RequestVoteRPC call to all other servers in the cluster.
Split Votes & Randomized Timeouts
If multiple followers timeout at the same time, they may all become candidates simultaneously, causing votes to split such that no candidate obtains a strict majority. To mitigate this:
- Raft randomizes election timeouts across a fixed range (typically 150ms to 300ms).
- This ensures that one candidate’s timeout will expire first, allowing it to claim votes and win the term before other nodes timeout.
// ResetTimer randomizes timeout to prevent split votes.
func (rf *Raft) ResetTimer() {
rf.electionTimeout = 150*time.Millisecond + time.Duration(rand.Intn(150))*time.Millisecond
rf.timerResetTime = time.Now()
}