LSM-Trees and SSTables

How a log-structured merge-tree turns random writes into sequential ones, what compaction costs, and how Bloom filters keep reads fast.

Overview

A log-structured merge-tree (LSM-tree) is a way to store sorted key-value data on disk that never updates a file in place. New writes collect in memory, get written out as a new sorted file, and background jobs later merge those files. RocksDB, LevelDB and Cassandra all store data this way, and so does Bigtable.

The idea comes from a 1996 paper by Patrick O'Neil and others. Their problem was a table that received inserts all day: keeping a B-tree index on it cost a random disk write per insert. The LSM-tree batches those changes in memory and pushes them to disk in large sorted runs, the way merge sort works. Google's Bigtable paper (2006) gave the parts the names used today: memtable, SSTable and compaction.

The write path

A write touches two places and nothing else. First it is appended to a write-ahead log (WAL), a file on disk that only grows at the end, so the write survives a crash. Then it is inserted into the memtable, a sorted structure in memory. RocksDB's default memtable is a skip list. The write is then done: no page on disk was read or rewritten.

When the memtable reaches its size limit (64 MB by default in RocksDB), it is frozen, a new empty memtable takes new writes, and a background thread writes the frozen one to disk as an SSTable (sorted string table). An SSTable is a file of key-value pairs sorted by key, with a small index of where each block starts. It is never changed after it is written. Once its data is in an SSTable, the matching part of the log can be deleted.

> [!WARNING] > 'Written to the log' does not always mean 'on the disk'. RocksDB's default write returns once the data is handed to the operating system. A process crash loses nothing, but a machine crash can lose the last few writes unless the write sets sync.

Key concepts

  • LSM-tree
  • Memtable
  • SSTable
  • Write-ahead log (WAL)
  • Compaction
  • Tombstone
  • Bloom filter
  • Write amplification
  • Leveled compaction
  • Size-tiered compaction

Interview questions

  • Walk me through a write and then a read in an LSM-tree.
  • Why can an LSM-tree take writes faster than a B-tree?
  • What is compaction, and how do size-tiered and leveled compaction differ?
  • How does a Bloom filter speed up reads, and what can go wrong?
  • When would you not choose an LSM-tree engine?

Sign up free to read the full topic

More DDIA topics

Start free on Cariara · Coding problems · System design studio