LSM trees
How log-structured merge trees turn random writes into sequential ones, what compaction costs, and how to choose between an LSM tree and a B-tree.
The problem
A team stores click events in a table with a B-tree index and ingests 50,000 events per second. For a few weeks all is well. Then the index outgrows memory, and throughput falls off a cliff.
The cause is how a B-tree handles a write. Each insert belongs on one particular leaf page, and for most keys that page is effectively random. Once the index is larger than memory, the database has to read the page from disk, change about 100 bytes in it, and later write the whole 8 or 16 kB page back. See indexes and B-trees for the structure.
On spinning disks this is severe. A typical hard disk manages roughly 100 to 200 random operations per second, and can write 100 MB per second or more sequentially. For 100-byte records that is the difference between a few hundred writes per second and a million. SSDs narrowed the gap and did not close it: writing a whole page to change a few bytes still wastes throughput and wears the drive.
Engineers tried buffering writes in memory and batching them, which loses data in a crash unless there is also a log. Following that thought to its end gives the design that Patrick O’Neil and colleagues published in 1996 as the log-structured merge-tree. Google’s Bigtable paper (2006) described the form used today, with a memtable and SSTables, and LevelDB and RocksDB turned it into libraries.
The write path: never update in place
An LSM tree does only two things when a write arrives.
- Append it to the write-ahead log (WAL) on disk, so the write survives a crash. Cassandra calls this the commit log.
- Insert it into the memtable, a sorted structure in memory, usually a skip list.
Then it acknowledges the write. Updates and deletes follow the same path. An update is a newer entry for the same key. A delete is a marker called a tombstone.
When the memtable reaches a size limit (64 MB by default in RocksDB), it is frozen and written to disk in one sequential pass as an SSTable, a sorted string table. An SSTable is immutable: once written it is never changed, only read and eventually replaced. The matching part of the WAL can then be deleted.
Step 1 of 9
A write arrives for the key user:42. First the engine appends the record to the write-ahead log on disk. An append is a sequential write, the cheapest kind, and it means the write survives a crash.
Read the steps as text
- A write arrives for the key user:42. First the engine appends the record to the write-ahead log on disk. An append is a sequential write, the cheapest kind, and it means the write survives a crash.
- Next the engine inserts the record into the memtable, a sorted structure held in memory. The write is now acknowledged. No data file has been read or changed.
- Thousands of writes follow the same path. An update is simply a newer entry for the same key, and a delete is a marker called a tombstone. Nothing is changed in place.
- The memtable reaches its size limit, 64 MB in this example. It is frozen, and a new empty memtable with a new log segment takes over, so incoming writes do not wait.
- A background thread writes the frozen memtable to disk as an SSTable, a sorted file that is never modified again. It is written in one sequential pass with an index and a Bloom filter. The old log segment can then be deleted.
- Each flush adds another file to level 0. These files cover overlapping key ranges, so a read may have to check every one of them. Left alone, reads would get slower with every flush.
- Compaction fixes that. A background job merge-sorts the level 0 files with the level 1 files they overlap, keeps only the newest version of each key, and writes new level 1 files whose ranges do not overlap.
- When level 1 grows past its target size, some of its files are merged down into level 2, which is about ten times larger. A record is rewritten several times on its way down. That repeated rewriting is write amplification.
- Every disk write on this path was sequential, which is why an LSM tree absorbs writes much faster than a structure that updates pages in place. The bill arrives later, as background compaction and as reads that must check several files.
The read path and Bloom filters
Writes got cheap by making reads do more. The newest version of a key could be in the memtable or in any SSTable, so a read checks them from newest to oldest and stops at the first hit.
Three things keep this affordable:
- Each SSTable has a small index of its blocks, so finding a key in a file costs one block read, not a scan.
- Each SSTable has a Bloom filter, a compact bit array that answers “is this key possibly in this file?”. It can say “maybe” wrongly but never says “no” wrongly. With about 10 bits per key, the false positive rate is roughly 1%, so nearly every file that lacks the key is skipped without a disk read.
- Compaction keeps the number of files small.
Bloom filters do not help range scans, which have to merge sorted streams from the memtable and every overlapping file.
Step 1 of 8
A read arrives for the key user:42. The value could be in memory or in any of several files, so the engine searches from the newest data to the oldest and stops at the first version it finds.
Read the steps as text
- A read arrives for the key user:42. The value could be in memory or in any of several files, so the engine searches from the newest data to the oldest and stops at the first version it finds.
- The memtable holds the most recent writes, so it is checked first. This is a lookup in memory. The key is not there.
- Next come the level 0 files, newest first. Each file has a Bloom filter held in memory. The filter for SSTable 9 answers that the key is definitely not in the file, so the engine skips it without touching the disk.
- The filter for SSTable 8 answers maybe. The engine uses the file's index to read one block from disk, and the key is not in it. This is a false positive. With about 10 bits per key it happens roughly 1 time in 100.
- In level 1 the files do not overlap, so only one file can contain the key. Its filter answers maybe, the engine reads one block, and this time the key is there.
- The search stops here. Level 2 may hold an older version of the same key, but anything deeper is older, so it is ignored. If the newest entry had been a tombstone, the answer would be not found, and the search would also stop.
- The costly case is a key that does not exist. Every level has to be ruled out. Bloom filters turn most of those checks into memory lookups, which is why they matter so much to an LSM tree.
- Read cost depends on how many sorted runs the engine has to consult. Compaction keeps that number small by merging files, and it pays for that with extra writes. Tuning an LSM tree is choosing where to pay.
Compaction strategies
Compaction is a background merge sort. It reads several SSTables, keeps the newest version of each key, drops data that has been overwritten or deleted, and writes new SSTables. The strategy decides which files are merged and when.
| Strategy | How it merges | Good at | Cost |
|---|---|---|---|
| Size-tiered | When about four files of similar size exist, merge them into one larger file | Write-heavy and append-only data | A key may sit in many files, and a big merge needs a lot of spare disk |
| Levelled | Level 0 takes flushes. Each lower level is about 10 times larger and its files do not overlap | Read-heavy data with updates, and tight disk space | Each record is rewritten many times |
| Time-window | Group files by time window and compact within a window | Time-series with expiry, where whole old files are dropped | Poor for data updated long after it was written |
Size-tiered compaction was long Cassandra’s default. Levelled compaction comes from LevelDB and is RocksDB’s default style.
The three amplifications
Storage engines are compared on three ratios.
- Write amplification: bytes written to disk per byte the application wrote. Levelled compaction commonly reaches 10 to 30, because data is rewritten as it moves down each level. Size-tiered is lower.
- Read amplification: disk reads per query. Low for levelled, where a key is in at most one file per level. Higher for size-tiered.
- Space amplification: disk used per byte of live data. Levelled stays close to 1.1 in the ideal case, since about 90% of the data sits in the last level. Size-tiered can temporarily need up to twice the data size during a large merge.
You cannot minimise all three at once. Lowering one raises another, and tuning an LSM tree means choosing which to pay. There is also an operational risk: if writes arrive faster than compaction can merge them, files pile up, reads slow down, and the engine deliberately stalls writes until it catches up.
B-tree or LSM tree
| B-tree | LSM tree | |
|---|---|---|
| Writes | Page updated in place, random I/O | Sequential appends, batched |
| Point reads | One path down the tree | Memtable plus one or more files |
| Space | Pages partly empty, harder to compress | Compact files, compress well |
| Latency | Steady | Can spike during heavy compaction |
B-tree engines: PostgreSQL, MySQL InnoDB, SQL Server, Oracle, SQLite, and MongoDB’s WiredTiger in its default configuration.
LSM engines: Cassandra, ScyllaDB, HBase, Bigtable, LevelDB and RocksDB. RocksDB is embedded in many other systems, including TiKV (under TiDB), MyRocks (an LSM storage engine for MySQL built at Facebook) and Kafka Streams state stores. CockroachDB uses Pebble, its own LSM engine in the RocksDB tradition.
Insert the same run of keys into both structures and compare: the B-tree rewrites a page for every key, and the LSM tree buffers keys in memory and then writes a whole sorted file at once.
When to choose it and when not to
Choose an LSM-based store when writes dominate: event ingestion, logs, metrics, messaging history, or any table that takes tens of thousands of inserts per second. Choose it too when disk space is the main cost, since immutable sorted files compress well.
Do not choose it when the workload is mostly reads with strict latency targets, when you need range scans over data that changes constantly, or when rows are deleted soon after they are written. A B-tree engine gives steadier read latency and has no compaction to fall behind. For most transactional applications, the relational database’s B-tree is the right default.
In the interview
You rarely pick a storage engine directly. You pick a database, and the engine explains its behaviour. Bring LSM trees up when you justify a write-heavy store: “This is 200,000 appends per second and rarely updated, so I want an LSM-based store such as Cassandra. Writes are sequential: a log append and a memtable insert. Reads cost more, since a key may be in several SSTables, but Bloom filters and compaction keep that bounded.”
If the interviewer pushes, name the trade: write, read and space amplification cannot all be low, levelled compaction favours reads and space, and size-tiered favours writes. Then say what you would watch in production: pending compactions, disk headroom and tombstones.
Key takeaways
- An LSM tree never updates data in place. A write is an append to a log plus an insert into an in-memory table, so every disk write is sequential.
- Full memtables are flushed to immutable sorted files called SSTables, and background compaction merges them and discards old versions.
- A read may check the memtable and several files. Bloom filters let it skip most files without touching the disk.
- Size-tiered compaction writes less and wastes more space. Levelled compaction keeps reads and space tight and rewrites data more often.
- You cannot minimise write, read and space amplification together. Choosing a compaction strategy is choosing which one to pay.
- B-trees suit read-heavy and transactional workloads with predictable latency. LSM trees suit write-heavy workloads and compress better.
Try it
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What happens on a write to an LSM tree?
The record is appended to the write-ahead log and inserted into the memtable, then acknowledged. No data file is read or modified.
What is an SSTable?
A sorted string table. An immutable file of key-value pairs in key order, with an index and usually a Bloom filter, produced by flushing a memtable or by compaction.
What does compaction do?
It merge-sorts SSTables into new ones, keeps only the newest version of each key, and drops deleted data. It bounds the number of files a read must check and reclaims space.
Size-tiered versus levelled compaction?
Size-tiered merges files of similar size, with low write amplification but more files per read and more spare disk needed. Levelled keeps non-overlapping levels, each about 10 times larger, with better reads and space but more rewriting.
What are the three amplifications?
Write amplification is disk bytes written per byte of user data. Read amplification is disk reads per query. Space amplification is disk space used per byte of live data.
Which databases use B-trees and which use LSM trees?
B-trees, PostgreSQL, MySQL InnoDB, SQL Server, Oracle and SQLite. LSM trees, Cassandra, HBase, Bigtable, ScyllaDB, RocksDB and the systems built on it such as TiKV and MyRocks.