SysDesignAtlas

Storage Engines — B-Tree vs LSM

The two ways databases put bytes on disk, why one favours reads and the other writes, and how compaction and write amplification decide your workload's fate.

CoreHard11 min readb-treelsmstoragecompaction
Confidence

#Why this matters

"Should I use Postgres or Cassandra?" is really a question about storage engines. The read/write asymmetry of your workload maps almost directly onto B-tree versus LSM, and being able to explain why an LSM tree suits write-heavy workloads means reasoning one level below where most explanations stop.

A storage engine is the part of a database that actually puts bytes on disk and finds them again. Everything above it — SQL, query planning, transactions — eventually calls down into it.

The one constraint driving every design below: writing data in a continuous stream is dramatically faster than writing it in scattered pieces. On spinning disks the gap was around 100×. On SSDs it's smaller but still real, and scattered writes make an SSD do extra internal shuffling on top (write amplification — the disk physically writes more bytes than you asked it to). So every storage engine is a strategy for turning scattered writes into sequential ones, or a considered decision not to.

#B-trees

The classic. Used by Postgres, MySQL/InnoDB, Oracle, SQL Server, and most relational systems.

Data lives in fixed-size pages (typically 4–16 KB) arranged in a balanced tree, kept sorted by key. See Indexing for the structure.

Writing means finding the right page and modifying it in place:

   UPDATE row 4711
     1. traverse the tree to find its leaf page   (random reads)
     2. modify the page in the buffer pool
     3. write to the WAL (sequential, durable)
     4. eventually flush the dirty page           (random write)

   If the page is full → SPLIT into two pages,
   update the parent, possibly cascading upward.

Two terms in that picture. The buffer pool is the database's in-memory cache of pages — changes are made to the copy in memory first. A dirty page is one that has been changed in memory but not yet written back to disk. The WAL (write-ahead log, covered below) is what keeps that change safe in the meantime.

Strengths:

  • Predictable reads. Every lookup is O(log n) — about 3–4 page reads for any dataset size. There's exactly one place a key can be.
  • Excellent range scans. Leaves are sorted and each one points to the next, so a query like "all orders from 1–7 March" finds the first matching leaf once and then just walks along to its neighbours.
  • Mature transactional support. In-place updates fit naturally with MVCC and locking.

Weaknesses:

  • Random writes. Each update goes to whatever page its key lives on, so a stream of updates lands all over the disk instead of in one continuous run.
  • Write amplification. Changing 100 bytes rewrites an entire 8 KB page — and the WAL entry too. Amplification of 10–100× is normal.
  • Page splits leave half-empty pages behind (fragmentation, which wastes space) and make the occasional write much slower than the rest.
  • Random primary keys make it worse. With an increasing key, new rows all go into the rightmost leaf. With a random key such as a UUID, each insert lands in a random leaf, so inserts touch pages all over the tree and split them more often — see the UUID discussion in Unique ID Generation.

#LSM trees

Log-Structured Merge trees. Used by Cassandra, RocksDB, LevelDB, HBase, ScyllaDB, InfluxDB — and increasingly as an option inside traditional databases.

The core idea: never go back and edit something on disk. Only ever add to the end.

Three terms carry the whole design. The memtable is a sorted table of recent writes held in memory. An SSTable is what that becomes when it's full and gets written out — a sorted file that is never modified again. Compaction is the background job that merges those files together, discarding superseded values, so reads don't have to consult an ever-growing pile of them.

   WRITE PATH
   ┌─────────────────────────────────────────────┐
   │ 1. append to WAL (sequential, for crash     │
   │    recovery only)                            │
   │ 2. insert into MEMTABLE (sorted in-memory    │
   │    structure — skip list or red-black tree)  │
   └─────────────────────────────────────────────┘
                     │ memtable full
                     ▼
   ┌─────────────────────────────────────────────┐
   │ 3. FLUSH to disk as an immutable, sorted     │
   │    SSTable — one big SEQUENTIAL write        │
   └─────────────────────────────────────────────┘

   DISK LAYOUT
   L0  [SST][SST][SST]        newest, may overlap
   L1  [SST][SST][SST][SST]   non-overlapping, 10× bigger
   L2  [SST]...               10× bigger again

