diff --git a/toy-raft/raft/raft.go b/toy-raft/raft/raft.go index 9f14923..0df0732 100644 --- a/toy-raft/raft/raft.go +++ b/toy-raft/raft/raft.go @@ -616,6 +616,14 @@ func (rn *RaftNodeImpl) handleAppendEntriesRequest(appendEntriesRequest *AppendE return } + // NOTE: optimization to ignore outdated requests below commit index + if appendEntriesRequest.PrevLogIdx < rn.commitIndex { + // we've matched at least up to the entries we've already achieved quorum on + resp.MatchIndex = rn.commitIndex + rn.SendMessage(appendEntriesRequest.LeaderId, resp) + return + } + // check if log state is consistent with leader if appendEntriesRequest.PrevLogTerm != NoPreviousTerm { // no entry exists diff --git a/toy-raft/raft/raft_test.go b/toy-raft/raft/raft_test.go index 21dcc10..c2e9ee1 100644 --- a/toy-raft/raft/raft_test.go +++ b/toy-raft/raft/raft_test.go @@ -712,14 +712,14 @@ func TestFollowerHandleAppendEntries(t *testing.T) { // TODO: remove these vars and all like it, use req struct instead var ( - prevLogEntryIdx uint64 = 2 - prevLogEntryTerm uint64 = 1 + prevLogEntryIdx uint64 = 3 + prevLogEntryTerm uint64 = 2 ) reqTerm = 2 duplicateAndNewAEReq := &AppendEntriesRequest{ Term: reqTerm, LeaderId: leaderId, - Entries: []Entry{{Term: 2, Cmd: []byte("baz")}, {Term: 2, Cmd: []byte("faz")}}, + Entries: []Entry{{Term: 2, Cmd: []byte("faz")}}, PrevLogIdx: prevLogEntryIdx, PrevLogTerm: prevLogEntryTerm, LeaderCommitIdx: leaderCommit,