LSM trees: how write-heavy stores index
Some stores take hundreds of thousands of writes a second on ordinary disks, where a B-tree would spend its time rewriting pages. They use a log-structured merge tree. Here is how it turns every write into an append, what a read has to do in return, and the background merging that keeps it fast.
01 The cost of updating in place
A B-tree, like the one in How an index makes a Postgres query fast, keeps every key on its page. To change one key, the database reads that page, edits it, and writes the whole page back. Keys arrive in random order, so the writes land on random pages all over the disk. A page is several kilobytes; the change may be a few bytes.
An LSM tree never edits a page. It collects writes in memory, sorts them, and writes them out as one new file, front to back. Files are never changed after that. Old versions pile up and are merged away later, in the background, in big sequential passes. LevelDB, RocksDB, Cassandra, ScyllaDB and HBase all store data this way.
02 Three pieces: a log, a memtable, sorted files
| Part | Where | Job |
|---|---|---|
| Write-ahead log (WAL) | disk, appended | makes a write survive a crash before it reaches a file |
| Memtable | memory, sorted | holds the newest writes; answers reads for them |
| SSTables | disk, immutable | sorted files from earlier flushes, each with an index and a Bloom filter |
| Levels | disk | SSTables grouped by age and size; compaction moves data down |
Each SSTable has three parts: data blocks of sorted keys, a small index giving the first key of each block, and a Bloom filter, a bit array that can say “this key is definitely not here”. The index and filter are small enough to keep in memory, so finding a key in one file costs at most one block read.
03 The write path
Six writes, with a memtable limit of four keys so you can see a flush happen.
- just written
- not written yet
An empty store. Writes will land in three places: a log on disk, a sorted table in memory, and later, sorted files on disk.
In a real store the full memtable is first frozen, a fresh one takes writes at once, and the frozen one is flushed by a background thread. Writes only stall if flushing falls behind.
04 The read path: newest first
The same key can now be in the memtable and in several files, and the newest record is the true one. So a read checks places from newest to oldest and stops at the first record it finds, whether a value or a tombstone.
- checked, no match
- newest record found
- skipped or hidden
After a second flush the store holds two SSTables, newest first, and one more write, gnu=9, sits in the memtable. SST-2 contains ant=⊘: the record a delete writes, a tombstone. Three reads follow.
A lookup for a key that does not exist is the worst case: it must rule out every file. Bloom filters make that cheap. With about 10 bits per key, a filter is wrong roughly 1% of the time, so a missing key usually costs no disk reads at all. Range scans cannot use the filters; they merge a cursor from every file at once.
05 Compaction: merging sorted files
Left alone, files pile up, every read gets slower, and dead versions keep their disk space. Compaction picks some files, merges them into new ones, and deletes the inputs. Because every input is already sorted, the merge reads each file once, front to back, and writes the output the same way.
- under a pointer
- just written
- dropped
Both files are sorted, so merging them is the merge step of merge sort: one pointer per file, always take the smaller key. Here SST-1 and SST-2 are merged into one new file, SST-3.
A tombstone can only be dropped when the merge includes the oldest data for that key. If an older file outside the merge still held ant=2, dropping the tombstone would bring the deleted value back. That is why deletes free space late in an LSM store.
06 A toy LSM in 45 lines
This Python keeps “files” as sorted lists, newest first. It makes the same writes as the traces (without gnu) and prints what a store would hold:
That is a real run on Python 3.14. A real engine adds the log, binary search, Bloom filters, and a rule for which files to merge and when, which is where most of the engineering goes.
07 Choosing what to merge
Every LSM store pays in three currencies. Write amplification: how many times each byte is rewritten by compaction. Read amplification: how many places a read checks. Space amplification: how much disk old versions take. The compaction strategy decides the mix.
| Measure | Leveled | Size-tiered |
|---|---|---|
| How it works | levels each about 10× bigger than the last; files within a level do not overlap | merge a few files of similar size into one bigger file |
| Used by default in | LevelDB, RocksDB | Cassandra (long-time default), ScyllaDB |
| Write amplification | higher: a key is rewritten as it moves down each level | lower |
| Read amplification | low: at most one file per level holds a key | higher: several files of each size may hold it |
| Space amplification | low | high: a big merge needs room for inputs and output at once |
Write-heavy workloads such as metrics, logs and event streams favour size-tiered. Read-heavy workloads and tight disks favour leveled.
08 When it bites
level0_slowdown_writes_trigger = 20Compaction falls behindIf writes arrive faster than compaction merges, files pile up in the top level and reads slow down. RocksDB then throttles writes on purpose: by default it slows them once level 0 holds 20 files and stops them at 36.DELETE FROM events WHERE day < ... -- millions of rowsMass deletes add data firstEach delete writes a tombstone, so disk use goes up before it goes down. Scans over a deleted range must still step over every tombstone until compaction drops them; Cassandra warns, and later fails the query, when one read meets too many.gc_grace_seconds = 864000Deleted data coming backIn a replicated store, a replica that missed a delete still holds the old value. If tombstones are dropped before repair copies them everywhere, the value returns. Cassandra keeps tombstones for gc_grace_seconds, 10 days by default, and expects repair to run within that time.SELECT ... WHERE key BETWEEN a AND zRange scans touch every levelBloom filters only answer “is this one key here?”. A range query must open a cursor in the memtable and in every file that overlaps the range.df -h # 85% fullNo room to compactA merge writes its output before it deletes its inputs. With size-tiered compaction a large merge can need as much free space again as the data it is merging.