Sub topic 6
Log Matching and Repairing Divergent Followers
This chapter covers how a Raft leader brings a follower's log in line with its own after crashes and leader changes. It assumes you know the following:
- Raft's roles and terms.
- How RequestVote elects a leader.
- The basic shape of an AppendEntries call.
- Python at the level of the code samples below.
Entries are numbered from 1. Index 0 holds a sentinel entry with term 0, so "the entry before the first real entry" always exists.
The Log Matching Property
Raft guarantees two things about any two logs, on any two servers:
- If two entries have the same index and the same term, they store the same command.
- If two entries have the same index and the same term, then all entries before them are identical in both logs.
Together these mean a log can be summarized by its last (index, term) pair. If two servers agree on that pair, they agree on the whole history up to it.
The guarantees come from two mechanisms:
- One creator per slot. A leader creates at most one entry for a given index in its term, and it never changes or reorders entries once written. Each term has at most one leader, so an (index, term) pair names exactly one entry. That gives guarantee 1.
- A consistency check on every AppendEntries. The leader sends the index and term of the entry that immediately precedes the new ones. The follower accepts only if it has an entry with that index and term. By induction, each accepted append extends a prefix that already matches, which gives guarantee 2.
How Logs Diverge
A follower's log can differ from the new leader's log in three ways:
- It can be missing entries, because the follower was down or slow.
- It can have extra entries, because an old leader replicated them to the follower but crashed before they were committed.
- It can have conflicting entries, a mix of the two over several leader changes.
The table shows terms by index. A new leader holds the log in the first row.
| Server | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Leader | 1 | 1 | 1 | 4 | 4 | 5 | 5 | 6 | 6 | 6 | - |
| F1 (missing) | 1 | 1 | 1 | 4 | 4 | 5 | 5 | 6 | 6 | - | - |
| F2 (extra) | 1 | 1 | 1 | 4 | 4 | 5 | 5 | 6 | 6 | 6 | 6 |
| F3 (conflict) | 1 | 1 | 1 | 2 | 2 | 2 | 3 | 3 | 3 | 3 | 3 |
Raft does not try to merge these logs. The leader's log is authoritative. The election rule from the previous chapters ensures the leader holds every committed entry, so anything on a follower that disagrees with the leader is uncommitted and safe to discard. The leader never overwrites or deletes its own entries.
The Follower Side
This is the follower's handler. It implements the consistency check, the conflict deletion, and the commit index update.
def handle_append_entries(s, req):
# s.log[0] is a sentinel entry with term 0, so real entries start at index 1.
if req.term < s.current_term:
return (s.current_term, False)
if req.term > s.current_term:
s.current_term = req.term
s.voted_for = None
s.role = "follower"
s.reset_election_timer()
# Consistency check: our log must contain the entry just before the new ones.
if req.prev_log_index >= len(s.log) or s.log[req.prev_log_index].term != req.prev_log_term:
s.persist()
return (s.current_term, False)
index = req.prev_log_index
for entry in req.entries:
index += 1
if index < len(s.log) and s.log[index].term != entry.term:
del s.log[index:] # drop the conflicting entry and everything after it
if index >= len(s.log):
s.log.append(entry)
if req.leader_commit > s.commit_index:
s.commit_index = min(req.leader_commit, index)
s.persist()
return (s.current_term, True)Several details here are easy to get wrong.
- Stale terms are rejected first. A request from an old leader must never modify the log. A higher term makes the server update its term and clear its vote.
- A valid request resets the election timer, even if the consistency check then fails. The sender is a legitimate leader for the current term, so the follower should not start an election.
- Truncation happens only on a real conflict. The loop deletes from
indexonward only when an existing entry has a different term than the incoming one. If the entries already match, the follower keeps its log as it is. - The commit index is capped. The follower sets it to
min(leader_commit, index), whereindexis the last entry the request verified. Anything past that point has not been checked against the leader, so it cannot be treated as committed.
The Leader Side: nextIndex and matchIndex
The leader tracks two numbers for each follower:
next_indexis the next entry the leader will try to send. When a leader takes office, it sets this to its last log index plus 1 for every follower. This is an optimistic guess that the follower is up to date.match_indexis the highest index the leader knows is replicated on that follower. It starts at 0 and only moves forward.
The repair procedure follows from these two numbers:
- Send AppendEntries with
prev_log_index = next_index - 1and every entry fromnext_indexon. - If the follower replies false, decrement
next_indexand retry. - If the follower replies true, set
match_index = prev_log_index + len(entries)andnext_index = match_index + 1.
The loop always ends. At next_index = 1 the previous entry is the sentinel at index 0, which matches on every server.
The following program simulates this procedure. It uses the logs from the table and a simplified version of the follower handler with the term and persistence handling removed.
from dataclasses import dataclass
@dataclass
class Entry:
term: int
def make_log(terms):
return [Entry(0)] + [Entry(t) for t in terms] # index 0 is the sentinel
def terms(log):
return [e.term for e in log[1:]]
def follower_append(log, prev_index, prev_term, entries):
if prev_index >= len(log) or log[prev_index].term != prev_term:
return False
index = prev_index
for entry in entries:
index += 1
if index < len(log) and log[index].term != entry.term:
del log[index:]
if index >= len(log):
log.append(entry)
return True
def replicate(leader_log, follower_log, next_index):
attempts = 0
while True:
attempts += 1
prev = next_index - 1
entries = leader_log[next_index:]
if follower_append(follower_log, prev, leader_log[prev].term, entries):
return attempts, prev + len(entries) # attempts, match_index
next_index -= 1
leader = make_log([1, 1, 1, 4, 4, 5, 5, 6, 6, 6])
followers = {
"F1 missing": make_log([1, 1, 1, 4, 4, 5, 5, 6, 6]),
"F2 extra": make_log([1, 1, 1, 4, 4, 5, 5, 6, 6, 6, 6]),
"F3 conflict": make_log([1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3]),
}
for name, log in followers.items():
attempts, match = replicate(leader, log, len(leader))
print(f"{name}: attempts={attempts} match_index={match} terms={terms(log)}")
# The new leader accepts a client command in term 8 and sends it to F2.
leader.append(Entry(8))
attempts, match = replicate(leader, followers["F2 extra"], 11)
print(f"F2 after new entry: attempts={attempts} match_index={match} terms={terms(followers['F2 extra'])}")Running it prints:
F1 missing: attempts=2 match_index=10 terms=[1, 1, 1, 4, 4, 5, 5, 6, 6, 6]
F2 extra: attempts=1 match_index=10 terms=[1, 1, 1, 4, 4, 5, 5, 6, 6, 6, 6]
F3 conflict: attempts=8 match_index=10 terms=[1, 1, 1, 4, 4, 5, 5, 6, 6, 6]
F2 after new entry: attempts=1 match_index=11 terms=[1, 1, 1, 4, 4, 5, 5, 6, 6, 6, 8]Each follower behaves differently:
- F1 rejects the first attempt because it has no entry 10. It accepts the second attempt, which carries entry 10.
- F3 rejects seven attempts, because its terms at indexes 10 down to 4 disagree with the leader's. It accepts at
prev_log_index = 3, deletes its conflicting entries 4 to 11, and takes the leader's entries 4 to 10. - F2 accepts immediately, because its entry 10 matches. It keeps its extra entry 11, since an empty heartbeat has nothing that conflicts with it. The leader records
match_index = 10, not 11. That is correct, because entry 11 on F2 is not known to match the leader's log. The extra entry disappears when the leader's new term-8 entry arrives at index 11 and conflicts with it.
Speeding Up the Backoff
Backing up one entry per round trip is fine when logs differ by a few entries. A follower that was down for a long time can be thousands of entries behind, and then the repair takes thousands of round trips.
The usual fix is to let the rejection carry a hint. A follower rejecting a request can reply with the term of its conflicting entry and the first index it holds for that term. The leader can then skip past a whole term at once. Alternatively, a follower that is simply too short can reply with its log length. This is an optimization, not part of the safety argument. The one-step backoff is always correct, and the hint only has to move next_index to a value that is not too high.
Common Errors
- Using the follower's log length as
match_index. The follower may hold unverified extra entries, as F2 does. Computematch_indexfrom the request you sent:prev_log_index + len(entries). This also makes late or duplicated replies harmless, because they carry the same value they would have carried the first time. - Letting
match_indexgo backward. Replies can arrive out of order. Take the maximum of the old value and the new one. - Off-by-one on the sentinel. If your log is a zero-based list with no sentinel,
prev_log_index = 0needs special handling. The consistency check must treat "no previous entry" as always matching. - Skipping the term check on AppendEntries. A deposed leader can still send requests. Without the
req.term < s.current_termcheck it could rewrite the log of a follower that has moved to a newer term. - Replying before the log is durable. A follower's success reply tells the leader the entry is stored. If the server crashes after replying but before writing to disk, the entry can be lost after the leader counted it toward a majority. Persist first, then reply.
Summary
Log matching rests on two facts: one leader per term writes each index once, and every AppendEntries is checked against the entry before it. The leader finds the last point of agreement by decrementing next_index. The follower then deletes its conflicting suffix and copies the leader's entries. The leader advances match_index only to what it actually verified, and a follower advances its commit index only to what the request verified.
Exercise
A follower's log has terms [1, 1, 2, 2, 2] at indexes 1 to 5. The leader's log has terms [1, 1, 2, 3, 3, 3] at indexes 1 to 6, and its next_index for this follower is 6. Without running anything, how many AppendEntries calls does the leader need before the follower accepts, and what does the follower's log look like afterwards?
Show answer
Three calls. The first has prevlogindex=5 with prevTerm 3, but the follower's entry 5 has term 2, so it is rejected. The second has prevlogindex=4 with prevTerm 3, and the follower's entry 4 has term 2, so it is rejected. The third has prevlogindex=3 with prevTerm 2, which matches the follower's entry 3, so it is accepted. The leader's entries 4 to 6 (terms 3, 3, 3) replace the follower's entry 4 conflict, and the follower's log becomes [1, 1, 2, 3, 3, 3].
Exercise
A follower with log terms [1, 1, 2] at indexes 1 to 3 receives AppendEntries with prevlogindex=1, prevlogterm=1, entries=[term 2 at index 2], and leadercommit=5. What is the follower's commitindex afterward, assuming it started at 0, and why is it not 5?
Show answer
The commitindex is 2. The request verified entries only up to index 2 (prevlogindex 1 plus one new entry), so the follower sets commitindex to min(5, 2). Entry 3 on the follower was not checked against the leader's log, so it must not be treated as committed. The follower's entry 2 already matches the incoming entry (term 2), so nothing is deleted and entry 3 stays in the log.
Exercise
Why does the leader set matchindex to prevlog_index + len(entries) instead of the length of the follower's log, and what can go wrong with the second choice?
Show answer
The follower may hold extra entries beyond what the leader sent, and those entries are not known to match the leader's log. Using the follower's length would overstate how much of the leader's log is replicated. The leader could then count a majority for an entry that is not actually stored on enough servers and commit it unsafely. Using the values from the request also makes delayed or duplicated replies harmless.