Skip to content

Snapshots and log compaction

A snapshot writes the full state at one point in a log so earlier entries can be dropped; log compaction keeps the latest record per key and removes superseded ones. Both keep a growing log from making recovery slower.

On this page

What it is

A replicated log, a write-ahead log or an event stream grows with each request it records, and replaying it is how a node rebuilds its state. When a stream is long, replaying all of it to rehydrate an entity gets expensive in time and compute, and a log that records each change to records that are updated many times grows without bound. Plain retention drops old records by age or size, but then replaying from the start no longer rebuilds current state. This page covers two fixes that keep the log useful for rebuilding. Snapshotting writes the whole current state to durable storage; a consensus log such as Raft's then discards the entries the snapshot covers, while an event store can keep the full stream and use the snapshot as a shortcut. Compaction works on part of the log at a time: it recopies segments, drops records that a later record for the same key has replaced, and frees the space, which spreads the work over time instead of rewriting everything at once.

A snapshot in a consensus log. In Raft each server snapshots independently, covering the committed entries in its log. The snapshot holds the state machine's state plus a little metadata: the index of the last entry it includes and that entry's term, which the AppendEntries consistency check needs for the first entry after the snapshot, and the latest cluster configuration as of that index. A leader that has already discarded the next entry a lagging follower needs sends the snapshot instead, through an InstallSnapshot RPC that carries it in chunks at byte offsets with a flag on the last one. On receipt the follower saves the file and drops any older or partial snapshot. If it holds a log entry with the snapshot's last index and term, it keeps the entries after that one; otherwise it discards its whole log and resets its state machine from the snapshot, loading the snapshot's configuration.

Per-key compaction in a stream. A compacted Kafka topic, as Confluent's current documentation describes it, keeps at least the most recent record for each message key and removes earlier records for that key, so a consumer that reads from the start sees the final state of each key in the order the records were written. Records need a key for this to work. A delete is a record whose payload is null, called a tombstone; it removes the earlier value and is itself cleaned out after delete.retention.ms, 24 hours by default. The cleaner runs in the background by recopying older segments, it keeps the order and offsets of surviving records, and it doesn't touch the active segment. min.compaction.lag.ms holds a record in the uncompacted head for at least that long, and max.compaction.lag.ms makes it eligible for cleaning after at most that delay, though the deadline still depends on cleaner threads being free.

SystemSnapshot or compactionWhat makes it work

Raft (consensus log)

Each server snapshots its committed entries; the leader ships a snapshot to a follower whose next entry it has already discarded

The snapshot's last index, term and configuration let replication resume right after it

Kafka compacted topic

Latest record per key; tombstones for deletes

A background cleaner recopies segments; reads aren't blocked and its I/O can be throttled

Redis RDB

Point-in-time dump of the data set on a schedule such as save 60 1000

A forked child writes a temporary file and then replaces the old one

Redis AOF rewrite

The shortest command sequence that rebuilds the current data set replaces the full command history

Since Redis 7.0.0 the parent opens a new incremental file while a child writes a new base file; a manifest swaps them in atomically

Event-sourced entity

Serialized entity state each N events

Rehydrate from the latest snapshot plus the events after it; the stream stays the source of truth

The cost that stays. Serializing a large state takes time, and nobody wants writes to wait for it. Redis's answer for both RDB saves and AOF rewrites is to fork: the child writes the new file from a copy-on-write image of memory while the parent keeps serving clients, and the finished file then takes over from the old one (since Redis 7.0, an AOF rewrite swaps a manifest that names its base and incremental files). The documentation also names the downside: on a big data set with a weak CPU the fork can stall the server for milliseconds, or up to a second, and before Redis 7.0 writes that arrived during a rewrite were buffered in memory and written to disk twice. A snapshot design should say where that pause lands.

When to use it

Snapshot when replay time or disk is the limit. Redis gives the plain case: a counter incremented 100 times leaves 100 entries in the AOF when a single value would rebuild the state, and RDB restarts faster than AOF on big data sets. Since Redis 2.4 the AOF rewrite can trigger automatically when the file gets too big, and RDB saves fire after N seconds if at least M keys changed. For an event-sourced entity the same trade is made per stream: snapshot each N events and weigh the storage the snapshots cost against the rehydration time they save. Our advice: tie the trigger to how much the log has grown since the last snapshot, not to the clock, so a quiet system doesn't rewrite the same state over and over.

