Apache Cassandra

Compaction Strategies: STCS, LCS, TWCS

Choose the right compaction strategy to balance read performance, write throughput, and space amplification for different workloads.

Because Cassandra's storage engine is an LSM-tree (Log-Structured Merge tree), writes accumulate as immutable SSTables on disk over time, and compaction is the background process that merges these SSTables together, discarding overwritten data and expired tombstones. The choice of compaction strategy has major implications for read latency, write amplification, and disk space usage.

STCS is like periodically merging piles of similarly-sized papers on your desk into one bigger pile. LCS is like maintaining strict alphabetized filing drawers where each drawer never has duplicate/overlapping labels. TWCS is like using a new labeled box for each week's mail and simply throwing out the entire box once its contents are no longer needed.

Key Concepts

1
SizeTieredCompactionStrategy (STCS) is the default; it merges SSTables of similar size together once enough of them accumulate. It's write-friendly and requires low compaction overhead, but can cause read amplification (many SSTables to check per read) and temporary space spikes (up to 2x data size during large compactions).
SizeTieredCompactionStrategy (STCS)
2
LeveledCompactionStrategy (LCS) organizes SSTables into levels of exponentially increasing size, guaranteeing that within a level, SSTables have non-overlapping key ranges. This dramatically reduces the number of SSTables a read must check, making it ideal for read-heavy workloads, but it incurs significantly higher I/O overhead from more frequent compactions.
LeveledCompactionStrategy (LCS)
3
TimeWindowCompactionStrategy (TWCS) groups SSTables into time-based windows and compacts within each window, then leaves older windows alone. It's purpose-built for time-series data with TTLs, since entire SSTables representing an expired time window can be dropped efficiently without ever needing to compact across windows.
TimeWindowCompactionStrategy (TWCS)