AlgoViz

LSM tree

hard 28 min

A log-structured merge tree collects writes in memory, flushes them as sorted files and merges those files in the background.

Video lesson · Chapter 1 of 5

Accept a burst without updating a tree on disk

0:00 / 3:25

Log, sort, merge in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

An LSM tree, short for log-structured merge tree, is a way to organise a whole storage engine. A write is appended to a log and put into a sorted table in memory. When that table is full it is flushed to disk as an SSTable. Background compaction merges these files.

Files are arranged in levels. New files arrive in level 0, where key ranges overlap. In the common leveled form, each deeper level is about ten times larger and its files do not overlap.

Why it exists

An update in place must find and rewrite a page for each small change. With scattered keys and more data than memory, that means many random reads and writes. An LSM tree never updates in place: it turns many small writes into a few large sequential ones.

The price is paid elsewhere. A read may have to look in several files, old versions take space until they are merged, and the merging writes the same data again. An LSM tree is a deal between these three costs.

A short history

  1. 1996

    Patrick O'Neil, Edward Cheng, Dieter Gawlick and Elizabeth O'Neil publish "The log-structured merge-tree" in Acta Informatica.

  2. 2006

    Google's Bigtable paper describes a store built from a commit log, a memtable, SSTables and compactions.

  3. 2011

    LevelDB is written by the Bigtable authors as an open library with the same general design.

  4. 2012

    RocksDB is created at Facebook as a fork of LevelDB for server workloads.

  5. 2016

    WiscKey, presented at FAST, separates keys from values so that compaction moves less data.

Words to know

Memtable
The sorted table in memory that takes all writes.
Immutable memtable
A full memtable that is being flushed while a new one takes writes.
Level 0
The newest files on disk. Their key ranges may overlap.
Compaction
Merging files to drop old versions and keep reads cheap.
Tombstone
A marker that says a key was deleted.
Write amplification
Bytes written to storage for each byte written by the application.
Read amplification
Disk reads for one lookup.
Space amplification
Bytes on disk for each byte of live data.

How it works

Step through the idea, or press Play.

Step 1 of 3

Log and memtable. Append for safety, insert into a sorted table in memory

Understand it

Start here

The post office story

Letters arrive all day. Walking to the right shelf for each one would take forever, so the clerk sorts them in a tray on the desk. A full tray is sealed in a box. When too many boxes stand around, they are merged into well-ordered ones. Collecting trading cards works the same: first a pile, then a small sorted box, then a bigger one.

Tray, boxes, shelves
Top shelfLower shelfACEBookA C EInto the tray

Quick now, tidy later. The tidying has to keep up.

The idea

Architecture

One LSM storage engine

A client writes to one database server. Inside, the write goes to a write-ahead log on disk and a memtable in memory. The memtable is flushed to level 0 files. Compaction merges level 0 into level 1 and level 1 into level 2.
Pink is the path of a write before it is confirmed. Orange work happens in the background.

The levels in leveled compaction

PlaceKey rangesSize, RocksDB defaults
Active memtableEverything new64 MB
Immutable memtableBeing flushed64 MB
Level 0OverlapCompaction starts at 4 files
Level 1No overlap: a-f, g-m, n-s, t-z256 MB
Level 2No overlap, finer pieces10 times level 1
Level 3 and deeperNo overlap10 times the level above
Values from the RocksDB options. LevelDB uses 4 MB, 4 files, 10 MB for level 1 and then also a factor of 10.
  • Fast writes

    An append and an insert in memory.

  • Growing levels

    Each about ten times the one above.

  • Background work

    Flush and compaction run beside the traffic.

  • No update in place

    A newer version hides an older one.

Write path

What a write does

  1. 1

    Append to the log

    So the write survives a crash. How safe it is depends on when the log is flushed.

  2. 2

    Insert into the memtable

    A sorted structure in memory, O(log n).

  3. 3

    Confirm

    The client gets its answer. No data file was touched.

  4. 4

    Flush, later

    A full memtable is written as a new file in level 0. Then its part of the log can go.

  5. 5

    Compact, later

    Files are merged so that reads stay cheap.

The write path

Why it is quick

  • Sequential log

    Only appended.

  • Memory

    The insert needs no disk.

  • No random writes

    Nothing on disk is changed in place.

  • Batching

    Thousands of writes become one file.

Sorted structures for a memtable

StructureWhereWhy
Skip listDefault in RocksDB; LevelDB tooSimple, and friendly to many readers
Red-black treeSome enginesBalanced, O(log n)
AVL treeRareStricter balance, more work on insert
Vector, hash variantsOptions in RocksDBBulk loading, or no ordered scans

Read path

What a read does

  1. 1

    Memtables

    The active one, then the immutable ones. Found: done.

  2. 2

    Level 0

    All files whose range holds the key, newest first, because they overlap.

  3. 3

    Level 1 and deeper

    At most one file in each level. A binary search over the ranges finds it.

  4. 4

    Not found

    No level had the key, or the newest version is a tombstone.

A lookup stops at the newest version

Before each file, its Bloom filter is asked.

What keeps reads cheap

HelpEffect
Bloom filterSkips files that certainly do not hold the key; see SSTable
Block cacheHot blocks stay in memory
Index in memoryOne disk read for each file that is really searched
CompactionFewer places to look

