Compaction Strategies

What compaction is managing

Three issues at once: read latency (more SSTables = more files per lookup), disk bloat (overwritten keys persist in old files), and write amplification (how much disk I/O is done per application write).

write amplification = total bytes written to disk ÷ bytes written by the application

The problem: unbounded SSTable accumulation

sstable-001.sst:  key K = "v1"
sstable-002.sst:  key K = "v2"  ← overwrites v1
sstable-003.sst:  key K = "v3"  ← overwrites v2

✗ Without compaction — 30 days × 100 MB/day

Total disk:     3,000 MB
Unique data:    ~1,000 MB
Stale data:     2,000 MB (67% bloat)
Read (hot key):     1 SSTable  → <1 ms
Read (missing key): 30 SSTables → 2–5 ms

✓ With compaction — 30 files merged into 1

Total disk:     1,000 MB (stale removed)
Read latency:   always 1 SSTable → <1 ms
Cost:           background CPU + disk I/O
                (schedulable off-peak)

1. Size-tiered compaction

The idea: group SSTables of similar size together. Once enough pile up, merge the whole group into one bigger file and promote it to the next tier. No key-range boundaries are enforced — files within a tier can overlap freely.

Size-tiered compaction with size ratio 10 and 100 MB flushes. New writes flush into Tier 0 as 100 MB SSTables. When 10 files pile up in Tier 0, all 10 are merged into one file of about 900 MB, moved to Tier 1, and the originals deleted. When 10 files pile up in Tier 1 they merge into one file of about 8.1 GB in Tier 2. Each tier compacts only when it is full, independently of the others; merging Tier 0 never reads or rewrites Tier 1.
Size-tiered: a full tier merges into one file a tier down (ratio 10, 100 MB flushes)
TierFilesSize eachTotalAge
T0 (hot)10100 MB1 GBDays
T1 (warm)10900 MB9 GBWeeks
T2 (cold)108.1 GB81 GBMonths
Total~91 GB

The same key can exist in T0, T1 and T2 simultaneously (newer versions in hotter tiers) — which is exactly why disk usage lands at ~2–3× the unique data.

Why write amplification stays low (~5–10×): each byte passes through each tier exactly once. Crucially, when merging Tier 0 you touch only Tier 0 files — you never read or rewrite Tier 1, you just append the merged result.

2. Leveled compaction

The idea: every level except L0 has a fixed size limit and one strict rule — no two files in the same level own the same key. That non-overlap guarantee makes reads fast and requires constant rewriting to maintain.

L0 is different: memtable flushes land here directly, so L0 files can overlap. L0 is a buffer drained into L1 quickly.

L0 → L1: compact all L0 files at once

Since L0 files can overlap, any key might live in several of them — so you can't pick just one. You take all of them.

Leveled compaction from L0 into L1, drawn on an a-to-z key axis. Before: L0 holds three files whose key ranges overlap — keys b f r y, keys a f m s, and keys c r z — and L1 holds two non-overlapping files, a to m and n to z. Because any L0 file may hold any key, all three L0 files and every overlapping L1 file go into the merge. After: L0 is empty and L1 again holds two non-overlapping files, a to m and n to z, each with the newest versions.
L0 → L1: every L0 file goes in, because any of them may hold the key

The non-overlap guarantee isn't passively preserved — it is actively rebuilt on every compaction.

L1 → L2: one file at a time

Since L1+ files don't overlap, compaction can be incremental: pick one file from L1, find only the L2 files whose ranges overlap it, merge just those. The rest of L2 is untouched.

Leveled compaction from L1 into L2 on an a-to-z key axis. L1 holds a to d, e to h, i to m and n to z; the file i to m is picked. L2 holds a to b, c to e, f to j, k to o and p to z; only f to j and k to o overlap i to m. Those three files are merged and re-split into new L2 files covering f to o. After: L1 holds a to d, e to h and n to z; L2 holds a to b, c to e, the new files, and p to z. The other L1 and L2 files are never read or rewritten.
L1 → L2: one file, plus only the L2 files its key range overlaps

RocksDB picks files round-robin so every key range gets its turn.

files per level = level size limit ÷ target file size

e.g. L1 max 640 MB ÷ 64 MB target = 10 files. 64–256 MB is the sweet spot: granular enough for incremental compaction, large enough to avoid file-metadata overhead.

Why reads are fast: at L1+, exactly one file per level can own any given key, so a read is one binary search per level with exactly one candidate file. In size-tiered, multiple files in the same tier can hold different versions of the same key, so you must check all of them.

Why write amplification is high (~10–30×): compacting one file from Li into Li+1 means the destination level is T× larger, so the incoming file's key range overlaps ~T existing files — all read and rewritten.

1 file from L1 overlaps ~10 files in L2 → ~10× amplification per transition
Repeat across all level transitions: (L − 1) × T = 3 × 10 = ~30×

That is the price of the non-overlap guarantee: you can never just append, you always merge with what's already there.

