Skip to content

LSM trees: how write-heavy stores index

Deep diveUnder the hood

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.

B-treeRewrite a page per writeReads are cheap: one place to look per key. Writes are random page writes.
LSM treeAppend, sort, merge laterWrites are sequential and cheap. Reads may have to look in several places, and merging costs disk work later.

02 Three pieces: a log, a memtable, sorted files

The parts of an LSM tree
PartWhereJob
Write-ahead log (WAL)disk, appendedmakes a write survive a crash before it reaches a file
Memtablememory, sortedholds the newest writes; answers reads for them
SSTablesdisk, immutablesorted files from earlier flushes, each with an index and a Bloom filter
LevelsdiskSSTables 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.

The write path
Step 1 of 8
WAL on disk (append-only)
Empty
Memtable, sorted, in memory (flush at 4 keys)
Empty
SSTables on disk
1234
SST-1
  • 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.

The read path: newest first
Step 1 of 6
Memtable
gnu→9
SST-2 (newer)
ant=⊘
dog=6
eel=7
fox=8
SST-1 (older)
ant=2
bee=5
cat=4
dog=3
Answers
Empty
  • 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.

Compaction: merge two sorted files
Step 1 of 7
SST-1 (older)
iant=2
bee=5
cat=4
dog=3
SST-2 (newer)
jant=⊘
dog=6
eel=7
fox=8
SST-3 (being written)
Empty
  • 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:

lsm.py
TOMBSTONE = None
LIMIT = 4 # flush after 4 keys (real stores flush after megabytes)
class LSM:
def __init__(self):
self.memtable = {} # newest writes, in memory
self.tables = [] # sorted runs on "disk", newest first
def put(self, key, value):
self.memtable[key] = value
if len(self.memtable) >= LIMIT:
self.flush()
def delete(self, key):
self.put(key, TOMBSTONE) # a delete is a write too
Text
$ python3 lsm.py
files: [[('ant', None), ('dog', 6), ('eel', 7), ('fox', 8)], [('ant', 2), ('bee', 5), ('cat', 4), ('dog', 3)]]
get cat: 4 get ant: None get dog: 6
after compaction: [[('bee', 5), ('cat', 4), ('dog', 6), ('eel', 7), ('fox', 8)]]

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.

Two common strategies
MeasureLeveledSize-tiered
How it workslevels each about 10× bigger than the last; files within a level do not overlapmerge a few files of similar size into one bigger file
Used by default inLevelDB, RocksDBCassandra (long-time default), ScyllaDB
Write amplificationhigher: a key is rewritten as it moves down each levellower
Read amplificationlow: at most one file per level holds a keyhigher: several files of each size may hold it
Space amplificationlowhigh: 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.

09 Check yourself

Question

You get a key that was never written. In a well-tuned store, what is usually read from disk?

Question

Why can’t compaction drop a tombstone the moment it sees one?

Question

A store takes heavy writes and no reads. After an hour its write throughput falls sharply. What is the most likely cause?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?