Sub topic 11
Snapshots and Log Compaction
This chapter assumes you know how AppendEntries replicates entries, how commit_index and last_applied advance, and why currentTerm and votedFor are persisted. You should also be comfortable reading short Python. Earlier chapters used a log that grows forever. This one shows how a real Raft server stops that growth.
Why the log cannot grow forever
Every client command becomes a log entry. A busy cluster accepting 1,000 commands per second at 200 bytes each adds about 17 GB per day to every server. Three problems follow:
- Disk space. The log is stored on every server.
- Restart time. A server that replays the whole log to rebuild its state machine takes longer to recover every day.
- New or slow followers. A fresh server would have to receive the entire history before it could help.
Most of that history is redundant. If the state machine is a key-value store and set x was applied 10,000 times, only the latest value matters. A snapshot is a copy of the state machine's state at a given point in the log. Once a snapshot exists, the log entries before that point can be deleted. Replacing a log prefix with a snapshot is called log compaction.
What a snapshot contains
A snapshot is not just the state machine's data. It needs metadata so the rest of the log still lines up:
| Field | Purpose |
|---|---|
| `last_included_index` | Index of the last log entry the snapshot covers. |
| `last_included_term` | Term of that entry. AppendEntries needs it for the consistency check at the snapshot boundary. |
| State machine state | For example, the whole key-value map. |
| Cluster configuration | The latest membership at `last_included_index`, so membership changes are not lost with the deleted entries. |
| Client session data | If the state machine deduplicates client requests, the table of last-seen request IDs must be included. Otherwise a retried command could run twice after a restart. |
The term matters because the log matching check compares prev_log_term. When the leader's next entry follows the snapshot boundary, the follower must still answer "what was the term at last_included_index?" even though that entry is gone.
Each server snapshots independently
In Raft, every server takes snapshots on its own schedule, with no coordination. The leader does not need to approve a follower's snapshot. This works because a snapshot only contains committed, already-applied entries. Those entries can never change, so no server can disagree about them. Consensus has already been reached on that prefix.
This is a deliberate departure from Raft's strong-leader design, where data otherwise flows only from leader to followers. The alternative, having the leader build one snapshot and push it to everyone, wastes bandwidth and complicates the leader. Independent snapshots keep each server's work local.
Which entries may be included
A server may snapshot only up to last_applied. It must not snapshot up to commit_index or to the end of the log. The snapshot holds the state machine's state, and the state machine has only applied entries up to last_applied. An entry that is committed but not yet applied is not reflected in that state. Snapshotting past last_applied would label the snapshot with an index it does not match.
When to snapshot
The simplest trigger is a size threshold. When the log exceeds N bytes, or N entries since the last snapshot, take a snapshot. Choose N large enough that snapshots are infrequent, since each costs disk I/O. Make it small enough that restarts stay fast. Some systems also snapshot on a timer.
Writing a snapshot of a large state machine can take seconds, and the server must keep handling requests meanwhile. Two common techniques avoid pausing:
- Copy-on-write data structures. The snapshot reads an immutable version while new writes create a new version.
- Fork the process. The operating system's copy-on-write memory pages give the child a frozen view. Redis uses this approach for its own snapshots.
A compactable log in Python
Earlier chapters used s.log[0] as a sentinel entry with term 0. With snapshots, the sentinel generalizes. After compaction, entries[0] stands in for the last included entry, and it stores that entry's term. A base_index field records its absolute index.
from dataclasses import dataclass
@dataclass
class Entry:
term: int
command: tuple = ()
class SnapshotLog:
"""A log whose first slot is a sentinel for the last compacted entry."""
def __init__(self):
self.base_index = 0 # last_included_index of the snapshot (0 = none)
self.entries = [Entry(0)] # entries[0] is the sentinel, term of base_index
def last_index(self):
return self.base_index + len(self.entries) - 1
def term_at(self, index):
if index < self.base_index:
raise IndexError(f"index {index} was compacted")
return self.entries[index - self.base_index].term
def entry_at(self, index):
if index <= self.base_index:
raise IndexError(f"index {index} was compacted")
return self.entries[index - self.base_index]
def append(self, entry):
self.entries.append(entry)
def compact(self, upto):
"""Discard entries up to and including `upto`, keeping its term."""
term = self.term_at(upto)
self.entries = [Entry(term)] + self.entries[upto - self.base_index + 1:]
self.base_index = upto
def install(self, last_index, last_term):
"""Apply a snapshot received from the leader."""
if last_index <= self.base_index:
return # stale snapshot, we already cover this much
if last_index <= self.last_index() and self.term_at(last_index) == last_term:
self.compact(last_index) # our log agrees: keep the entries after it
else:
self.entries = [Entry(last_term)] # our log conflicts or is too short
self.base_index = last_index
class KV:
"""A tiny state machine: a dictionary plus the index it has applied up to."""
def __init__(self):
self.data = {}
self.last_applied = 0
def apply(self, index, command):
op, key, value = command
if op == "set":
self.data[key] = value
self.last_applied = index
def take_snapshot(log, kv):
upto = kv.last_applied # never commit_index, never last_index
snap = {
"last_included_index": upto,
"last_included_term": log.term_at(upto),
"state": dict(kv.data),
}
# A real server writes `snap` to disk and fsyncs it here,
# and only then discards the log prefix.
log.compact(upto)
return snap
def next_message(log, next_index):
"""What the leader sends to a follower whose next entry is next_index."""
if next_index <= log.base_index:
return "install_snapshot"
return f"append_entries(prev_log_index={next_index - 1}, prev_log_term={log.term_at(next_index - 1)})"
if __name__ == "__main__":
log, kv = SnapshotLog(), KV()
for i in range(1, 6):
log.append(Entry(1, ("set", f"k{i}", i)))
for i in range(1, 5): # entries 1-4 applied, entry 5 not yet
kv.apply(i, log.entry_at(i).command)
snap = take_snapshot(log, kv)
print(log.base_index, log.last_index()) # 4 5
print(next_message(log, 3)) # install_snapshot
print(next_message(log, 5)) # append_entries(prev_log_index=4, prev_log_term=1)
follower = SnapshotLog()
follower.append(Entry(1, ("set", "k1", 1)))
follower.install(snap["last_included_index"], snap["last_included_term"])
restored = KV()
restored.data = dict(snap["state"])
restored.last_applied = snap["last_included_index"]
print(follower.base_index, follower.last_index(), restored.data)Note what happens with next_index = 5. The previous index is 4, which is exactly base_index. The sentinel supplies the term, so the normal AppendEntries consistency check still works at the snapshot boundary.
Sending snapshots to lagging followers
Sometimes a follower is so far behind that the next entry it needs, next_index[f], has already been compacted away on the leader. The leader can no longer send those entries. It sends its snapshot instead, using a third RPC called InstallSnapshot.
The follower's handling has these steps:
- Reject the RPC if
term < current_term. Otherwise step down to follower and reset the election timer, as with AppendEntries. - Ignore the snapshot if
last_included_indexis not greater than its own snapshot point. - If the follower already has a log entry at
last_included_indexwith the same term, the snapshot only describes a prefix it already agrees with. It discards that prefix and keeps the entries after it. They may include entries the leader has not yet confirmed, and deleting them is unnecessary. - Otherwise, discard the whole log, replace the state machine with the snapshot's state, and set
last_appliedandcommit_indextolast_included_index.
Step 3 is the install method in the code above. Step 4's reset matters: after installing, the follower's state machine must contain exactly the snapshot's state and nothing else.
Large snapshots
A snapshot can be gigabytes, which does not fit in one RPC. The Raft paper's InstallSnapshot sends it in chunks. Each chunk carries a byte offset and a done flag. The follower writes chunks to a temporary file and applies the snapshot only after the last chunk arrives. If the leader changes mid-transfer, the follower can discard a partial file and start over.
Crash recovery with snapshots
On restart, a server with a snapshot does this:
- Load the latest snapshot into the state machine.
- Set
last_appliedandcommit_indextolast_included_index. - Load the remaining log entries, which start after the snapshot.
- Let
commit_indexadvance normally through AppendEntries from the leader, and apply entries as it does.
commit_index is not persisted, so the server cannot know how far it had committed. It does know that everything in the snapshot was committed, so starting there is safe.
Ordering and atomicity
Writing the snapshot and truncating the log are two separate disk operations, so their order matters:
- Write the snapshot to a temporary file.
fsyncthe file, then rename it over the old snapshot. A rename is atomic on most file systems.- Truncate or delete the log prefix.
A crash after step 2 but before step 3 leaves a snapshot plus a redundant log prefix. That is harmless, since the server can skip entries at or below last_included_index. A crash before step 2 leaves the old snapshot and the full log, which is also consistent. The dangerous order is truncating first.
Trade-offs and common mistakes
Snapshotting more often keeps the log short but costs more disk writes and CPU. Snapshotting rarely keeps the system quiet but makes recovery slower. There is another trade-off for slow followers. If the leader compacts aggressively, a follower that is briefly offline needs a full snapshot instead of a few entries. Some implementations keep a margin of recent entries after a snapshot, such as the last 1,000, so brief outages do not trigger large transfers.
Common mistakes:
- Snapshotting past
last_applied. The labeled index no longer matches the state. - Dropping
last_included_term. The consistency check at the boundary then has no term to compare. - Forgetting membership and client session data. After a restart the cluster configuration or deduplication table is gone.
- Deleting log entries before the snapshot is durable. A crash then loses committed data.
- Wiping a follower's log when the snapshot matches it. This discards entries the follower had already replicated.
- Letting the snapshot lock the state machine. Long pauses can look like a failed leader and trigger elections. Use copy-on-write or a forked process.
Exercise
A follower has log entries 1 to 8 (all term 2) and receives InstallSnapshot with lastincludedindex = 5 and lastincludedterm = 2. What should it do with entries 6 to 8, and what changes if the snapshot instead had lastincludedterm = 3?
Show answer
With lastincludedterm = 2, the follower's entry 5 has the same index and term as the snapshot's last entry, so its log agrees with the snapshot. It discards entries 1 to 5, keeps entries 6 to 8, and loads the snapshot state. With lastincludedterm = 3, entry 5 conflicts with the leader's log. The follower discards its whole log, sets base_index to 5 with sentinel term 3, loads the snapshot state, and waits for the leader to send entries from 6 onward.
Exercise
A server has commitindex = 120 and lastapplied = 100. It wants to snapshot. Up to which index may the snapshot go, and why not 120?
Show answer
Up to 100. The snapshot copies the state machine, which contains only the effects of entries up to last_applied. Labeling it with index 120 would claim it includes entries 101 to 120, which have not been applied. After a restart, those entries would be skipped and their effects lost.