# Why LSM Trees Exist: The Disk Math Behind Every Write-Heavy Database

If you've ever put a random UUID primary key on a busy MySQL table, you've probably seen this graph.

For weeks, insert latency is flat and boring. Then one day the p99 starts climbing. Nothing changed in the code. Traffic didn't spike. Disk utilisation is pinned at 100%, but the amount of data you're inserting per second is tiny: a few megabytes.

The table didn't get slower because it got bigger. It got slower because it got **bigger than memory**, and from that moment every insert started costing a random disk read and a random disk write.

This is the problem the log-structured merge tree (LSM tree) was invented to solve. In this article we won't just describe an LSM tree. We'll **derive** it: start from what a disk actually charges you for, and arrive at the LSM design one forced step at a time. By the end you'll know why RocksDB, Cassandra, ScyllaDB, HBase, CockroachDB's Pebble and Kafka Streams' state stores all look the way they do, and when you should *not* use one.

Everything here is backed by two small Python scripts you can run yourself (links at the end).

---

## 1\. What a disk actually charges you for

### Spinning disks: you pay for the arm

A hard disk is a spinning platter with an arm that moves across it. To read or write a random location, two slow mechanical things happen:

1. **Seek.** The arm moves to the right track: about 4–9 ms.
2. **Rotation.** You wait for the right sector to spin under the head. At 7,200 rpm one rotation takes \\(60/7200 = 8.33\\) ms, so on average you wait half of that: 4.17 ms.

Add them up and a random I/O costs **roughly 10 ms**. That gives the number every storage engineer remembers:

> **A spinning disk does about 100 random I/Os per second.**

Now compare two ways of writing data:

- **Random 16 KB writes:** \\(100 \times 16\text{ KB} \approx 1.6\\) MB/s
- **Sequential writes:** the arm stays put and the platter streams data at about 200 MB/s

That is a gap of more than **100×**, for the same disk, the same bytes. The only difference is *where* the bytes go.

### SSDs: no arm, but the gap didn't disappear

"That's a 1990s problem," you might say. "We run on NVMe now." Partly true. An SSD has no moving parts, so the seek penalty is gone. But three costs remain.

**1\. You can't write less than a page.** Flash and databases both work in pages (4–16 KB). Changing a 200-byte row still means writing the whole page.

**2\. You can't overwrite in place.** Flash can only be *erased* in big blocks (often several MB). So the SSD's firmware writes your new page somewhere fresh and marks the old one stale. Later, garbage collection copies the still-live pages out of a block so it can erase it. Small random writes scatter live and dead pages across every block, so the drive ends up copying a lot. Large sequential writes fill whole blocks that later die together (when a file is deleted), so there's almost nothing to copy.

**3\. Every I/O has a fixed overhead.** System call, queueing, the device's own bookkeeping. Fewer, bigger I/Os amortise it.

I measured the third point on a cloud VM's virtual SSD, writing the same 64 MB with different I/O sizes (`O_DIRECT`, so the OS cache can't help):

| I/O size | Random MB/s | Sequential MB/s | I/Os needed for 64 MB |
| --- | --- | --- | --- |
| 16 KB | 227 | 273 | 4,096 |
| 64 KB | 468 | 566 | 1,024 |
| 256 KB | 724 | 775 | 256 |
| 1 MB | 795 | 637 | 64 |
| 4 MB | 703 | 745 | 16 |

Look at the columns, not the rows. Random vs sequential barely matters on this device. **I/O size** matters about 3×.

So here's the modern version of the rule:

> **On SSDs, "sequential" really means "large". The device rewards you for writing big, contiguous chunks it can later throw away whole.**

Keep that sentence in mind. The entire LSM design follows from it.

---

## 2\. Where a B+tree pays the bill

A B+tree (InnoDB, PostgreSQL indexes, most relational databases) is an **update-in-place** structure. Every key has exactly one home: a specific leaf page. To insert a row you:

1. Find the leaf page that owns the key.
2. If it's not in the buffer pool (RAM), **read it from disk**: one random read.
3. Modify it in memory. It's now dirty.
4. Eventually, when the buffer pool needs room, **write the whole page back**: one random write.

While the table fits in memory, steps 2 and 4 rarely happen, and life is great. That's the flat part of the graph.