Expected disk reads for one key

hit in the last level=1+(n−1) pmissing key=n p\text{hit in the last level} = 1 + (n-1)\,p \qquad \text{missing key} = n\,p
nn is the number of files that could hold the key and pp the false positive rate. With 4 files in level 0, levels 1 to 6 and 1%: n=10n = 10, so about 1.09 reads for a hit and 0.10 for a miss, when filters and indexes are in memory.

A range scan cannot use these filters. It opens an iterator on every memtable, every level 0 file and every level, and merges them: from the memtable a, c, e, g, from level 0 b, d, f, from level 1 h, i, j, so the result is a to j in order.

Compaction

Keeping order

Without compaction there would be thousands of small files, and a read would have to check them all. Compaction merges files, drops versions that were replaced and removes deleted keys when that is safe.

Leveled

  • Levels without overlap, each 10 times larger
  • At most one file per level for a key
  • Little extra space, about 11% in a steady state
  • More rewriting
  • Default in RocksDB; also LevelDB

Size-tiered

  • Merge files of similar size, such as four of 1 MB into one of 4 MB
  • Less rewriting
  • More files for a key
  • A big merge may need as much free space as its input
  • Cassandra's default when no strategy is named

Level 0 into level 1

Four overlapping files and the level 1 files they touch go in; new level 1 files come out, and level 0 is empty.

Other strategies exist. Time-window compaction groups data by time, so old windows can be dropped whole. Cassandra's current documentation recommends its unified strategy for most workloads, because it can be tuned to behave like the others.

Three costs

Write, read and space amplification

Write amplification, leveled, worst case

WA≈1⏟log+1⏟flush+2⏟L0→L1+3×11⏟L1→L4=37WA \approx \underbrace{1}_{\text{log}} + \underbrace{1}_{\text{flush}} + \underbrace{2}_{L0 \to L1} + \underbrace{3 \times 11}_{L1 \to L4} = 37
For about 280 GB with levels of 256 MB, 2.5 GB, 25 GB and 250 GB. Moving one byte down rewrites up to ten bytes that were there. Real figures are often lower, roughly 10 to 30, so treat them as estimates and measure.
LeveledSize-tiered
Write amplificationHigh, about the factor times the levelsLower, about one per tier
Read amplificationLow: one file per levelHigher: several files per tier
Space amplificationAbout 1.1Up to 2 and more during a big merge
Choose forReads, updates, tight spaceHeavy inserts
Steady state with a factor of 10. An unmerged upper level adds 1/10 + 1/100 + ..., about 11%.

Deletes

Tombstones

A file cannot be changed, so a delete writes a tombstone: key user:1, value deleted. A read that meets the tombstone first answers not found, although an older file may still hold Alice.

When may a tombstone go?

Drop it too early and the old value comes back to life.

In a replicated system a node that was away may not know about the delete. Cassandra therefore keeps tombstones for ten days by default (gc_grace_seconds = 864,000). Many tombstones in one range make scans slow, because each must be read and skipped.

Trouble

When compaction falls behind

From busy to stalled

RocksDB slows writes at 20 level 0 files and stops them at 36 by default.

What to watch

SignalMeaningMove
Level 0 files riseCompaction is too slowMore compaction threads, limit the writers
Pending compaction bytes riseDebt is buildingAdd disk bandwidth or nodes
Latency peaks every few minutesCompaction competes with readsRate limit compaction
Disk fills during a mergeInputs and outputs exist togetherKeep free space, or leveled compaction
Scans slow after mass deletesTombstonesCompact that range, drop by time window

Compare

LSM tree or B-tree?

LSM treeB-tree
WritesVery fast: sequential, batchedSlower when keys are scattered
Reads of one keyGood with filters, several placesOne path, steady
Range scansMerge of several sourcesFollow linked leaves
Write amplificationCompaction: roughly 10 to 37 leveledWhole page for a small change: up to 80 for 100 bytes in 8 KB
SpaceOld versions until mergedPartly empty pages
Background workCompaction must keep upCheckpoints
Neither side of the write amplification row is always lower. It depends on row size, memory and how often one page is changed between checkpoints.

Choose

LSM tree when

  • Logs, metrics, sensor data, messages
  • Time series that are mostly appended
  • High ingest rates
  • Compression matters
  • Some extra read latency is fine

B-tree when

  • Reads dominate, as in many OLTP systems
  • Latency must be steady
  • Point lookups and ranges are everything
  • Many short transactions
  • Nobody wants to tune compaction

Summary

The whole topic in one minute.

Log, sort, merge: append to a log, sort in memory, flush a file, merge later. Writes are quick because nothing is updated in place and many of them share one sequential write.

Reads go from the newest data to the oldest and use Bloom filters to skip files. Compaction decides between rewriting, reading and space: leveled compaction favours reads and space, size-tiered favours writes. If compaction falls behind, reads slow down and then writes must wait.

  • Log, memtable, flush, compaction.
  • Level 0 overlaps; deeper levels in leveled compaction do not.
  • Reads go from new to old; Bloom filters skip files.
  • Deletes are tombstones until compaction may drop them.
  • Leveled favours reads and space, size-tiered favours writes.
  • Compaction must keep up, or writes stall.

Sources