Skip to content

Commit

Permalink
feat: missed heartbeat logic tolerant to network delay
Browse files Browse the repository at this point in the history
  • Loading branch information
nick-bisonai committed Aug 22, 2024
1 parent 5206f51 commit 6a6c353
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
14 changes: 13 additions & 1 deletion node/pkg/raft/raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func NewRaftNode(
HeartbeatTimeout: HEARTBEAT_TIMEOUT,

LeaderJobTimeout: leaderJobTimeout,
MissedHeartbeats: 0,
}
return r
}
Expand Down Expand Up @@ -129,6 +130,8 @@ func (r *Raft) handleHeartbeat(msg Message) error {
r.Mutex.Lock()
defer r.Mutex.Unlock()

r.MissedHeartbeats = 0

currentRole := r.Role
currentTerm := r.Term

Expand Down Expand Up @@ -387,13 +390,22 @@ func (r *Raft) startElectionTimer() {
}

func (r *Raft) startElection(ctx context.Context) {
log.Debug().Msg("start election")
r.Mutex.Lock()
defer r.Mutex.Unlock()

if r.MissedHeartbeats < MaxMissedHeartbeats {
r.MissedHeartbeats++
log.Debug().Int("missed heartbeats", r.MissedHeartbeats).Msg("missed heartbeats")
r.startElectionTimer()
return
}

log.Debug().Msg("start election")
r.Term++
r.VotesReceived = 0
r.Role = Candidate
r.VotedFor = r.GetHostId()
r.MissedHeartbeats = 0

r.startElectionTimer()

Expand Down
4 changes: 4 additions & 0 deletions node/pkg/raft/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const (
Leader RoleType = "leader"
Candidate RoleType = "candidate"
Follower RoleType = "follower"

MaxMissedHeartbeats = 3
)

type Message struct {
Expand Down Expand Up @@ -67,4 +69,6 @@ type Raft struct {
LeaderJobTicker *time.Ticker
HandleCustomMessage func(context.Context, Message) error
LeaderJob func(context.Context) error

MissedHeartbeats int
}

0 comments on commit 6a6c353

Please sign in to comment.