DEV Community

Cover image for B-Tree vs LSM-Tree: Two Ways to Store Data
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

B-Tree vs LSM-Tree: Two Ways to Store Data

Under every database there is a storage engine: the part that decides how keys and values are laid out on disk. Two designs dominate. B-trees power PostgreSQL, MySQL's InnoDB, SQLite and most relational databases. Log-structured merge trees (LSM-trees) power RocksDB, LevelDB, Cassandra, ScyllaDB and the storage layers of many newer distributed databases.

Both store sorted key-value data. Both support point lookups and range scans. They differ in one basic choice: whether to change data where it lives, or to always write somewhere new and clean up later. That choice shapes everything else.

The B-tree: update in place

A B-tree keeps keys sorted in fixed-size pages arranged as a shallow, balanced tree. Internal pages hold separator keys that route a search; leaf pages hold the actual entries.

To write a key, the engine:

  1. Walks down from the root to the leaf where the key belongs.
  2. Changes that leaf page in memory (inserting, updating or deleting the entry).
  3. Eventually writes the whole page back to its place on disk. If the page was full, it splits into two and the parent gets a new separator.

For crash safety, the change is first recorded in a write-ahead log (WAL), so the modified page can be written later.

Reads are simple and predictable: a lookup is a walk of three or four pages from root to leaf, and there is exactly one place where each key can be.

The cost is on the write side. Changing a 100-byte row means eventually rewriting a whole page (often 8 or 16 KB), plus the WAL record. Writes land at random places on disk, wherever the right leaf happens to be. And pages are often not full after splits, which wastes some space.

The LSM-tree: append, then merge

An LSM-tree never modifies data on disk. It works in layers:

  1. Write to the log and the memtable. A new write is appended to a WAL for durability, then inserted into an in-memory sorted structure called the memtable (often a skip list).
  2. Flush to an SSTable. When the memtable reaches a size limit, it is written to disk as one sorted, immutable file called an SSTable (sorted string table). This is a single sequential write.
  3. Compact in the background. Over time, many SSTables pile up. A background process called compaction merges them, keeping only the newest version of each key and dropping deleted ones, and writes new, larger sorted files.

Updates and deletes are just new writes. An update writes the key again with a newer value. A delete writes a marker called a tombstone. The old values stay on disk until compaction removes them.

A read has more work to do, because a key might be in several places:

  1. Check the memtable.
  2. Check the SSTables, from newest to oldest, and stop at the first match.

To avoid opening every file, each SSTable keeps a sparse index of its keys and usually a Bloom filter, a small structure that can say "this key is definitely not in this file" without touching the disk. Most files are skipped that way.

A concrete example

Suppose you update the balance of user 42 five times in an hour.

In a B-tree, the engine finds the leaf for key 42 each time and modifies the same entry. On disk, there is one copy, and that page is rewritten (sooner or later) after the changes.

In an LSM-tree, each update is a new entry in the memtable. If flushes happen in between, you may have several SSTables on disk, each holding a different version of key 42. A read finds the newest one first. Later, compaction merges the files and only the last balance survives.

The three amplifications

Storage engineers compare these designs with three ratios:

  • Write amplification: bytes written to disk per byte of data you wrote. B-trees pay by rewriting whole pages. LSM-trees pay by rewriting data again at each compaction. Which is worse depends on the workload and settings, but LSM-trees turn random writes into sequential ones, which disks and SSDs handle well.
  • Read amplification: how much work a read does. B-trees have one location per key. LSM-trees may check the memtable and several files; Bloom filters and caching keep this low for point lookups, but range scans must merge results from several files.
  • Space amplification: extra disk used. B-trees leave free space in pages. LSM-trees hold obsolete versions and tombstones until compaction, but files are written densely and compress well.

You cannot minimize all three at once. Compaction strategies (leveled versus size-tiered, for example) move the balance between them.

Trade-offs side by side

B-tree LSM-tree
Write path modify page in place append to memtable, flush sorted file
Write throughput good usually higher, sequential I/O
Point reads fast and predictable fast with Bloom filters, more variable
Range scans very good, sorted leaves good, merges several files
Background work vacuum or page cleanup compaction, can compete with traffic
Typical users PostgreSQL, InnoDB, SQLite RocksDB, Cassandra, ScyllaDB

Common mistakes

  • Assuming LSM means "faster". It usually favours writes. Read-heavy workloads with lots of range scans often do well on a B-tree.
  • Ignoring compaction. In an LSM-tree, compaction uses disk bandwidth and CPU. If writes arrive faster than compaction can keep up, files pile up, reads slow down and some engines throttle writes.
  • Ignoring tombstones. Deleting many keys in an LSM-tree does not free space right away, and scans can slow down while they skip over tombstones.
  • Forgetting the B-tree's own maintenance. B-trees also need care: index bloat and, in PostgreSQL, vacuum to reclaim dead row versions.

When each one fits

Pick (or prefer a database built on) a B-tree when reads dominate, when you need predictable latency for lookups and range scans, and for general transactional workloads. That is why most relational databases use it.

Pick an LSM-tree when writes dominate: event logs, metrics, time series, messaging, high-volume ingestion, and key-value workloads where most reads hit recent data. It is also a good fit for SSDs, where sequential writes reduce wear.

Some systems let you choose. MySQL can use MyRocks, an LSM engine built on RocksDB, as an alternative to InnoDB, and many distributed SQL databases put an LSM engine under a SQL layer.

In short

  • B-trees update pages in place: one home per key, predictable reads, random writes.
  • LSM-trees append to memory, flush sorted immutable files and merge them in the background: fast writes, reads that check several places.
  • Bloom filters and compaction are what make LSM reads and disk usage acceptable.
  • Read-heavy and transactional: B-tree. Write-heavy ingestion: LSM-tree.

Originally published at abdeldjalilchougui.biz.

Top comments (0)