Lesson 13 of 38Data internals
How Databases Store Data
Pages, the write-ahead log, B-trees, LSM trees, and column stores: what happens on disk when you write a row, and why it decides what a database is good at.
The building blocks treated the database as one box with a few dials. This unit opens the box. Your team runs an events table in Postgres. It started at a few hundred inserts per second and now takes 40,000. Write latency is climbing, and someone suggests moving the table to Cassandra "because it is fast at writes". Is that true, and why? The answer is in the storage engine: the part of the database that decides how bytes are laid out on disk. Once you know the two main designs, you can predict which workloads a database will love and which will hurt it, and you can answer "what happens to a write when the server loses power?"
Pages, not rows
A database never reads one row from disk. It reads a page: a fixed-size block that holds many rows. Postgres uses 8 KB pages. MySQL's InnoDB uses 16 KB pages by default. SQLite defaults to 4 KB. To return one 200-byte row, the engine reads the whole page that contains it.
Pages are cached in memory in the buffer pool (Postgres calls it shared_buffers, InnoDB calls it the buffer pool). A query that finds its pages there never touches the disk. A query that misses waits for I/O. Much of database tuning is really about keeping the hot pages in that pool.
The other cost that drives every design below is random vs sequential I/O. Writing pages scattered across the disk is slower than streaming through them in order. On spinning disks the gap was about a hundred times. SSDs shrink it, but sequential writes are still kinder to the drive's internal garbage collection and mean fewer, larger I/O calls. Storage engines are mostly clever ways to turn random writes into sequential ones, or to make random reads rare.
The write-ahead log
Here is the problem. A transaction updates three pages. The server loses power after the first page is written. Now the data on disk is half old and half new, and nothing tells you which.
The fix is the write-ahead log (WAL). Before changing any data page, the engine appends a record of the change to the end of a log file and forces it to disk with fsync. Only then does it report the commit as done. The data pages themselves are updated in memory and written back lazily, later, in the background.
- Append "set balance of account 7 to 90" to the WAL. Sequential write, cheap.
fsyncthe WAL. Now the change is durable.- Reply "COMMIT" to the client.
- Some time later, a checkpoint writes the dirty pages to their real places and marks the log position up to which everything is safe.
After a crash, the engine reads the WAL from the last checkpoint and replays every committed change. Pages that were half written get rebuilt. Postgres calls this file the WAL. InnoDB calls it the redo log. Cassandra calls it the commit log. Same idea.
The fsync in step 2 is the expensive part, because the disk must confirm the bytes are really stored. That is the knob databases expose:
- Postgres
synchronous_commit = offreplies before the WAL is flushed. A crash can lose the last fraction of a second of commits, but the database is never corrupted. Good for analytics events, wrong for payments. - InnoDB
innodb_flush_log_at_trx_commit = 1(the default) flushes on every commit. Setting2or0trades the same kind of durability for speed. - Group commit is the trick that makes
fsyncaffordable: many concurrent transactions share one flush.
One log, many readers
Because the WAL is an ordered record of every change, other systems read it too. Replication in Postgres and MySQL ships the log to followers, as you saw in Replication and Sharding. Change data capture (CDC) tools such as Debezium read the same log through Postgres logical decoding (or the MySQL binlog) and publish each change to Kafka, so search indexes and caches stay in sync without the app writing to both.
The commit is durable the moment the WAL record is flushed. No data page has been written yet.
B-trees: update in place
The first big design is the B-tree (strictly a B+tree in most databases: all rows or row pointers live in the leaves, and the leaves are linked in key order). Postgres indexes, InnoDB tables and indexes, SQLite, SQL Server, and Oracle all use them. How Indexes Work in the SQL & Databases course shows how a query walks one; this section is about what a write does to it.
Each node is one page. An internal page holds hundreds of keys and child pointers, so the fan-out is huge. With 500 children per page, three levels reach 125 million leaf pages, so a lookup touches three or four pages, and the top levels are almost always in the buffer pool. The databases lesson showed this as a depth table. Here is the part it skipped:
- Writes go to one place. To update a key, the engine finds its leaf page and changes it in place (logging the change to the WAL first). That is a random write.
- Page splits. When a leaf is full, the engine splits it into two half-full pages and adds a pointer in the parent. Splits can ripple upward. Inserting keys in random order causes splits all over the tree and leaves pages half empty. Inserting in increasing order fills the rightmost page and moves on. You will see why this matters in Generating Unique IDs.
- Range scans are cheap. Leaves are sorted and linked, so
WHERE created_at BETWEEN ...walks neighboring pages.
A B-tree page holds 400 child pointers. How many leaf pages can a tree with 3 levels of internal pages point to?
print(f"{400 ** 3:,}")LSM trees: never update in place
The second design is the log-structured merge tree (LSM tree), used by Cassandra, ScyllaDB, RocksDB, LevelDB, HBase, and many systems built on RocksDB (CockroachDB uses Pebble, a RocksDB-style engine). It refuses to do random writes at all.
- A write is appended to the commit log (the WAL) for durability.
- It goes into the memtable, a sorted structure in memory.
- When the memtable is full (tens of MB), it is written out as an SSTable (sorted string table): an immutable, sorted file. One big sequential write.
- Updates do not modify old files. A newer SSTable simply holds a newer value for the same key.
- Deletes write a tombstone, a marker that says "this key is gone".
- In the background, compaction merges SSTables, keeps the newest value per key, drops overwritten values and expired tombstones, and writes fresh files.
Reads pay for this. A key might be in the memtable or in any SSTable, so a read checks newest to oldest. Two things keep that cheap: each SSTable carries a Bloom filter that answers "definitely not here" for most files without touching disk, and a sparse index that points to the right block within a file.
Compaction has two classic strategies:
| Strategy | How it works | Good at | Cost |
|---|---|---|---|
| Size-tiered | Merge several SSTables of similar size into one bigger one | Write-heavy loads; low write amplification | A key can live in many files, so reads check more; needs lots of spare disk during big merges |
| Leveled | Each level is about 10x the previous; files in a level do not overlap | Reads (about one file per level) and space | Rewrites data many times on its way down, so higher write amplification |
RocksDB defaults to leveled compaction. Cassandra has offered both for years and added a unified strategy in 5.0 that can behave like either; check the docs for the version you run.
Run a toy version of both engines. Same 12 writes plus a delete.
Press Run (⌘ Enter) to see what happens.The B-tree did 12 random writes, each rewriting a whole page. The LSM did a few sequential file writes, but a read had to check three files until compaction merged them, and compaction itself wrote data a second time. Neither is free. They pay in different places.
The three amplifications
Engineers compare engines with three numbers:
- Write amplification: bytes written to disk per byte the app wrote. A B-tree rewrites an 8 KB page to change a 100-byte row (plus the WAL record, plus sometimes a full page image after a checkpoint). An LSM writes each value once to the log, once on flush, then again on every compaction it passes through.
- Read amplification: pages or files touched per lookup. A B-tree is about one page per level. An LSM may check the memtable and several SSTables, softened by Bloom filters.
- Space amplification: disk used per byte of live data. B-trees waste space in half-full pages after splits. LSMs hold old versions and tombstones until compaction removes them.
| B-tree | LSM tree | |
|---|---|---|
| Optimized for | Reads, mixed OLTP | Heavy writes and ingest |
| Write pattern | Random, in place | Sequential, append only |
| Point read | Predictable, few pages | Memtable plus several files, helped by Bloom filters |
| Range scan | Excellent | Good, but merges several files |
| Latency surprises | Page splits, checkpoints | Compaction stalls, tombstone buildup |
| Typical users | Postgres, MySQL, SQLite | Cassandra, ScyllaDB, RocksDB, HBase |
So, back to the events table. Cassandra is fast at writes because a write is a log append plus a memory insert. No page is read, nothing is updated in place, and the merging happens later in the background. The price is paid on reads, disk space, and running compaction. For time-series or log ingest read by key, that is a good trade. For an orders table with joins and transactions it is not, and the first move is cheaper anyway: batch inserts, drop unused indexes, and partition the table by time.
Match each symptom to the storage-engine mechanism behind it.
Rows vs columns
Everything so far stores data row by row: all columns of a row sit together in one page. That is right for OLTP (online transaction processing): fetch order 812, update one customer, insert one event.
Analytics asks a different question: "average order value by country for last year" reads two columns out of thirty, across a billion rows. A row store must read every page, including the 28 columns it does not need.
A column store keeps each column in its own file or segment. The query reads only country and amount. Values in one column look alike, so they compress extremely well (run-length and dictionary encoding often shrink data by 5 to 10 times or more), and the engine can run vectorized execution: tight loops over batches of thousands of values, often using SIMD instructions. Parquet files, ClickHouse, BigQuery, Snowflake, Redshift, and DuckDB all work this way.
The cost: updating one row touches many column files, so column stores want large batches. This is why analytics belongs in a separate store fed by CDC or batch exports, not in heavy reports on your production primary.
MVCC: why old versions stick around
One more thing lives in the storage layer: multi-version concurrency control (MVCC). Instead of overwriting a row while someone might be reading it, the engine keeps old versions so readers see a consistent snapshot and do not block writers. The two big engines do it differently:
- Postgres writes every
UPDATEas a brand-new row version in the table and marks the old one dead. Dead versions stay until VACUUM (usually autovacuum) reclaims the space. A table with heavy updates and lagging autovacuum grows bloat: more pages to scan for the same live data. - InnoDB updates the row in place and keeps the previous version in an undo log, which a background purge cleans up.
Either way, one long-running transaction forces the engine to keep every old version it might still need, which is how a forgotten open session makes tables swell for hours. Isolation Levels and Anomalies in the SQL & Databases course covers snapshots and isolation levels properly.
What actually happens on a Postgres UPDATE
Postgres finds the current row version (a tuple) in the heap page. It writes a new tuple with the new values, stamps the old one with the id of the updating transaction (xmax), and writes a WAL record for both. If any indexed column changed, or there is no room on the same page, every index on the table gets a new entry pointing at the new tuple. When no indexed column changed and the page has space, a HOT (heap-only tuple) update skips the index writes. Leaving free space in pages with a lower fillfactor makes HOT updates more likely on update-heavy tables. This is why "index fewer columns" helps write throughput in Postgres in a way that is easy to miss.
Put the life of one write to an LSM store in order.
- Tap the steps below in the right order.
- page
- The fixed-size block (8 KB in Postgres, 16 KB in InnoDB) that a database reads and writes. Never a single row.
- write-ahead log (WAL)
- An append-only log of changes, flushed before a commit is acknowledged, replayed after a crash. Also feeds replication and CDC.
- B-tree
- A wide, shallow sorted tree of pages, updated in place. Fast, predictable reads and range scans. Used by most relational databases.
- LSM tree
- A memtable plus immutable sorted files (SSTables) merged by compaction. Turns writes into sequential appends at the cost of extra read and background work.
- compaction
- Background merging of SSTables that keeps the newest value per key and removes overwritten data and expired tombstones.
- write amplification
- Bytes physically written to disk for each byte the application wrote.
- column store
- Storage that keeps each column together, so analytics reads only the columns it needs and compresses well.