Skip to main content
← CONCEPTS / DISTRIBUTED-SYSTEMS
An end-to-end domain learning journey

Raft Log Compaction, InstallSnapshot
RPC & WAL Truncation.

Periodic Copy-on-Write snapshotting at (lastIncludedIndex, lastIncludedTerm), O(1) WAL prefix truncation, and chunked InstallSnapshot RPCs bound Raft disk growth and cut follower recovery from 4+ hours to under 45 seconds.
Start the journey7 sections· Last modified Nov 25, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Dual compaction triggers (100K entries or 256 MB WAL) and chunked `InstallSnapshot` cut recovery from 4+ hours to < 45 seconds.

TL;DR30-second simplified summary
▾

At 50K writes/sec, uncompacted Raft WALs reach 500 GB and cause 4-hour replay storms. Using O(1) RocksDB checkpoints or CoW clones avoids locking the apply loop.

Once fsynced with (lastIncludedIndex, lastIncludedTerm), older WAL segments are pruned (retaining a small suffix), and lagging followers catch up via chunked InstallSnapshot RPCs.

Full walkthrough · 7 stages
01
foundation

Stage 1: Why Unbounded Raft Logs Fail at 50K Writes/Sec.

Why this matters: Quantify WAL growth, recovery replay latency, and election-storm risks when Raft logs are never compacted.

Every committed mutation appends to the Raft WAL. At 50,000 writes/sec (~800 bytes/entry), a cluster generates ~3.4 TB/day of raw log history—or 500 GB in just 3.5 hours. On node restart, replaying 1B+ entries through the state machine takes 4+ hours, starving reads and risking quorum loss.

FOUNDATION · UNBOUNDED WAL

50K Writes/Sec Uncompacted WAL Growth & 4-Hour Replay Storm

50K Writes/sec (800B)Write Load500 GB UncompactedWALDisk Bloat4-Hour FollowerReplayRecovery StallMissed ElectionTimeoutCluster InstabilityRestart replays from idx=1

1.Redundant History: Overwriting the same key 10,000 times stores 10,000 log entries even though only 1 current value exists.

2.Quorum Fragility: While one node spends 4 hours replaying WAL, losing a second node breaks Raft majority quorum.

Unbounded Raft logs grow to 500 GB at 50K writes/sec, causing 4-hour recovery replays and quorum fragility.

02
foundation

Stage 2: Snapshot Metadata & Atomic WAL Prefix Truncation.

Why this matters: Define the Snapshot header (lastIncludedIndex, lastIncludedTerm) and safe prefix truncation invariants.

A Raft snapshot captures the deterministic state machine at a committed lastIncludedIndex and lastIncludedTerm (plus the latest cluster config). Only AFTER the snapshot file is durably fsynced and atomically renamed can the node truncate WAL segments strictly below lastIncludedIndex, preserving prevLogIndex/prevLogTerm continuity.

FOUNDATION · SNAPSHOT INVARIANTS

Durable Snapshot Commit Before WAL Prefix Truncation

Committed StateMachineKV StateSnapshot + MetadataDurable Filefsync() + AtomicRenameDurability GateTruncate WAL <CutoffDisk ReclaimPersist to disk

1.Crash-Safety Ordering: Truncating WAL before fsyncing the snapshot risks losing committed state if power fails mid-compaction.

2.Suffix Retention: Keeping a small suffix (e.g. 10K entries) avoids InstallSnapshot for followers that only paused briefly.

Nodes must fsync and atomically rename the snapshot before unlinking older WAL segments while keeping a small suffix.

03
intermediate

Stage 3: Copy-on-Write & RocksDB Checkpoint Snapshotting.

Why this matters: Eliminate stop-the-world state machine freezes during gigabyte snapshot serialization.

Locking an in-memory map to serialize 20 GB of KV state stalls Raft apply threads for minutes and triggers election timeouts. Instead, in-memory engines use fork() Copy-on-Write (or persistent HAMT trees), while disk-backed engines (etcd/RocksDB) create an instant hard-link Checkpoint/MVCC read snapshot in < 1 ms and stream it asynchronously.

INTERMEDIATE · ZERO-STALL SNAPSHOT

Zero-Freeze Snapshotting via RocksDB Checkpoints & CoW

Raft Apply LoopHot PathRocksDB Checkpoint /CoWPoint-in-TimeBackgroundSerializerAsync WorkerImmutable SnapshotArchiveArtifactStream SSTables offline

1.Sub-Millisecond Pause: Hard-linking immutable RocksDB SSTables takes < 1 ms regardless of whether the DB is 5 GB or 500 GB.

2.Checksumming: Always attach per-chunk CRC32C or SHA-256 checksums to detect silent bit-rot during snapshot transfer.

RocksDB hard-link checkpoints and Copy-on-Write clones decouple gigabyte snapshot I/O from the live Raft apply loop.

04
intermediate

Stage 4: Detecting Lagging Followers & InstallSnapshot RPC.

Why this matters: Handle followers whose nextIndex falls behind the leader's compacted firstLogIndex.

