Databases & Storage · Paper 03 / 05

The Log-Structured Merge-Tree (LSM-Tree)

Patrick O'Neil, Edward Cheng, Dieter Gawlick, Elizabeth O'Neil

1996 · Acta Informatica · ~12 min read

Read the original paper

The LSM-tree batches index inserts in memory and merges them into disk in large sequential passes instead of updating pages in place. Read it to reason about RocksDB, Cassandra and their compaction, tombstones and write stalls.

Take a bank that records every account movement in a history table. Rows are only ever appended, but the bank also wants an index on account and time, so that a teller can pull up the recent movements for one customer. The appends are cheap. The index is the problem. Each new row’s index entry belongs on whichever B-tree leaf covers that account, and consecutive rows belong to unrelated accounts, so every insert lands on a different, effectively random leaf. If that leaf is not in memory, the disk has to seek to read it and seek again to write it back.

On a 1996 disk a seek cost on the order of ten milliseconds, so one disk arm could do at most about a hundred random page accesses a second. A busy system inserting thousands of rows a second needed dozens of disks, bought not for their capacity but for their arms, to maintain one index. The same disks could stream data sequentially many times faster than that. The hardware had the bandwidth. The access pattern was wasting it.

Patrick O’Neil, Edward Cheng, Dieter Gawlick and Elizabeth O’Neil proposed the log-structured merge-tree to fix this. After this explainer you should be able to trace a key from a write through memory, a flush and a compaction, say what a read must check to find it, and reason about the three costs, write, read and space amplification, that every LSM store trades against each other.

Paying for each insert with a fraction of a sequential write

The B-tree’s problem is not the cost of a page write. It is that each page write carries only one new entry. If a leaf holds forty index entries and we write it to add one, we paid a seek and a full page transfer for a fortieth of a page of new information.

update in place (B-tree)7 writes → 7 seeksthe disk arm does the workappend (LSM)7 writes → 1 sequential burstsorting is deferred to a background mergein 1996 a seek cost ~10 ms; sequential transfer of the same bytes, microseconds
Seven updates, two ways. Updating a B-tree in place means a seek for each; appending them and sorting later turns them into one sequential write. The LSM-tree is built on the gap between those two costs.

The paper’s idea is to batch. New index entries go into a small tree in memory, which the authors call C0. A much larger tree on disk, C1, holds everything older. Inserts never touch C1 directly. Instead, a process the paper calls the rolling merge continuously walks C0 and C1 together in key order, the way the merge step of merge sort walks two sorted lists. It reads C1’s leaves sequentially in large multi-page blocks, merges in the C0 entries that fall in each key range, and writes the combined leaves out to new positions on disk, again sequentially. Old blocks are freed once their contents have been rewritten.

Here is the arithmetic that makes this pay, with illustrative numbers. Say a leaf holds forty entries and C1 is ten times larger than C0. On average, as the merge passes over each C1 leaf, about four new entries from C0 fall into it. The merge reads and writes that leaf once, sequentially, and the cost is shared by those four entries. Compare that with the B-tree, which spends a random read and a random write per entry. The LSM-tree has replaced two random I/Os per insert with roughly half a sequential page I/O per insert. The paper derives this ratio in general and shows that the saving grows with the number of entries merged per page and with the gap between random and sequential cost.

One structure on disk is not enough when the data is large, because C0 must then be large to keep the merge efficient, and memory is expensive. The paper generalises to a chain of components, C0 in memory and C1 through Ck on disk, each larger than the one before, with a rolling merge between every adjacent pair. It also shows that, for a fixed largest component, total merge cost is lowest when the size ratio between consecutive components is the same at every step. That result is why every LSM store you will meet has a single “level size multiplier”, commonly ten.

Following keys through a modern LSM store

The stores built on this idea since 2006 took the structure from Bigtable rather than directly from the paper, and they look different in detail. Instead of one continuously merged tree per level, they write immutable sorted files, called SSTables, and merge them in discrete compactions. The principle is the same: absorb writes in memory, write them out sequentially in sorted batches, and merge batches into larger ones in the background.

memorymemtable (sorted)← every write lands here, sequentially loggedflushlevel 0runrunruncompaction: merge, drop overwritten versionslevel 1one sorted run · ~10× largerlevel 2one sorted run · ~100× larger · most of the data lives herea read checks memtable, then each levela Bloom filter per run skips most of them
The modern form. Every write is logged and inserted into an in-memory memtable. A full memtable is written out as an immutable sorted run in level 0. Compaction merges runs into larger, older levels. A read checks the memtable, then each level from newest to oldest.

Let us run a small store by hand, with the same settings as the simulation below: the memtable holds four distinct keys, and when level 0 has three runs they are compacted into level 1. Every write is also appended to a write-ahead log so that the memtable can be rebuilt after a crash. We write thirteen operations:

1-5    put k03=v1, k07=v2, k03=v3, k11=v4, k01=v5
       memtable full at 4 keys -> flush run R1: k01:v5 k03:v3 k07:v2 k11:v4

6-9    put k07=v6, k02=v7, k09=v8, delete k11
       flush run R2: k02:v7 k07:v6 k09:v8 k11:<tombstone>

10-13  put k03=v10, k05=v11, k07=v12, k12=v13
       flush run R3: k03:v10 k05:v11 k07:v12 k12:v13
       level 0 now has three runs -> compact R3, R2, R1 into level 1

Notice first that k03=v1 never reached disk. It was overwritten while still in the memtable, so the flush wrote only v3. Short-lived values cost almost nothing in an LSM store, which is one reason it suits counters and session state.

Next, the delete. An LSM store cannot find k11 in R1 and erase it, because R1 is immutable and rewriting it would be the random write we are trying to avoid. So a delete is a write: a tombstone record for k11 that is newer than v4. Until compaction removes them, both the old value and the tombstone take up space.

Now the compaction. It reads R3, R2 and R1 together in key order and, for each key, keeps only the newest version: k01:v5, k02:v7, k03:v10, k05:v11, k07:v12, k09:v8, k12:v13. For k11 it finds the tombstone in R2 shadowing v4 in R1. Because level 1 is the bottom of this store, no older copy of k11 can exist anywhere else, so the compaction drops both the tombstone and v4. Level 1 ends up with seven entries.

Count what we wrote to disk. Thirteen operations became twelve entries across three flushes, then seven more entries written by compaction: nineteen entries written for thirteen operations, a write amplification of about 1.5. With more levels, each byte is rewritten once for every level it passes through, and often more, so that number grows with the depth of the tree.

Try itWrite a firehose, read it back

Every write is an append into a small sorted memtable. When it fills, it is flushed as an immutable sorted run; when runs pile up, they are merged. Nothing is ever updated in place.

memory · memtable (0/4)
memtable (sorted)
empty
disk · level 0 (newest first)
no runs yet
empty
disk · level 1 (merged)
nothing compacted yet
empty
puts0
flushes0
compactions0
write amplification—×entries written to disk per entry ingested

A write never seeks: it lands in memory and later in one sequential run, which is why these stores absorb far more writes per second than a tree updated in place. The price is paid on reads, which may check several runs, and in compaction, which rewrites data in the background. Bloom filters make most of those checks free.

Predict first

Stop just before the compaction, with R1, R2 and R3 in level 0 and an empty memtable. A client reads k11. Which runs does the read look at, in what order, and what does it return? What would go wrong if the store checked runs oldest-first?

Show the worked answer

The read checks the memtable (miss), then the newest run R3. R3’s Bloom filter almost certainly says k11 is not there, so R3 is skipped without a disk read. Next is R2, which holds the tombstone for k11. The read stops and returns “not found”.

Checked oldest-first, the read would hit R1 first and return v4, a value the client deleted. The newest-first order is not an optimisation; it is what makes overwrites and deletes correct. It is also why a tombstone must survive until compaction reaches the level holding the oldest copy of the key.

Reads pay for what writes saved

The paper is candid that the LSM-tree is built for workloads where inserts greatly outnumber lookups. Our read of k11 had to consult up to four places. A B-tree lookup is one descent. In a real store with a dozen level 0 files and five or six levels below, a lookup for a key that does not exist could touch every one of them.

Two additions made reads acceptable, and neither is in the 1996 paper. The first is the Bloom filter. Bigtable kept one per SSTable: a small bit array that answers “definitely not here” or “possibly here” for any key. With around ten bits per key, the false positive rate is about one percent, so a lookup reads from disk only the files that probably hold the key. The second is leveled compaction, introduced by LevelDB, in which every level below level 0 is a single sorted run split into non-overlapping files. A lookup then checks at most one file per level.

Range scans are harder. A Bloom filter cannot say whether a range is empty, so a scan from k02 to k09 must open an iterator on every run that could overlap the range and merge them on the fly. Prefix Bloom filters and range filters are later attempts to recover some of that, with mixed success. If your workload is dominated by short range scans over data that is rarely written, a B-tree is usually the better structure.

Three amplifications, and the knob that trades them

Once a store has several levels, every design decision moves cost among three quantities. Write amplification is bytes written to disk per byte the application wrote. Read amplification is the number of places, or disk reads, a lookup touches. Space amplification is bytes on disk per byte of live data, inflated by old versions and tombstones not yet compacted away. Athanassoulis and colleagues later framed this as the RUM conjecture: an access method cannot be optimal for reads, updates and memory at the same time.

