Compaction

Part 4 made every write an append into an immutable file, and Part 5 showed what that costs a read: a merge across every SSTable that might hold the partition. Compaction is the background process that pays that debt down — merging files, resolving duplicates, and finally removing tombstones. The consequence worth internalizing is that choosing a compaction strategy is choosing a read-latency contract: each strategy bounds how many SSTables a read can touch, and each charges a different price in write amplification, disk headroom, and I/O contention for that bound.

Why Compaction Exists

Compaction is the direct consequence of SSTable immutability (Part 4 — Stage 3, SSTable).

Because SSTables are never modified, every update and every delete creates a new SSTable entry rather than overwriting an old one. Over time:

  1. The same row exists in multiple SSTables with different timestamps.
  2. Tombstones accumulate across many SSTables.
  3. Bloom filters, key caches, and index structures exist for each file — multiplied by the number of SSTables.

Reads become slower because they must open more files and merge more data. Disk space is wasted by redundant copies.

Compaction solves this by periodically merging multiple SSTables into fewer, larger SSTables — applying LWW to resolve duplicates and discarding tombstones that have aged past gc_grace_seconds.

The result

Fewer SSTables, faster reads, freed disk space, eliminated tombstones.

The cost

Compaction is I/O-intensive. During compaction, Cassandra reads source SSTables and writes the merged output — temporarily consuming 2x the disk space and significant I/O bandwidth.

  • Guarantees: After a compaction, the merged output holds at most one live version of each cell (the LWW winner), and tombstones older than gc_grace_seconds among its inputs are gone.
  • Does not guarantee: That a partition ends up in one file. Compaction only reconciles the SSTables it picked as inputs; versions in SSTables outside that set are untouched until a later compaction includes them.

Compaction Strategies

The cleanest way to compare the strategies: each one is a read-latency contract.

Writes are O(1) appends under every strategy; what differs is the bound each strategy puts on N — the number of SSTables a read may have to merge (Part 5). STCS offers no bound (a partition can fragment across many SSTables between compactions), LCS guarantees at most one SSTable per level regardless of update rate, and TWCS aligns fragmentation with time windows so time-range queries only touch the files for their window. Choosing a strategy is choosing where on the read-cost spectrum you sit, and what write amplification you'll pay for the bound.

StrategyBound on N (SSTables per read)Optimizes forPays with
STCSNone — a partition can fragment across many SSTables between compactionsWrite throughputRead performance, space amplification
LCSAt most one SSTable per level, regardless of update rateRead performance, space efficiency~10x write amplification, continuous compaction I/O
TWCSAligned with time windows — a time-range query touches only its window's filesTime-series with TTL / expiryCross-window queries; breaks on out-of-order writes

STCS — Size-Tiered Compaction Strategy

How it works: When enough SSTables of similar size accumulate (default: 4), Cassandra merges them into one larger SSTable. The result is a new, larger SSTable that will later be merged with other large SSTables in the next tier.

Size-tiered compaction in three tiers. In tier 1, four 1 MB SSTables merge into one 4 MB SSTable. That 4 MB file joins tier 2, where it waits until three other 4 MB peers exist; the four then merge into 16 MB. The 16 MB file joins tier 3 and waits for three peers; four 16 MB files merge into 64 MB. The trigger is four SSTables of similar size, the default threshold. Box widths are not to scale.
STCS — four similar-sized SSTables merge, and the result waits for three peers
Optimizes forWrite throughput. Writes flow into small SSTables quickly. Compaction triggers only when a threshold of same-size files accumulates.
SacrificesRead performance (many SSTables to check) and space efficiency. During a compaction of 4 × 16MB SSTables, you need 16MB × 4 = 64MB of source data plus 64MB of output space in flight simultaneously — 2x peak space usage.
Use caseWrite-heavy workloads where the data is not frequently read back or where the data model is append-only and you don't query for the latest value of a key. Time-series data that is never updated is the textbook fit — but TWCS is strictly better for that (see below).

LCS — Leveled Compaction Strategy

How it works: SSTables are organized into levels (L0, L1, L2, ...). Each level has a size budget 10x larger than the level below. SSTables within a level do not overlap in key range — each key exists in exactly one SSTable per level.

Leveled compaction with Cassandra defaults. L0 holds freshly flushed SSTables whose key ranges overlap. Below it, levels L1, L2 and L3 each hold SSTables that do not overlap, and each level’s budget is ten times the one above with 160 MB SSTables: about 1.6 GB, 16 GB and 160 GB. L0 compacts down into L1, and so on down the levels. A read for one key k may touch every overlapping L0 file, then exactly one SSTable in each of L1, L2 and L3.
LCS — overlapping L0, then non-overlapping levels; one key hits at most one SSTable per level

