Sub topic 5
Replicating the log with AppendEntries
This chapter assumes you know the roles and terms from the earlier chapters, how RequestVote elects a leader, and what a majority quorum is. You should also be comfortable reading short Python. Here we follow one client command from the leader's log to the followers' logs. Log repair and the commit rule are only previewed. They get their own chapters.
What AppendEntries is for
Once a server wins an election, it is the only server that accepts new commands in its term. For each command it does three things:
- It appends a new entry to its own log. The entry holds the command and the leader's current term.
- It sends that entry to every follower with an
AppendEntriesRPC. - It counts how many servers have stored the entry. Once a majority has it, the entry can be committed.
One RPC serves two purposes. With entries attached, it replicates the log. With an empty entry list, it is a heartbeat that tells followers the leader is alive and resets their election timers. The follower handles both with the same code path.
The request and the reply
| Field | Meaning |
|---|---|
| `term` | The leader's current term. Followers use it to detect stale leaders. |
| `leader_id` | Lets followers redirect clients to the leader. |
| `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 reply has two fields: the follower's current_term and a boolean success. The leader uses the term to step down if it learns it is out of date. It uses success to decide whether to move forward or back.
The prev_log_index and prev_log_term pair is the key to the design. A leader never sends entries blindly. It says, "Append these after the entry at index N, which has term T." A follower accepts only if its own log has an entry at N with term T. Chapter 6 shows why this single check keeps all logs consistent.
The leader's bookkeeping
For each follower the leader keeps two numbers:
next_index[peer]is the index of the next entry to send. It is an optimistic guess. When a leader is elected, it starts at the leader's last log index plus one.match_index[peer]is the highest index known to be stored on that follower. It is a proven fact. It starts at 0.
The leader moves next_index back by one when a follower rejects an RPC. It moves both values forward when a follower accepts. The commit rule later reads only match_index.
The sketch below uses a Leader object and shows how a request is built and how a reply is handled. It runs as written.
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Entry:
term: int
command: str
@dataclass
class AppendEntriesRequest:
term: int
leader_id: int
prev_log_index: int
prev_log_term: int
entries: list
leader_commit: int
@dataclass
class Leader:
id: int
current_term: int
log: list # log[0] is a sentinel entry with term 0
commit_index: int
next_index: dict
match_index: dict
role: str = "leader"
voted_for: Optional[int] = None
def persist(self):
pass # a real server writes currentTerm, votedFor, log to disk
def build_append_entries(leader, peer):
next_i = leader.next_index[peer]
prev = next_i - 1
return AppendEntriesRequest(
term=leader.current_term,
leader_id=leader.id,
prev_log_index=prev,
prev_log_term=leader.log[prev].term,
entries=leader.log[next_i:], # empty list means heartbeat
leader_commit=leader.commit_index,
)
def handle_append_entries_reply(leader, peer, req, reply_term, success):
if reply_term > leader.current_term:
leader.current_term = reply_term
leader.voted_for = None
leader.role = "follower"
leader.persist()
return
# Ignore replies to requests sent in an earlier term or after stepping down.
if leader.role != "leader" or req.term != leader.current_term:
return
if success:
last_sent = req.prev_log_index + len(req.entries)
leader.match_index[peer] = max(leader.match_index[peer], last_sent)
leader.next_index[peer] = leader.match_index[peer] + 1
else:
leader.next_index[peer] = max(1, leader.next_index[peer] - 1)
leader = Leader(
id=1,
current_term=2,
log=[Entry(0, ""), Entry(1, "set x=1"), Entry(2, "set y=2")],
commit_index=1,
next_index={2: 3, 3: 1},
match_index={2: 0, 3: 0},
)
for peer in (2, 3):
req = build_append_entries(leader, peer)
print(peer, req.prev_log_index, req.prev_log_term, [e.command for e in req.entries])
handle_append_entries_reply(leader, 2, build_append_entries(leader, 2), 2, False)
print(leader.next_index)Peer 2 is up to date, so its request carries no entries. Peer 3 is new, so its request carries both entries. The sentinel at log[0] lets prev_log_index = 0 work without a special case.
The handler updates match_index from what the request contained (prev_log_index + len(entries)), not from the leader's current last index. The log may have grown between sending and receiving the reply. Using the current last index would claim the follower holds entries it was never sent. The max guards against replies that arrive out of order, so a delayed reply cannot move match_index backward.
The follower's side
The follower runs this handler, which is the one from the topic plan:
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 handler works in five steps.
- Reject stale leaders. A request with an older term comes from a deposed leader. The follower replies with its own term, so that leader learns it is out of date and steps down.
- Adopt newer terms and reset the timer. A request from the current or a newer term is from a legitimate leader. The follower becomes (or stays) a follower and resets its election timer. A candidate that receives such a request in its own term gives up and returns to follower. This happens before the log check. Even a request that is later rejected still proves a live leader exists.
- Check consistency. If the follower has no entry at
prev_log_index, or the entry has a different term, it rejects. It changes no log entries. - Merge entries. The loop walks the new entries. It truncates only when an existing entry conflicts with the incoming one, meaning the same index but a different term. Matching entries are left alone.
- Advance the commit index. The follower takes the leader's commit index but caps it at
index, the last entry this request covered.
One replication round
The leader can answer the client after a majority has stored the entry, and it does not have to wait for the slowest follower. Followers learn the new commit index from the next AppendEntries, which may be the next heartbeat. They apply the entry to their state machines only then.
Heartbeats
If a leader has nothing to send, it still sends an empty AppendEntries to every follower at a fixed interval. The heartbeat interval must be much shorter than the election timeout, or followers will time out and start needless elections. A common choice is a heartbeat of 50 ms with election timeouts of 150 to 300 ms.
Heartbeats also repair logs. A follower that was down will reject the first heartbeat if its log is behind. The leader then backs next_index up and retries, as the next chapter describes.
Edge cases and common errors
Most bugs in Raft implementations come from the follower handler, so check these first.
- Truncating on every request. Network delay can deliver an old, shorter
AppendEntriesafter a newer one. If the follower deleted everything afterprev_log_indexunconditionally, it would throw away entries the leader believes are stored, and the leader may already have counted them toward a majority. Truncate only on an actual term conflict. - Setting
commit_indextoleader_commitunchanged. The follower may not hold all the entries the leader has committed, for example after a heartbeat to a lagging follower. Cap the value at the last index this request verified. - Using
len(s.log) - 1for the cap. The follower's log may have extra, unverified entries beyond the ones in the request. Those entries may not match the leader. Only the entries covered by the consistency check are known to match. - Forgetting
voted_for = Noneon a new term. The vote belongs to a term. Keeping an old vote while moving to a newer term can block the follower from voting in that term, or allow it to vote twice. - Replying before persisting. The follower's success reply tells the leader the entries are stored. If they only exist in memory, a crash after the reply could lose an entry that the leader counted toward a majority. Write to disk first, then reply.
- Treating a failed RPC as a rejection. A timeout or lost message means nothing about the follower's log. Only a reply with
success = Falseshould movenext_indexback. On a timeout, the leader simply sends again. - Handling stale replies. A reply can arrive after the leader changed terms or stepped down. The check
req.term != leader.current_termdiscards these.
What comes next
Replication alone does not say when an entry is safe to treat as committed, and a rejected request only says "go back one step." The next chapter explains how the leader walks next_index back to find where a divergent follower's log last agreed with its own, and why the entries it overwrites are never committed ones.
Exercise
A leader in term 4 has log terms [1, 1, 2, 4, 4] at indexes 1 to 5, and next_index[F] = 6 for follower F. F's log has terms [1, 1, 2] at indexes 1 to 3. (a) What are prev_log_index and prev_log_term in the first request to F? (b) What does F reply, and what does the leader do with next_index[F]? (c) After next_index[F] reaches 4, what does F reply, what is its log, and what is match_index[F]?
Show answer
(a) The request has prev_log_index = 5 and prev_log_term = 4, with an empty entry list. (b) F has no entry at index 5, so the consistency check fails and F replies success = False with its current term. The leader decrements next_index[F] to 5, then 4 on the next failure (index 4 is also missing on F). (c) With next_index[F] = 4, the request has prev_log_index = 3 and prev_log_term = 2. F's entry at index 3 has term 2, so the check passes. The request carries entries 4 and 5 (both term 4), F appends them, and replies success = True. F's log becomes terms [1, 1, 2, 4, 4]. The leader sets match_index[F] = 3 + 2 = 5 and next_index[F] = 6.