Data · L1B-tree vs LSM-tree

B-tree vs LSM-tree

Every database pays for keeping data sorted on disk. A B-tree pays when you write. An LSM-tree pays later, in the background and on reads.

L1 Must-knowData20 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 21 Oct 2026 · How we check content
Senior at work · lesson 16 of 26
Section 1 of 8

What broke

In 2017, Discord stored its chat messages in a Cassandra cluster of 12 nodes. By early 2022, the same cluster had 177 nodes and trillions of messages. The on-call team was paged often, and latency was hard to predict. 2

Writes were cheap. In Cassandra, a write is added to a commit log and to a table in memory. Reads cost more, because they may have to look in memory and in several files on disk. 2

Those files must be merged in the background. This is called compaction. Discord's nodes often fell behind on it. Then reads got more expensive. When a node tried to compact, Discord saw latency that cascaded to other parts of the system. 2

So the team did what they called a "gossip dance". They stopped sending traffic to one node, let it compact, brought it back, and repeated this until the backlog was empty. 2

This is not a Cassandra bug. It is the price of the design that makes its writes cheap. In this lesson you will see where each storage engine pays, so you can choose the costs you can accept.

Section 2 of 8

The idea in simple words

A database keeps data sorted by key, so it can find a row without reading everything. There are two main ways to keep it sorted on disk.

A B-tree keeps one sorted tree made of fixed-size pages. It changes those pages in place. To insert a key, it finds the right page and writes that page again. Postgres creates B-tree indexes by default, and MySQL's InnoDB stores its indexes as B-trees. 3 8

An LSM-tree never changes a file after writing it. It collects new writes in memory, writes them out as a new sorted file, and later merges files in the background. Cassandra works this way, and so do RocksDB and LevelDB. 10 15 7

The key idea. A B-tree does the sorting work when you write, in place. An LSM-tree puts that work off and does it later in big batches. Batched work is cheaper per write, but you still pay for it: in background disk work and in slower reads.

The LSM-tree paper says it is most useful when you add entries to an index more often than you look them up. 1 The real answer for your data comes from your own load test.

Section 3 of 8

How it works

Step through one write in an LSM-tree, then one insert in a B-tree. Use Next and Back, or the ← and → keys.

One write in an LSM-tree, and one page split in a B-treeLSM-tree WAL (disk) Memtable SSTables SST 1 SST 2 … + k=42append at end insert7 · 42 · 90sorted, in RAM flushSST 3 (new) 1 merged SSTcompactionmerge SST 1 + 2 + 3 B-tree root: 40 | 80 10 20 30 41 43 45 47 81 85 90 +42: page fullno room root: 40 | 45 | 8041 42 4345 47 (new)Split: new page, new pointer in root SeniorPath
  1. LSM-tree. A write for key 42 arrives. First it is added to the end of the write-ahead log (WAL) on disk. Adding to the end of a file is fast.
  2. Then the key goes into the memtable, a sorted table in memory. The write is now done. No file on disk was changed in place.
  3. When the memtable is full, it is written to disk as a new sorted file, SST 3. That file is never changed again.
  4. Later, in the background, compaction merges SST 1, 2 and 3 into one file. It keeps only the newest version of each key. This is the work the LSM-tree put off.
  5. B-tree. Key 42 belongs in the middle leaf page, between 41 and 43. The change goes to the WAL first (not shown). But the page has no room left.
  6. The page splits. Some keys move to a new page, and the root gets a pointer to it. The B-tree did its sorting work at once, in place.
Step 1 of 6

B-tree: pages and page splits

Disks are read in blocks, so a B-tree is built from pages. In InnoDB a page is 16 KB by default. 8 In Postgres, leaf pages hold keys that point to the table rows. 4 In InnoDB, the primary key index stores the rows themselves. 9 Pages above the leaves hold keys that guide you down to the right leaf. In Postgres, usually over 99% of all pages are leaf pages. 4

A lookup starts at the root and goes down one page per level. Trees stay shallow. Here is a rough example. Say each page is 4 KB and points to 500 pages below it.

Then four levels of branching reach 500 × 500 × 500 × 500 = 62.5 billion pages. At 4 KB each, that is about 256 TB. So a handful of page reads can find any key.

When a new key does not fit in its leaf page, the page splits. Some keys move to a new page, and the parent page gets a pointer to it. If the parent is full too, it splits as well. When the root splits, the tree gets one level taller. 4

The order of your keys matters. InnoDB tries to leave 1/16 of each page free. If you insert keys in order, pages end up about 15/16 full. If you insert them in random order, pages are between 1/2 and 15/16 full. 8

Random keys, like random UUIDs, cause a second problem. Each insert lands on a different page. When the index is too big for memory, each insert may need a page read and a page write on disk. The LSM-tree paper shows the same effect for an index whose keys arrive in random order. Its example is an index by account ID on a fast-growing History table. A B-tree there can double the disk input and output (I/O) of each transaction. 1

The write-ahead log

Changing pages in place is risky. A crash in the middle can leave a page half written. So the database first writes a record of the change to the write-ahead log (WAL) and flushes it to disk. Only after that may the data pages change. 5

After a crash, the database replays the log to redo the missing changes. The log is written in order, so flushing it costs much less than flushing data pages. One flush can even commit many small transactions at once. 5 LSM engines keep a log too. Cassandra calls it the commit log. 10

LSM-tree: memtable, SSTables, compaction

  1. A write is added to the commit log on disk. 10
  2. Then it goes into the memtable, a sorted table in memory. 10
  3. When the memtable reaches a size limit, it is flushed to disk as an SSTable. This is a sorted file that is never written again. 10
  4. Over time you get many SSTables. Compaction merges several of them into a new one. Then the old SSTables can be removed. 10

While it merges, compaction drops values that were overwritten. LevelDB's docs say this plainly. 7

A delete is also a write. Cassandra writes a marker called a tombstone. By default, compaction can remove it after 10 days. 11

A read checks the memtable first, then the SSTables. With many SSTables, that can mean many files. A Bloom filter avoids most of this work. Each SSTable has a small filter that answers "this key may be here" or "this key is surely not here". It is sometimes wrong when it says "may be here". It is never wrong when it says "not here". 16

The filter uses memory. In RocksDB, about 10 bits per key gives about 1% false positives. 16

Two ways to compact

Size-tiered. Wait until there are several SSTables of a similar size, then merge them. Cassandra starts when it has 4 by default. 12 This rewrites data less often than leveled compaction. 14 But versions of one row can spread over many files, so reads get slower. During a big compaction, the old and new files must fit on disk at the same time. 12

Leveled. Keep files in levels, and make each level about 10 times bigger than the one above. Inside one level, files do not overlap. So a read needs to look at only one SSTable per level. Leveled compaction needs less spare disk, about 10%. But it uses much more disk I/O and CPU when there are many writes. 13

Three kinds of amplification

Engineers compare storage engines with three numbers:

You cannot make all three small at once. The RocksDB docs say it plainly. Leveled compaction keeps space low, but costs more reads and writes. Tiered compaction keeps writes low, but costs more reads and space. 14 For leveled compaction, write amplification is often larger than 10. 15

B-trees have write amplification too. In Postgres, each change goes to the WAL first, and later to the data page. 5 So each change reaches disk at least twice.

Also, the first change to a page after a checkpoint writes the whole page to the WAL, even if only a few bytes changed. This is on by default. 6

Section 4 of 8

Trade-offs

EngineWritesReadsDisk spaceWatch out for
B-tree (Postgres, InnoDB)WAL plus a page write in place. Slows down when the index no longer fits in memory.Fast and steady: one walk from root to leaf.Pages are partly empty, more so with random keys.Random keys, page splits, big indexes.
LSM, size-tieredCheapest. Data is rewritten less often.Slower. One key can be spread over many SSTables.Needs free disk for old and new files during a compaction.Compaction backlog. Slow reads after a burst of writes.
LSM, leveledMore rewriting. Often over 10x in RocksDB.Better. One SSTable per level.Low. About 10% spare in Cassandra.Heavy compaction I/O and CPU under many writes.

Simple rule: start with a B-tree database like Postgres or MySQL. Choose an LSM store when writes clearly dominate, for example events, logs, metrics or chat messages, and plan for compaction from day one.

Section 5 of 8

At work: how a senior uses this

  • Before you pick a store, write down the read/write ratio, and whether reads are by one key or by a range. That decides more than any benchmark blog.
  • On an LSM store, put pending compactions and SSTables per read on a dashboard. Alert when they keep growing. A backlog that keeps growing is a problem, even before anything fails.
  • Keep enough free disk for compaction to write new files before it deletes the old ones. Put this in the capacity plan.
  • Pick the compaction strategy for the data. The Cassandra docs suggest leveled for read-heavy tables or tables with many updates and deletes. They suggest time window for time-series data with a TTL, and UCS (Unified Compaction Strategy) for new workloads. 11
  • For B-tree tables with heavy inserts, prefer keys that grow over time, like time-ordered IDs. Random keys spread writes over many pages. 8
  • Treat deletes on an LSM store as writes. A mass delete creates many tombstones, and they stay until compaction removes them.
  • Load test long enough. A B-tree slows down most when the index outgrows memory. A compaction backlog shows only after hours of writes.
Section 6 of 8

With AI

What to ask the agent

"Here is our table schema, our 10 most common queries and our write rate. Tell me whether a B-tree database or an LSM store fits better, and why. For each, say what it costs us in disk space and background work."

"Write a load test that inserts 50 million rows into Postgres twice: once with a random UUID primary key and once with a time-ordered key. Report the insert rate over time and the final index size."

"Our Cassandra table has slow reads. Here is the schema and the compaction settings. Explain how many SSTables one read may touch, and suggest a compaction strategy with reasons and risks."

