Skip to the workspace
Pebellslearn by building
Probabilistic & System-Scale Structures  ›  Lesson

LSM Trees & Write Amplification

LSM Trees 32 minBuffer writes in memory, flush them sorted, then pay to rewrite surviving data again at compaction — trading write cost for a read path a Bloom filter can shrink

dsa / LSM Trees & Write Amplification

Explore each scene at your own pace.

01 · Flush a memtable, then pay for it again at compaction

Flush a memtable, then pay for it again at compaction

LSM Trees & Write Amplification

Definition
A log-structured merge tree is a storage structure that buffers writes in memory, flushes them to disk as sorted, never-edited files, and periodically merges those files into larger ones. The extra rewriting this causes is called write amplification.
In plain words
It is like jotting notes on a scratchpad and, when it is full, copying them neatly into a sorted folder. Now and then you merge folders into one bigger folder. Writing is quick, but notes get recopied several times along the way.

In short: a log-structured merge tree never edits a file on disk. A write only ever touches an in-memory memtable; once that fills up, it flushes — sorted, once — into a new sstable at the top level, L0. Once a level holds enough sstables, compaction merges them into one bigger sstable one level down, dropping any stale values along the way. Every flush and every compaction writes bytes to disk, so the same record can get paid for more than once before it settles into its final level — that repeated cost is write amplification. The trade buys something real: writes are always a cheap append, never a random-access rewrite. Reads pay the other side of the bill, scanning sstables newest-first until a key turns up — which is exactly where a Bloom filter per sstable earns its keep, by saying "definitely not here" and skipping the scan entirely.

Stacked levels — memtable on top, L0, L1, L2 below — with one write's path flushing down and a second arrow showing compaction merging two sstables into one, a level lower

Flush a memtable, then pay for it again at compaction

Quarry's engine buffers writes in memory, flushes them sorted, and merges sstables down through the levels once a level gets crowded:

step through it
1def make_sstable(memtable):
2 return sorted(memtable.items())
3 
4def merge_sstables(sstables):
5 merged = {}
6 for sst in sstables:
7 for k, v in sst:
8 merged[k] = v
9 return sorted(merged.items())
10 
11def run_lsm_traced(writes, memtable_limit, compaction_threshold):
12 memtable, levels, bytes_written = {}, [], 0
13 for key, value in writes:
14 memtable[key] = value
15 if len(memtable) >= memtable_limit:
16 sstable = make_sstable(memtable)
17 bytes_written += len(sstable)
18 print(f"flush: {sstable} -> L0 (+{len(sstable)} bytes)")
19 while len(levels) == 0:
20 levels.append([])
21 levels[0].append(sstable)
22 memtable = {}
23 i = 0
24 while i < len(levels) and len(levels[i]) >= compaction_threshold:
25 merged = merge_sstables(levels[i])
26 bytes_written += len(merged)
27 print(f"compact L{i}: {levels[i]} -> {merged} in L{i+1} (+{len(merged)} bytes)")
28 levels[i] = []
29 while len(levels) <= i + 1:
30 levels.append([])
31 levels[i + 1].append(merged)
32 i += 1
33 print("total bytes written:", bytes_written, "for", len(writes), "writes")
34 
35run_lsm_traced([("k1", "v1"), ("k2", "v2"), ("k3", "v3"), ("k1", "v4"),
36 ("k4", "v5"), ("k5", "v6"), ("k2", "v7"), ("k6", "v8"),
37 ("k7", "v9")], memtable_limit=3, compaction_threshold=2)

Nine writes, but 14 bytes end up written to disk: two flushes of 3 entries each (6 bytes), then — because L0 just reached the compaction threshold of 2 sstables — one compaction that merges those two sstables, deduplicating k1 and k2 down to their newest values, into a fresh 5-entry sstable in L1 (5 more bytes). A third flush (3 more bytes) lands the last three writes back in L0, for 14 total. k1 and k2 each got written twice: once at flush, once again at compaction. That's the whole definition of write amplification: 14 / 9 ≈ 1.56 bytes written per byte the caller actually asked to write.

Scene 1 of 5
Project context and further resources
You're building a piece ofQuarry — the storage engine
This piece — lsm_report(): Flushes and compacts writes through an LSM pipeline, and measures write amplification and read probes.
Scenario Quarry's engineers want one number for 'how much does this write cost us later' and one number for 'how much does the Bloom filter actually save on reads' — before they tune memtable_limit and compaction_threshold for real traffic.
lsm_report.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
lsm_report(writes, memtable_limit, compaction_threshold, queries, m, k) → dictWrite amplification for the whole write sequence, plus how many sstables each query actually had to probe, with and without a Bloom filter.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.