Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Zero-Stall Raft Log
Compaction & Snapshot Streaming Engine.

Design a Raft log compaction and snapshot streaming subsystem for a 50K writes/sec consensus cluster that bounds WAL size under 1 GB, sustains sub-10ms write P99, and recovers restarted followers in < 45 seconds.
Start the journey7 stages· Last modified Nov 25, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Jittered dual triggers (100K entries or 256 MB WAL) and token-bucket snapshot pacing maintain < 10 ms write P99 and < 45s recovery.

TL;DR30-second simplified summary
▾

The engine uses RocksDB CreateCheckpoint() (< 1 ms) and Zstd-3 + CRC32C background framing, unlinks sealed 64 MB WAL segments behind snapIdx - 10,000, and paces InstallSnapshot at 50% NIC capacity on a separate bulk lane.

Full walkthrough · 7 stages
01
foundation

Stage 1: SLO Framing — Bounded WAL, Sub-10ms P99 & < 45s Recovery.

Why this matters: Define disk bounds, write-latency targets, and recovery-time objectives for a 50K writes/sec Raft group.

At 50K writes/sec (~40 MB/s WAL append rate), the compaction engine must keep uncompacted WAL under 256-512 MB per node, avoid any write-path P99 spike > 10 ms during snapshotting, and recover a wiped/restarted follower (e.g., 4 GB compressed snapshot) in < 45 seconds without disturbing leader stability.

FOUNDATION · SYSTEM SLOS

Balancing Disk Bounds, Write P99 & Follower Recovery Speed

50K Writes/sec (40MB/s)Ingress LoadWAL Cap <= 256 MBDisk SLOWrite P99 < 10 msLatency SLOFollower Recovery <45sRecovery SLOZero-lock CoW/Checkpoint

1.32-Second Transfer: A 4 GB compressed snapshot streams at 1 Gbps (125 MB/s) in ~32 seconds, leaving 13 seconds for suffix replay.

2.Zero Quorum Disruption: Maintaining < 10 ms P99 ensures Raft client leases and ReadIndex queries never time out.

The engine targets <= 256 MB uncompacted WAL, < 10 ms write P99 during compaction, and < 45s follower recovery.

02
foundation

Stage 2: Compaction State Machine & Jittered Dual Triggers.

Why this matters: Design non-overlapping compaction triggers so replicas never compact simultaneously.

Each Raft node evaluates uncompacted_entries >= entry_thresh OR wal_bytes >= byte_thresh after committing an apply batch. Adding +/-15% node-specific jitter (seeded by node_id) prevents all 3-5 replicas from entering compaction at the exact same index and spiking cluster-wide tail latency.

FOUNDATION · COMPACTION TRIGGERS

Jittered Dual-Threshold Compaction Controller

Apply Batch MonitorTrigger WatcherNode-ID Jitter(+/-15%)Stagger PolicySingle-Flight LockOverlap GuardSpawn AsyncCompactionDispatcherCheck compaction_in_flight

1.Single-Flight Guard: If a previous snapshot is still streaming to disk, skip triggering a second concurrent compaction.

2.Staggered Replicas: Jitter ensures at least a majority of replicas remain unburdened by compaction I/O at any instant.

Jittered dual thresholds and a single-flight compaction guard stagger replica snapshots and prevent overlapping builds.

03
intermediate

Stage 3: Zero-Stall Checkpoint Fork & Streaming Checksums.

Why this matters: Implement O(1) RocksDB hard-link checkpoints with Zstd compression and per-chunk CRC32C.

On trigger, the apply thread invokes rocksdb::Checkpoint::CreateCheckpoint() (creating hard-links to immutable SSTables and copying the small active memtable) in < 1 ms, tagging (lastIncludedIndex, lastIncludedTerm). A background thread tars/Zstd-compresses the checkpoint into 4 MB chunks with CRC32C trailers and atomically commits snapshot.meta.

INTERMEDIATE · ZERO-STALL CHECKPOINT

O(1) RocksDB Checkpoint -> Zstd + CRC32C Background Pipeline

RocksDBCreateCheckpoint()Instant ForkBackground ZstdStreamerCompactor4 MB Chunk + CRC32CVerifierfsync() + AtomicRenameCommitEmit 4 MB framed chunks

1.Zstd Level 3 Sweet Spot: Zstd level 3 compresses KV snapshots ~2.5x at 400+ MB/s per core, cutting network transfer time in half.

2.Bounded I/O Nice: Run background compression with cgroup/ionice throttling so foreground WAL fsyncs keep < 2 ms latency.

RocksDB hard-link checkpoints plus background Zstd-3 compression and CRC32C framing build durable snapshots without blocking writes.

04
intermediate

Stage 4: WAL Segment Rotation & Suffix-Preserving GC.

Why this matters: Reclaim disk space safely via fixed-size WAL segments while keeping a 10K-entry suffix.

Store the Raft WAL as 64 MB sealed segments (wal-000001.log, wal-000002.log). After a snapshot is durably committed at S, the WAL garbage collector unlinks any sealed segment whose max_index <= S - 10,000, reclaiming disk in O(1) unlink() calls without rewriting active log files.

INTERMEDIATE · SEGMENTED WAL GC

O(1) Unlink of Sealed 64 MB WAL Segments Behind Suffix Cutoff

Sealed 64 MB WALSegmentsLog StoreCutoff = snapIdx -10,000Safety MarginActive StreamRefcheckReader GuardO(1) unlink()ReclaimGarbage CollectVerify no open cursor

1.Zero In-Place Rewrite: Segmented WALs avoid copying remaining suffix entries during truncation—just unlink old segment files.

2.Active-Cursor Pinning: Ref-counting sealed segments prevents deleting a file while an AppendEntries batch is still reading it.

64 MB segmented WALs let the GC unlink obsolete prefixes in O(1) while preserving a 10K-entry suffix for minor follower lag.

05
intermediate

Stage 5: Token-Bucket InstallSnapshot & Priority Heartbeat Lane.

Why this matters: Stream snapshots to lagging followers without starving AppendEntries heartbeats or saturating NICs.

Leaders maintain two gRPC/TCP channels per peer: a high-priority control channel for AppendEntries heartbeats and RequestVote, and a bulk data channel for InstallSnapshot chunks. A token-bucket limiter caps snapshot egress at 50% NIC capacity (and max 2 concurrent peers) so heartbeats always arrive in < 10 ms.

INTERMEDIATE · NETWORK ISOLATION

Dual-Channel Raft Transport: Priority Heartbeats vs. Paced Snapshots

Control Channel(Priority)Quorum LaneBulk Data ChannelTransfer LaneToken-Bucket PacerBandwidth GuardFollower Staging +SwapCatch-Up SinkPace chunk egress

1.No Head-of-Line Blocking: Separate TCP connections prevent a 4 MB snapshot chunk from delaying a 64-byte heartbeat packet.

2.Staggered Multi-Node Rebuild: Capping concurrent snapshot streams at 2 prevents 3 simultaneous node restarts from saturating leader egress.

Separating heartbeats onto a priority lane and pacing InstallSnapshot chunks via token buckets keeps quorum stable during rebuilds.

06
advanced

Stage 6: Resumable Snapshot Transfers & PreVote Election Safety.

Why this matters: Handle mid-transfer network drops and prevent partitioned followers from disrupting the leader.

If a follower loses connectivity at byte offset 2.5 GB of a 4 GB snapshot, resumable chunking (keyed by snapshot_id + offset) lets the follower continue from 2.5 GB instead of restarting from 0. Meanwhile, PreVote ensures any lagging or briefly congested follower checks whether a majority would vote for it before incrementing currentTerm.

ADVANCED · RESUMABILITY & PREVOTE

Offset-Resumable Transfers & PreVote Term Protection

Transient Link Drop@ 2.5 GBNetwork FaultResume from Offset2.5 GBOffset RecoveryPreVote HandshakeLeader ShieldAtomic Swap +AppendEntriesSynced FollowerIf election timer fires

1.Snapshot Pinning: The leader pins the active snapshot_id in memory/disk until transfer completes or times out so GC won't delete it mid-stream.

2.Zero Spurious Term Bumps: PreVote stops isolated followers from forcing healthy leaders to step down upon reconnection.

Keying chunks by snapshot_id enables offset resumption after drops, while PreVote shields the leader from spurious term bumps.

07
advanced

Stage 7: Operational Telemetry, Corruption Drills & ReadIndex.

Why this matters: Monitor compaction lag, verify snapshot checksums in CI/chaos drills, and uphold ReadIndex linearizability.

Track raft_wal_bytes, raft_snapshot_duration_ms, and raft_install_snapshot_active_peers with alerts if WAL exceeds 2x threshold. Run automated chaos drills that corrupt a chunk's CRC32C (verifying clean rejection) and validate that ReadIndex queries remain linearizable across follower snapshot swaps.

ADVANCED · OBSERVABILITY & CHAOS

WAL Lag Telemetry, CRC Chaos Drills & ReadIndex Verification

Prometheus RaftMetricsTelemetryCRC32C Chaos DrillIntegrity TestReadIndexLinearizabilitySafety Check2x WAL ThresholdAlertSRE GateVerify safe state swap

1.Snapshot-Before-GC Alert: If disk usage rises while snapshots fail, alert immediately before the node hits ENOSPC.

2.Linearizability Invariant: A follower that just installed a snapshot at index S never serves ReadIndex < S.

WAL-size alerts, CRC32C fault-injection drills, and ReadIndex checks keep the compaction engine production-safe.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does a Raft leader separate `AppendEntries` heartbeats onto a priority connection distinct from `InstallSnapshot`?

Recommended Learning Flow