What to check yourself

  • Any number the agent gives, like "LSM is 10x faster", comes from a source or from a test you ran.
  • The load test runs long enough for the index to outgrow memory and for compaction to start.
  • The test machine has the same disk type and memory size as production.
  • Free disk for compaction is in the capacity plan, not left to chance.
  • A change of compaction strategy is tried on one node or on a copy first.
  • Bloom filter memory is counted when you size the machines.
Section 7 of 8

Check yourself

1. Why is a write cheap in an LSM-tree?

Show answer

It is added to the end of a log and put in a sorted table in memory. No file on disk is changed in place. The slow work, sorting into files on disk and merging them, happens later during flush and compaction.

2. An SSTable's Bloom filter says "key 42 is surely not here". What do you know?

Show answer

Key 42 is not in that file, so the read can skip it. A Bloom filter can wrongly say "may be here", but it never wrongly says "not here".

3. You insert random UUIDs as keys into a large B-tree index that no longer fits in memory. What happens?

Show answer

Each insert may need a random page read and write on disk, and pages end up partly empty. Random keys land on random pages. InnoDB says random inserts leave pages between 1/2 and 15/16 full.

4. Your Cassandra table is read-heavy and has many updates. Which compaction strategy do the Cassandra docs point to?

Show answer

Leveled (LCS) The docs say LCS is optimized for read-heavy workloads, or workloads with lots of updates and deletes.

5. What did Discord's Cassandra cluster often fall behind on?

Show answer

Compaction. Reads got more expensive and busy nodes got slow. Discord says they were "prone to falling behind on compactions", and stopped sending traffic to nodes to let them compact.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 16 sources and related lessons
  1. O'Neil, Cheng, Gawlick, O'Neil, “The Log-Structured Merge-Tree (LSM-Tree)”, Acta Informatica 33, 1996 (opens in a new tab)
    The paper that named the LSM-tree (free copy; the journal version is doi 10.1007/s002360050048). The abstract and section 1 explain why a B-tree index on a busy table doubles the disk I/O.
  2. Discord Engineering, “How Discord Stores Trillions of Messages” (2023) (opens in a new tab)
    A real Cassandra cluster that grew from 12 to 177 nodes, and the read and compaction pain that came with it.
  3. PostgreSQL documentation: Index Types (opens in a new tab)
    CREATE INDEX makes a B-tree by default. B-trees handle equality and range queries.
  4. PostgreSQL documentation: B-Tree Indexes (Implementation) (opens in a new tab)
    Section on B-tree structure. Leaf and internal pages, page splits that cascade upwards, and root splits.
  5. PostgreSQL documentation: Write-Ahead Logging (WAL) (opens in a new tab)
    Why changes are logged before data pages change, and why one log flush can commit many transactions.
  6. PostgreSQL documentation: Write Ahead Log settings (full_page_writes) (opens in a new tab)
    With full_page_writes on (the default), the first change to a page after a checkpoint writes the whole page to the WAL.
  7. LevelDB documentation: Implementation notes (opens in a new tab)
    LevelDB's log, memtable, sorted tables and levels, and how compactions drop overwritten values.
  8. MySQL 8.4 Reference Manual: The Physical Structure of an InnoDB Index (opens in a new tab)
    InnoDB indexes are B-trees with 16 KB pages by default. How full pages get with ordered and random inserts.
  9. MySQL 8.4 Reference Manual: Clustered and Secondary Indexes (opens in a new tab)
    The InnoDB clustered (primary key) index stores the row data. Secondary indexes store the primary key.
  10. Apache Cassandra documentation: Storage Engine (opens in a new tab)
    Commit log, memtables, flushes to SSTables that never change, and compaction.
  11. Apache Cassandra documentation: Compaction overview (opens in a new tab)
    The compaction strategies (STCS, LCS, UCS, TWCS), which to use when, and tombstones.
  12. Apache Cassandra documentation: Size Tiered Compaction Strategy (opens in a new tab)
    When size-tiered compaction starts, and why it makes reads slower.
  13. Apache Cassandra documentation: Leveled Compaction Strategy (opens in a new tab)
    Levels that grow 10 times each, one SSTable per level per read, and the extra I/O it costs.
  14. RocksDB wiki: Compaction (opens in a new tab)
    A short, clear statement of the read, write and space trade-off between leveled and tiered compaction.
  15. RocksDB wiki: Leveled Compaction (opens in a new tab)
    How files move from level to level, and why write amplification is often larger than 10.
  16. RocksDB wiki: RocksDB Bloom Filter (opens in a new tab)
    What the filter answers, and a table of bits per key against false positive rate.

Case studies: Discord: Moving trillions of messages from Cassandra to ScyllaDB

Related: Storage engine internals (coming soon) · Secondary, composite and special indexes · Cassandra in depth · PostgreSQL in depth · Choosing a database

Next: Secondary, composite and special indexes. It builds on the B-tree pages you saw here. For an LSM database in production, see Cassandra in depth.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper