TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท storage engines ยท data structures ยท performance

LSM trees

A log-structured merge tree buffers writes in a sorted in-memory memtable backed by a write-ahead log, flushes it to immutable sorted SSTables, and merges those files in the background through compaction. Writes are fast and sequential; reads may have to check several files.

14 min6 animations

๐Ÿ“š Builds on๐Ÿ“‘ Database indexes๐Ÿ’ก Bloom filters

๐Ÿ–จ๏ธ Cheat sheet

A desk full of incoming notes

Mia is a journalist. All day, people phone her with news: "Zoe moved to Leeds", "Bob moved to Rome". She keeps one note per person, sorted by name.

Finding the right page in a giant sorted binder for every call would be far too slow. So Mia does two quick things. First she jots the note at the bottom of her day book, in the order calls come in. That's fast, because she never has to look for the right spot. Then she drops the note into the tray on her desk, in its place by name. Only then does she say "got it".

Why both? The tray is easy to search, but if someone knocks it off the desk, the notes scatter. The day book is safe in her bag, so she can rebuild the tray from it, as long as she'd finished writing the line. This sorted tray on the desk is called the memtable.

The write path: WAL and memtable

A log-structured merge tree (LSM tree) turns every write into two cheap operations:

  1. Append to the write-ahead log (WAL), a sequential file on disk (Cassandra calls it the commit log).
  2. Insert into the memtable, a sorted in-memory structure (a skip list by default in RocksDB).

The write is then acknowledged. Nothing on disk is searched or updated in place, so the cost of a write barely depends on how much data is already stored.

The memtable is lost if the process crashes, so on restart the engine replays the WAL to rebuild it. How durable an acknowledged write is depends on when the WAL is synced to disk: RocksDB doesn't fsync on every write by default (WriteOptions.sync is false), so a process crash is safe but a power cut can lose the last writes unless you set WriteOptions.sync to true (RocksDB batches concurrent synced writes into one fsync) or call FlushWAL(true)/SyncWAL() periodically.

The write path5 steps
Day book01234๐Ÿ“žCaller๐Ÿ“ฅ Desk tray
Press play and watch it happen!

Filing a full tray

The tray only holds so many notes. When it's full, Mia takes the whole stack, already sorted, puts it in a new folder, writes the date on it and files it in the cabinet. That folder is never opened to fix anything again.

Now she starts a fresh, empty tray, and she can throw away the day book pages for those notes, because the folder keeps them safe.

This is why Mia never falls behind, however busy it gets: she never hunts through old folders to fix a note. She only ever adds new notes and files new folders. If Bob moves again, Bob just gets a newer note.

Flushing to immutable SSTables

When the memtable reaches its size limit (write_buffer_size in RocksDB), it becomes immutable, a new memtable takes new writes, and a background thread flushes the old one to disk as a Sorted String Table (SSTable): a file of key-value pairs sorted by key. Once the SSTable is durable, the matching WAL segment can be deleted.

SSTables are never modified. An update to a key is just a newer entry in the memtable, later in a newer SSTable; the old value stays in its file until compaction removes it. That gives LSM trees their main strength:

  • Writes are sequential I/O: WAL appends and whole-file flushes, no random page rewrites. That suits both disks and SSDs, and sustains high write throughput.
  • No read-before-write: an update or delete doesn't need to find the old value first.
  • Simple concurrency and recovery: immutable files can be read without locks, copied for backups, and never end up half-updated.
Flushing a full memtable4 steps
Day book pages0123Folder 10123๐Ÿ“žCaller๐Ÿ“ฅ Desk tray
Press play and watch it happen!

Finding a note again

Someone asks: "Where does Bob live now?" Mia looks in the tray first, because it has the newest notes. Then the folders, newest first. The first Bob she finds is the most recent one, so she stops there. An older Bob note in an older folder is out of date anyway.

Opening every folder would be slow, so each folder has a little check card on its cover. One look tells her "surely no Bob in here", so she skips that folder, or "maybe Bob", so she opens it. A "maybe" is sometimes wrong, but a "surely not" never is.

Inside the folder, tabs every few pages (A, F, M, T) let her open it near Bob instead of reading it all. The check card on each cover is called a Bloom filter.

The read path: newest first, Bloom filters, sparse indexes

A point lookup checks the sources from newest to oldest and stops at the first entry for the key:

  1. the active memtable, then any immutable memtables waiting to flush;
  2. the SSTables, newest first.