When L0 fills up, SSTables are compacted down into L1, ensuring non-overlapping ranges. This cascades down the levels.

Optimizes forRead performance. Because SSTables within a level don't overlap, a read for any key needs to check at most one SSTable per level. With bloom filters, most levels are skipped. Reads are fast and predictable.
SacrificesWrite throughput. To maintain non-overlapping invariants, compaction runs continuously and aggressively. Write amplification is approximately 10x: each byte written by the client is rewritten ~10 times as it cascades through levels. This saturates disk I/O on write-heavy clusters (see Part 4 — Write Amplification).
Use caseRead-heavy workloads where reads are latency-sensitive and reads are more frequent than writes. Also useful when disk space efficiency matters — LCS wastes less space than STCS because compacted data doesn't accumulate in same-size tiers.

TWCS — Time-Window Compaction Strategy

How it works: Data is divided into time windows (e.g., 1 hour, 1 day). SSTables are compacted only with other SSTables from the same time window. Once a time window closes (it's now in the past), its SSTable is finalized and never compacted again.

Time-window compaction across four hourly windows, oldest to newest. The oldest window’s data has all expired its TTL, so its SSTable is dropped whole without being read. The 09:00 and 10:00 windows are closed: each was compacted to one SSTable and is never compacted again. The current 11:00 window is still receiving flushes, and its several small SSTables compact internally into one.
TWCS — compact within a window, freeze it when it closes, drop it whole when it expires

When TTLs expire, the entire SSTable for an old window falls below the gc_grace_seconds threshold, and Cassandra can drop the entire SSTable file — without reading it. Zero amplification for deletions.

Optimizes forTime-series workloads with TTL or expiry. Compaction is extremely efficient because data is naturally grouped by time. Old data disappears by dropping whole files, not by merging tombstones row by row.
SacrificesQueries that span multiple time windows still require reading multiple SSTables. TWCS assumes the dominant query pattern is "give me recent data within a time range" not "give me all data for key X across all time."
Use caseAny time-series table where rows are written once, read within a recent window, and expire via TTL. IoT sensor data, metrics, logs, audit trails.
  • Guarantees: LCS: a read touches at most one SSTable per level (L1 and below). TWCS: a time-range read touches only its windows' files, and expired windows leave by whole-file deletion.
  • Does not guarantee: Any bound under STCS; nor LCS's bound while L0 is backlogged; nor TWCS's efficiency once backdated writes or mixed TTLs reach a closed window.

Space Amplification During Compaction

During an active compaction, source SSTables and the output SSTable coexist on disk until the compaction finishes. For STCS, this means you may temporarily need 2x the space of the data being compacted.

The 50% figure is driven by STCS, whose largest compactions can involve most of a table's data at once. LCS compacts in small, fixed-size SSTable units, so its in-flight headroom requirement is far smaller — one more place where the strategy choice in §2 shows up as an operational number.

  • Guarantees: A compaction never destroys its inputs before its output is complete — a failed compaction loses no data.
  • Does not guarantee: That there is room to finish. If the disk fills mid-compaction, the compaction fails, the stale data stays, and the node is left fuller than before it started.

Read Latency During Compaction

Compaction consumes disk I/O. Reads happening concurrently must compete for the same disk bandwidth. Symptoms: p99 read latency spikes during large compaction events.

Mitigations

MitigationHow
Rate-limit compaction I/OSet compaction_throughput_mb_per_sec (renamed compaction_throughput in Cassandra 4.1; the old name is still accepted).
Adjust dynamically without restartUse nodetool setcompactionthroughput.
Move the heavy work off-peakSchedule intensive compactions during off-peak hours with nodetool compact.
Remove the contention at the hardware levelUse NVMe SSDs where random I/O is fast enough that compaction and reads don't visibly compete.
nodetool getcompactionthroughput        # current limit
nodetool setcompactionthroughput 64     # MB/s; 0 = unthrottled
nodetool compact <keyspace> <table>      # major compaction — see caveat below

The right answer is not to suppress compaction — letting it fall behind is worse. The right answer is hardware that can absorb both.

  • Guarantees: Throttling caps compaction's share of disk bandwidth, which bounds how much it can hurt concurrent reads.
  • Does not guarantee: That compaction keeps up. A throttle below the incoming write rate means SSTable count — and read cost (Part 5) — grows without bound.