Storage Engines: B-trees vs LSM Trees, WAL and MVCC


System Design Phase 5: Database Internals & Modeling
Core Lesson 18 of 86 18 min read Updated Nov 30, 2026

An IoT team moves sensor ingestion from Postgres to Cassandra because Postgres is “too slow for writes”. The new cluster swallows 400,000 writes per second without complaint. Three months later, the dashboard that reads the last hour of data for one device has a p99 of 900 ms, disk usage is twice the raw data size, and every afternoon the nodes spend 40% of their I/O on something called compaction.

Nothing is broken. The team traded one set of costs for another without knowing the price list. Postgres pays at write time: it updates pages in place, so every write is a random I/O into a tree that stays tidy for readers. Cassandra pays later: it appends everything sequentially and cleans up in the background, so writes are cheap and reads, disk space and background I/O carry the bill.

That price list is the storage engine. Before you can choose between “SQL and NoSQL”, before indexes and isolation levels make sense, you need to know what happens to a row between INSERT and the disk.

What a storage engine is

A storage engine is the part of a database that turns logical operations (put this key, read that range) into bytes on disk and back. It decides the on-disk layout, how writes become durable, how a crash is repaired, and how concurrent readers see a consistent version of the data.

Almost every OLTP engine in production is one of two families:

  • B-tree engines (Postgres, MySQL InnoDB, SQLite, MongoDB’s WiredTiger by default) keep data in fixed-size pages arranged as a balanced tree and update those pages in place.
  • Log-structured merge (LSM) engines (RocksDB, Cassandra, ScyllaDB, Pebble in CockroachDB, TiKV, YugabyteDB’s DocDB) buffer writes in memory, flush them as immutable sorted files, and merge those files in the background.

Both families share two building blocks: pages and a write-ahead log.

How it works

Pages: the unit of I/O

Disks and SSDs do not read single bytes. The engine reads and writes whole pages: 8 KB in Postgres, 16 KB by default in InnoDB. A page holds a header, an array of pointers to records, and the records themselves. Everything the engine does is counted in pages, because a page that is not in memory costs a storage read.

The gap between memory and storage is why engines are designed the way they are. Try the widget: compare a main memory reference with an SSD random read, then with a disk seek.

Latency numbers, to scale

Tap a row to compare everything against it, or switch on human scale where 1 ns lasts 1 second.

Order of magnitude figures for typical 2026 server hardware and cloud networks (log scale). Exact values vary with CPU, drive model, distance and load; the ratios are what matter.

A main memory read is about 100 ns and an NVMe random read is on the order of 100 microseconds, roughly 1,000 times slower. A design that saves one page read per query saves more than any amount of CPU tuning.

The write-ahead log and crash recovery

If the engine updated pages in memory and wrote them to disk whenever convenient, a crash would lose committed data or leave half-written pages. The fix is the write-ahead log (WAL, called the redo log in InnoDB and the commit log in Cassandra):

  1. Append a record describing the change to the WAL.
  2. On commit, fsync the WAL up to that record. Now the change is durable.
  3. Modify the page in the buffer pool and mark it dirty.
  4. Flush dirty pages lazily. A periodic checkpoint guarantees that every change before a certain WAL position is in the data files.

On restart, the engine replays the WAL from the last checkpoint and re-applies every change. The WAL is sequential, so commit costs one sequential append plus an fsync, not a random page write. Engines batch many transactions into one fsync (group commit), which is how a database commits tens of thousands of transactions per second on a disk that can only fsync a few thousand times per second.

Two details matter in interviews. First, a page write can be torn by a crash halfway through an 8 KB write. Postgres defends against this by logging a full page image the first time a page changes after a checkpoint (full_page_writes), and InnoDB writes pages through a doublewrite buffer. Second, the WAL is also how replicas stay in sync: physical replication ships WAL records to followers, covered in replication strategies.

sequenceDiagram
participant C as Client
participant E as Engine
participant W as WAL on disk
participant B as Buffer pool
participant D as Data files
C->>E: UPDATE row
E->>W: append redo record
E->>B: modify page in memory, mark dirty
C->>E: COMMIT
E->>W: fsync (group commit)
E-->>C: OK, durable
Note over B,D: later, background writer or checkpoint
B->>D: flush dirty page
Note over E,W: after a crash, replay WAL from last checkpoint

B+trees: sorted pages, updated in place

Databases use the B+tree variant: internal pages hold only separator keys and child pointers, and all values (or row pointers) live in the leaf pages, which are linked left to right so range scans walk sideways without going back up.

