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:
- Append to the write-ahead log (WAL), a sequential file on disk (Cassandra calls it the commit log).
- 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.
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.
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:
- the active memtable, then any immutable memtables waiting to flush;
- 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.
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.
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:
| Means | Grows with | |
|---|---|---|
| Write amplification | bytes written to disk per byte the app wrote | how often data is rewritten by compaction |
| Read amplification | files or blocks checked per lookup | how many SSTables can hold a key |
| Space amplification | disk used per byte of live data | old 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.
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-tree | LSM tree | |
|---|---|---|
| Write | find the page, rewrite it (random I/O) | append to WAL and memtable (sequential I/O) |
| Point read | one root-to-leaf path | memtable plus possibly several SSTables, eased by Bloom filters |
| Space | free space inside pages, fragmentation | old versions and tombstones until compaction |
| Background work | page splits, vacuum in some engines | flushes 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 key3Options options = new Options()4.setCreateIfMissing(true)5.setCompactionStyle(CompactionStyle.LEVEL) // the default, made explicit6.setTableFormatConfig(new BlockBasedTableConfig().setFilterPolicy(bloom));7RocksDB db = RocksDB.open(options, "/var/data/notes")) {8db.put("zoe".getBytes(UTF_8), "Leeds".getBytes(UTF_8)); // WAL + memtable9byte[] city = db.get("zoe".getBytes(UTF_8)); // memtable, then SSTables10db.delete("zoe".getBytes(UTF_8)); // writes a tombstone11}
In Cassandra the strategy is a table option:
1ALTER TABLE news.notes2WITH compaction = { 'class': 'LeveledCompactionStrategy' };
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.