Storage Engines: B-Trees vs LSM-Trees

How databases actually lay data out on disk, and why that choice decides whether they're better at reads or writes.

What is it?

Under every database's query layer sits a storage engine: the code that decides how bytes are arranged on disk, how a key is found, and how data survives a crash. Two designs dominate:

- B-trees keep data in fixed-size pages arranged as a balanced tree and update pages in place. Reads are fast and predictable. This is the classic relational database design. - LSM-trees (log-structured merge-trees) never modify files in place. Writes go to memory, then are flushed as immutable sorted files that are merged in the background. Writes are fast and sequential; reads may have to check several files.

Both rely on a write-ahead log (WAL): before changing data structures, append the change to a sequential log and flush it to disk. After a crash, replaying the log restores everything that was acknowledged.

Choosing between them is mostly about three costs, the amplification factors: how many bytes are written to disk per byte the application writes (write amplification), how much work a read does (read amplification), and how much disk is used compared to the live data (space amplification). No engine minimizes all three.

Explain like I'm 10

A B-tree is a well-organized filing cabinet: to change a document you find its folder and edit it in place, so finding things is quick, but every edit means walking to the right drawer. An LSM-tree is an in-tray: you drop new notes on top instantly and once in a while sort the pile into the cabinet. Writing is effortless, but to find something you may have to check the tray and several sorted stacks.

Examples

A toy LSM-tree write and read path

class TinyLsm {
  private memtable = new Map<string, string | null>(); // null = tombstone
  private sstables: Map<string, string | null>[] = []; // newest first, immutable
  private readonly memtableLimit = 1_000;

  put(key: string, value: string | null): void {
    wal.append(key, value);            // 1. durable first (sequential write)
    this.memtable.set(key, value);     // 2. then in memory
    if (this.memtable.size >= this.memtableLimit) this.flush();
  }

  delete(key: string): void {
    this.put(key, null); // deletes are writes too: a tombstone
  }

  get(key: string): string | undefined {
    if (this.memtable.has(key)) return this.memtable.get(key) ?? undefined;
    for (const table of this.sstables) {           // newest to oldest
      // Real engines skip most tables via per-table Bloom filters.
      if (table.has(key)) return table.get(key) ?? undefined;
    }
    return undefined;
  }

  private flush(): void {
    const sorted = new Map([...this.memtable].sort(([a], [b]) => a.localeCompare(b)));
    this.sstables.unshift(sorted);     // written once, never modified
    this.memtable = new Map();
    wal.truncate();                    // flushed data no longer needs the log
  }
}

Real engines keep the memtable as a sorted structure (often a skip list), store SSTables on disk with a sparse index, and compact them in the background.

Where amplification comes from

B-tree, update one 100-byte row:
  WAL record (~100+ bytes) + rewrite the whole page (e.g. 8 KB in PostgreSQL,
  16 KB in InnoDB) when it's flushed
  → high write amplification for small random updates
  → reads: ~tree height page lookups (3–4 for huge tables, mostly cached)

LSM-tree, same update:
  WAL record + memtable, later written to an SSTable at flush,
  then rewritten again each time compaction merges it into a lower level
  → total write amplification depends on compaction strategy
  → reads: memtable + possibly one SSTable per level (Bloom filters help)
  → space: old versions and tombstones linger until compacted

Amplification numbers depend heavily on configuration and workload; benchmark your own access pattern rather than relying on rules of thumb.

How it works

Write-ahead log. Every change is appended to the WAL and fsynced before it's acknowledged. Sequential appends are cheap even on spinning disks. On restart, the engine replays the log from the last checkpoint. The WAL also feeds replication and CDC in many databases (PostgreSQL's WAL, MySQL's binlog is a separate logical log).

B-trees. - Data lives in fixed-size pages. Interior pages hold keys and pointers to child pages; leaf pages hold rows (or pointers to them). The tree stays balanced, so lookups touch O(log n) pages, typically 3–4 levels even for very large tables, with upper levels cached in memory. - Updates modify the leaf page in place. If a page is full it splits, and the split propagates upward as needed. - Page writes aren't atomic at the disk level, so engines use the WAL plus mechanisms like full-page writes (PostgreSQL) or a doublewrite buffer (InnoDB) to recover torn pages. - Pages gain free space as rows are deleted or moved, so B-trees carry some fragmentation.

LSM-trees. - Memtable: an in-memory sorted structure (e.g. a skip list) receiving writes after the WAL. - Flush: when the memtable fills, it's written to disk as an SSTable (sorted string table): an immutable file of sorted key-value pairs with a sparse index and usually a Bloom filter. - Reads: check the memtable, then SSTables from newest to oldest. Bloom filters let most SSTables be skipped for keys they don't contain. - Deletes write tombstones, which shadow older values until compaction drops both. - Compaction merges SSTables, keeping only the newest version of each key, to bound read cost and reclaim space: - Size-tiered (Cassandra's default): merge several similar-sized tables into a bigger one. Lower write amplification, but higher space amplification and temporary space spikes. - Leveled (LevelDB, RocksDB's default): levels of non-overlapping key ranges, each roughly 10x bigger than the last. Lower read and space amplification, higher write amplification.

The trade-off (the RUM conjecture). You can optimize two of Read, Update and Memory/space overhead, not all three. B-trees favour reads and point updates with predictable latency. LSM-trees favour write throughput and compression (immutable files compress well), at the cost of compaction I/O that can cause latency spikes if it falls behind.

