Home›Learn›B-tree and LSM tree
Course · Inside one serverLesson 8 of 330 read

B-tree and LSM tree, side by side

Why are some databases fast at writes and others at reads?

Two animated write paths and a comparison table.

Press Play, or step with the arrows.

Under every database is a storage engine, and almost all of them are one of two designs. A B-tree keeps data sorted in pages and updates them where they are. A log-structured merge tree (LSM) writes everything new into memory and sorted files, and merges them later.

When each one wins

Go deeper
B-treeLSM tree
Write pathFind the page, change it, write it back laterAppend to memory, flush whole files
Random keysScattered page reads and splits (Notebook 10: 10 times slower in MySQL)No difference at write time
Point readsOne path, a few pagesMemtable, then bloom filters, then possibly several files
Range scansLeaves are in key orderMerged across files on the fly
DeletesRemove the entry; space reused laterA tombstone, removed only by compaction
Background workCheckpoints, VACUUM or purgeCompaction, which can use a lot of I/O
Used byPostgreSQL, InnoDB, WiredTiger, SQL Server, OracleCassandra, ScyllaDB, RocksDB, HBase

Neither is better in general. A B-tree pays at write time to keep reads simple. An LSM tree makes writes cheap and pays later, in compaction and in reads that may look in several places. If writes dominate and keys arrive in any order, LSM fits. If reads dominate and you need ranges and joins, a B-tree fits.

See the difference yourself

Go deeper
-- PostgreSQL: how full are the B-tree's leaf pages?
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT leaf_pages, avg_leaf_density FROM pgstatindex('orders_pkey');
# Cassandra: how many SSTables does a read touch?
nodetool tablehistograms shop orders
Connected

Where this shows up

The same mechanism, indexes and plans, old row versions, vacuum and long transactions, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 3 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. Where does an LSM tree put a new write first, after the commit log?

2. What does an LSM tree do with a delete?

3. Which engine family suffers most from random primary keys at insert time?

Part 1 of 4 · Learn · 23 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.