When a restarted or newly added follower has nextIndex < leader.firstLogIndex, the leader no longer holds the log entries needed for AppendEntries. The leader switches that peer's replication state to StateSnapshot and streams InstallSnapshot(term, leaderId, lastIncludedIndex, lastIncludedTerm, offset, data[], done) chunks.

INTERMEDIATE · FOLLOWER CATCH-UP

Switching from AppendEntries to Chunked InstallSnapshot RPC

Check nextIndex <firstLogIndexLag DetectorEnter StateSnapshotReplication ModeStreamInstallSnapshot…Chunk TransferSet nextIndex =snapIdx + 1Normal SyncSend 4 MB chunks

1.Idempotent Offsets: Streaming fixed-size chunks (e.g., 1-4 MB) with explicit byte offsets lets followers recover cleanly from transient network drops.

2.Term Guard: Followers reject any InstallSnapshot RPC with term < currentTerm, preserving Raft leader safety.

Leaders switch lagging followers to chunked InstallSnapshot RPCs when nextIndex < firstLogIndex, then resume AppendEntries.

05
intermediate

Stage 5: Follower Atomic State-Machine Swap & Suffix Replay.

Why this matters: Apply an incoming snapshot safely on a follower without corrupting local state if a crash occurs mid-transfer.

A follower writes incoming InstallSnapshot chunks to a temporary staging file (snapshot.tmp). Only when done == true and checksums pass does it fsync, atomically rename the snapshot, discard any conflicting log entries up to lastIncludedIndex, reload its state machine from the snapshot, and ACK the leader.

INTERMEDIATE · FOLLOWER INSTALL

Crash-Safe Follower Snapshot Staging & Atomic Reload

Write snapshot.tmpStaging Filedone == true +fsync()Completeness GateAtomic State SwapState ResetACK Leader(matchIndex)Quorum ReadyRename & reload engine

1.Sub-45s Recovery: Transferring a compacted 4 GB snapshot at 1 Gbps takes ~32 seconds—vs. 4+ hours replaying 1B WAL entries.

2.Preserve Newer Suffix: If the follower's log already matches (lastIncludedIndex, lastIncludedTerm), retain entries after lastIncludedIndex.

Followers stage InstallSnapshot chunks in a temp file, verify checksums, atomically swap state on done=true, and recover in < 45 seconds.

06
advanced

Stage 6: Rate-Limiting Snapshot Streams & Heartbeat Isolation.

Why this matters: Prevent multi-gigabyte snapshot transfers from saturating NICs and causing heartbeat election timeouts.

If a leader blasts a 20 GB snapshot to two restarting followers at full 10 Gbps line rate, NIC saturation and TCP queue bloat can delay Raft AppendEntries heartbeats past electionTimeout (e.g., 150-500 ms), triggering split-brain elections. Production clusters separate heartbeat RPCs onto a high-priority QoS/transport channel and token-bucket rate-limit InstallSnapshot streams.

ADVANCED · QOS & RATE LIMITING

Token-Bucket Snapshot Throttling & Dedicated Heartbeat Lane

Priority HeartbeatLaneQuorum GuardToken-Bucket LimiterBandwidth CapMax ConcurrentTransfers=2Fanout LimitPreVote + LeaderLeaseElection GuardThrottle chunk pacing

1.Heartbeat Priority: Dedicated connections for AppendEntries heartbeats prevent head-of-line blocking behind 4 MB snapshot chunks.

2.PreVote Extension: PreVote prevents a briefly congested node from incrementing cluster terms and disrupting the active leader.

Dedicated heartbeat connections, token-bucket snapshot throttling, and PreVote prevent election storms during follower rebuilds.

07
advanced

Stage 7: Compaction Triggers, ReadIndex & Quorum Safety.

Why this matters: Choose snapshot thresholds (entry count vs. WAL bytes) and preserve linearizable ReadIndex across compactions.

Triggering snapshots solely by entry count (e.g., every 100K entries) can snapshot too often on tiny writes or too rarely on large 1 MB values. Dual triggers (entries >= 100K OR wal_bytes >= 256 MB) keep disk bounded predictably, while jittering thresholds across peers prevents all 3-5 replicas from compacting simultaneously.

ADVANCED · TRIGGER POLICY

Jittered Dual Triggers & Concurrent Quorum Stability

Entry Count >= 100KCount TriggerWAL Size >= 256 MBByte TriggerPer-Node +/-15%JitterAnti-HerdLeader ReadIndexConsistencyOR condition

1.Anti-Herd Jitter: Jittering compaction thresholds by +/-15% ensures only one replica compacts at a time, preserving write P99.

2.ReadIndex Continuity: Snapshots never roll back commitIndex, so ReadIndex linearizability remains unbroken.

Jittered dual triggers (entries OR WAL bytes) bound both disk usage and replay time without synchronized replica pauses.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

When must a Raft leader send an `InstallSnapshot` RPC instead of `AppendEntries` to a lagging follower?

Recommended Learning Flow