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:
- The same row exists in multiple SSTables with different timestamps.
- Tombstones accumulate across many SSTables.
- 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_secondsamong 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.
| Strategy | Bound on N (SSTables per read) | Optimizes for | Pays with |
|---|---|---|---|
| STCS | None — a partition can fragment across many SSTables between compactions | Write throughput | Read performance, space amplification |
| LCS | At most one SSTable per level, regardless of update rate | Read performance, space efficiency | ~10x write amplification, continuous compaction I/O |
| TWCS | Aligned with time windows — a time-range query touches only its window's files | Time-series with TTL / expiry | Cross-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.
| Optimizes for | Write throughput. Writes flow into small SSTables quickly. Compaction triggers only when a threshold of same-size files accumulates. |
|---|---|
| Sacrifices | Read 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 case | Write-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.
When L0 fills up, SSTables are compacted down into L1, ensuring non-overlapping ranges. This cascades down the levels.
| Optimizes for | Read 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. |
|---|---|
| Sacrifices | Write 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 case | Read-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.
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 for | Time-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. |
|---|---|
| Sacrifices | Queries 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 case | Any 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
| Mitigation | How |
|---|---|
| Rate-limit compaction I/O | Set compaction_throughput_mb_per_sec (renamed compaction_throughput in Cassandra 4.1; the old name is still accepted). |
| Adjust dynamically without restart | Use nodetool setcompactionthroughput. |
| Move the heavy work off-peak | Schedule intensive compactions during off-peak hours with nodetool compact. |
| Remove the contention at the hardware level | Use 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 belowThe 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.