Sub topic 14
Leveled Compaction
This chapter assumes you know the memtable, SSTables, tombstones, and the basic compaction idea of merging files so newer values replace older ones. Leveled compaction is the second main strategy for deciding which files to merge and when.
The core idea
Leveled compaction organizes SSTables into numbered levels. Level 0 (L0) holds files flushed straight from the memtable. Their key ranges can overlap. Every level below L0 follows one rule: the files in a level have non-overlapping key ranges. Together they form one sorted run split into many small files.
Each level has a size limit, and each deeper level is larger by a fixed factor, often 10. If L1 holds 100 MB, L2 holds about 1 GB and L3 about 10 GB.
How a compaction runs
When a level exceeds its size limit, the engine picks a file from it and merges it into the next level:
- Choose a file in level N.
- Find the files in level N+1 whose key ranges overlap it.
- Merge them, with newer values winning over older ones.
- Write the result as new files in level N+1, then delete the inputs.
Only a small slice of the next level is rewritten each time, so compactions are small and short. L0 is handled differently. Its files overlap each other, so an L0 compaction usually merges all of them with the overlapping part of L1.
Tombstones
A tombstone can be dropped once it reaches the deepest level that holds the key. No older version can exist below it, so nothing is left for it to hide. Until then it must travel down with each merge.
Trade-offs
| Cost | Leveled compaction |
|---|---|
| Read amplification | Low. About one file per level, plus L0 files. |
| Space amplification | Low. Most data sits in the last level with few stale copies. |
| Write amplification | High. Data is rewritten each time it moves down a level. |
The write cost comes from the size ratio. Moving a file from level N into level N+1 rewrites it together with about 10 times its size in overlapping data. Over the life of a key, that can add up to tens of rewrites.
A sketch of picking overlaps
This function finds the files in the next level that a chosen file must be merged with. Each file is a (min_key, max_key) pair.
def overlapping(file, next_level):
lo, hi = file
return [f for f in next_level if f[0] <= hi and f[1] >= lo]
l1_file = ("a", "f")
l2 = [("a", "c"), ("d", "g"), ("h", "k")]
print(overlapping(l1_file, l2))This prints [('a', 'c'), ('d', 'g')]. The file ("h", "k") is left alone.
Exercise
Why does leveled compaction have lower read and space amplification than size-tiered compaction, and what does it pay for that?
Show answer
Non-overlapping files in each level mean a lookup checks about one file per level, and stale copies are merged away quickly, so few duplicates remain. The cost is higher write amplification, because data is rewritten each time it moves to a deeper level.