A lookup starts at the root, binary-searches the keys in the page to pick a child, and repeats until it reaches a leaf. An insert finds the right leaf and writes into it. If the leaf is full, it splits into two half-full pages and pushes a new separator key into the parent, which can cascade up to the root. The tree stays balanced: every leaf is at the same depth.

The key number is fanout, the number of children per internal page. Because a page is 8 or 16 KB and a key plus pointer is 10 to 40 bytes, fanout is in the hundreds. Depth grows with the logarithm of the row count in base “hundreds”, which is why a B+tree over billions of rows is still only 4 or 5 levels deep.

flowchart TB
R["Root page<br/>~400 separator keys"]
I1["Internal page<br/>~400 keys"]
I2["Internal page<br/>~400 keys"]
L1["Leaf page<br/>~367 keys + row pointers"]
L2["Leaf page"]
L3["Leaf page"]
L4["Leaf page"]
R --> I1
R --> I2
I1 --> L1
I1 --> L2
I2 --> L3
I2 --> L4
L1 -->|"next leaf"| L2
L2 -->|"next leaf"| L3
L3 -->|"next leaf"| L4
style R fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style I1 fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style I2 fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style L1 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style L2 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style L3 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style L4 fill:#E1F5EE,stroke:#0F6E56,color:#085041

How indexes are built on top of this structure, including composite and covering indexes, is the next article in this phase.

LSM trees: append, then merge

An LSM engine never updates data in place. The write path:

  1. Append the write to the WAL (commit log) for durability.
  2. Insert it into the memtable, a sorted in-memory structure (RocksDB uses a skiplist, 64 MB by default).
  3. When the memtable is full, freeze it and flush it to disk as an SSTable: an immutable file of sorted key-value pairs with a sparse index and a Bloom filter.
  4. In the background, compaction merges SSTables, keeps the newest version of each key, and drops deleted keys and overwritten values.

Every disk write is sequential and large. There is no read-before-write and no page split. That is the whole appeal.

The read path pays for it. A point read checks the memtable, then any frozen memtables, then the SSTables from newest to oldest until it finds the key. Deletes are writes too: a tombstone marker that hides older values until compaction removes both.

flowchart LR
W["Write"] --> WAL["WAL<br/>sequential append"]
W --> M["Memtable<br/>sorted, in RAM"]
M -->|"flush when full"| L0["L0 SSTables<br/>may overlap"]
L0 -->|"compaction"| L1["L1<br/>non-overlapping"]
L1 -->|"compaction"| L2["L2<br/>10x larger"]
L2 -->|"compaction"| L3["L3<br/>10x larger"]
RD["Read"] -.->|"1. check"| M
RD -.->|"2. Bloom filter per file"| L0
RD -.->|"3. one file per level"| L1
style M fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style WAL fill:#F1EFE8,stroke:#888780,color:#444441
style L0 fill:#FAEEDA,stroke:#854F0B,color:#633806
style L1 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style L2 fill:#E1F5EE,stroke:#0F6E56,color:#085041
style L3 fill:#E1F5EE,stroke:#0F6E56,color:#085041

Compaction: leveled vs size-tiered

Compaction strategy decides where an LSM engine sits on the cost curve.

Size-tiered compaction waits until there are several SSTables of similar size (four by default in Cassandra) and merges them into one bigger file. Each byte is rewritten only a few times, so write amplification is low. But a key can live in many overlapping files, so reads touch more files, and a big merge temporarily needs room for both the inputs and the output. The classic Cassandra advice to keep about half the disk free comes from this.

Leveled compaction (the RocksDB default, and Cassandra’s LCS) organises files into levels. Level 1 has a target size (256 MB by default in RocksDB) and each following level is 10 times larger. Within a level, files do not overlap, so a read touches at most one file per level. To keep that invariant, each file pushed down is merged with the roughly 10 overlapping files below it, so write amplification is much higher. Space amplification is low, about 1.1x, because about 90% of the data sits in the last level and is already deduplicated.

Cassandra 5.0 added the Unified Compaction Strategy, which can be tuned anywhere between tiered and leveled behaviour. Time-window compaction, which groups SSTables by time bucket so whole files expire together, is the usual choice for TTL’d time-series data (see time-series databases).

Bloom filters keep LSM reads cheap

Without help, a read for a missing key would open every SSTable. Each SSTable therefore carries a Bloom filter, a compact bit array that answers “definitely not here” or “maybe here”. A “no” skips the file without any I/O. The data structure itself is covered in Bloom filters, HyperLogLog and friends; here, what matters is the budget.

Read, write and space amplification

