← Back to home

Database Internals - LSM Trees

24 min read
Cover Image for Database Internals - LSM Trees
Lucas LemosLucas Lemos

Introduction

B-Trees ended on the write bill: change a 16-byte index entry and an 8 KB page goes back to disk, in a random spot of the file. A log-structured merge tree, or LSM tree, avoids that by never updating anything in place. Writes collect in memory, memory is written out as sorted files that never change again, and background work merges those files.

The idea comes from a 1996 paper by O'Neil and others, and it reached everyday use through Google's Bigtable and then LevelDB. RocksDB forked LevelDB and is now underneath MyRocks and TiKV, CockroachDB runs on Pebble, a Go engine modeled on RocksDB, and Cassandra and ScyllaDB use the same design. Writes get much cheaper, and the bill moves to reads and to a background process that never quite finishes.

Back to the append-only store

The toy store from Essentials already had the fast half of this. Set was one sequential append. What it lacked was everything else: the hash index had to fit in RAM, range queries meant reading the whole file, and overwriting a key a million times left a million records on disk.

An LSM tree keeps the rule that a write never touches old data and changes what gets written. Instead of appending each record to one unordered log, it buffers records in a sorted in-memory structure called the memtable. When the memtable is full, it goes to disk in one pass as a sorted string table, or SSTable, and that file is never modified again.

The log file is there because the memtable dies with the process. It's the same job the write-ahead log does in PostgreSQL, and the next article is about exactly that, so the code below leaves it out.

Immutable files buy more than sequential writes. A reader needs no lock on an SSTable, because nobody will change it. A crash during a flush can't corrupt a page, since the half-written file was never registered and gets deleted on restart. The torn page problem from Pages & Storage Layout simply doesn't come up.

The cost is that a key now lives in several places. Its newest value is in the memtable, an older one is in last hour's file, and one from last week is in another. Reads have to check them newest first, and something has to clean up the old copies.

A small LSM tree in Go

Same method names as the Essentials store, plus Delete and Scan. Let's start with the memtable:

type entry struct {
	key, value string
	tombstone  bool
}

func cmpEntry(e entry, key string) int { return strings.Compare(e.key, key) }

// memtable keeps entries sorted. LevelDB uses a skip list here.
type memtable struct {
	entries []entry
	size    int
}

func (m *memtable) put(e entry) {
	i, found := slices.BinarySearchFunc(m.entries, e.key, cmpEntry)
	if found {
		m.size += len(e.value) - len(m.entries[i].value)
		m.entries[i] = e
		return
	}
	m.entries = slices.Insert(m.entries, i, e)
	m.size += len(e.key) + len(e.value)
}

func (m *memtable) get(key string) (entry, bool) {
	i, found := slices.BinarySearchFunc(m.entries, key, cmpEntry)
	if !found {
		return entry{}, false
	}
	return m.entries[i], true
}

The tombstone flag is how deletes work. You can't remove a key from a file that never changes, so Delete writes a new entry saying the key is gone, and that entry hides the older values during reads.

A sorted slice makes each insert O(n), which is fine for a toy. LevelDB uses a skip list (db/skiplist.h), which gives O(log n) inserts and, more importantly, lets readers walk it with no locks while a single writer adds to it.

Writing an SSTable

A flush streams the sorted entries into a file, cut into 4 KB blocks, and records the first key of each block:

const blockSize = 4 << 10

type blockHandle struct {
	firstKey string
	offset   int64
	length   int
}

// table is an open SSTable. A real one stores index and filter at the end of
// the file; here they stay in memory.
type table struct {
	f      *os.File
	index  []blockHandle
	filter *bloom
	size   int64
	count  int
}

// writeTable streams sorted entries into a new file, one block at a time.
func writeTable(path string, entries iter.Seq[entry], count int) (*table, error) {
	f, err := os.Create(path)
	if err != nil {
		return nil, err
	}
	t := &table{f: f, filter: newBloom(count), count: count}
	var block []byte
	var firstKey string
	flush := func() error {
		if len(block) == 0 {
			return nil
		}
		t.index = append(t.index, blockHandle{firstKey, t.size, len(block)})
		n, err := f.Write(block)
		t.size += int64(n)
		block = block[:0]
		return err
	}
	for e := range entries {
		if len(block) == 0 {
			firstKey = e.key
		}
		t.filter.add(e.key)
		block = appendEntry(block, e)
		if len(block) >= blockSize {
			if err := flush(); err != nil {
				return nil, err
			}
		}
	}
	if err := flush(); err != nil {
		return nil, err
	}
	return t, f.Sync()
}