Now let the table grow past memory. Say the table has \\(\mathit{S}\\) leaf pages and the buffer pool holds \\(\mathit{B}\\) of them. With random keys, each insert hits a random page, and the chance it's already cached is \\(B/S\\). So the chance it costs a disk trip is \\(1 - B/S\\).

Each of those trips eventually writes back a full page of \\(\mathit{P}\\) bytes, to store one row of \\(\mathit{r}\\) bytes. That gives the B+tree's write amplification for random inserts:

$$\text{WA}_{\text{B+tree}} \\;\approx\\; \left(1 - \frac{B}{S}\right) \cdot \frac{P}{r}$$

Plug in real numbers: 16 KB InnoDB pages, 200-byte rows, buffer pool holding 5% of the table:

$$\text{WA} \approx 0.95 \times \frac{16384}{200} \approx 78$$

**Every byte you insert costs about 78 bytes of disk writes**, plus one random read and one random write per insert. And that's before page splits, and before InnoDB's doublewrite buffer, which writes every dirty page twice to protect against torn pages.

I simulated exactly this: a B+tree with 400,000 leaf pages, an LRU buffer pool of 20,000 pages, and 2 million random 200-byte inserts.

```plaintext
B+tree, random keys:    1,900,665 random page reads, 1,900,665 random page writes
   bytes written per byte inserted:   77.9x   | random write I/Os per insert: 0.950
```

The formula predicted 0.95 and 78×. The simulation measured 0.950 and 77.9×.

### Why auto-increment keys "fix" it

Run the same simulation with **monotonic keys** (auto-increment IDs, timestamps):

```plaintext
B+tree, monotonic keys:         0 random page reads,    24,692 random page writes
   bytes written per byte inserted:    1.0x   | random write I/Os per insert: 0.012
```

Every insert goes to the rightmost leaf. That one page stays hot in memory, fills up with 81 rows, and gets written once. Write amplification drops from 78× to 1×.

