LSM Tree Design

The write-optimized storage engine behind LevelDB, RocksDB and Cassandra, built as code: log, memtable, sorted files, Bloom filters, compaction and tombstones.

Overview

A log-structured merge tree (LSM tree) is a way to store a key-value index so that writes are cheap. Instead of updating a record in place on disk, it appends every write to a log, keeps recent writes sorted in memory, and writes them out in sorted batches. Background merges keep the number of files on disk under control. The design comes from a 1996 paper by O'Neil, Cheng, Gawlick and O'Neil, and it is the engine inside LevelDB, RocksDB, Cassandra and many others.

The interview version asks you to build one. You should be able to draw the write path and the read path, trace a handful of operations through memtable, files and a compaction, explain why a delete is a write, and say what compaction costs. This topic does each of those on a tree small enough to check by hand, with a runnable Python implementation.

The write path

A write touches two things: the write-ahead log (WAL), an append-only file that makes the write durable, and the memtable, a sorted in-memory structure (RocksDB's default is a skip list). When the memtable is full it is written to disk as one sorted, immutable file, an SSTable (sorted string table), and a fresh memtable starts. LevelDB converts its memtable at about 4 MB; the size is a tuning knob.

Each of the three steps has a cost and a reason, and none of them updates anything on disk in place.

  • Append to the WAL. This costs one sequential write. It buys durability: after a crash, the log is replayed into a new memtable.
  • Insert into the memtable. This costs O(log n) in memory. It keeps recent keys sorted, so the flush can be a straight scan.
  • Flush when the memtable is full. This costs one sequential write of the whole memtable. Many random updates become one sorted file.

Interview questions

  • Explain the LSM tree write and read paths.
  • What is compaction and why is it necessary?
  • How are deletions handled in an LSM tree?
  • When would you pick an LSM tree over a B-tree?
  • How does a Bloom filter fit in, and what does it cost?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio