Zum Hauptinhalt springen

The Log That Never Stops Growing: Snapshots and Compaction

· 9 Minuten Lesezeit
Clustron Team
Engineering für verteilte Systeme

An append-only operation log is the cleanest durability substrate a store can have. Every mutation is recorded exactly once, in the order it happened, and the materialized state — the actual key-value map a client reads — is just a projection of that log. Lose the in-memory map to a crash and you rebuild it by replaying the log from the start; the log is the replayable source of truth, and the map is a cache of it. That property is what makes acknowledged writes survivable: a write is durable the instant its record is on the log, long before the map is updated.

The append log has exactly one fatal flaw if you leave it alone: it grows forever. Every write adds a record and nothing is ever removed. The obvious symptom is that the disk fills, but that is the benign failure — you notice it, you add storage, you carry on. The dangerous symptom is quieter and compounding: the time to rebuild state by replaying the whole log climbs without bound. A crash recovery that took five seconds when the log held a million records takes five minutes at sixty million and an hour beyond that, and the day you actually need a fast recovery is the day a node died, which is the worst possible day to discover that coming back online takes an hour.

So every system built on an append log needs a way to make the log finite without losing what it means. There are two such techniques, and they are complementary rather than alternatives: snapshots bound how far back recovery has to start, and compaction removes records the log no longer needs.

A snapshot bounds the replay​

A snapshot is a point-in-time dump of the materialized state — the whole key-value map as it stood at a particular log offset. Once that snapshot exists on disk, every log record before its offset is redundant, because the snapshot already encodes their combined effect. Recovery stops being "replay the entire log" and becomes "load the newest snapshot, then replay only the short tail of records written after it." The log prefix behind the snapshot can be truncated and the disk reclaimed.

This changes recovery time from a function of total history to a function of snapshot age. If you snapshot every few minutes, the tail to replay is at most a few minutes of writes no matter how old the store is, so recovery time is bounded and predictable — which is the whole point.

operation log — oldest on the left, newest on the rightsnapshot @ Nmaterialized statetruncated & reclaimedtail replayed on recoverywith a snapshot: recovery = load state at N, then replay the 5-record tailwithout one: recovery = replay all 12 records from the far left — and that count only ever growsthe dial is cadence: snapshot often → short tail, fast recovery, more steady-state I/O

Taking a snapshot without stopping the world​

The naive way to snapshot is to freeze all writes, copy the map to disk, and unfreeze. That produces a perfectly consistent snapshot and a latency spike that stalls every client for as long as the dump takes — unacceptable for anything serving live traffic. The real techniques capture a consistent image while writes continue.

The cleanest approach pins the snapshot to a specific log offset and uses copy-on-write. At snapshot time the store records the current log offset N and begins writing the map to disk; any key mutated during the dump is first copied aside so the snapshot writer still sees the value as of N, while new writes proceed against the live map and append to the log past N. The result is a snapshot that reflects exactly the state at offset N — no earlier write missing, no later write leaking in — which is the invariant recovery depends on. A runtime that can fork a process gets this almost for free: the child holds a frozen copy-on-write view of memory and dumps it while the parent keeps serving.

// Snapshot pinned to a log offset; writes never block on it.
long snapOffset = log.CurrentOffset(); // the boundary the snapshot means
var view = state.SnapshotView(); // copy-on-write; cheap, no freeze
await disk.WriteSnapshot(view, snapOffset); // dump proceeds while writes continue

// Recovery: newest snapshot, then only the records past its offset.
var (state, from) = disk.LoadNewestSnapshot(); // from == snapOffset
foreach (var rec in log.ReplayFrom(from)) // short, bounded tail
state.Apply(rec);
log.TruncateBefore(disk.OldestSnapshotOffset); // reclaim the prefix

Compaction removes what the log no longer needs​

Snapshotting bounds how far back recovery starts. Compaction attacks a different redundancy: within the log itself, most records are stale. If a key was written a thousand times, only the latest value matters for reconstructing state — the earlier 999 records contribute nothing to the final map. Key-level compaction walks the log and keeps only the most recent record per key, rewriting it into a smaller log with the same meaning. This is the same idea as a log-structured merge tree's merge step, and the same idea as Redis's or Kafka's log compaction: retain the last write per key, discard the superseded ones.

Compaction is also where deletions finally get cleaned up. A delete is not an erasure but a tombstone — a marker that says "this key is gone" — and it has to linger long enough for every replica to learn of the deletion, or a stale copy would resurrect the key. Compaction is the natural moment to reclaim a tombstone whose grace period has elapsed: once it is safe, the tombstone and the key's older records drop out of the compacted log together. The same mechanism handles keys that simply expired by TTL — their final state is "absent," so a compacted log need not carry them at all.

The one dial that matters​

Everything above reduces to a single operational knob: how often to snapshot. Snapshot frequently and the replay tail stays tiny, so recovery is fast — but each snapshot is real I/O and CPU spent dumping state that steady-state traffic would rather have. Snapshot rarely and steady-state cost drops, but the tail grows and worst-case recovery stretches out. There is no universally right answer; there is the answer that matches your recovery-time objective. Size the cadence so that the tail you would replay after a crash fits inside the recovery time you are willing to promise, and let compaction run in the background to keep the dumped state and the retained log from bloating between snapshots. A node rebuilding from its replicas leans on exactly the same artifacts: ship the newest snapshot, then stream the tail.

Wrap-up​

An append-only log is the right durability substrate precisely because it never forgets — and that is also why, left alone, it becomes a recovery-time bomb rather than merely a disk problem. Snapshots bound recovery to the age of the newest checkpoint rather than the whole history, and the consistent ones pin to a log offset and dump under copy-on-write so writes never stall. Compaction removes the records the log no longer needs — superseded values, expired keys, tombstones past their grace — keeping both the log and the snapshots small. Tune the snapshot cadence to the recovery time you are willing to promise, run compaction underneath it, and the log that would otherwise grow forever stays exactly as long as it needs to be.