Raft Consensus from Scratch: Leader Election to Log Replication
Build a working Raft consensus implementation from the ground up. Covers leader election, log replication with conflict resolution, and a complete working implementation in Go. No Paxos required.
Leader Election in Raft
Raft separates consensus into leader election and log replication. This lesson covers the election mechanism.
How Elections Work
Every node starts as a follower. If a follower receives no heartbeat within a randomized timeout (150-300ms), it becomes a candidate and starts an election.
The Election Process
- Candidate increments its term
- Votes for itself
- Sends RequestVote RPCs to all other nodes
- Wins if it receives votes from a majority
Split Vote Prevention
Randomized election timeouts prevent most split votes. If two candidates start simultaneously, the one with the higher term wins.
Implementation Notes
The election timeout must be significantly larger than the network round-trip time. A good default is 150-300ms with heartbeats every 50ms.
Exercise
Implement the election timer and RequestVote RPC handler. Test with three nodes and verify that exactly one leader is elected.