Because newer data shadows older data, the first hit is the current value. A key that doesn't exist is the worst case: every source has to say no.

Two structures keep that cheap:

  • A Bloom filter per SSTable answers "definitely not here" or "maybe". A "definitely not" skips the file without touching disk; about 10 bits per key gives roughly a 1% false-positive rate. In RocksDB you enable them with a filter policy on the table format.
  • A sparse index per SSTable: the file is split into blocks, and a small index holds one key per block. A binary search in that index finds the single block that can hold the key, so one block is read, not the whole file.

Whole-key Bloom filters can't help range scans (RocksDB's prefix filters can help scans within one key prefix): they merge sorted iterators over the memtable and every overlapping SSTable. Sorted files make that merge cheap, much like a merge step in merge sort.

Reading newest first4 steps
Folder 3 (newest)0123Folder 20123Folder 1 (oldest)0123๐Ÿ™‹Asker๐Ÿ“ฅ Desk tray
Press play and watch it happen!

Deleting without crossing out

Zoe asks to be taken out of Mia's notes. But Mia never edits a folder, so she can't cross out Zoe's old note. Instead she adds a new note to the tray: a bright "Zoe: deleted" sticky note.

When someone asks about Zoe, Mia meets the sticky note first, because it's newer, and says "no note for Zoe". The old note still sits in its folder, taking up room, but nobody reads it.

Now and then Mia tidies up. She takes a few folders and merges them into one new sorted folder. For each person she keeps only the newest note, drops the sticky notes along with the old notes they hide, and throws the old folders away. The sticky note is called a tombstone.

Tombstones and compaction

A delete can't remove anything from an immutable SSTable, and it can't simply skip writing: an older SSTable still holds the key and would answer the next read. So a delete writes a tombstone, a marker entry for the key that shadows every older value. Reads that meet the tombstone first report the key as absent.

Compaction merges several SSTables into new ones. It streams the sorted inputs together, keeps only the newest entry per key, and drops shadowed values. A tombstone can only be dropped once every older file that might hold the key is part of the same compaction; otherwise the old value would come back.

Tombstones have costs: they take space until compacted, and range scans over many of them slow down. In a replicated store like Cassandra they must also live long enough to reach every replica. Cassandra keeps them for at least gc_grace_seconds (default 864000, ten days) and drops them at a later compaction; a replica that stays down longer than that and isn't repaired can bring deleted data back.

Tombstones and merging5 steps
Folder 2 (newer)012Folder 1 (older)012Merged folder012๐Ÿ“žCaller๐Ÿ™‹Asker๐Ÿ“ฅ Desk tray
Press play and watch it happen!

Two ways to tidy

Mia has two habits to choose from for merging folders.

The pile habit: when about four folders of the same thickness pile up, merge them into one thicker folder. Thick folders later merge with other thick folders. Each note gets copied only a few times, so filing stays quick. But Bob may sit in several folders, so finding him can mean opening more of them, and a big merge needs room for the old folders and the new one at the same time.

The shelf habit: the cabinet has shelves, and each shelf holds about ten times more than the one above it. On every shelf below the top one, the folders cover separate letters (A to M, N to Z), so only one folder per shelf can hold Bob. Finding is quicker and little room is wasted, but notes get copied again each time they move down a shelf.

Every habit trades three things: how often notes get copied, how many folders a search opens, and how much room old notes take. This tidying is called compaction.

Compaction strategies and amplification

Compaction strategies trade three kinds of amplification:

MeansGrows with
Write amplificationbytes written to disk per byte the app wrotehow often data is rewritten by compaction
Read amplificationfiles or blocks checked per lookuphow many SSTables can hold a key
Space amplificationdisk used per byte of live dataold versions and tombstones not yet compacted

Size-tiered compaction (Cassandra's STCS, close to RocksDB's universal style) merges SSTables of similar size once enough of them exist (in Cassandra, min_threshold 4 by default). Write amplification is low, which suits write-heavy workloads. But a key can live in many tiers, so reads check more files, and a large merge temporarily needs free space for both its inputs and its output.

Leveled compaction (LevelDB, RocksDB's default, Cassandra's LCS) organises SSTables into levels L0, L1, L2โ€ฆ, each about 10 times larger than the last. L0 files are fresh flushes and may overlap; within each lower level, files have non-overlapping key ranges, so a lookup reads at most one file per level. Compacting a file into the next level rewrites the overlapping files there, so write amplification is higher, while read and space amplification are lower. It suits read-heavy and update-heavy tables.

