LSM trees and the write-optimised world
Memtables, SSTables, compaction and the triangle of read, write and space amplification you cannot escape
A RocksDB database holds 1 million orders in about 130 MB of SST files. You delete every second key, 500,000 deletes, and flush. Before any manual compaction, how much space do the SST files take?
A B+ tree updates data where it lives. To change one row it reads the leaf page, modifies it, and eventually writes the whole page back, usually 8 or 16 KB, to the same place on disk. Random writes into random pages are the price of keeping every key in exactly one place, where a read finds it in three or four page reads.
The log-structured merge tree makes the opposite bet. It never updates in place. Every write goes to memory, memory is written out as sorted immutable files, and background work merges those files. Writes become sequential and cheap; reads may have to look in several places; and the background merging rewrites the same data many times. O’Neil and colleagues proposed the structure in 1996 for exactly this trade, a history table taking a high rate of inserts. Today it is the engine under RocksDB, LevelDB, Cassandra, ScyllaDB, HBase, and the storage layers of CockroachDB (Pebble), TiDB (TiKV on RocksDB) and many more.
The write path and the read path
The simulation runs the core mechanism. Play WRITE, FLUSH, READ first, then the two crash scenarios, then the tombstone scenarios.
Log-structured merge tree
===================================================
WRITE(k, v)
1. append (k, v) to the WAL and fsync <- durability
2. insert into the memtable (sorted, in memory)
3. acknowledge
DELETE(k) is a write of a tombstone (k, †)
FLUSH (memtable full)
write it out as an immutable sorted SSTable, then truncate the WAL
READ(k)
memtable, then SSTables newest -> oldest
the FIRST table that mentions k decides:
a value -> return it
a tombstone -> "not found", stop (do not look further)
(Bloom filters let a read skip tables that cannot hold k)
COMPACT(newer, older)
merge-sort; for each key the newer entry wins
a tombstone may be dropped ONLY if no older SSTable below
the merge can still hold the key (e.g. the merge reaches the
bottom level); otherwise keep it, or the old value resurrects
Trade-off: sequential writes and cheap ingest, paid for with
read amplification (many tables to probe) and write amplification
(data rewritten by compaction).
Used by: RocksDB, LevelDB, Cassandra, ScyllaDB, HBase What to watch:
- The write path. A
PUTis appended to the write-ahead log, then inserted into the memtable, an in-memory sorted structure (a skip list in RocksDB). Then it is acknowledged. Nothing else touches the disk on the write path, and the log append is sequential. That is why an LSM engine takes hundreds of thousands of small writes per second on one core. - Flush. When the memtable reaches its size limit (
write_buffer_size, 64 MB by default in RocksDB), it becomes immutable and a background thread writes it out as an SSTable (sorted string table): a file of key-sorted data blocks, an index block, and a filter block. Once flushed, the matching WAL segment can be deleted. - The read path. A
GETchecks the memtable, then each SSTable newest-first, and stops at the first table that mentions the key. Newer data shadows older data because the search order is by age. - The crash scenarios. Without a WAL, a crash loses everything in the memtable that the client was already told was written. The WAL closes that window, at the cost of an fsync per write or per group of writes, the same trade the WAL chapter covered for B-trees.
- Tombstones. A
DELETEwrites a tombstone. Compaction may drop a tombstone only once no older file can still hold the key, which in practice means when the merge reaches the bottom level. Drop it early and the deleted value comes back.
Break it yourself before reading on:
This engine runs without a write-ahead log. Every PUT and DELETE is acknowledged as soon as it reaches the memtable. Insert one crash so that something the client was told succeeded is gone after restart.
GOAL: an acknowledged write or delete is lost after the restart
The simulation has a handful of tables. A real database has thousands, and that is where the interesting decisions are: how those files are organised, and when they are merged.
Levels and compaction
If flushed files only accumulated, a read would probe every file ever written. Compaction merges files: it reads several sorted files, merge-sorts them, keeps the newest version of each key, drops shadowed versions (and tombstones where it safely can), and writes new files. It is the only place an LSM tree reclaims space, and the only thing that bounds how many files a read must check.
RocksDB organises files into levels, L0 to L6 by default:
- L0 holds freshly flushed memtables. Its files overlap in key range, because each one covers whatever keys arrived during one memtable’s lifetime. A read has to check every L0 file.
- L1 and below are each one sorted run: files within a level do not overlap, so a read checks at most one file per level, found by binary search on file key ranges.
- Each level is about 10 times larger than the one above (
max_bytes_for_level_multiplier = 10). With dynamic level sizing, the default since RocksDB 8.4, the last level holds about 90% of the data and the one above it about 9%.
How files move between levels is the compaction style, and it is the most consequential setting in an LSM engine. RocksDB implements three:
| style | RocksDB name | how it merges | write amp | read amp | space amp | good for |
|---|---|---|---|---|---|---|
| Levelled | level (default) |
when a level exceeds its target, pick a file and merge it into the overlapping files of the next level | high: often over 10, up to about 30 for large databases | low: one file per level below L0 | low: about 1.1 | general-purpose OLTP, read-heavy workloads, space-constrained SSDs |
| Tiered | universal |
let sorted runs accumulate; merge several adjacent runs of similar size into one larger run | low: a few times | higher: many runs to probe | high: up to 2x or more, and a full compaction needs free space equal to the data | ingest-heavy workloads, write-bound SSD wear budgets |
| FIFO | fifo |
never merge; when total size exceeds max_table_files_size, delete the oldest file |
1 | high: every file is a run | bounded by the cap | time-series and caches where old data may be dropped |
RocksDB’s levelled style is really a hybrid: L0 is tiered (overlapping files) and everything below is levelled. Tiered compaction is the original Cassandra default (size-tiered compaction strategy); levelled came from LevelDB. FIFO is the one that deletes data you did not delete, so use it only where losing the oldest data is the point.
The amplification triangle
Three numbers describe what an LSM tree costs you, and no compaction style minimises all three.
Write amplification is bytes written to storage per byte the application wrote. With levelled compaction each byte is written once to the WAL, once at flush, and then roughly once per level per unit of fanout as it is merged down, which is how a 10x fanout over five or six levels reaches 10 to 30. On an SSD that is wear and compaction bandwidth: an application writing 50 MB/s can drive over 1 GB/s of device writes. If compaction falls behind, L0 fills, and RocksDB first slows writes (level0_slowdown_writes_trigger, 20 files) and then stops them (level0_stop_writes_trigger, 36). A write stall is the LSM version of an outage.
Read amplification is the work per read: files probed, blocks read. A point lookup in a levelled tree checks the memtable, every L0 file, and one file per lower level. Without help that is six or more disk reads for a key that does not exist.
Space amplification is bytes on disk per byte of live data. Shadowed versions and tombstones occupy space until compaction removes them. Levelled compaction keeps this near 1.1 because 90% of data sits in one fully compacted level. Tiered compaction can hold several full copies of a key range at once.
The RocksDB team’s own retrospective, Dong et al., describes their optimisation target moving over eight years from write amplification to space amplification, as SSDs got faster and storage cost became the bill that mattered, and then to CPU. Monkey and Dostoevsky, which the storage-research chapter covers, formalise the triangle and show where you can move along it. The rule for now: pick the corner you can least afford to lose, and accept paying in the other two.
Bloom filters: making negative reads cheap
The read path’s worst case is a key that is not there, or is only in the bottom level: every file above it is probed for nothing. The fix is a Bloom filter per SSTable, a bit array that answers “definitely not in this file” or “possibly in this file” (the bloom-filter lesson has the mechanism). RocksDB builds one per file at flush and compaction time, stores it in the file’s filter block and keeps it in memory or the block cache.
At 10 bits per key the false-positive rate is about 1%, so a read for a missing key touches the disk for about one file in a hundred instead of every file. RocksDB’s newer Ribbon filter reaches the same 1% with about 7 bits per key, at 3 to 4 times the CPU to build. The cost is memory: 10 bits per key is 1.25 bytes per key, so a billion keys need about 1.25 GB of filter. Filters only answer point lookups. A range scan cannot use a whole-key filter at all (prefix filters help when the range shares a prefix), so it merges an iterator over the memtable, every L0 file and every level, which is the structural reason LSM range scans are slower than a B+ tree walking linked leaves.
Tombstones and what deletes really cost
A delete costs a write now and work later. The tombstone must survive every compaction until it reaches the level that holds the oldest copy of the key; in a 6-level tree that can take a long time for a cold key range. Until then every read and every scan that crosses the range must skip it. That is Discord’s incident: a scan over a partition of a few live messages and millions of tombstones does millions of units of work to return one row.
Distributed LSM stores add another constraint. Cassandra keeps tombstones for gc_grace_seconds, 10 days by default, so a replica that missed the delete can learn about it during repair before the tombstone vanishes; drop it earlier and the deleted value comes back from that replica. Discord shortened it to 2 days because they repaired nightly. Patterns that create tombstones heavily, such as queue-like tables where rows are inserted and deleted, writing nulls (a null column is a tombstone in Cassandra), or wide DELETE of time ranges, are the ones to avoid or to design for with range tombstones, TTL and partitioning by time so whole files can be dropped.
When LSM wins and when it does not
| workload | better fit | why |
|---|---|---|
| sustained high write rate, many small writes, keys arriving in random order | LSM | sequential writes, no read-before-write, batching in the memtable |
| dataset much larger than RAM on SSD, cost matters | LSM (levelled) | compressed, densely packed files beat half-full B-tree pages; Facebook moved MySQL’s storage to MyRocks for this and reported roughly half the space |
| append-mostly time series with expiry | LSM (FIFO or time-windowed) | old data dropped by deleting whole files |
| read-latency-sensitive point lookups, tight p99 | B+ tree | one root-to-leaf path, no compaction stalls, no L0 pile-ups |
| range scans and ordered iteration | B+ tree | one ordered pass over linked leaves instead of a merge across levels |
| heavy update-in-place of a small hot set that fits in memory | B+ tree | the buffer pool absorbs it; an LSM tree writes a new version every time |
| delete-heavy, queue-like access | B+ tree (or rethink the design) | tombstones make every scan pay for history |
Two cautions. First, a B-tree with a write-ahead log and a large buffer pool also turns many writes into sequential I/O; the gap narrows when the working set fits in memory. Second, LSM latency has a long tail: compaction competes with foreground reads for I/O and CPU, and a read that arrives during a burst of L0 files pays for all of them. Measure p99, not the mean.
You will load a million shop-shaped orders into RocksDB through the rocksdict package, watch SST files form levels, switch compaction style and measure, compare with SQLite’s B-tree on the same data, and watch deletes grow the database. rocksdict ships prebuilt wheels for macOS (Intel and Apple Silicon), Linux (x86-64 and ARM64) and Windows, so there is nothing to compile. The values mirror the shop’s orders rows from docs/LABS.md, generated locally so you do not need the Postgres stack running.
1. Set up.
mkdir lsm-lab && cd lsm-lab
python3 -m venv .venv && . .venv/bin/activate
pip install rocksdict
python -c "import rocksdict; print('ok')"ok. If pip tries to build from source, your Python is older than the published wheels; use 3.9 or newer.2. The load-and-measure script. Create lsm_lab.py. It writes a million orders in random key order in batches of 10,000, flushes, waits for compaction to settle, then times 100,000 random point reads. The memtable is set to 8 MB so 130 MB of data produces many flushes and compactions, and compression is off so sizes compare honestly with SQLite.
import os, sys, time, json, random, shutil, sqlite3
from rocksdict import Rdict, Options, WriteBatch, DBCompactionStyle, DBCompressionType, FifoCompactOptions
N = int(os.environ.get("N", "1000000"))
READS = 100_000
STATUSES = ["shipped"] * 17 + ["placed", "paid", "cancelled"]
def value(i):
return json.dumps({"id": i, "customer_id": (i * 7919) % 500000, "status": STATUSES[i % 20],
"total_cents": (i * 104729) % 100000, "created_at": "2025-06-01T00:00:00Z"}).encode()
def key(i):
return b"order:%012d" % i
def du(path):
return sum(os.path.getsize(os.path.join(d, f)) for d, _, fs in os.walk(path) for f in fs)
def run_rocks(style):
path = f"./lsm-{style}"
shutil.rmtree(path, ignore_errors=True)
opt = Options(raw_mode=True)
opt.create_if_missing(True)
opt.set_write_buffer_size(8 * 1024 * 1024) # 8 MB memtable: many flushes
opt.set_target_file_size_base(8 * 1024 * 1024)
opt.set_max_bytes_for_level_base(32 * 1024 * 1024)
opt.set_compression_type(DBCompressionType.none())
if style == "level":
opt.set_compaction_style(DBCompactionStyle.level())
elif style == "universal":
opt.set_compaction_style(DBCompactionStyle.universal())
elif style == "fifo":
opt.set_compaction_style(DBCompactionStyle.fifo())
f = FifoCompactOptions(); f.max_table_files_size = 64 * 1024 * 1024 # keep 64 MB, drop the oldest
opt.set_fifo_compaction_options(f)
db = Rdict(path, opt)
order = list(range(N)); random.Random(1).shuffle(order) # random key order, like real traffic
t = time.perf_counter()
for start in range(0, N, 10_000):
wb = WriteBatch(raw_mode=True)
for i in order[start:start + 10_000]:
wb.put(key(i), value(i))
db.write(wb)
db.flush()
load = time.perf_counter() - t
for _ in range(50): # let background compaction settle (max 10 s)
if not db.property_int_value("rocksdb.num-running-compactions"): break
time.sleep(0.2)
rnd = random.Random(2); found = 0
t = time.perf_counter()
for _ in range(READS):
if db.get(key(rnd.randrange(N))) is not None: found += 1
reads = time.perf_counter() - t
print(f"== RocksDB {style}: {N/load:,.0f} writes/s; {READS/reads:,.0f} reads/s ({found} found); "
f"on disk {du(path)/1e6:.0f} MB")
print(db.property_value("rocksdb.levelstats"))
for line in db.property_value("rocksdb.stats").splitlines():
if line.lstrip().startswith("Sum") or line.startswith("Cumulative compaction"):
print(line)
db.close()
def run_sqlite():
path = "./lsm-sqlite.db"
for p in (path, path + "-wal", path + "-shm"):
if os.path.exists(p): os.remove(p)
db = sqlite3.connect(path, isolation_level=None)
db.execute("pragma journal_mode=wal"); db.execute("pragma synchronous=normal")
db.execute("create table kv(k blob primary key, v blob) without rowid")
order = list(range(N)); random.Random(1).shuffle(order)
t = time.perf_counter()
for start in range(0, N, 10_000):
db.execute("begin")
db.executemany("insert into kv values (?,?)", ((key(i), value(i)) for i in order[start:start + 10_000]))
db.execute("commit")
db.execute("pragma wal_checkpoint(truncate)")
load = time.perf_counter() - t
rnd = random.Random(2); found = 0
t = time.perf_counter()
for _ in range(READS):
if db.execute("select v from kv where k=?", (key(rnd.randrange(N)),)).fetchone(): found += 1
reads = time.perf_counter() - t
print(f"== SQLite B-tree: {N/load:,.0f} writes/s; {READS/reads:,.0f} reads/s ({found} found); "
f"on disk {os.path.getsize(path)/1e6:.0f} MB")
db.close()
if __name__ == "__main__":
for arg in sys.argv[1:] or ["level", "universal", "fifo", "sqlite"]:
run_sqlite() if arg == "sqlite" else run_rocks(arg)3. Levelled compaction, and the files on disk.
python lsm_lab.py level
ls lsm-level
ls lsm-level/*.sst | wc -l
grep -c "compaction_started" lsm-level/LOG== RocksDB level: 290,000 writes/s; 200,000 reads/s (100000 found); on disk 132 MB. The level table shows one file in L0 and the rest in the bottom two levels, for example 4 files (28 MB) in L5 and 15 files (93 MB) in L6: dynamic level sizing put about 75% of this small database in the last level. The Sum line shows a W-Amp around 3, and Cumulative compaction about 0.36 GB written for 0.13 GB ingested. The directory holds about 20 numbered .sst files plus LOG, MANIFEST-* (the list of live files per level), OPTIONS-*, and a .log file, which is the WAL. The LOG records every flush and compaction. Write amp is only about 3 because 130 MB fills two levels; at 100 GB the same settings reach 10 to 30.4. Tiered and FIFO.
python lsm_lab.py universal fifo5. The same data in a B-tree.
python lsm_lab.py sqliteshuffle lines) and the B-tree’s write gap shrinks sharply: sequential keys append to the rightmost leaf.6. Deletes make it bigger. Create tomb.py:
import os, sys, time
from rocksdict import Rdict, Options, WriteBatch
def sst_mb(p):
return sum(os.path.getsize(os.path.join(p, f)) for f in os.listdir(p) if f.endswith(".sst")) / 1e6
path = sys.argv[1]
db = Rdict(path, Options(raw_mode=True)) # reopens with the options saved at creation
print(f"before: {sst_mb(path):.0f} MB of SST files")
wb = WriteBatch(raw_mode=True)
for i in range(0, 1_000_000, 2):
wb.delete(b"order:%012d" % i)
if len(wb) >= 10_000:
db.write(wb); wb = WriteBatch(raw_mode=True)
db.write(wb); db.flush()
print(f"after 500k deletes: {sst_mb(path):.0f} MB")
t = time.perf_counter(); n = sum(1 for _ in db.keys())
print(f"full scan: {n} live keys in {time.perf_counter() - t:.2f}s")
db.compact_range(None, None)
print(f"after compaction: {sst_mb(path):.0f} MB")
t = time.perf_counter(); n = sum(1 for _ in db.keys())
print(f"full scan: {n} live keys in {time.perf_counter() - t:.2f}s")
db.close()python tomb.py ./lsm-levelbefore: 132 MB, after 500k deletes: 164 MB, a full scan of 500,000 live keys in about 0.24 s, then after compaction: 66 MB and the same scan in about 0.10 s. The deletes added 30 MB of tombstones; the scan was more than twice as slow because it skipped a tombstone for every live key; and only a full compaction to the bottom level reclaimed anything. This is the Predict, measured.opt.set_level_zero_file_num_compaction_trigger(100) and opt.set_disable_auto_compactions(True) added after the compression line. Writes get slightly faster, since no compaction competes with them. Then look at the level table: all 17 flushes are still in L0 as overlapping files, and point reads drop about four times, from around 200,000/s to around 55,000/s, because every read now probes every L0 file. With compaction enabled but falling behind under a real write load, the same pile-up is what trips RocksDB’s L0 triggers: writes slow down at 20 files and stop at 36. Compaction is not housekeeping you can defer; it is the read path’s budget, paid in advance.You are choosing storage for an event-ingestion service: 40,000 events per second at peak, 500 bytes each, retained for 90 days (about 150 TB raw before replication), keyed by (tenant, timestamp). Reads are a dashboard that scans the last hour per tenant, plus occasional point lookups by event id. Deletes happen only by expiry. The team knows Postgres well. What storage engine do you pick?
- PAPER The Log-Structured Merge-Tree (LSM-Tree) O'Neil, Cheng, Gawlick, O'Neil, 1996
The original design, argued from disk-arm economics: why batching inserts into a memory component and merging them sequentially beats in-place B-tree updates. The multi-component tree in section 3 is what became levels. Read: Acta Informatica 33(4). Read section 1 (the history-table motivation and the five-minute rule cost argument) and section 2 (the two-component tree and rolling merge); skim the cost analysis in section 3.
- DOC RocksDB wiki: Compaction
The RocksDB team's own map of levelled, tiered, tiered-plus-levelled and FIFO compaction and which amplification each trades. Follow its links to the Leveled Compaction and Universal Compaction pages for the sizing rules and options used in the lab.
- PAPER Evolution of Development Priorities in Key-value Stores Serving Large-scale Applications: The RocksDB Experience Dong, Kryczka, Jin, Stumm, 2021
Eight years of running RocksDB at Facebook scale. Shows the amplification triangle as an engineering history rather than a diagram, and why the defaults are what they are. Read: FAST '21. Read the account of how the optimisation target moved from write amplification to space amplification and then CPU, with production numbers; skim the lessons on large-scale deployment and failure handling.
- DOC RocksDB wiki: RocksDB Bloom Filter
How per-SST filters are built, stored and cached, the bits-per-key versus false-positive table, Ribbon filters, and prefix versus whole-key filtering. Skip the format-version details.
- POST How Discord Stores Billions of Messages Stanislav Vishnevskiy, 2017
The incident in this chapter's opening, with the design around it: partitioning by time bucket, tombstones from nulls and deletes, gc_grace_seconds, and the read path paying for write-optimised storage.
- BOOK Designing Data-Intensive Applications Martin Kleppmann, 2017
The clearest short comparison of the two families, including write amplification, compaction interference with reads, and why benchmarks often mislead. Read it after the lab and see how many of its claims you have now measured. Read: chapter 3, sections 'SSTables and LSM-Trees' and 'Comparing B-Trees and LSM-Trees'.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.