Storage engines: LSM-tree vs B-tree

In one sentence

B-trees update pages in place for cheap reads; LSM-trees append and compact later for cheap writes, so choose by the amplification your workload can afford: write, read or space.

Writes are cheap sequential appends; compaction rewrites data level by level, and Bloom filters keep point reads from touching every file.

How it works

  • B-trees update fixed pages in place: cheap point and range reads, but small changes rewrite whole pages.
  • LSM-trees buffer writes in a memtable, flush immutable SSTables and merge them later by compaction.
  • Compare engines by write, read and space amplification; no design minimizes all three.
  • Leveled compaction keeps reads and space low (~1.1×); size-tiered cuts write amp but can need 2× disk.
  • When compaction falls behind, reads slow and writes stall: alert on the compaction backlog.

Check yourself

Answer to mark it learned; your answers aren't scored.

A RocksDB-backed service runs a bulk backfill. Write latency climbs, then writes stop for seconds at a time. Metrics show the L0 file count and pending compaction bytes rising. What is happening?

Go deeper

Full explanation

Both engines first append each write to a WAL for durability; they differ in where the data goes next (indexing basics: Database indexes: B-tree vs LSM).

  • B-tree (InnoDB, WiredTiger, Postgres indexes): data lives in fixed-size pages updated in place. A point read walks ~3–4 levels, mostly cached. Changing a 100-byte row dirties a whole 8–16 KB page, and half-full pages waste space.
  • LSM-tree (RocksDB, Cassandra, ScyllaDB, Bigtable): writes land in an in-memory memtable, flushed as immutable sorted SSTables. Compaction later merges files, keeps the newest version and drops tombstones.

Judge them by three amplifications: write (bytes written to disk ÷ bytes the app wrote), read (disk reads per query) and space (disk size ÷ live data).

Leveled compaction (RocksDB's default) keeps one sorted run per level, each ~10× larger: low read and space amp (~1.1×), but write amp is often above 10. Size-tiered (universal) merges similar-size files: lower write amp, more runs to read, and up to 2× disk during a full compaction.

Compaction is debt: when it falls behind, reads slow down and the engine stalls writes.

Code A toy LSM: memtable, flush, newest-first reads, compaction
pythonA toy LSM: memtable, flush, newest-first reads, compaction
import bisect

TOMBSTONE = object()  # a delete is a write of this marker

class TinyLSM:  # toy: no WAL, no Bloom filters, one flat list of runs
    def __init__(self, memtable_limit: int = 4):
        self.memtable, self.runs, self.limit = {}, [], memtable_limit  # runs: oldest first

    def put(self, key, value):
        self.memtable[key] = value  # real engines append to a WAL first
        if len(self.memtable) >= self.limit:
            self.runs.append(sorted(self.memtable.items()))  # flush: one sequential write
            self.memtable = {}

    def delete(self, key):
        self.put(key, TOMBSTONE)

    def get(self, key):
        if key in self.memtable:
            v = self.memtable[key]
            return None if v is TOMBSTONE else v
        for run in reversed(self.runs):  # newest first; each probe is read amplification
            i = bisect.bisect_left(run, (key,))
            if i < len(run) and run[i][0] == key:
                v = run[i][1]
                return None if v is TOMBSTONE else v
        return None

    def compact(self):
        merged = {}
        for run in self.runs:  # oldest first, so newer values overwrite older ones
            merged.update(run)
        # Dropping tombstones is safe only because every run is merged
        self.runs = [sorted((k, v) for k, v in merged.items() if v is not TOMBSTONE)]
Real example

Facebook moved its main MySQL user database (UDB) from compressed InnoDB to MyRocks, a RocksDB-based engine, and reported ~50% less storage. InnoDB's fixed compressed page sizes and half-full leaf pages wasted space; LSM files are dense and compress well. The flip side: assume a store taking 50 MB/s of user writes under leveled compaction with write amp ~20. The SSDs absorb ~1 GB/s of writes, and that, not the app's 50 MB/s, sets the disk budget and wear.

Trade-offs +3 · −3

+ You gain

  • LSM: sequential writes and dense, compressible files: high ingest, less storage.
  • B-tree: one place per key, so point and range reads are predictable and cheap.
  • Tunable: compaction style and level sizes trade write, read and space amp per workload.

− You pay

  • LSM: compaction competes with queries for disk and causes latency spikes.
  • LSM: misses and range scans may touch several runs; deletes leave tombstones until compaction.
  • B-tree: small random writes rewrite whole pages, and fragmentation wastes space.

Use it when

LSM for write-heavy, append-mostly data (events, logs, time series, messages) or when storage cost dominates. B-tree for read-heavy OLTP with range scans and steady latency.

Avoid it when

Skip an LSM for a small, read-mostly dataset that fits in RAM; skip a B-tree for sustained random-write ingest beyond what your disks absorb.

Numbers to know 5
  • RocksDB tuning guide, 500 GB with 10× levels: write amp ~33, space amp ~1.14.
  • Leveled compaction keeps ~90% of data in the last level, so space amp stays near 1.1×.
  • Universal (size-tiered) compaction can temporarily double disk usage during a full compaction.
  • B-tree pages: 8 KB in Postgres, 16 KB in InnoDB, written whole even for a 100-byte change.
  • Facebook UDB on MyRocks: ~50% less storage than compressed InnoDB (2016).
Common pitfalls 4
  • Benchmarking an LSM on a fresh database: no compaction debt yet, so write numbers look far too good.
  • Filling disks past ~50% with size-tiered compaction: a full compaction needs room for a second copy.
  • Ignoring compaction backlog: L0 files pile up until RocksDB slows writes, then stops them.
  • Picking an LSM for a read-heavy, range-scan workload: you pay read amplification for ingest you don't need.
Interview questions 2

Answer out loud first, then reveal.

A KV store must absorb 500k small writes/s. LSM or B-tree, and how do you tune it?Show answer

LSM: it turns random writes into sequential flushes, so the same disks sustain far more ingest. Then I tune by amplification. If reads are rare or mostly recent, size-tiered keeps write amp low; if point reads matter, leveled plus Bloom filters keeps read and space amp low, at write amp often above 10. I size disks for that write rate plus compaction headroom, and alert on pending compaction bytes before stalls hit.

Your Cassandra cluster's read p99 spikes every afternoon. What do you check?Show answer

Compaction first. Afternoon peaks often mean writes outrun compaction: SSTables per read climb, so each read touches more files, and compaction I/O competes with queries. I'd check pending compactions, SSTables per read and tombstone warnings. Fixes: throttle or reschedule heavy compactions, move read-heavy tables to leveled compaction, fix delete patterns that leave tombstones, and add disk bandwidth if the backlog never drains.