LSM-Tree Write Amplification and Compaction Stalls: Why Heavy Ingestion Freezes RocksDB and Cassandra
Log-Structured Merge-trees provide lightning-fast sequential writes by buffering mutations in memory before flushing SSTables to disk. But under sustained ingestion, background compaction falls behind, triggering write stalls that freeze application throughput. How leveled compaction, write amplification, and compaction debt interact in production.
Log-Structured Merge-tree (LSM-tree) storage engines power some of the most critical write-intensive databases in modern computing, including RocksDB, Apache Cassandra, ScyllaDB, and ClickHouse. By converting random application mutations into sequential disk writes, LSM storage delivers orders of magnitude higher ingestion throughput than traditional B-trees. In our telemetry ingestion pipeline, a 3-node RocksDB-backed cluster comfortably handled 120,000 metric writes per second with sub-millisecond p99 write latency.
Yet under sustained peak loads, LSM engines can exhibit a devastating vulnerability: the write stall. Without warning, write throughput plummets from 120,000 operations per second to absolute zero. Client requests queue up, upstream connection pools saturate, and HTTP 504 gateway timeouts cascade across the system. The underlying cause is not hardware failure or CPU exhaustion, but an intrinsic trade-off of LSM architectures: compaction debt.
1. The Anatomy of an LSM Storage Engine
Unlike a B-tree that modifies database pages in-place on disk, an LSM-tree operates on an append-only basis across distinct memory and disk layers:
- MemTable: An in-memory data structure (typically a skip list or concurrent skiplist) that buffers incoming writes in sorted key order. Every write is also appended sequentially to a Write-Ahead Log (WAL) on disk for crash durability.
- Immutable MemTable: When the active MemTable reaches its capacity threshold (such as 64MB), it is converted into a read-only immutable MemTable and scheduled for background disk flushing. A fresh MemTable immediately accepts new client traffic.
- Sorted String Tables (SSTables): The disk-backed files where flushed data resides. Each SSTable contains sorted key-value pairs along with a Bloom filter and block indexes to accelerate point lookups.
2. The Compaction Pyramid and Amplification Factors
Because keys are continually updated or deleted, an LSM engine must periodically merge SSTables to remove superseded versions, purge deleted tombstones, and organize keys into bounded levels. This background merge process is known as compaction.
Every LSM design balances three competing operational costs:
- Write Amplification Factor (WAF): The ratio of bytes written to underlying storage versus bytes submitted by the client application. In leveled compaction, a single byte written by the user may be rewritten 15 to 30 times as it migrates down the level hierarchy.
- Space Amplification Factor (SAF): The ratio of disk storage consumed versus actual active user data. High space amplification occurs when dead records and tombstones wait for compaction.
- Read Amplification Factor (RAF): The number of disk reads required to satisfy a single user query. If a key might exist in multiple overlapping SSTables, the engine must inspect multiple files.
In Leveled Compaction (LCS), storage is partitioned into tiers (L0, L1, L2, through Ln). Level 0 holds newly flushed SSTables directly from memory. Because L0 files are flushed concurrently, their key ranges overlap. All subsequent levels (L1 and higher) enforce strict non-overlapping key ranges, with each level typically sized to hold 10 times the capacity of the previous level (L1 = 256MB, L2 = 2.5GB, L3 = 25GB).
3. Why Compaction Falls Behind: The Write Stall Trigger
A write stall occurs when incoming client write volume consistently exceeds the disk I/O throughput available for background compaction. When compaction cannot keep pace, SSTable files accumulate in memory and on disk. To prevent unbounded memory consumption or catastrophic read degradation, the engine enforces protective backpressure throttles.
In RocksDB, this escalation follows three deterministic thresholds:
Compaction Backpressure Cascade:
1. MemTable Flush Backlog:
- If immutable MemTables cannot flush to L0 fast enough, active MemTables fill up.
- When max_write_buffer_number is reached, all client writes block completely.
2. L0 File Accumulation (Slowdown):
- When L0 file count reaches level0_slowdown_writes_trigger (default: 20 files),
RocksDB artificially injects microsecond delays into every client write.
- Throughput degrades smoothly to allow background threads to catch up.
3. L0 File Saturation (Hard Stop):
- When L0 file count hits level0_stop_writes_trigger (default: 36 files),
RocksDB halts incoming client writes entirely. Write latency spikes to multiple seconds.
Why is L0 file count the primary trigger? Because L0 files have overlapping key ranges, every single read operation must query the Bloom filter and block index of every L0 file. If L0 grew to 200 files, point read latency and CPU utilization would explode, destroying the database read path. The engine deliberately sacrifices write availability to protect read integrity.
4. The Vicious Cycle of Compaction Debt
When an ingestion burst triggers a write stall, a dangerous feedback loop emerges:
- Compacting L0 files into L1 requires reading all L1 files that overlap with the selected L0 key range, merging them in memory, and writing fresh L1 files.
- Because L0 files cover wide key ranges, an L0-to-L1 compaction frequently touches the entirety of L1, resulting in massive disk I/O amplification.
- If the underlying NVMe drive or cloud disk (such as AWS EBS gp3) reaches its maximum IOPS or throughput burst ceiling, compaction tasks queue up.
- Application threads waiting on stalled writes time out. Upstream services mistake this latency for transient network loss and retry their requests, compounding the load on the choked storage engine.
5. Production Strategies to Prevent Write Stalls
A. Decouple and Scale Background Threads
By default, storage engines share a single thread pool for both MemTable flushes and multi-level compactions. Because a flush is a fast, lightweight sequential dump of memory to L0, it must never wait behind a massive 50GB multi-way compaction:
// RocksDB Thread Pool Separation
options.max_background_jobs = 8;
options.env->SetBackgroundThreads(2, Env::Priority::HIGH); // Dedicated flush threads
options.env->SetBackgroundThreads(6, Env::Priority::LOW); // Dedicated compaction threads
B. Implement Dynamic Level Base Sizing
In standard leveled compaction, L1 has a fixed size (e.g., 256MB). If total database size grows to hundreds of gigabytes, the ratio between L0 and L1 becomes mismatched. Enabling dynamic level base sizing (level_compaction_dynamic_level_bytes = true in RocksDB) automatically computes the target size of each level based on the actual size of the last level (Ln), drastically reducing write amplification at upper tiers.
C. Rate Limit Ingestion with Token Buckets
Rather than letting client threads hammer the engine at full speed until hitting a sudden cliff, configure RocksDB internal RateLimiter to smooth out bursty ingestion:
// Cap total disk write rate (flush + compaction) to 80% of sustained disk bandwidth
std::shared_ptr<RateLimiter> rate_limiter =
std::shared_ptr<RateLimiter>(NewGenericRateLimiter(250 * 1024 * 1024)); // 250 MB/s
options.rate_limiter = rate_limiter;
D. Choose the Right Compaction Strategy
For time-series data or append-only event logs where updates and deletes are rare, Leveled Compaction is unnecessarily expensive. Switching to FIFO Compaction (which simply purges expired SSTables by timestamp) or Universal Compaction (which merges adjacent tiers without strict level boundaries) drops write amplification from 25x down to under 3x, freeing up vast disk I/O headroom.
Summary
LSM-tree write stalls are not random glitches; they are predictable mechanical limits reached when compaction debt exceeds I/O bandwidth. By isolating flush and compaction thread pools, tuning L0 file triggers, configuring rate limiters, and selecting compaction strategies aligned with data access patterns, high-throughput systems can maintain predictable write latencies without risking catastrophic ingestion freezes.