The compaction strategy is the main knob. Change one variable, the policy, and watch the three move. Assume a store with a size ratio of ten and five levels.

PolicyWrite amplificationRead amplificationSpace amplificationWhere it is used
Leveled (one run per level)High: moving data into a level rewrites the overlapping part of that level, up to about ten times its size, at each of five levelsLow: one file per levelLow: about 10% extra, since most data sits in the last levelRocksDB and LevelDB default; Cassandra LCS
Tiered (several runs per level, merged together when full)Lower: each byte is written about once per levelHigher: up to ten runs per level to checkHigher: a full merge can need twice the space temporarilyCassandra STCS; RocksDB universal compaction
B-tree, for contrastA whole page per changed entryOne descentPages left partly empty by splitsInnoDB, PostgreSQL, most relational engines

Research since 2016 has mostly been about moving along this curve more cleverly. WiscKey stores keys in the LSM-tree and values in a separate log, so compaction moves small keys instead of large values; RocksDB’s BlobDB and BadgerDB adopt the idea. Monkey showed that giving deeper levels fewer Bloom filter bits per key and shallower levels more lowers lookup cost for the same memory. Dostoevsky proposed lazy leveling, tiered in the upper levels and leveled at the bottom. Cassandra added time-window compaction for time series, where whole files expire together and can be dropped without merging.

When the deferred bill comes due

An LSM store accepts writes at memory speed and promises to do the sorting later. The failure mode is a write rate that the background compaction cannot keep up with. Here is how it unfolds in RocksDB, step by step.

A bulk import starts writing faster than usual. Memtables fill and flush quickly, and level 0 files accumulate faster than compaction can merge them into level 1. Reads start to slow because every lookup must check every level 0 file, whose key ranges overlap. When the number of level 0 files passes a slowdown threshold, RocksDB deliberately delays writes to let compaction catch up; past a higher stop threshold it blocks writes entirely. From the application’s side, write latency that was a fraction of a millisecond jumps to seconds, and nothing in the application changed.

The fixes all cost something. More compaction threads finish the work sooner but take CPU and disk bandwidth from foreground reads. Larger memtables mean fewer, larger flushes but more memory and longer recovery from the write-ahead log. A rate limiter on ingestion keeps the store healthy by making the import take longer. Switching to tiered compaction lowers the write cost per byte but makes reads and space worse. The decision should be written down as which of those costs the system can afford.

Deletes have their own version of this. A delete-heavy workload, such as a queue implemented on top of Cassandra, can accumulate large numbers of tombstones that every read must step over until compaction reaches the bottom. Cassandra keeps tombstones for a grace period so that replicas which missed the delete do not resurrect the data, which makes the problem longer lived. Reads that scan through many tombstones are a common cause of Cassandra latency incidents.

Why the idea survived SSDs

The paper’s cost model is written in terms of disk arms, and solid-state drives have no arm. It would be reasonable to expect the LSM-tree to have faded with spinning disks. It did the opposite. LevelDB appeared in 2011, Facebook forked it into RocksDB the following year, and RocksDB now sits under MyRocks, CockroachDB’s earlier storage layer, TiKV, Kafka Streams state stores and much of Meta’s infrastructure. Cassandra, HBase and ScyllaDB are LSM-trees too.

Two properties of flash kept the design relevant. Flash cannot overwrite a page in place; it must erase a large block first, so random small writes cause internal write amplification in the drive and wear it out sooner. Large sequential writes of immutable files are close to what flash wants. And LSM stores compress well, because each file is written once and can be compressed as a whole, which matters when storage is paid for by the gigabyte. Facebook’s stated reason for building MyRocks was space and write efficiency on flash compared with InnoDB.

How to read the original

The paper is long and analytical. Start with the introduction, which sets out the history table example and the cost argument based on the five-minute rule, the observation that it is cheaper to keep a page in memory than to fetch it repeatedly from disk if it is used often enough. That framing is how the authors justify spending memory on C0. Then read the two-component algorithm closely, with attention to how the rolling merge reads and writes multi-page blocks and how a lookup searches C0 before C1.

The cost analysis is the paper’s evaluation; there are no benchmarks. Read it for the ratio between LSM and B-tree insert cost and for the multi-component result that equal size ratios minimise total cost. You can skim the details of concurrency and recovery during a merge on a first read. The comparison with other structures near the end is useful for seeing which workloads the authors thought the design was not for. While reading, translate the paper’s terms into today’s: C0 is the memtable, the components are levels, the rolling merge is compaction, and the paper’s deletion entries are tombstones.

The next paper, Bigtable, is where most engineers first met this structure in practice. It puts a memtable and SSTables behind every server in a cluster of thousands and adds the Bloom filters this design needed, then asks a new question: if all data is sorted by key, how should the key be designed?