Sub topic 5
Replicating the log with AppendEntries
This chapter assumes you know what a replicated log is and how terms and RequestVote produce a leader. Here you will follow one client command from the leader to its followers. How a leader repairs a follower whose log has diverged, and when an entry counts as committed, are covered in the next two chapters.
What the leader does with a command
Once a server wins an election, it is the only server that accepts new commands. A command can be any operation the state machine understands, such as set x=5. The leader handles it in three steps:
- Append a new entry to its own log, tagged with its current term.
- Send that entry to every follower with an
AppendEntriesRPC. - Wait until a majority of servers have stored it.
The leader does not apply the command to its state machine yet. It applies the command only after the entry is committed.
The AppendEntries RPC
AppendEntries does two jobs. It carries new log entries, and with an empty entry list it acts as a heartbeat that stops followers from starting elections. Both use the same message.
| Field | Meaning |
|---|---|
| `term` | The leader's current term |
| `leader_id` | Lets followers know who the leader is |
| `prev_log_index` | Index of the entry immediately before the new ones |
| `prev_log_term` | Term of that entry |
| `entries` | New entries to store (empty for a heartbeat) |
| `leader_commit` | The leader's commit index |
The prev_log_index and prev_log_term fields are the core of the design. Every message says: "my new entries come right after entry N, which has term T." A follower accepts the entries only if its own log has that same entry at N.
Per-follower bookkeeping
The leader tracks two numbers for each follower:
next_indexis the index of the next entry the leader will send. A new leader starts it at its own last index plus one.match_indexis the highest index known to be identical on that follower. It starts at 0.
Followers can be at different positions, so the leader builds a separate message for each one:
from dataclasses import dataclass
@dataclass
class Entry:
term: int
command: str
def build_append_entries(term, leader_id, log, next_index, commit_index, follower):
# log[0] is a sentinel entry with term 0, so real entries start at index 1.
prev = next_index[follower] - 1
return {
"term": term,
"leader_id": leader_id,
"prev_log_index": prev,
"prev_log_term": log[prev].term,
"entries": log[next_index[follower]:],
"leader_commit": commit_index,
}
log = [Entry(0, ""), Entry(1, "set x=1"), Entry(2, "set y=2"), Entry(2, "set x=3")]
next_index = {"B": 4, "C": 2} # B is caught up, C is behind
print(build_append_entries(2, "A", log, next_index, 1, "B")["entries"]) # []: heartbeat
print(len(build_append_entries(2, "A", log, next_index, 1, "C")["entries"])) # 3Follower B is up to date, so it gets a heartbeat. Follower C is behind, so it gets three entries in one message.
The follower's side
The follower code below was introduced with the RPC rules. Read it as a sequence of checks:
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)The order of the checks matters:
- A message from an older term is rejected. This is how a stale leader learns it has been replaced.
- A valid message from the current or a newer term resets the election timer, even if the log check fails. The follower has still heard from a real leader.
- The
prev_log_indexcheck decides whether the entries can be attached. - Only then does the follower modify its log. The leader's
leader_commitvalue is the last thing it uses.
Handling the reply
The leader reacts to each response:
- On success, set
match_index[f] = prev_log_index + len(entries)andnext_index[f] = match_index[f] + 1. - On failure caused by a log mismatch, decrease
next_index[f]and retry. The next chapter explains this repair loop. - If the reply carries a higher term, the leader steps down to follower.
Common mistakes
- Sending only new entries and omitting
prev_log_indexandprev_log_term. Without them, followers cannot detect gaps or conflicts. - Not resetting the election timer when the consistency check fails. Followers then start needless elections while a healthy leader is talking to them.
- Treating a lost or delayed RPC as an error. Leaders retry indefinitely, so followers must tolerate repeated messages. The delete-then-append loop makes a repeated message harmless.
Exercise
A leader has a log with entries 1 through 5. Follower C has next_index = 3. What prev_log_index and entries does the leader put in its next AppendEntries to C? What happens to next_index[C] and match_index[C] if C replies success?
Show answer
prev_log_index is 2, and prev_log_term is the term of entry 2. entries holds entries 3, 4, and 5. On success, match_index[C] becomes 2 + 3 = 5 and next_index[C] becomes 6.