Every engine is a compromise between three amplification factors. You can make two of them good, never all three.

  • Write amplification: bytes written to storage per byte the application wrote.
  • Read amplification: storage reads per logical read.
  • Space amplification: bytes on disk per byte of live data.
Engine Write amp Read amp (point) Space amp
B+tree, in place High per small write: one 100-byte update eventually rewrites an 8 KB page, plus WAL and full page images Low: 1 to 2 I/Os when internal pages are cached Medium: pages 50 to 90% full after splits, plus MVCC bloat
LSM, leveled High: commonly 10x to 30x from repeated merges Low to medium: one file per level, filtered by Bloom Low: about 1.1x
LSM, size-tiered Low: a few times Medium to high: many overlapping files High: up to 2x during big merges

The B-tree’s write cost is random I/O into the middle of a file. The LSM’s write cost is sequential, in large batches, and deferred. On SSDs that matters less for latency than it once did, but it still matters for throughput, flash wear and how predictable your p99 is.

MVCC: how readers avoid blocking writers

Both families use multi-version concurrency control (MVCC): instead of locking a row while someone reads it, the engine keeps old versions so each transaction reads from a consistent snapshot. Where those old versions live differs sharply, and it explains a lot of operational behaviour.

Postgres keeps versions in the heap. An UPDATE writes a complete new tuple and marks the old one with the deleting transaction’s ID (xmax); the new one carries the creating ID (xmin). Each reader checks those IDs against its snapshot to decide which version it can see. Old versions stay in the table until VACUUM (usually autovacuum) removes those no transaction can still see. Two consequences: a long-running transaction holds back cleanup for the whole database, so tables and indexes bloat, and because transaction IDs are 32 bits, vacuum must also freeze old rows to prevent wraparound.

InnoDB keeps versions in undo logs. An UPDATE changes the row in place in the clustered index and writes the previous values to an undo log, linked from the row by a rollback pointer. A reader with an older snapshot follows that chain backwards to rebuild the version it needs. A purge thread discards undo records once no snapshot needs them. The failure mode is the same idea in a different place: a transaction left open for hours makes the undo history (history list length) grow and old-snapshot reads slow down as chains get longer.

LSM engines keep versions as sequence numbers. RocksDB tags each write with a sequence number. A snapshot is just a sequence number, and compaction keeps any old version that an open snapshot still needs.

What these snapshots guarantee, and what anomalies they still allow, is the subject of transactions and isolation levels.

Where it breaks

Random primary keys hurt B-trees. With random UUIDv4 keys, each insert lands on a random leaf. The working set becomes the whole index instead of the rightmost few pages, the buffer pool hit rate collapses once the index outgrows memory, and splits leave pages half full. Time-ordered keys fix this; see distributed ID generation.

Compaction debt hurts LSMs. If writes arrive faster than compaction can merge, L0 files pile up, every read checks more files, and RocksDB eventually slows or stalls writes on purpose once the L0 file count crosses a threshold. This is the afternoon latency spike from the opening scenario. The fix is capacity for compaction (I/O headroom, more compaction threads), not just more write throughput.

Tombstones are writes that make reads slower. In Cassandra a delete writes a tombstone that must survive at least gc_grace_seconds (10 days by default) so repairs do not resurrect the data. A queue-like table where you insert and delete constantly forces range reads to step over thousands of tombstones. Cassandra warns at 1,000 tombstones scanned per query and fails the query at 100,000 by default.

Vacuum debt hurts Postgres. An idle-in-transaction session left open by a buggy connection pool can block cleanup for hours. Table bloat, slower index scans and, in the worst case, a forced anti-wraparound vacuum follow. Set idle_in_transaction_session_timeout and alert on the age of the oldest transaction.

“LSM is for writes, B-tree is for reads” is too simple. A B-tree with a working set in memory handles very high write rates, and a leveled LSM with Bloom filters serves point reads well. The real question is what your write pattern does to the amplification factor you can least afford.

Real-world systems

System Engine Notes
PostgreSQL Heap files plus B-tree indexes MVCC versions in the heap, cleaned by vacuum. Indexes point to heap tuples.
MySQL InnoDB Clustered B+tree Rows stored in primary key order. Secondary indexes store the primary key. MVCC via undo logs.
SQLite B-tree Single file, WAL mode for concurrent readers.
MongoDB WiredTiger, B-tree by default Document-level concurrency, compression.
RocksDB LSM, leveled by default Embedded library from Meta, the base of many engines. MyRocks puts MySQL on top of it.
Apache Cassandra LSM Size-tiered, leveled, time-window and, since 5.0, unified compaction.
ScyllaDB LSM C++ rewrite compatible with Cassandra’s protocol, shard-per-core design.
TiKV (TiDB) RocksDB under Raft Each Raft group’s data stored in RocksDB.
CockroachDB Pebble Go LSM engine inspired by RocksDB, replaced RocksDB in 2020.
YugabyteDB DocDB, a RocksDB fork Per-tablet LSM under Raft.