3. Head-to-head

✗ Size-tiered — worst-case read (key not found)

Tier 0: up to 10 files → 10 block reads
Tier 1: up to 10 files → 10 block reads
Tier 2: up to 10 files → 10 block reads
Total: up to 30 block reads

✓ Leveled — worst-case read (key not found)

L0: 3 files (overlap allowed) → 3 block reads
L1: binary search → exactly 1 file → 1 read
L2: binary search → exactly 1 file → 1 read
L3: binary search → exactly 1 file → 1 read
Total: up to 6 block reads  (~5× fewer)

Write throughput: size-tiered wins. Its compactions are batched, infrequent and bursty. In leveled, compaction runs continuously, competing with writes — and under extreme write load leveled can trigger write stalls (see Memtable, flush and ref-counting), pausing incoming writes until compaction catches up.

SSD wear: every compaction rewrites data, and SSDs have a finite TBW rating. Size-tiered lands around ~5–10× total write amplification, leveled around ~10–30× (the figures derived above). A write-heavy workload on leveled compaction wears drives out meaningfully faster.

Size-TieredLeveled
Disk space2–3× bloat~1.1× bloat
Read speedSlower (overlapping files per tier)Faster (1 file per level per key)
Write throughputHigher (infrequent batch)Lower (continuous compaction)
Write amplification~5–10×~10–30×
Disk I/O rateBursty (large merges)Steady (incremental)
CPU costLower per writeHigher per write
SSD wearLowerHigher
Stale dataAccumulates until the tier compactsCleaned up faster (per-file)
Temporary disk~2× the tier size during a mergeLow — one file's worth at a time
Best forWrite-heavy (logs, events, metrics)Read-heavy (user data, lookups)
Used byCassandra (default), HBaseRocksDB (default), LevelDB

4. Other strategies

  • Time-based: compact on SSTable age rather than size. Useful for TTL data — e.g. compact every 30 days to purge expired keys.
  • TWCS — Time Window Compaction Strategy (Cassandra 3.8+): time-based + size-tiered. Size-tiers within a time window (say, one day), then seals each window into one SSTable that is never merged with its neighbours. Expired windows are dropped whole, which is what makes TTL data cheap to purge. Cassandra 5 adds UCS (Unified), a single strategy with a knob that slides between tiered and leveled behaviour.
  • Reverse-leveled / hybrid tiered: experimental. Aims to beat pure size-tiered on reads while beating pure leveled on write amplification. Not yet standard.

5. Choosing

WorkloadUse
High write throughput — logs, events, IoT, metricsSize-tiered
Frequent key overwrites — prices, profiles, inventoryLeveled
Mostly unique keys, written onceSize-tiered
Read-heavy with random key lookupsLeveled
SSD with a tight TBW budgetSize-tiered
Need predictable, consistent read latencyLeveled
Data has an expiration (TTL)Time-based

6. Worked example — 500 MB/day logs, 30-day retention

Write-once keys (each log line is new), read in bulk by batch analytics. Unique data at steady state: 30 × 500 MB = 15 GB. Flushes are 50 MB, size ratio 10.

✓ Size-tiered

T0: up to 10 × 50 MB  =   500 MB   (today)
T1: 3 × ~500 MB       = ~1.5 GB    (10 days each)
T2: never fills — 30-day retention expires
    data before 10 T1 files accumulate,
    so the rest sits as T1 files: ~15 GB

Disk:      ~15–16 GB  (unique keys → no bloat)
Write amp: each byte rewritten once per tier ≈ 3×
           → 500 MB × 3 ≈ 1.5 GB disk I/O/day
Miss:      up to ~13 files to check —
           cheap, the Bloom filters do it

✗ Leveled

L0: up to 10 × 50 MB  =   500 MB   (today)
L1:  1 GB limit        (key-partitioned)
L2: 10 GB limit        (key-partitioned)
L3: the remaining ~4 GB

Disk:      ~16.5 GB  (~1.1×)
Write amp: ~10× per level crossing × 3 crossings
           ≈ 20–30× → 500 MB × 25 ≈ 12.5 GB I/O/day
           (~8× more than size-tiered)
Miss:      L0 files + exactly 1 file per level

The decision, stated as a trade rather than a winner: size-tiered spends ~1.5 GB/day of disk I/O and accepts a wider miss path; leveled spends ~12 GB/day to guarantee one candidate file per level. For write-once logs read in bulk, that read guarantee is never cashed in — so size-tiered wins here, which is exactly what the Choosing table says for logs. Flip the workload to hot-key overwrites with random point reads and the same arithmetic flips the answer.

The Invariants

  • Guarantees: Leveled guarantees at most one candidate file per level per key. Size-tiered guarantees each byte is rewritten once per tier promotion, and nothing else is touched.
  • Does not guarantee: That compaction keeps up. Neither strategy bounds how far background work can fall behind under sustained write load — that is what backpressure and write stalls exist to handle.