Outlining detailed Go Raft election design
I’ve mapped out a complete plan for a Go Raft leader election simulation with randomized timeouts, RPCs (RequestVote and AppendEntries), network message drop simulation, state locking, and test verifying leader convergence under packet loss. Next is implementing the described node struct, network, timeouts, RPC handlers, and a test with 3 nodes and drop rate.
Below is a self–contained example that implements the leader–election portion of Raft in Go. It includes randomized election timeouts to break split–vote ties, a very simple “network” that can drop packets, and a test that demonstrates that the cluster converges to a single leader despite packet loss.
For brevity we ignore log replication and treat AppendEntries as a heartbeat only.
// raft.go
package raft
import (
"log"
"math/rand"
"sync"
"time"
)
type State int
const (
Follower State = iota
Candidate
Leader
)
type RequestVoteArgs struct {
Term int
CandidateID int
}
type RequestVoteReply struct {
Term int
VoteGranted bool
}
type AppendEntriesArgs struct {
Term int
LeaderID int
}
type AppendEntriesReply struct {
Term int
Success bool
}
// Network simulates unreliable RPC delivery.
type Network struct {
mu sync.Mutex
nodes map[int]*Node
dropRate float64
}
func NewNetwork(dropRate float64) *Network {
return &Network{
nodes: make(map[int]*Node),
dropRate: dropRate,
}
}
func (net *Network) Register(node *Node) {
net.mu.Lock()
defer net.mu.Unlock()
net.nodes[node.id] = node
}
func (net *Network) SendRequestVote(from, to int, args RequestVoteArgs) {
net.mu.Lock()
target := net.nodes[to]
net.mu.Unlock()
if target == nil {
return
}
if rand.Float64() < net.dropRate {
// simulate drop
return
}
reply := target.handleRequestVote(args)
if rand.Float64() < net.dropRate {
return
}
net.mu.Lock()
sender := net.nodes[from]
net.mu.Unlock()
if sender != nil {
sender.handleRequestVoteReply(reply)
}
}
func (net *Network) SendAppendEntries(from, to int, args AppendEntriesArgs) {
net.mu.Lock()
target := net.nodes[to]
net.mu.Unlock()
if target == nil {
return
}
if rand.Float64() < net.dropRate {
return
}
reply := target.handleAppendEntries(args)
if rand.Float64() < net.dropRate {
return
}
_ = reply // for heartbeat we don't care about reply
}
// Node implements a Raft peer with only leader election.
type Node struct {
mu sync.Mutex
id int
peers []int
network *Network
state State
currentTerm int
votedFor int
voteCount int
electionTimer *time.Timer
electionTimeout time.Duration
heartbeatInterval time.Duration
stopCh chan struct{}
// if leader, heartbeats will be sent by a goroutine
}
func NewNode(id int, peers []int, net *Network) *Node {
n := &Node{
id: id,
peers: peers,
network: net,
state: Follower,
votedFor: -1,
electionTimeout: randomElectionTimeout(),
heartbeatInterval: 50 * time.Millisecond,
stopCh: make(chan struct{}),
}
n.resetElectionTimerLocked()
return n
}
func randomElectionTimeout() time.Duration {
// 150-300 ms by convention
return time.Duration(150+rand.Intn(150)) * time.Millisecond
}
func (n *Node) Start() {
n.network.Register(n)
go n.run()
}
func (n *Node) Stop() {
close(n.stopCh)
n.mu.Lock()
if n.electionTimer != nil {
n.electionTimer.Stop()
}
n.mu.Unlock()
}
func (n *Node) run() {
for {
select {
case <-n.stopCh:
return
case <-n.getElectionTimer().C:
n.startElection()
}
}
}
func (n *Node) getElectionTimer() *time.Timer {
n.mu.Lock()
defer n.mu.Unlock()
return n.electionTimer
}
// startElection transitions this node to a candidate and starts requesting votes.
func (n *Node) startElection() {
n.mu.Lock()
n.state = Candidate
n.currentTerm++
termStarted := n.currentTerm
n.votedFor = n.id
n.voteCount = 1 // vote for self
n.resetElectionTimerLocked()
log.Printf("[Node %d] Starting election for term %d", n.id, termStarted)
n.mu.Unlock()
// send RequestVote to all peers
for _, peer := range n.peers {
go n.network.SendRequestVote(n.id, peer, RequestVoteArgs{Term: termStarted, CandidateID: n.id})
}
}
func (n *Node) handleRequestVote(args RequestVoteArgs) RequestVoteReply {
n.mu.Lock()
defer n.mu.Unlock()
reply := RequestVoteReply{Term: n.currentTerm, VoteGranted: false}
if args.Term < n.currentTerm {
return reply
}
if args.Term > n.currentTerm {
n.currentTerm = args.Term
n.state = Follower
n.votedFor = -1
}
// grant vote if haven't voted or already voted for this candidate
if n.votedFor == -1 || n.votedFor == args.CandidateID {
n.votedFor = args.CandidateID
reply.VoteGranted = true
reply.Term = n.currentTerm
n.resetElectionTimerLocked() // reset election timeout on granting vote
}
return reply
}
func (n *Node) handleRequestVoteReply(reply RequestVoteReply) {
n.mu.Lock()
defer n.mu.Unlock()
// ignore stale replies
if n.state != Candidate {
return
}
if reply.Term > n.currentTerm {
// discovered higher term, step down
n.currentTerm = reply.Term
n.state = Follower
n.votedFor = -1
n.voteCount = 0
n.resetElectionTimerLocked()
return
}
if reply.VoteGranted {
n.voteCount++
if n.voteCount > len(n.peers)/2 {
// win the election
n.state = Leader
log.Printf("[Node %d] Became leader for term %d", n.id, n.currentTerm)
n.resetElectionTimerLocked() // no elections while leader
go n.sendHeartbeats(term = n.currentTerm)
}
}
}
// sendHeartbeats sends periodic AppendEntries with no entries.
func (n *Node) sendHeartbeats(term int) {
t := time.NewTicker(n.heartbeatInterval)
defer t.Stop()
for {
select {
case <-n.stopCh:
return
case <-t.C:
n.mu.Lock()
if n.state != Leader || n.currentTerm != term {
n.mu.Unlock()
return
}
peers := append([]int(nil), n.peers...)
n.mu.Unlock()
for _, peer := range peers {
go n.network.SendAppendEntries(n.id, peer, AppendEntriesArgs{Term: term, LeaderID: n.id})
}
}
}
}
func (n *Node) handleAppendEntries(args AppendEntriesArgs) AppendEntriesReply {
n.mu.Lock()
defer n.mu.Unlock()
reply := AppendEntriesReply{Term: n.currentTerm, Success: false}
if args.Term < n.currentTerm {
return reply
}
reply.Success = true
if args.Term > n.currentTerm || n.state != Follower {
n.currentTerm = args.Term
n.state = Follower
n.votedFor = -1
}
n.resetElectionTimerLocked()
return reply
}
func (n *Node) resetElectionTimerLocked() {
if n.electionTimer != nil {
n.electionTimer.Stop()
}
n.electionTimeout = randomElectionTimeout()
n.electionTimer = time.NewTimer(n.electionTimeout)
}
// State returns current state for testing.
func (n *Node) State() State {
n.mu.Lock()
defer n.mu.Unlock()
return n.state
}
And a test that simulates packet loss and asserts that the cluster converges to a leader:
// raft_test.go
package raft
import (
"math/rand"
"testing"
"time"
)
func TestLeaderElectionWithPacketLoss(t *testing.T) {
rand.Seed(time.Now().UnixNano())
net := NewNetwork(dropRate=0.3) // 30% packet loss
// create three nodes
nodeIDs := []int{1, 2, 3}
nodes := make([]*Node, 0, len(nodeIDs))
for _, id := range nodeIDs {
peers := []int{}
for _, pid := range nodeIDs {
if pid != id {
peers = append(peers, pid)
}
}
n := NewNode(id, peers, net)
nodes = append(nodes, n)
}
// start them
for _, n := range nodes {
n.Start()
}
defer func() {
for _, n := range nodes {
n.Stop()
}
}()
// Wait for some time to allow elections.
time.Sleep(2 * time.Second)
// Check for a single leader.
leaders := []int{}
for _, n := range nodes {
if n.State() == Leader {
leaders = append(leaders, n.id)
}
}
if len(leaders) != 1 {
t.Fatalf("expected exactly one leader, got %v", leaders)
}
t.Logf("Leader elected: %v", leaders[0])
}
This test constructs a three–node cluster, starts all nodes, and waits for up to two seconds. The randomized election timeouts break split votes, and even with 30 % simulated packet loss in the network, the cluster will eventually converge on a single leader. Adjust the dropRate, timeouts, and sleep duration as needed for your environment.
Note: This is a minimal illustrative implementation of Raft's election mechanism. The full Raft algorithm includes persistent storage, log replication, and other details that are beyond the scope of this example.