Storage engines, visually

How log-structured merge trees work

RocksDB, LevelDB, Cassandra, ScyllaDB, and HBase store their data in LSM trees. This page shows how an LSM tree handles writes, what an SSTable file contains, how a read finds the newest version of a key, and how compaction merges files in the background.

Writes

Append, never overwrite

Files

Sorted and immutable

Reads

Newest version wins

Upkeep

Merge in the background

01 · The core idea

Turn random writes into sequential ones

A B-tree keeps data in sorted pages on disk and updates those pages in place. Each write goes to the page that holds its key. That costs a random seek, and the disk rewrites the whole page even when only a few bytes change. An LSM tree never updates data in place. It buffers writes in memory, writes them to disk as sorted, immutable files, and merges those files later in the background.

B-tree: update in place

0 random seeks

Each cell is a disk page. Every write goes to the page that holds its key and rewrites that page.

LSM tree: append, sort later

0 sequential appends

The engine batches writes and appends them to the end of a file. Disks and SSDs write sequential data faster than scattered updates.

1Buffer in memory
Writes go into a sorted in-memory table called the memtable. The engine also appends each write to a log, so a crash loses nothing.
2Flush sorted files
When the memtable is full, the engine writes it to disk in one pass as an SSTable. Nothing modifies an SSTable after it is written.
3Merge in the background
Compaction merge-sorts SSTables into fewer, larger files. It drops old versions and deleted keys as it merges.

02 · The write path

Two cheap steps per write, then a flush

Every put first appends the change to the write-ahead log on disk so it survives a crash. It then inserts the change into the memtable, a sorted in-memory structure, usually a skip list. An update is a newer entry for the same key. A delete writes a marker called a tombstone.

When the memtable reaches its size limit, the engine freezes it as an immutable memtable and starts a new memtable for incoming writes. A background thread then writes the frozen memtable to a new SSTable in level 0. Its keys are already sorted, so this is one sequential write. Once the SSTable is on disk, the engine deletes the log segment that the flush covered.

03 · Sorted string tables

Inside an SSTable

An SSTable is an immutable file of key-value pairs sorted by key. The file never changes after it is written, so readers need no locks. Entries are packed into data blocks of 4 to 64 KiB each. Metadata at the end of the file lets a reader find a key by reading one data block.

Data blocks
Sorted entries, often prefix-compressed and checksummed. A read loads one block, not the whole file.
Filter block
A bloom filter over every key in the file. It rules out a missing key without reading a data block.
Index block
One entry per data block: its last key and byte offset. Binary search picks the right block.
Footer
A fixed-size trailer that points to the index and filter blocks. A reader opens the file by reading the footer.

How the bloom filter works. It is a bit array. Adding a key sets k bits chosen by k hash functions. Checking a key looks at the same bits: if any is 0, the key was never added. If all are 1, the key might be present, or other keys may have set those bits by coincidence.

A bloom filter never gives a false negative. At 10 bits per key, it gives a false positive for about 1% of missing keys. A filter that size fits in memory, so engines check it before reading any file.

04 · The read path

Search newest to oldest, stop at the first match

The engine never overwrites data, so one key can have versions in the memtable, in several L0 files, and in deeper levels at once. Newer data is always in a higher level, so a read checks levels from top to bottom and returns the first version it finds. If that version is a tombstone, the answer is "not found".

  1. 1

    Memtable, then immutable memtables

    Both are sorted and in memory, so checking them reads nothing from disk. Reads of recently written keys end here.

  2. 2

    Every L0 file, newest first

    L0 files are raw memtable flushes, so their key ranges overlap. Any of them could hold the key, so the reader checks each one.

  3. 3

    One file per deeper level

    From L1 down, files in a level never overlap. A binary search over file boundaries picks the single file that could contain the key.

  4. 4

    Inside each candidate file

    The reader checks the key range, then the bloom filter, then the index, and reads one data block. The range check and the filter rule out most files before any disk read.

Read amplification

A single get can check the memtable, every L0 file, and one file in each deeper level. Bloom filters turn most of those checks into memory lookups. A lookup for a missing key checks every level, but most of those checks are filter lookups in memory.

Range scans can't use bloom filters. A range scan opens an iterator on every sorted run and merges the iterators as it reads, so each extra file adds an iterator to every scan.

Try get in the playground

05 · Compaction

Merge sorted files, keep only the newest version

Without compaction, every flush adds a file and nothing removes one. Every read would check more files, and stale versions and tombstones would waste disk space. Compaction picks a set of SSTables and runs the merge step of merge sort over them. Every input is already sorted, so one pass is enough. Compaction then writes the result as new SSTables. When a key appears more than once, compaction keeps only the newest version.

Why compaction can't drop tombstones right away. A tombstone hides older versions of its key in lower levels. If compaction dropped it while an older cat:v1 still existed in a lower level, reads would return the deleted value again. Compaction can drop a tombstone only when it reaches a level with nothing older below it.

Why it runs all the time. Compaction runs on background threads and shares disk bandwidth with user requests. If writes arrive faster than compaction merges them, L0 grows and reads slow down. Engines then stall writes until compaction catches up.

Two families of compaction strategy

Every strategy trades three costs against each other. Write amplification is how many times the engine rewrites each byte. Read amplification is how many places a read must check. Space amplification is how much extra disk stale data uses. No strategy minimizes all three.

Leveled, the default in RocksDB and LevelDB
L0
L1
L2

Each level is one sorted run, about 10 times larger than the level above. When a level is over its size limit, compaction merges one of its files into the files it overlaps in the next level. Reads check at most one file per level. In exchange, the engine rewrites each byte about 10 times per level it passes through.

Tiered, used by Cassandra STCS and RocksDB universal compaction
T0
T1
T2

Each tier holds several runs of similar size, and their key ranges overlap. When a tier has enough runs, compaction merges them into one larger run in the next tier. The engine rewrites each byte about once per tier. In exchange, reads search more runs, and duplicate versions stay on disk until the next merge.

Cost Leveled Tiered
Write amplification Higher, about 10 times per level Lower, about once per tier
Read amplification Low, one file per level Higher, every overlapping run
Space amplification Low, about 10% stale data Higher, up to double during large merges
Good fit Read-heavy, space-sensitive Write-heavy, time series

06 · Playground

Put it all together

A small leveled LSM tree. The memtable flushes at 4 keys. L0 compacts into L1 once it has 3 files. L1 pushes one file down into L2 when it holds more than 8 keys. Put the same key several times, delete a key and read it back, and watch which level drops its tombstone.

07 · Glossary

The vocabulary, in one place

Memtable
The sorted in-memory buffer, usually a skip list, that holds writes until the engine flushes it to an SSTable.
Write-ahead log (WAL)
The append-only file on disk that the engine replays after a crash to rebuild the memtable.
SSTable
An immutable, sorted file made of data blocks, a filter block, an index block, and a footer.
Level / sorted run
A group of SSTables. In leveled compaction, every level below L0 is one sorted run whose files never overlap.
Tombstone
A delete marker. It hides older versions and is only dropped once nothing older can exist below it.
Bloom filter
A bit array that answers "definitely not in this file" or "maybe in this file". It never answers "not in this file" for a key that is there.
Compaction
The background merge of SSTables that drops older versions and keeps the number of files small.
Amplification
Write amplification is bytes written to disk per byte the user writes. Read amplification is places checked per lookup. Space amplification is disk used per byte of live data.