Sub topic 2
Replicating the Log with AppendEntries
Assume you know nodes, RPC messages, network partitions, and append-only logs. Raft uses one leader to copy commands into followers’ logs.
Replicating the log with AppendEntries
The leader sends an AppendEntries RPC containing:
term: the leader’s current term.prevLogIndexandprevLogTerm: the entry immediately before the new entries.entries: zero or more log entries.leaderCommit: the leader’s commit index.
An empty entries list is a heartbeat. It confirms that the leader is still active and carries the current commit index.
A follower accepts entries only when its log contains the specified previous entry. This check connects the new entries to the existing log.
def append_entries(log, prev_index, prev_term, entries):
# Each entry is a (term, command) pair.
if prev_index >= len(log) or log[prev_index][0] != prev_term:
return False
index = prev_index + 1
for entry in entries:
if index < len(log) and log[index][0] != entry[0]:
del log[index:]
if index == len(log):
log.append(entry)
index += 1
return True
log = [(0, "sentinel"), (1, "set x=1")]
ok = append_entries(log, 1, 1, [(2, "set y=2")])
print(ok, log)The leader tracks nextIndex for each follower, which is the next entry to send. It also tracks matchIndex, the highest entry known to be replicated on that follower.
:::warning A successful RPC response means the follower stored the entries. It does not necessarily mean the entries are committed. :::
Log matching and repairing divergent followers
A follower can contain extra or conflicting entries after a crash or partition. When the previous-entry check fails, the leader moves nextIndex backward and retries. Once the logs meet, the follower deletes its conflicting suffix and appends the leader’s entries.
This process establishes the log-matching property: entries with the same index and term have the same preceding entries.
When an entry is committed, and why it is safe
An entry is committed when the leader knows that a majority, including itself, stores it. The leader normally commits only entries from its current term. After that entry is committed, earlier entries become committed indirectly.
Majorities overlap. Therefore, a future leader must share at least one server with the committing majority. Log up-to-date checks prevent that server from voting for a candidate that could lose the committed entry.
Exercise
Why does a leader reject a follower’s success unless the previous index and term match?
Show answer
The match proves that new entries attach to the same log history. Without it, the leader could overwrite an unrelated prefix.