That index is sparse. It has one entry per block rather than one per key, so 100,000 keys need about 2,900 index entries instead of 100,000. This is the fix for the hash index that had to fit in RAM: to find a key you binary search the index, read one block, and look inside it. A real SSTable stores the index and the filter at the end of the file with a small footer pointing at them, and our toy just keeps them in memory.

The DB ties it together. Tables are ordered newest first, and that order is what makes a read correct:

type Options struct {
	MemtableLimit int  // flush the memtable at this many bytes
	MaxTables     int  // compact when there are more tables than this
	Filters       bool // consult bloom filters on Get
}

type DB struct {
	dir    string
	opts   Options
	mem    *memtable
	tables []*table // newest first
	nextID int

	UserBytes, DiskBytes int64 // written by callers / written to files
	BlockReads           int64
}

func (db *DB) Set(key, value string) error {
	return db.write(entry{key: key, value: value})
}

func (db *DB) Delete(key string) error {
	return db.write(entry{key: key, tombstone: true})
}

func (db *DB) write(e entry) error {
	db.UserBytes += int64(len(e.key) + len(e.value))
	db.mem.put(e)
	if db.mem.size < db.opts.MemtableLimit {
		return nil
	}
	return db.flush()
}

func (db *DB) flush() error {
	t, err := db.newTable(slices.Values(db.mem.entries), len(db.mem.entries))
	if err != nil {
		return err
	}
	db.tables = slices.Insert(db.tables, 0, t)
	db.mem = &memtable{}
	if len(db.tables) > db.opts.MaxTables {
		return db.compact()
	}
	return nil
}

func (db *DB) Get(key string) (string, bool, error) {
	if e, ok := db.mem.get(key); ok {
		return e.value, !e.tombstone, nil
	}
	for _, t := range db.tables {
		if db.opts.Filters && !t.filter.mayContain(key) {
			continue
		}
		i := t.blockFor(key)
		if i < 0 {
			continue
		}
		db.BlockReads++
		block, err := t.readBlock(i)
		if err != nil {
			return "", false, err
		}
		if j, found := slices.BinarySearchFunc(block, key, cmpEntry); found {
			return block[j].value, !block[j].tombstone, nil
		}
	}
	return "", false, nil
}

The first hit wins, because the first hit is the newest. A tombstone counts as a hit too, which is why Get returns !e.tombstone instead of carrying on to older tables, where the deleted value is still sitting.

Skipping tables with a Bloom filter

A key that doesn't exist is the worst case for that loop, since it has to check every table to be sure. A Bloom filter answers "is this key in this table?" with either "definitely not" or "probably", using a few bits per key:

// bloom is a Bloom filter with 10 bits per key and 6 probes.
type bloom struct{ bits []byte }

func newBloom(n int) *bloom { return &bloom{bits: make([]byte, (n*10+7)/8+1)} }

func probes(key string, nbits uint32) iter.Seq[uint32] {
	h := fnv.New64a()
	h.Write([]byte(key))
	sum := h.Sum64()
	h1, h2 := uint32(sum), uint32(sum>>32)|1
	return func(yield func(uint32) bool) {
		for i := uint32(0); i < 6; i++ {
			if !yield((h1 + i*h2) % nbits) {
				return
			}
		}
	}
}

func (b *bloom) add(key string) {
	for p := range probes(key, uint32(len(b.bits)*8)) {
		b.bits[p/8] |= 1 << (p % 8)
	}
}

func (b *bloom) mayContain(key string) bool {
	for p := range probes(key, uint32(len(b.bits)*8)) {
		if b.bits[p/8]&(1<<(p%8)) == 0 {
			return false
		}
	}
	return true
}