Notice that every distributed SQL database in the list uses an LSM. Replicated logs produce a steady stream of sequential writes, and LSMs ingest that stream cheaply; range-partitioned keys keep scans efficient.

How to apply it

Start from the workload, then check which amplification factor the workload punishes.

If your workload is Lean towards Why
Mixed OLTP, many secondary indexes, ad hoc queries B-tree (Postgres, InnoDB) Predictable read latency, mature planners, cheap range scans
Very high ingest, append-mostly, point reads by key LSM (Cassandra, ScyllaDB, RocksDB) Sequential writes, no read-before-write
Time-series with TTL expiry LSM with time-window compaction Whole files drop at once, no per-row deletes
Read-heavy, latency-critical, data fits in RAM Either; B-tree is simpler Amplification matters less when every page is cached
Delete-heavy or queue-like Avoid LSM tombstone patterns; use a queue Tombstones slow every subsequent scan

A quick checklist before you commit to an engine:

  • What is the write rate, and what is the ratio of inserts to updates to deletes?
  • Are reads point lookups by key, short ranges, or large scans?
  • What is the working set, and does it fit in memory?
  • How much disk headroom can you keep for compaction or vacuum?
  • Are primary keys sequential or random?

Interview questions

1. Why can an LSM engine accept writes faster than a B-tree engine on the same hardware?

An LSM turns every write into a sequential append to the WAL plus an in-memory insert into the memtable. Data reaches disk in large sorted batches when the memtable flushes, and there is no need to read the existing page first. A B-tree must find the target leaf, which may need a random read if the page is not cached, modify it and eventually write the whole page back, and occasionally split pages. The LSM does not avoid the work, it defers and batches it into compaction, so total bytes written can be higher (leveled write amplification of 10x to 30x) while the foreground path stays fast.

2. A RocksDB-backed service has fine p50 but p99 read latency climbs every afternoon at peak write load. What is likely happening and what do you do?

Compaction is falling behind. When writes outpace compaction, L0 files accumulate, and because L0 files overlap, each point read must check all of them, raising read amplification. If it gets worse, RocksDB throttles or stalls writes. Confirm with the engine’s L0 file count, pending compaction bytes and stall counters. Fixes: give compaction more I/O and threads, increase the memtable size so flushes are larger and fewer, check that Bloom filters are enabled for every level, and if the data is time-series with TTL, switch to a compaction style that drops whole files. Adding nodes only helps if it reduces per-node write rate.

3. Why does Postgres need VACUUM while InnoDB does not have the same problem?

Postgres writes every new row version into the heap next to the old one, so dead versions accumulate in the table and indexes until vacuum reclaims them. Vacuum also freezes old transaction IDs to prevent 32-bit wraparound. InnoDB updates rows in place and writes old versions to separate undo logs, which a purge thread trims once no snapshot needs them. InnoDB still has an equivalent failure: a long-running transaction makes the undo history grow. Both engines suffer from long transactions; they just accumulate the debt in different places.

✅ Key takeaways

  • Every engine writes a WAL first and fsyncs it on commit; data pages are flushed later and the WAL is replayed after a crash.
  • B+trees update pages in place. Fanout in the hundreds keeps depth at 3 to 4 levels for tens of millions of rows, and the upper levels always fit in memory.
  • LSM trees append to a memtable, flush immutable SSTables, and compact in the background. Leveled compaction trades write amplification for low space and read amplification; size-tiered does the opposite.
  • Bloom filters at about 10 bits per key give about 1% false positives and make LSM point reads cheap, but do nothing for range scans.
  • MVCC keeps old versions in the heap (Postgres, cleaned by vacuum) or in undo logs (InnoDB, cleaned by purge). Long transactions hurt both.
  • Choose an engine by asking which of write, read and space amplification your workload can least afford.

🧠 Check your understanding

0 / 4
  1. 1A Postgres B-tree index on a bigint column covers 50 million rows. Roughly how many levels does it have?

  2. 2Which change most directly reduces write amplification in a RocksDB or Cassandra table?

  3. 3A Postgres database shows growing table bloat even though autovacuum runs constantly. What is the most likely cause?

  4. 4Why do LSM engines still perform reasonably on point reads despite storing data in many files?

Where to go next

Finished this lesson?

Mark it complete to track your progress across the roadmap.