Sub topic 11
Snapshots and Log Compaction
This chapter assumes you know Raft's log replication, the commit index, and the persistent state a server must write before replying. It covers how a long-running cluster stops its log from growing forever.
Why the log needs compaction
A Raft log is append-only. Left alone, it grows without bound. Replaying a huge log after a restart would be slow, and the disk would eventually fill.
Most of that history is redundant. Once a prefix of the log has been applied to the state machine, the state machine's current state already reflects it. A snapshot saves that state and lets the server discard the log entries it covers.
What a snapshot contains
Each server takes snapshots independently. It does not need the leader's permission, because a snapshot only contains committed, applied entries. Those entries can never change.
A snapshot holds:
- The state machine's state after applying all entries up to some index.
last_included_index: the index of the last entry the snapshot covers.last_included_term: the term of that entry.- Optionally, the latest cluster configuration (see the membership chapter).
The last two values are not optional. After discarding the log prefix, the server still has to answer the AppendEntries consistency check. That check compares the term at prev_log_index. If prev_log_index equals last_included_index, the server uses last_included_term to answer.
Taking a snapshot
The code below shows the idea. The server snapshots only up to last_applied, never beyond it. It keeps the log indexes stable by remembering an offset.
class Entry:
def __init__(self, term, command=None):
self.term = term
self.command = command
class Server:
def __init__(self):
# log[0] is a sentinel. After compaction it stands for the snapshot's last entry.
self.log = [Entry(0)]
self.snapshot_index = 0 # last_included_index
self.snapshot_term = 0 # last_included_term
self.last_applied = 0
self.snapshot_state = {}
def term_at(self, index):
return self.log[index - self.snapshot_index].term
def take_snapshot(self, state):
# Only applied (hence committed) entries may be discarded.
index = self.last_applied
if index <= self.snapshot_index:
return
term = self.term_at(index)
keep = self.log[index - self.snapshot_index + 1:]
self.snapshot_state = state
self.snapshot_index = index
self.snapshot_term = term
self.log = [Entry(term)] + keep # sentinel carries last_included_term
# In a real system: write the snapshot durably, then truncate the log.
s = Server()
for t in (1, 1, 2, 2):
s.log.append(Entry(t))
s.last_applied = 3
s.take_snapshot({"x": 3})
print(s.snapshot_index, s.snapshot_term, len(s.log))Running this prints 3 2 2. The snapshot covers entries 1 to 3, and the log keeps the sentinel plus entry 4.
The order of writes matters. Write the new snapshot to disk and make it durable first, then delete the old log prefix. A crash between the two steps leaves extra log entries, which is harmless. The reverse order could lose data.
Sending snapshots to slow followers
Normally a leader repairs a follower by walking next_index backward. Compaction breaks this when the follower needs an entry the leader has already discarded. The leader cannot send entries it no longer has.
In that case the leader sends its snapshot with the InstallSnapshot RPC. The request carries the leader's term, leader_id, last_included_index, last_included_term, and the snapshot data, often split into chunks.
The follower handles it like this:
- Reject the request if the term is older than its own.
- Reset its election timer, as with any message from a valid leader.
- If its log already contains an entry at
last_included_indexwithlast_included_term, keep the entries after that point. The snapshot only describes a prefix the follower already has. - Otherwise, discard the whole log. The snapshot supersedes it.
- Replace the state machine's state with the snapshot and set
commit_indexandlast_appliedto at leastlast_included_index.
After this, the leader sets next_index to last_included_index + 1 and resumes normal AppendEntries.
Common errors and trade-offs
- Snapshotting uncommitted entries. Entries beyond the commit index can still be overwritten. Never include them.
- Losing the last included term. Without it, the follower cannot answer the consistency check at the snapshot boundary.
- Blocking the server while snapshotting. Copying a large state machine can stall request handling. Real systems use copy-on-write snapshots or a forked process.
- Snapshotting too often. Each snapshot costs disk and CPU. Too rarely, and the log is large. A common rule is to snapshot when the log passes a fixed size.
- Sending snapshots too eagerly. Snapshots are large. A leader should send one only when the follower's
next_indexfalls behind its own log start.
Exercise
A follower's log ends at index 40. The leader took a snapshot at index 100 and discarded entries 1 to 100. The leader's next_index for this follower is 41. What does the leader send, and why?
Show answer
It sends InstallSnapshot, not AppendEntries. Entry 41 no longer exists in the leader's log, so it cannot build the AppendEntries payload. The follower has none of the entries 41 to 100, so it discards its log, loads the snapshot, and the leader then sets next_index to 101.
Exercise
Why must a snapshot record lastincludedterm as well as lastincludedindex?
Show answer
The AppendEntries consistency check compares the term of the entry at prevlogindex. When prevlogindex is the snapshot boundary, the entry is gone, so the server answers from lastincludedterm.