This is the real reason behind the classic advice "don't use UUIDv4 as a MySQL primary key." It's not about the 16 bytes. It's that random keys turn every insert into random I/O once the table outgrows RAM. (It's also why UUIDv7 and ULIDs, which start with a timestamp, became popular.)

But you don't always get to choose your keys. A secondary index on `user_id`, a messages table keyed by `(channel_id, message_id)`, an events table keyed by `(item_id, ts)`: these are random inserts by nature. You need a structure that doesn't care.

---

## 3\. Deriving the LSM tree, one step at a time

Let's design a storage engine with one rule:

> **Never do a small random write.**

### Step 1: Just append

The simplest structure that obeys the rule is a log. Every write goes to the end of a file. Writes are perfect: purely sequential, write amplification of 1.

Reads are terrible. To find a key you scan the whole file: \\(\mathit{O}(n)\\).

### Step 2: Sort in memory, flush in bulk

We need the data on disk to be **sorted**, so reads can binary search. But sorting on disk means moving things around, which means random writes.

So sort in **memory** instead. Keep an in-memory sorted structure (the **memtable**; usually a skip list). When it reaches a size limit (say 64 MB), write it out in one go as an immutable, sorted file: a **Sorted String Table**, or **SSTable**.

That flush is one long sequential write.

Memory is volatile, so to survive a crash every write also goes to an append-only **write-ahead log** (WAL) first. That's sequential too. Once the memtable is flushed, its WAL can be deleted.

Now we have a write path made entirely of sequential writes:

```plaintext
write(k, v)
   │
   ├──► WAL (append, sequential)          ← durability
   │
   └──► memtable (sorted, in RAM)
            │  full?
            ▼
        SSTable file (sorted, immutable, written once, sequentially)
```

### Step 3: Too many files, so merge them

After a day of traffic you have hundreds of SSTables. Each is sorted, but a read might have to check every one of them, newest first, because a key could live in any of them.

The fix: periodically **merge** SSTables into fewer, bigger ones. Merging sorted files is a streaming operation: read several sorted inputs sequentially, write one sorted output sequentially. Like the merge step of merge sort. Old versions of a key and deleted keys get dropped on the way. This is **compaction**.

Compaction obeys our rule. It reads big chunks and writes big chunks. No small random writes anywhere.

### Step 4: Don't merge everything every time

The naive version, "merge everything into one big file after each flush", rewrites the whole database every flush. With \\(\mathit{N}\\) bytes of data and a memtable of \\(\mathit{M}\\) bytes, each flush costs \\(\mathit{O}(N)\\). That's far too much.

The fix is to arrange files in **levels** that grow geometrically by a factor \\(\mathit{T}\\) (typically 10):

```plaintext
memtable   64 MB      (RAM)
L0         a few freshly flushed SSTables
L1         ~256 MB    ┐
L2         ~2.5 GB    │ each level ~T = 10× bigger than the one above,
L3         ~25 GB     │ and holds one sorted run, split into files
L4         ~250 GB    ┘
```

When a level gets too full, pick one file from it and merge it into the overlapping files of the next level down. Data trickles down level by level.

How many levels do we need? Each level is \\(\mathit{T}\\) times bigger, so:

$$L \\;\approx\\; \log_T \frac{N}{M}$$

With 250 GB of data, a 64 MB memtable and \\(T = 10\\), that's \\(\log_{10}(4000) \approx 3.6\\), so 4 levels.

And what's the write cost? Each byte is written once at flush, and then again every time it moves down a level. Moving a file into a level that's \\(\mathit{T}\\) times bigger rewrites up to \\(\mathit{T}\\) times as much overlapping data. So:

$$\text{WA}_{\text{LSM}} \\;\lesssim\\; 1 + T \cdot L$$

(Both engines also write every byte to a WAL once, so I'm leaving that out of the comparison.)

That's an upper bound. Real levels aren't always full, so the actual number is lower. My simulation of a leveled LSM with \\(T = 10\\) on the same 2 million random inserts measured:

```plaintext
LSM (leveled, T=10), random keys:
   bytes written per byte inserted:   15.5x   | 1 MB sequential write I/Os per insert: 0.0030
```

That's it. That's the LSM tree. We didn't pick it from a menu. Every piece was forced by the rule "never do a small random write":

| Piece | Why it exists |
| --- | --- |
| WAL | Memory is volatile, and appending is the only cheap durable write |
| Memtable | Sorting must happen somewhere that random access is free: RAM |
| SSTable | Flushing a sorted memtable is one big sequential write |
| Compaction | Many files make reads slow; merging sorted files is sequential |
| Levels with ratio \\(\mathit{T}\\) | Merging everything every time costs \\(\mathit{O}(N)\\) per flush |

---

## 4\. Putting the two side by side

Same workload, 2 million random inserts of 200 bytes:

|  | B+tree | LSM tree (leveled) |
| --- | --- | --- |
| Bytes written per byte inserted | **77.9×** | **15.5×** |
| Shape of each write | 16 KB, random | 1 MB+, sequential |
| Write I/Os per insert | 0.95 | 0.003 |
| Random reads per insert | 0.95 | 0 |

Notice something surprising. **The LSM tree still rewrites every byte 15 times.** It is not "write once". What it does is turn ~2 million small random I/Os into ~6,000 large sequential ones.

That's the core trade:

> **An LSM tree writes more bytes than you'd think, but in far fewer, far larger I/Os. A B+tree writes each update in place, but each one is a small random I/O on a full page.**

### What that means on real hardware

**On a spinning disk** (10 ms per random I/O, 200 MB/s sequential), the same 2 million inserts take:

- B+tree: about **10.6 hours**, roughly 53 inserts per second
- LSM: about **1 minute**, roughly 34,000 inserts per second

That 600× gap is exactly why the LSM tree was invented in the first place. Patrick O'Neil's 1996 paper was motivated by a bank's **history table**: every transaction appends a 50-byte row, and indexing it by account ID with a B-tree roughly doubled the I/O cost of the whole transaction. On 1990s disks, disk arms, not capacity, were the expensive resource.

**On an SSD**, IOPS are plentiful, so the fight moves to **bytes written**, because flash wears out. Take a write-heavy node handling 5,000 random inserts per second of 200-byte rows (the kind of event stream any recommendations or activity-feed system produces). That's only 1 MB/s of real data.

- B+tree: \\(0.95 \times 5000 \times 16\text{ KB} \approx 78\\) MB/s of page writes → **6.7 TB per day**
- LSM: \\(15.5 \times 1\text{ MB/s} \approx 15.5\\) MB/s → **1.3 TB per day**

On a 3.84 TB drive rated for one full drive write per day, the B+tree burns through its endurance budget **1.7× faster than allowed**. The LSM uses about a third of it. Plus the B+tree pays a random read for nearly every insert, competing with your real read traffic.

This is not just a thought experiment:

- **Facebook** moved its main social-graph database (UDB) from InnoDB to MyRocks, MySQL on top of RocksDB. The tier was limited by flash space, and after the migration they reported using **half the storage** of compressed InnoDB. Their 2020 VLDB paper reports instance sizes **62.3% smaller** and fewer I/O operations than InnoDB.
- **Discord** stores trillions of messages in Cassandra-family databases (first Cassandra, now ScyllaDB). Both are LSM-based. Chat is the textbook LSM workload: a firehose of small inserts that are rarely updated.
- **Kafka Streams** keeps its local state stores in RocksDB, and **CockroachDB** built Pebble, its own LSM engine. When you need an embedded engine that ingests fast, the default answer today is an LSM.

---

## 5\. There's no free lunch: what the LSM tree gives up

We optimised the write path. The costs moved somewhere else.

**1\. Reads got more expensive.** A key can now be in the memtable, in any L0 file, or in any level. A naive point lookup checks each place in turn, and a lookup for a key that *doesn't exist* has to check all of them. The fixes are **Bloom filters** (skip a file without touching disk) and per-file indexes. That's the next article.

**2\. Space amplification.** Old versions of a key and deleted keys (tombstones) sit on disk until compaction reaches them. Leveled compaction keeps this to about 10% extra; other compaction styles trade more space for less write amplification.

**3\. Compaction is background work that can fall behind.** If writes come in faster than compaction can merge, L0 fills up, reads slow down, and RocksDB eventually **stalls writes** on purpose to let compaction catch up. If you run an LSM in production, "pending compaction bytes" and write stalls are the metrics you'll learn to watch.

**4\. Write amplification didn't disappear.** 15× is a lot better than 78×, but it isn't 1×. Tuning that number (leveled vs tiered compaction, the size ratio \\(\mathit{T}\\)) is a whole article of its own.

### So when does a B+tree still win?

- **Read-heavy workloads** where predictable single-I/O point reads matter more than ingest speed.
- **Monotonic keys.** As we saw, a B+tree with auto-increment keys writes about 1×. Hard to beat.
- **The working set fits in memory.** If \\(B/S \approx 1\\), the B+tree's write amplification formula goes to nearly zero.
- **Heavy in-place updates of the same hot rows,** which a buffer pool absorbs well.

---

## The short version

1. Disks charge per I/O, not per byte. On HDDs that's the arm; on SSDs it's page size, erase blocks and per-I/O overhead. **Small random writes are the most expensive thing you can ask for.**
2. A B+tree with random keys and a table bigger than RAM pays roughly one random read and one random full-page write per insert: write amplification \\(\approx (1 - B/S) \cdot P/r\\), about **78×** for 200-byte rows on 16 KB pages.
3. An LSM tree refuses to do small random writes: buffer sorted in memory, flush sequentially, merge in the background across levels that grow by \\(\mathit{T}\\). It still rewrites each byte about \\(T \cdot L\\) times at most, but in **big sequential chunks**.
4. The price is paid on reads (fixed with Bloom filters), space (old versions), and background compaction that has to keep up.

---

## What's next

This is the first article in the series **LSM trees from first principles**. Next up: **Bloom filters**, and how to work out exactly how many bits per key to spend on each level, which turns out to have a surprisingly elegant answer.

**Code for this article** (run them yourself):

- [`write_cost_sim.py`](https://github.com/dev64-kartik/storage-engine-articles/blob/main/simulations/01-why-lsm/write_cost_sim.py): B+tree buffer pool vs leveled LSM, same workload
- [`io_size_bench.py`](https://github.com/dev64-kartik/storage-engine-articles/blob/main/simulations/01-why-lsm/io_size_bench.py): measure how I/O size affects throughput on your own disk

**Further reading**

- O'Neil, Cheng, Gawlick, O'Neil, *The Log-Structured Merge-Tree (LSM-Tree)*, Acta Informatica, 1996
- Matsunobu, Dong, Lee, *MyRocks: LSM-Tree Database Storage Engine Serving Facebook's Social Graph*, VLDB 2020
- Discord Engineering, *How Discord Stores Trillions of Messages*, 2023
