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.
| B-tree | LSM tree | |
|---|---|---|
| Write path | Find the page, change it, write it back later | Append to memory, flush whole files |
| Random keys | Scattered page reads and splits (Notebook 10: 10 times slower in MySQL) | No difference at write time |
| Point reads | One path, a few pages | Memtable, then bloom filters, then possibly several files |
| Range scans | Leaves are in key order | Merged across files on the fly |
| Deletes | Remove the entry; space reused later | A tombstone, removed only by compaction |
| Background work | Checkpoints, VACUUM or purge | Compaction, which can use a lot of I/O |
| Used by | PostgreSQL, InnoDB, WiredTiger, SQL Server, Oracle | Cassandra, 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.
-- 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
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.
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?
The memtable, after the write is appended to the commit log (WAL) on disk. Nothing else on disk is read or rewritten at write time.
2. What does an LSM tree do with a delete?
SSTables are immutable, so a delete is a new record. Too many tombstones slow reads until compaction clears them.
3. Which engine family suffers most from random primary keys at insert time?
Random keys scatter inserts across B-tree pages: more reads, more splits, half-empty pages. An LSM tree sorts in memory, so key order does not matter at write time.
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.