Adding a key sets six bits. Checking a key looks at the same six bits, and if any of them is zero the key was never added, so the table can be skipped without touching the disk. A false positive only costs one wasted block read. The numbers match LevelDB's: util/bloom.cc computes the probe count as bits_per_key * 0.69, which gives 6 for 10 bits per key, and derives the probes from one hash by double hashing, as we do here. That setting gives about a 1% false positive rate.

Merging and compaction

Sorted files can be merged in one pass, reading each from start to end. This merge is used by both range scans and compaction:

// merge yields entries from sources in key order. sources are ordered newest
// first, so on equal keys the lowest index wins and the rest are skipped.
func merge(sources []iter.Seq[entry]) iter.Seq[entry] {
	return func(yield func(entry) bool) {
		type cursor struct {
			next func() (entry, bool)
			head entry
			ok   bool
		}
		cursors := make([]*cursor, len(sources))
		for i, s := range sources {
			next, stop := iter.Pull(s)
			defer stop()
			c := &cursor{next: next}
			c.head, c.ok = next()
			cursors[i] = c
		}
		for {
			var best *cursor
			for _, c := range cursors {
				if c.ok && (best == nil || c.head.key < best.head.key) {
					best = c
				}
			}
			if best == nil {
				return
			}
			e := best.head
			for _, c := range cursors {
				for c.ok && c.head.key == e.key {
					c.head, c.ok = c.next()
				}
			}
			if !yield(e) {
				return
			}
		}
	}
}

Each step picks the smallest key across all sources, keeps the entry from the newest one, and advances every source sitting on that key. That's how the older versions disappear. If the linear search for the smallest key looks lazy, table/merger.cc in LevelDB does the same thing, with a comment saying a heap might be better but there are few children to merge.

Scan is that merge with bounds, and compaction is that merge written to a new file:

// Scan calls fn for every live key in [from, to].
func (db *DB) Scan(from, to string, fn func(key, value string)) {
	sources := []iter.Seq[entry]{db.mem.scan(from)}
	for _, t := range db.tables {
		sources = append(sources, t.scan(from))
	}
	for e := range merge(sources) {
		if e.key > to {
			return
		}
		if !e.tombstone {
			fn(e.key, e.value)
		}
	}
}

// compact merges every table into one. There is nothing older than the
// result, so tombstones have done their job and are dropped.
func (db *DB) compact() error {
	sources := make([]iter.Seq[entry], len(db.tables))
	count := 0
	for i, t := range db.tables {
		sources[i] = t.scan("")
		count += t.count
	}
	live := func(yield func(entry) bool) {
		for e := range merge(sources) {
			if !e.tombstone && !yield(e) {
				return
			}
		}
	}
	t, err := db.newTable(live, count)
	if err != nil {
		return err
	}
	for _, old := range db.tables {
		old.f.Close()
		os.Remove(old.f.Name())
	}
	db.tables = []*table{t}
	return nil
}

Compare Scan with the B+tree one from the last article. There, one descent found the start and the leaves did the rest. Here every table contributes a cursor, and every key goes through the merge.

The comment in compact matters. A tombstone can only be dropped when nothing older could still hold the key. Our compaction merges everything, so that's always true. Real engines compact a few files at a time, so they have to check. LevelDB does it in DoCompactionWork with IsBaseLevelForKey, which confirms no deeper level overlaps the key before dropping the marker.

Using it:

db, _ := lsm.Open("data", lsm.Options{MemtableLimit: 1 << 20, MaxTables: 4, Filters: true})
db.Set("user:1", "ana")
db.Set("user:1", "ana maria")
db.Set("user:2", "bruno")
db.Set("user:3", "carla")
db.Delete("user:2")

v, ok, _ := db.Get("user:1")
fmt.Println(v, ok) // ana maria true

db.Scan("user:1", "user:9", func(k, v string) { fmt.Println(k, v) })
// user:1 ana maria
// user:3 carla

This passes a randomized test against a plain map, but it's still a toy. There's no log, no record of which files exist, and compaction blocks the caller.

What each piece does for reads

Write a million random updates over 100,000 keys, with 100-byte values and a 1 MB memtable, then count block reads per Get:

ConfigurationTablesOn diskWritten / user bytesBlocks per hitBlocks per miss
No compaction100107.7 MB1.09.7399.99
No compaction + Bloom100107.7 MB1.01.000.82
Compaction414.6 MB3.23.214.00
Compaction + Bloom414.6 MB3.20.940.02

Without compaction every byte is written once, the disk holds over nine times the live data, and a missing key reads a block from all 100 tables. The Bloom filter alone drops that to 0.82, which is the 1% false positive rate showing up across 100 tables. Compaction gets the space back and pays for it by writing everything 3.2 times. The hit rate falls under 1 at the end because some keys are still in the memtable.

Filters do so much here that it's surprising they're off by default. filter_policy is nullptr in both LevelDB's options.h and RocksDB's table.h, so if you're embedding either one, set it.

Our compaction has a problem those numbers hide, though. It rewrites the whole database every five flushes. That's cheap at 14 MB and hopeless at 1 TB, where every 5 MB of new data would set off a terabyte of rewriting. Real engines need a way to compact a small piece at a time.

What RocksDB keeps on disk

Before getting to that, let's look at a real one. Debian's rocksdb-tools package ships ldb and sst_dump, and they work like pageinspect did for PostgreSQL. All the output from here on is RocksDB 9.10.

Overwrite a key, delete it, and dump what's physically stored:

ldb --db=/tmp/demo --create_if_missing put user:1 ana
ldb --db=/tmp/demo put user:1 "ana maria"
ldb --db=/tmp/demo put user:2 bruno
ldb --db=/tmp/demo delete user:1
ldb --db=/tmp/demo idump
'user:1' seq:4, type:0 =>
'user:1' seq:2, type:1 => ana maria
'user:1' seq:1, type:1 => ana
'user:2' seq:3, type:1 => bruno
Internal keys in range: 4

ldb get user:1 answers Key not found, and yet all three versions are there. Each write gets a global sequence number, and the stored key is the user key plus that number plus a type, which is kTypeValue = 1 or kTypeDeletion = 0 in LevelDB's db/dbformat.h. Internal keys sort by user key ascending and sequence descending, so the newest version of a key always comes first. Our toy's "first hit wins" is the same rule, done with table order.

Sequence numbers also make snapshots nearly free: a reader pinned at seq:2 ignores anything higher and sees ana maria. We'll come back to this idea of old versions kept for readers when we get to MVCC.

After ldb --db=/tmp/demo compact:

'user:2' seq:0, type:1 => bruno
Internal keys in range: 1

The three user:1 entries are gone. The surviving row's sequence number was zeroed, because at the bottom level, with no snapshot that needs it, it has nothing left to order against. Zeros also compress well.

Now a real SSTable, with 100,000 keys of 13 bytes, 100-byte values, no compression, and a Bloom filter:

sst_dump --file=000008.sst --command=none --show_properties
# data blocks: 2858
# entries: 100000
raw key size: 2100000
raw value size: 10000000
data block size: 11372395
index block size (user-key? 1, delta-value? 1): 69341
filter block size: 125061

Raw keys average 21 bytes because the 13-byte key carries an 8-byte trailer with the sequence and type. The filter is 125,061 bytes, which is 10 bits for each of the 100,000 keys. The index for 11 MB of data is 69 KB.

Data blocks came out smaller than the raw keys and values, 11.4 MB against 12.1 MB, with compression off. That's prefix compression. Sorted neighbors like user:00001234 and user:00001235 share nearly everything, so table/block_builder.cc stores only the bytes that differ from the previous key, and every block_restart_interval keys (16 by default) writes a full key that binary search can land on. Sorted, immutable data is easy to pack tightly, and that's a real advantage over B-tree pages that have to keep gaps for future inserts.

The other files in the directory do the bookkeeping. CURRENT names the active MANIFEST-*, and the MANIFEST is a log of which SSTables exist and at which level. 000004.log is the log file for the current memtable. A compaction takes effect when it writes one MANIFEST record, which makes it atomic: a crash before that record leaves the old files in charge, and the new ones get deleted as garbage.

Levels: compacting a slice at a time

The fix for rewriting everything is to organize files into levels, each about ten times bigger than the one before. That's leveled compaction, and it's what doc/impl.md in LevelDB describes.