Writes are extremely fast — an in-memory insert plus a sequential WAL append. No tree traversal, no page reads, no random I/O. This is why LSM engines handle write-heavy workloads so much better.

Reads are harder, because a key may live in the memtable or any SSTable:

   1. check memtable                        (in memory)
   2. check L0 SSTables, newest first
   3. check L1, L2, ... (binary search within each)
   ...until found

Three optimizations make this viable, and they're worth naming:

  • Bloom filters per SSTable — skip files that definitely don't contain the key. This is the single most important read optimization; without it, a read might touch every level.
  • Sparse indexes — an in-memory index of every Nth key per SSTable, so you seek to a block rather than scanning.
  • Block caching of hot data.

Even so, a read may touch several files, and a read for a non-existent key is the worst case — it must check everything (which is why Bloom filters matter so much).

#Compaction

Because SSTables are never edited, they pile up. An update doesn't change the old value — it writes a new entry for the same key in a newer file, and reads stop at the newest entry they find, so the old one is hidden but still taking up disk. A delete works the same way: it writes a marker called a tombstone that says "this key is gone". Compaction merges SSTables, throws away the hidden old values, and drops tombstones once nothing older remains for them to hide.

This is where LSM engines earn their reputation for operational subtlety:

Size-tiered compaction merges SSTables of similar size. Cheap on writes, but read performance suffers: files cover overlapping key ranges, so a lookup may have to check many of them. It can also briefly need ~2× the disk space during a large merge, because the old input files can't be deleted until the new merged file is complete.

Leveled compaction keeps each level non-overlapping and ~10× the previous. Reads touch at most one file per level — much better and more predictable. Costs significantly more write amplification, since data is rewritten as it moves down levels.

The classic tradeoff, worth stating crisply:

   Size-tiered  → better WRITE throughput, worse read latency,
                  more space amplification
   Leveled      → better READ latency, predictable space,
                  higher write amplification

Deletes are the operational trap. A delete writes a tombstone, not a removal. Space isn't reclaimed until compaction, and until then reads must still scan past tombstones. A workload that deletes heavily can build up so many tombstones that reads become dramatically slower — a well-known Cassandra pathology, and a great detail to mention if a design involves lots of deletion or TTL expiry.

Compaction competes with foreground traffic — the reads and writes your users are making — for disk and CPU. Poorly tuned compaction shows up as unexplained p99 spikes: most requests stay fast, but the slowest 1% suddenly get much slower whenever a big merge is running. This is the main reason LSM engines are considered operationally harder.

#Amplification — the three-way tradeoff

Every storage engine trades among three quantities, and you cannot minimize all three (the "RUM conjecture"):

  • Read amplification — disk reads per logical read.
  • Write amplification — bytes written per logical byte.
  • Space amplification — disk used per logical byte.

"Logical" means what you asked for. If one GET costs 3 disk reads, read amplification is 3. If storing 10 GB of data uses 20 GB of disk, space amplification is 2×.

B-treeLSM (leveled)LSM (size-tiered)
Read ampLow (~1 page)Medium (per level)High (many files)
Write ampMedium-highHigh (rewrites on merge)Lower
Space ampMedium (fragmentation)Low (~1.1×)High (~2× transiently)
Write throughputModerateHighHighest
Read latencyPredictableGoodVariable

#Write-ahead logging

Both engines need durability before the real write lands, and both solve it the same way: append to a write-ahead log first, then do the actual work.

   1. append change to WAL, fsync           ← durability point
   2. acknowledge the client
   3. modify pages / memtable in memory
   4. flush to their permanent home later

   Crash after 1 → replay the WAL on restart