Compact when readers need the current value per key. Kafka's documentation lists the cases: a database change feed where a cache, search cluster or warehouse may need a full reload and not just recent updates; event sourcing, where knowing the latest state of each key matters; and journaling local state (counts, aggregations) so another process can take over after a failure, which is what Kafka Streams does. In each case the live feed and the occasional full rebuild come from the same topic.

Catch-up for replicas. A new or badly lagging member of a replicated group is often cheaper to bring up from a snapshot than from thousands of log entries, and in Raft a leader has no other option once it has discarded the entries the follower needs. Servers otherwise snapshot on their own, and the reasoning is worth saying aloud: each follower already holds the state, so producing a snapshot locally usually costs less than receiving one over the network, and the leader ships one to a member that has fallen too far behind.

When not to

When history is the product. Per-key compaction keeps at least the final value of each key, not all versions, so an audit trail, a ledger or anything that must answer "what did this look like last March" shouldn't be compacted. For an event-sourced system, snapshots are an optimization layered on top of the stream, not a replacement for it; the stream remains the source of truth and snapshots can be regenerated from it. If you need to drop old events for cost, plain time or size retention with an archive elsewhere is the honest choice, with the understanding that replaying from the beginning no longer rebuilds current state.

When the state is far larger than the churn. A full snapshot rewrites the whole state each time, even if a tiny fraction changed, and on a big data set the fork that starts it can itself stall the server. A segment-by-segment cleaner like Kafka's touches a slice of the log at a time, doesn't block reads and can be throttled, at the price of more machinery and its own lag settings. And if a log is small enough to replay in seconds, our advice is to skip the snapshot path for now: it is a second recovery mechanism to test and keep correct, and the simpler one still works.

When you need a prompt or exact delete. Compaction in Kafka doesn't promise a single record per key at any moment; several may coexist, including a tombstone, because the cleaner runs when conditions such as the dirty ratio are met, and the active segment is not cleaned. A consumer that takes longer than delete.retention.ms to read from the start can miss tombstones that were removed while it read. If a deletion has a legal deadline, handle it in the store that serves reads, not through the cleaner.

When the data is a cache. Redis documents turning persistence off as an option, one sometimes used when the instance serves as a cache. A snapshot of data you can rebuild from the system of record buys little, and the fork cost on a large data set is real.

Compared

ApproachWhat survivesMain costWhen the other option is right

Full snapshot (Raft, Redis RDB)

The whole state at one log position, plus the log tail after it

Serializing everything each time; a fork with copy-on-write keeps writes flowing, though the fork itself can stall a large data set briefly

Per-key compaction when readers want the latest value of each key from a shared stream rather than a whole-state image

Per-key compaction (Kafka compacted topic)

At least the latest record per key, in original order with original offsets; tombstones for a bounded time

Background recopying of segments; deletes are eventual and can be missed by a slow reader

A snapshot when a replica must be reset to an exact state, or full retention when all versions matter

Time or size retention (Kafka delete policy)

Roughly the recent part of the log; older records are dropped by age or size, whichever limit applies

Cheap, but replaying from the start no longer rebuilds current state

Compaction when a reader must reload complete state; keep it when consumers stay caught up and nobody rebuilds from the topic

AOF rewrite (Redis)

The full command log, shrunk to the shortest sequence that rebuilds the data set

A fork and a second file written in the background; usually a bigger file than an RDB dump

An RDB snapshot when a compact single file for backups and faster restarts matters more than durability, accepting that a crash can lose the latest minutes of writes

Snapshot each N events (event sourcing)

The full stream plus periodic state images

Storage for snapshots; a snapshot can be regenerated

No snapshots when streams are short enough that replaying them is already cheap

In a picture

commandapplyClientLeader logState machine

Step 1 of 4

The log grows

Clients send commands to the leader, which appends them to its log and applies committed entries to the state machine. Nothing is removed yet.

How to say it in an interview

The common mistake

Quiz

A Raft follower receives an InstallSnapshot whose last included index and term match an entry already in its log, and it has later entries too. What should it do?
A consumer rebuilds a cache by reading a compacted Kafka topic from offset 0, and the rebuild takes three days with the default delete retention. What can it miss?
Why does a Raft snapshot record the index and term of the last entry it covers?
Which situation fits a compacted topic better than a snapshot?

Questions that use this

Hear it in

Related

Sources

  1. SOFAStack (SOFAJRaft): Introduction to the Raft algorithm
  2. Wikipedia: Raft (algorithm)
  3. Confluent documentation: Kafka Log Compaction
  4. Redis documentation: Redis persistence
  5. Azure Architecture Center: Event Sourcing pattern
Sign in to report a mistake