Flushed files land in L0, and since each one is a memtable's worth of whatever keys arrived, they all overlap. From L1 down, files in a level cover disjoint key ranges, so each level behaves like a single big sorted run cut into small files. A Get checks at most one file per level.

When a level gets too big, LevelDB picks one file from it and merges that file with the files it overlaps in the next level. Since the next level is ten times larger, that's around ten files, and the amount of work no longer depends on the size of the database. compact_pointer_ in version_set.cc remembers where the last compaction stopped for each level, so the next one continues from there and rotates through the key space.

LevelDB has one more trigger I like. Each file starts with an allowed_seeks budget, computed from its size, and a read that had to look in a file and then go on to another one spends from it. When a file runs out, it's compacted, on the reasoning spelled out in a comment in version_set.cc: past some number of wasted seeks, the compaction is cheaper than continuing to pay for them.

RocksDB keeps the same shape with different defaults: a 64 MB memtable and 256 MB for its base level. Since level_compaction_dynamic_level_bytes became the default, it also fills from the bottom up. Here's a database after 5 million random writes, with buffers shrunk to 4 MB so it stays small:

Level Files Size(MB)
--------------------
  0        1        1
  1        0        0
  2        0        0
  3        0        0
  4        0        0
  5        3       13
  6       34      108

The levels are sized backward from the data that actually exists, so L1 through L4 stay empty and most of the data sits in L6. In a leveled LSM about 90% of the data is in the last level, which also means about 90% of it has exactly one version, and that's what keeps the space overhead low.

ldb manifest_dump lists the files with their key ranges, and you can see the disjoint ranges on L6:

--- level 6 --- version# 1 ---
 578:4268762[0 .. 0]['user:00000000' seq:0, type:1 .. 'user:00037139' seq:0, type:1]
 579:3161650[0 .. 0]['user:00037140' seq:0, type:1 .. 'user:00064629' seq:0, type:1]
 284:3862545[0 .. 0]['user:00064630' seq:0, type:1 .. 'user:00101641' seq:0, type:1]

Write, read and space: pick two

Three numbers describe an LSM tree: write amplification (bytes written to disk per byte you wrote), read amplification (places a read has to look), and space amplification (disk used per byte of live data). Compaction strategies move cost between them, and none of them gets all three down at once.

Leveled compaction spends writes to save the other two. Every time data moves down a level it's merged with about ten times its size, so in the worst case each level costs around 10x. Universal compaction in RocksDB, known as size-tiered in Cassandra, goes the other way. It lets several sorted runs pile up and merges runs of similar size, so each byte is rewritten less often and more versions stay on disk.

Here's the same workload through both: 5 million random writes over 1 million keys, 100-byte values, 4 MB memtable, no compression, WAL off. That's 565 MB of user data, with roughly 113 MB of it live at the end.

LeveledUniversal
Flushed576 MB576 MB
Compaction writes1867 MB1606 MB
Write amplification4.323.86
Final size128 MB216 MB
Peak size249 MB282 MB

Universal wrote 11% less in total and ended up using 69% more disk. The write gap looks small because this database is tiny and leveled only used two levels. Overwrites helped too: with five versions per key, leveled compaction threw away 3.8 million entries along the way. A bigger database with mostly unique keys pays for more levels, and that's where the two strategies move apart.

The peak matters as much as the final size. A compaction needs its inputs and outputs on disk at the same time, so a big merge temporarily needs a lot of free space. Running an LSM at 90% disk usage is asking for a compaction that can't finish.

Deletes that make reads slower

A tombstone is a write, and it stays around until compaction carries it down to where the data it hides lives. Until then, every scan over that range has to step through it. This makes one pattern especially bad: using an LSM store as a queue, where you insert at the tail and delete from the head.

To measure it, insert a million jobs, delete the oldest 999,000 in key order, and ask for the first remaining job with SeekToFirst:

before deletes:         first=job:00000000   0.08 ms  skipped_tombstones=0
after deletes:          first=job:00999000 138.96 ms  skipped_tombstones=550719
after auto compaction:  first=job:00999000  79.53 ms  skipped_tombstones=326686
after manual compaction: first=job:00999000  0.02 ms  skipped_tombstones=0

The first key went from 0.08 ms to 139 ms, and the iterator stepped over 550,719 tombstones to find it, a count that comes from RocksDB's internal_delete_skipped_count. Some of the deletes had already met their values in a compaction, so it isn't the full 999,000. Automatic compaction finished and still left 326,686 of them, because nothing pushed those files to the bottom. Only a forced full compaction brought it back down.

Reads that only want the first item suffer most, because the live row is right there and all the markers sit in front of it. There are a few ways out. Remember the last consumed key and Seek past it, or set iterate_lower_bound, so the iterator never sees the dead range. Use DeleteRange to drop a whole range with one marker. Or use NewCompactOnDeletionCollectorFactory, which flags files with too many tombstones for early compaction.

Distributed systems add one more problem. Cassandra can't drop a tombstone as soon as compaction reaches the bottom, because a replica that was down might still have the value and bring it back during repair. So tombstones stay for gc_grace_seconds, ten days by default, and a table with heavy deletes spends those days scanning them.

Writes that stop

The sequential write path has a limit that doesn't show in a benchmark's first minute. Flushes create L0 files at whatever rate you write, and compaction has to clear them at the same rate. If it can't, L0 fills up, every read has to check more overlapping files, and the engine starts holding back the writers on purpose.

LevelDB's constants in db/dbformat.h make the policy clear: compaction starts at 4 L0 files (kL0_CompactionTrigger), writes slow down at 8 (kL0_SlowdownWritesTrigger) and stop at 12 (kL0_StopWritesTrigger). RocksDB uses 4, 20 and 36, and adds limits on pending compaction bytes and on unflushed memtables.

Here's RocksDB pushed on purpose, with 20 million random writes as fast as one thread can go, 4 MB memtables, the WAL off, and only 2 background jobs:

20000000 puts in 65.0s, 307827 puts/s, worst put 63.2 ms
Cumulative stall: 00:00:31.955 H:M:S, 49.2 percent
l0-file-count-limit-delays: 119, memtable-limit-stops: 29

Writers spent half the run stalled. There were 119 slowdowns from L0 and 29 full stops because the memtables couldn't flush. The average still looks excellent at 300,000 writes per second, but the worst single write took 63 ms, and more than 16,000 of them took over a millisecond.

That's the usual shape of LSM trouble in production. A sustained write rate has a ceiling set by compaction, not by the memtable, and a burst above it looks fine until the debt comes due. The first number to watch is pending compaction bytes (rocksdb.estimate-pending-compaction-bytes), and rocksdb.stats prints the stall counts shown above. Compaction also competes with your reads for disk bandwidth and evicts their blocks from the page cache, which is why tail latency moves even when nothing is stalled.

B-tree or LSM tree

A B-tree does its work during the write, and an LSM tree defers it to the background. Most of the differences follow from that.

Pick an LSM tree when writes dominate and keys arrive randomly: event ingestion, metrics, message logs, or anything where a B-tree's working set would no longer fit in memory. Random inserts that would dirty a page each become sequential writes, the files compress well, and there's no half-empty page problem. Facebook built MyRocks to shrink MySQL's storage footprint for this reason.

Stick with a B-tree when reads dominate, when you need predictable latency, or when range scans are central. A lookup costs the same every time, a range scan reads leaves in order instead of merging several sources, and there's no background debt that can stall writes at a bad moment. Deletes also take effect right away, without tombstones lingering in scans.

Neither is free on writes. An LSM tree rewrites each byte several times across its levels, and a B-tree rewrites a whole page for each small change. The difference is that the LSM tree does it in large sequential batches, and that's usually the better deal on hardware, and also on SSDs, where small random writes wear the drive faster.

Conclusion

An LSM tree buys sequential writes by accepting that one key can live in many files, then spends its whole life cleaning up after that decision. Bloom filters keep reads from visiting every file, and compaction keeps the file count and the disk usage down, at the price of rewriting data several times. When compaction falls behind, the writes stall.

Throughout this article the log file was the part we skipped, and it's what makes all of the above survive a crash. Next is the Write-Ahead Log: what a WAL record contains, what fsync actually promises, and how checkpoints and crash recovery work.