ML
Database

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.

November 30, 202612 min readDatabaseStorageDistributed SystemsPerformanceArchitecture

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:

  1. 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.
  2. 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.
  3. 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.

SharePostLinkedIn

Reader Discussion

8 replies// weighed in

TopNewestAuthor
Add to the thread
Disagree, agree harder, or share your own experience…
Email instead →markdown okbe kind
  1. Highlighted by author
    Victor Petrov· Senior BackendAgrees

    "removing indexes is the third-year move" — saving this. first year you add, second year you tune, third year you realise half of them have been dead weight slowing every write since that one feature got cut.

    Dec 02, 2026·2 days later
  2. Mateus Silva· Backend DevAsks

    Q — SELECT FOR UPDATE SKIP LOCKED as a job queue: still a good fit in 2026 or do you reach for a real broker (sqs, rabbit, etc) past a certain QPS? we run ~400 jobs/sec on PG and it's been chill but I'm nervous

    Dec 06, 2026·6 days later
    • Aya Fujimoto· Database Engineer

      We do 11k jobs/sec on PG with SKIP LOCKED + LISTEN/NOTIFY. The thing that breaks first is your job table bloat — set up partman + auto-vacuum tuning before you scale.

      Dec 07, 2026
    • ML
      Minh LeAuthor

      Plus one. The cliff isn't the QPS — it's the visibility-of-dead-rows pattern. SKIP LOCKED holds up if you're disciplined about cleanup.

      Dec 08, 2026
  3. Greta Schäfer· Senior EngineerAgrees

    isolation levels are the part juniors skip and seniors keep underestimating. read committed feels safe; it's not — phantom reads still exist. the moment money is involved, default to repeatable read and benchmark.

    Dec 07, 2026·1 week later
  4. Aya Fujimoto· Database EngineerPushback

    small note on Postgres covering indexes — INCLUDE columns don't get the same treatment as key columns for HOT updates and dedup. people assume index-only scan == free, but the heap visibility map can still send you back to disk. measure first.

    Dec 04, 2026·4 days later
  5. Dan O'Connor· Eng ManagerStory

    N+1 cost us a P1 incident last Black Friday. ONE endpoint was firing 3,400 queries per cart load. Looked fine in dev (3 carts), looked fine in staging (50 carts), production hit 9k QPS to the DB and cardiac arrest. Add load tests.

    Dec 03, 2026·3 days later
  6. Isabella Costa· Junior EngineerKind words

    saved this. sharing at standup tomorrow — we've had exactly this problem for 2 sprints and nobody on the team had framed it this way 🙏

    Dec 02, 2026·2 days later

Worked on something similar? Email ducminhldm@gmail.com — I read every one. The good ones become future posts.

Comments seeded · live discussion via email