The WAL is sequential, so it's fast. The expensive random work (updating pages in their real locations) is put off and done later in batches.

fsync is the actual durability boundary. Writing to a file normally only puts the bytes in the operating system's memory; fsync forces them onto the physical disk. An acknowledged write that hasn't been fsynced can vanish in a power loss. Because each fsync is slow, databases use group commit: wait a moment, then fsync several transactions' log entries together in one go, so many commits share the cost of one disk flush.

The WAL is also the source of replication and CDC streams — it's already an ordered record of every change.

Checkpointing stops the log growing forever. Every so often the database writes all changed (dirty) pages to their real place on disk, after which the older part of the log is no longer needed and can be deleted. After a crash, it only has to replay the log from the last checkpoint. The trade-off: infrequent checkpoints mean less background I/O during normal running, but more log to replay — so slower recovery — after a crash.

#Choosing

WorkloadEngine
OLTP, mixed reads/writes, joinsB-tree (Postgres, MySQL)
Write-heavy, append-mostly, time-orderedLSM (Cassandra, RocksDB)
Time series, telemetry, event logsLSM, often with time-windowed compaction
Read-heavy with complex queriesB-tree
Embedded KV under another systemLSM (RocksDB is the default building block)
Analytics over huge scansNeither — columnar

The practical caveat worth adding: the engine is rarely the deciding factor by itself. Query capabilities, transactions, operational familiarity, and ecosystem usually matter more. But when the workload is genuinely write-dominated at high volume, the engine difference is large enough to drive the decision — and being able to say exactly why is what makes the answer credible.

#Check yourself

What one constraint drives every storage-engine design?Show answer
Sequential writes are far faster than scattered ones — about 100× on spinning disks, still significant on SSDs, where random writes also cause internal write amplification.
How does a B-tree write, and what does that cost?Show answer
It finds the leaf page and modifies it in place: random reads to traverse, a WAL append, then a random page write later. Changing 100 bytes rewrites an 8 KB page, so write amplification of 10–100× is normal.
Describe the LSM write path.Show answer
Append to the WAL for crash recovery, insert into an in-memory sorted memtable, and when it fills, flush it as an immutable sorted SSTable in one sequential write. No page reads, no random I/O.
Why are LSM reads harder, and what saves them?Show answer
A key could be in the memtable or any SSTable, so a read may check several files. Per-SSTable Bloom filters skip files that can't hold the key; sparse indexes and block caches do the rest. Missing keys are the worst case.
Size-tiered versus leveled compaction?Show answer
Size-tiered merges similar-sized files: better write throughput, worse reads, about 2× transient space. Leveled keeps each level non-overlapping and 10× bigger: one file per level on reads, predictable space, higher write amplification.
Why do heavy deletes hurt an LSM store?Show answer
A delete writes a tombstone instead of removing anything. Until compaction drops them, space isn't reclaimed and reads must scan past them — a well-known Cassandra pathology with TTL-heavy data.
What is the RUM conjecture?Show answer
You can't minimise read, update (write) and memory (space) amplification all at once; every storage engine picks a point on that trade-off.
Which engine for which workload?Show answer
B-tree for OLTP with mixed reads and writes, joins and range scans. LSM for write-heavy, append-mostly, time-ordered data and as an embedded KV (RocksDB). Columnar for analytics over huge scans.

#What to carry forward

  • Every engine is a strategy for turning scattered writes into sequential ones — or a choice not to.
  • B-trees: predictable reads, in-place updates, random writes. LSM: fast sequential writes, reads spread across files.
  • Bloom filters make LSM reads viable; compaction makes them bounded, at the cost of background I/O.
  • Read, write and space amplification trade against each other — name which one the workload can afford.
  • Tombstones and untuned compaction are the LSM operational traps, showing up as p99 spikes.
00:00
/ 11m