Other strategies exist for specific shapes of data: Cassandra's TWCS groups time-series data by time window so whole expired files can be dropped, and Cassandra 5.0 adds the Unified Compaction Strategy (UCS), which can be tuned between tiered and leveled behaviour. No strategy wins on all three: lowering one or two usually raises the other.

Size-tiered and leveled compaction5 steps
Thin folder01Thin folder01Thin folder01Thin folder01Thick folder01234Top shelf folder01Shelf 2 A to M01Shelf 2 N to Z01
Press play and watch it happen!

The in-tray or the ring binder

There's another way to keep notes: one big sorted ring binder. For every call, Mia flips to the right page and rewrites the note right there. Looking things up is easy, because each person is in exactly one place. But when calls pour in, all that flipping and rewriting can't keep up.

The in-tray is the opposite: taking a note is always quick, and finding one may mean checking a few places. A busy newsroom flooded with calls picks the in-tray. A library that mostly looks things up picks the binder. The ring binder is called a B-tree.

LSM trees versus B-trees, and where they're used

The usual alternative is the B-tree behind most database indexes: sorted pages updated in place.

B-treeLSM tree
Writefind the page, rewrite it (random I/O)append to WAL and memtable (sequential I/O)
Point readone root-to-leaf pathmemtable plus possibly several SSTables, eased by Bloom filters
Spacefree space inside pages, fragmentationold versions and tombstones until compaction
Background workpage splits, vacuum in some enginesflushes and compaction, which compete for disk I/O

B-trees give predictable, read-friendly lookups. LSM trees give high write throughput and compress well (files are written once, in full), at the cost of background compaction that can cause latency spikes if it falls behind.

LSM trees power LevelDB, RocksDB (embedded in many other systems), Apache Cassandra, ScyllaDB, HBase and Google's Bigtable, whose 2006 paper introduced the terms memtable and SSTable. From Java, RocksDB is available as RocksJava:

1RocksDB.loadLibrary();2try (BloomFilter bloom = new BloomFilter(10);              // about 10 bits per key3     Options options = new Options()4         .setCreateIfMissing(true)5         .setCompactionStyle(CompactionStyle.LEVEL)  // the default, made explicit6         .setTableFormatConfig(new BlockBasedTableConfig().setFilterPolicy(bloom));7     RocksDB db = RocksDB.open(options, "/var/data/notes")) {8    db.put("zoe".getBytes(UTF_8), "Leeds".getBytes(UTF_8));   // WAL + memtable9    byte[] city = db.get("zoe".getBytes(UTF_8));             // memtable, then SSTables10    db.delete("zoe".getBytes(UTF_8));                        // writes a tombstone11}

In Cassandra the strategy is a table option:

1ALTER TABLE news.notes2  WITH compaction = { 'class': 'LeveledCompactionStrategy' };
LSM tree versus B-tree4 steps
๐Ÿ“žCaller๐Ÿ“’ Ring binder๐Ÿ“ฅ Desk tray๐Ÿ—‚๏ธ Filed folders
Press play and watch it happen!
๐Ÿ”ง Going deeper

Write stalls: if flushes or compaction can't keep up (too many L0 files, too many immutable memtables), RocksDB slows down or stops writes until they catch up. Sustained write throughput is bounded by compaction throughput, not by the memtable.

Updates are blind writes: a put never reads the old value, which is why counters, read-modify-write and uniqueness checks need extra reads (or merge operators in RocksDB) on an LSM store.

Tombstone-heavy patterns such as using a table as a queue (insert, read, delete) leave long runs of tombstones that every scan must step over. Cassandra warns and eventually fails queries that scan too many tombstones.

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about LSM trees, told the same way as the story.
  1. Mia said "got it" for Zoe's note, then the tray was knocked off the desk before it was filed. What happens to Zoe's note?
  2. Bob has a note in the tray saying Rome and an older one in a folder saying Oslo. What does Mia answer, and why?
  3. Why does Mia add a "deleted" sticky note instead of just throwing Zoe's note away?
  4. Mia's notes change all the time and people ask about them constantly. Which tidying habit fits best?
  5. Compared with the ring binder, what does the in-tray give up?
Answer every question to check.Passing marks LSM trees as done.
Got the hang of LSM trees? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ—๏ธ Storing data at scaleStep 4 of 7

โ† Previous on the path๐Ÿ’ก Bloom filtersNext on the path โ†’๐Ÿ“š Replication and read replicas