Who uses what. - B-tree: PostgreSQL, MySQL InnoDB, SQL Server, Oracle, SQLite, MongoDB's WiredTiger (B-tree by default). - LSM: LevelDB, RocksDB, Cassandra, ScyllaDB, HBase, Bigtable, CockroachDB (Pebble), TiKV (RocksDB), MyRocks (MySQL on RocksDB).

B-tree (update in place)                LSM-tree (append, then merge)

         [ 30 | 60 ]                   write → WAL (append)
        /     |     \                        → memtable (sorted, in RAM)
  [10|20] [40|50] [70|80]                         │ full → flush
     leaf pages edited                            ▼
     in place, split when full          L0: [SST][SST][SST]   (may overlap)
                                                  │ compaction
                                        L1: [SST a–f][SST g–p][SST q–z]
                                                  │ compaction
                                        L2: [  ~10x larger, sorted runs  ]

  read: walk root → leaf               read: memtable → L0 → L1 → L2 …
        (3–4 pages)                          (Bloom filters skip most files)

Why does it exist?

Disks (and SSDs) are far faster at sequential I/O than small random writes, and memory is much faster than either. B-trees optimize for finding any key in a few page reads; LSM-trees turn random writes into sequential ones to sustain very high ingest. Knowing which engine sits under a database explains its strengths, its tuning knobs and its failure modes, like compaction storms or page bloat.

When to use it

- B-tree engines for read-heavy or mixed OLTP workloads, range scans with predictable latency, and transactional systems with lots of in-place updates. - LSM engines for write-heavy workloads: event logs, time series, metrics, messaging, IoT ingest, large key-value stores, and when compression and SSD wear matter. - Use the amplification lens when tuning: compaction strategy, page or block size, Bloom filter bits per key, cache size.

When not to use it

- Don't pick an LSM store for read-latency-critical point lookups on data that's updated constantly unless you've sized compaction and caches; read amplification and compaction stalls show up at p99. - Don't pick a B-tree store for firehose ingest of append-only data; random page writes and page splits limit throughput. - For analytical scans over a few columns of huge tables, neither row-oriented engine is ideal: use a columnar store.

Common mistakes

  • Assuming LSM databases are 'faster' in general. They're faster at writes; reads and space use depend on compaction keeping up.

  • Deleting lots of data in an LSM store and expecting space back immediately. Tombstones take space and slow reads until compaction (and, in Cassandra, gc_grace_seconds) removes them.

  • Ignoring write amplification on SSDs, which drives throughput limits and device wear for both B-trees (full-page writes) and leveled LSM compaction.

  • Disabling fsync on the WAL for speed without realizing acknowledged writes can now be lost on power failure.

  • Using random UUIDv4 primary keys in a clustered B-tree index, spreading inserts across all pages and causing page splits and cache misses; time-ordered ids insert near the right edge.

Practice exercises

  1. Easy:

    Explain what a write-ahead log is and why a database writes to it before changing its data files.

  2. Medium:

    Trace a read for a key that was written, then updated, then deleted in an LSM-tree, where each change landed in a different SSTable. What does the read return and why? When does the data finally leave the disk?

  3. Hard:

    You're storing 200k writes/s of sensor readings with rare reads by (sensor, time range). Compare a B-tree store and an LSM store with size-tiered vs leveled compaction on write, read and space amplification, and recommend one with tuning choices.

Interview questions

What is a write-ahead log?

An append-only file where every change is recorded and flushed before it's applied to the main data structures, so the database can replay it after a crash to recover acknowledged writes.

How does a B-tree handle an insert into a full page?

It splits the page into two half-full pages and inserts a new separator key into the parent, which may itself split, propagating up to the root and occasionally increasing the tree's height.

Describe the LSM-tree write path.

Append to the WAL, insert into the in-memory sorted memtable, and acknowledge. When the memtable fills, it's flushed as an immutable sorted SSTable; background compaction later merges SSTables.

How does an LSM-tree serve a read efficiently?

It checks the memtable, then SSTables from newest to oldest, stopping at the first hit. Per-SSTable Bloom filters skip files that definitely don't have the key, and sparse indexes find the right block within a file.

Define write, read and space amplification.

Write amplification: bytes written to storage per byte written by the application. Read amplification: storage reads per logical read. Space amplification: disk space used relative to the size of the live data.

Size-tiered vs leveled compaction?

Size-tiered merges similarly sized SSTables: low write amplification, but high space amplification and more files to check on reads. Leveled keeps non-overlapping files per level with ~10x growth: lower read and space amplification, higher write amplification.

How are deletes handled in an LSM-tree?

By writing a tombstone that shadows older versions. Compaction eventually removes the tombstone and the data it covers, once it's safe (e.g. after all replicas have seen it, in Cassandra's case gc_grace_seconds).

Name databases using each engine type.

B-tree: PostgreSQL, MySQL InnoDB, SQL Server, Oracle, SQLite, MongoDB WiredTiger. LSM: RocksDB, LevelDB, Cassandra, ScyllaDB, HBase, Bigtable, CockroachDB's Pebble, TiKV.

Why do B-trees tend to have more predictable read latency than LSM-trees?

A key lives in exactly one place reached by a fixed number of page reads. In an LSM-tree, a read may check several levels, and background compaction competes for I/O, which shows up as tail-latency spikes.

Your Cassandra cluster's read latency degrades over weeks on a delete-heavy table. What's happening and what do you do?

Tombstones are accumulating, so reads scan many shadowed entries, and possibly compaction is falling behind. Inspect SSTable counts and tombstone warnings; consider a data model that avoids range deletes (e.g. time-bucketed partitions with TTLs and time-window compaction), tune gc_grace_seconds alongside repair schedules, and ensure compaction throughput is sufficient.