DB·58
Storage Engine Internals
What a database actually does with your rows. Covers pages and the slotted-page layout, heap storage versus clustered (index-organised) tables, tuples and TOAST, B-trees and B+trees with splits and fill factor, HOT updates, hash, GIN, GiST, SP-GiST and BRIN indexes, the buffer cache and its replacement policy, the write-ahead log with LSNs, checkpoints and torn-page protection, and the LSM-tree alternative used by RocksDB, Cassandra and friends. PostgreSQL and InnoDB are compared throughout.
Start here: pages, trees and logs
Everything is a page
A database stores data in fixed-size pages (PostgreSQL: 8 KB; MySQL InnoDB: 16 KB; SQLite: 4 KB), because disks and the operating system move data in blocks and a page is the unit the database caches, locks, logs and reads. A million orders:
CREATE TABLE orders_s (id bigint PRIMARY KEY, customer_id int, total_paise int, placed_at timestamptz);
INSERT INTO orders_s SELECT g, 1 + g % 50000, (g * 37) % 50000, timestamptz '2026-01-01' + (g || ' seconds')::interval
FROM generate_series(1, 1000000) g;
table_size | pages | rows_per_page
------------+-------+---------------
50 MB | 6370 | 156
lp | lp_off | lp_len | t_ctid | t_hoff ← the first rows of page 0
----+--------+--------+--------+--------
1 | 8144 | 48 | (0,1) | 24
2 | 8096 | 48 | (0,2) | 24
3 | 8048 | 48 | (0,3) | 24
Each row is 48 bytes: a 24-byte header (t_hoff; the MVCC fields of chapter 57 live here) plus 24 bytes of data, stored from the end of the page backwards (offsets 8144, 8096, 8048…), while an array of pointers grows from the front. The table is called the heap: rows sit wherever there's room, in no particular order.
Finding one row: the B-tree
index_size | btree_levels_above_leaves
------------+---------------------------
21 MB | 2
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders_s WHERE id = 765432;
Index Scan using orders_s_pkey on orders_s (actual rows=1 loops=1)
Index Cond: (id = 765432)
Buffers: shared hit=7
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM orders_s WHERE total_paise = 4242;
Parallel Seq Scan on orders_s (actual rows=7 loops=3)
Filter: (total_paise = 4242)
Rows Removed by Filter: 333327
Buffers: shared hit=6370
Execution Time: 29.659 ms
The primary-key index is a B-tree: a sorted, balanced tree of pages. The root page holds a few hundred keys that divide the key range; each points to a page dividing its sub-range more finely, down to leaf pages holding every key with the address (ctid) of its row. Because each page holds hundreds of keys, the tree is very shallow: three levels for a million rows, still three for ten million in the lab (four for a few billion). Finding order 765432 touched 7 buffers; the unindexed filter on total_paise touched all 6,370 pages of the table. That ratio, a handful of pages versus all of them, is why indexes matter, and why "is there an index for this WHERE?" is the first question about any slow query.
The cost: every insert must also put its key in the right leaf (splitting full pages), every index takes space (21 MB here, almost half the table), and random keys scatter writes across the tree (chapter 55's UUID experiment).
Other index types
| Type | Structure | Good for | Example |
|---|---|---|---|
| B-tree (default) | Sorted tree | Equality, ranges, sorting, prefixes | WHERE id = 42, ORDER BY placed_at |
| Hash | Hash table | Equality only | rarely better than B-tree |
| GIN | Inverted index: value → rows | Containment in arrays, jsonb, full text, trigrams |
tags @> '{veg}', doc @> '{"city":"Chennai"}' |
| GiST / SP-GiST | Generalised search trees | Geometry, ranges, nearest neighbour, exclusion constraints | WHERE location <-> point(…), no overlapping bookings |
| BRIN | Min/max per block range | Huge tables physically ordered by the column | timestamps in an append-only log |
Two ways to write: update in place, or append
B-trees update pages in place (in the buffer cache, with the change also in the WAL). A very different design, the log-structured merge-tree (LSM), never modifies files: writes go to an in-memory table, which is flushed to disk as an immutable sorted file when full, and background compaction merges files into larger ones. RocksDB (inside many systems, including CockroachDB, TiKV and Kafka Streams), Cassandra, ScyllaDB and LevelDB work this way:
1M random-key writes: 3.52 s (284,341/s)
Level Files Size(MB)
--------------------
0 4 3 ← recently flushed files
6 1 7 ← merged, sorted, compressed
LSMs turn random writes into sequential ones and compress well, which makes them excellent for write-heavy workloads; the price is that a read may have to check several files (helped by in-memory Bloom filters) and that compaction keeps rewriting data in the background. The lab measures both sides: 10× faster random writes than a B-tree, and slower point reads.
How deep to go in storage engines
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain pages, heaps, B-trees and LSM-trees |
| L2 | Choose index types (B-tree, GIN, GiST, BRIN) and read buffer counts in plans |
| L3 | Explain page layout, B-tree splits and fan-out, buffer management, WAL and checkpoints, LSM compaction and amplification |
| L4 | Diagnose bloat, wrong index types, padding waste and engine-specific write or read amplification |
| L5 | Choose storage engines and physical designs for workloads (OLTP, write-heavy, analytical) |
| L6 | Tune and operate storage at scale (hardware, filesystems, compaction policies, capacity) |
Pages and rows
Why pages
Disks and SSDs read and write in blocks, and the OS caches files in pages. Databases therefore organise everything (tables and indexes) into fixed-size pages: 8 KB in PostgreSQL and SQL Server, 16 KB by default in InnoDB, and 4 KB by default in SQLite (configurable). A page is the unit of I/O, caching, locking (in some engines) and WAL logging. Performance is largely about how many pages a query touches, which is why EXPLAIN (BUFFERS) counts pages (Vol. 1 ch. 7–8 covers the memory and storage hierarchy).
The slotted page
Rows have variable length, so pages use a slotted layout:
- Item pointers (line pointers) at the start of the page point to tuples stored from the end. A row's physical address is the TID,
(block number, item number), and you can see it as the hiddenctidcolumn in PostgreSQL. - Indexes in PostgreSQL store TIDs. Since a tuple can move within a page (compaction) while its line pointer stays put, indexes don't need updating for in-page moves.
- Tuple header overhead: about 23 bytes plus alignment per row in PostgreSQL, so very narrow rows (such as a junction table with two
ints) carry more header than data. Column order affects padding: put 8-byte columns before 4-, 2- and 1-byte columns to reduce alignment waste. - TOAST (chapter 57) moves large values out of line, so most rows stay small enough for many to fit per page.
Heap tables versus clustered (index-organised) tables
Where do rows live?
| Heap (PostgreSQL, SQL Server heap tables, Oracle default) | Clustered index / index-organised table (InnoDB always, SQL Server with a clustered index, Oracle IOT, SQLite rowid/WITHOUT ROWID) |
|
|---|---|---|
| Row storage | Unordered pages; new rows go wherever there's space | Inside the primary key B+tree's leaf pages, ordered by primary key |
| Primary key index | A separate B-tree mapping key → TID | The table is the PK index |
| Secondary indexes store | TID (physical address) | The primary key value |
| Lookup via a secondary index | Index → TID → heap page (one extra page access) | Secondary index → PK → traverse the clustered B+tree (a second tree descent, called a bookmark lookup) |
| Range scans by PK | Rows scattered (unless CLUSTERed, which isn't maintained) |
Contiguous: very efficient |
| PK choice impact | Small | Huge: random PKs (UUIDv4) cause page splits all over the clustered tree; wide PKs bloat every secondary index |
That's why UUIDv4 primary keys hurt InnoDB more than PostgreSQL. In InnoDB the whole row is inserted at a random position, and every secondary index carries the 16-byte PK. Sequential or time-ordered keys (auto-increment, UUIDv7) append at the right edge of the tree. In PostgreSQL, random UUIDs still scatter the PK index (and hurt its cache locality), but the heap insert is unaffected.
Row stores versus column stores
Row stores (PostgreSQL, MySQL, SQL Server rowstore, Oracle) keep each row's columns together. That's ideal for OLTP: fetch or update whole records by key. Column stores (ClickHouse, DuckDB, Snowflake, BigQuery, Redshift, Parquet files, SQL Server columnstore indexes, Oracle In-Memory) keep each column's values together (Vol. 1 ch. 7's struct-of-arrays):
- Analytical queries (
SELECT sum(amount) … GROUP BY regionover billions of rows) read only the needed columns. - Same-type values compress extremely well (dictionary, run-length, delta encoding).
- Vectorised execution processes batches of values with SIMD.
- Single-row updates and point lookups are expensive.
That split is why OLTP and OLAP are usually separate systems: data flows from PostgreSQL (OLTP) to a warehouse or lakehouse (OLAP) via CDC or ETL. Hybrid "HTAP" systems (TiDB with TiFlash, SingleStore, AlloyDB's columnar engine, pg_duckdb and other columnar extensions for PostgreSQL) try to serve both.
Indexes
B-trees and B+trees
The B-tree (Bayer and McCreight, 1970) is the default index in essentially every relational database. Databases use the B+tree variant:
- Internal nodes hold only keys and child pointers, so they're compact and a node (page) holds hundreds of keys: high fan-out.
- Leaf nodes hold all keys with their row pointers (or the rows themselves, in clustered indexes), and are linked to their neighbours for fast range scans.
- The tree is balanced: every leaf is at the same depth.
Properties that matter in practice:
- Height is tiny: with about 300 entries per 8 KB page, three levels index about 27 million keys and four levels about 8 billion. Upper levels stay in cache, so a lookup costs roughly one or two real page reads.
- Ordered: B-trees support
=,<,>,BETWEEN,ORDER BY(in either direction without sorting),LIKE 'prefix%'(with a suitable collation ortext_pattern_ops),IS NULL, and min/max. - Multicolumn indexes are sorted by the first column, then the second, and so on, like a phone book (last name, first name). They help queries that constrain a leftmost prefix (chapter 60). PostgreSQL 18's skip scan relaxes this for low-cardinality leading columns.
- Page splits: inserting into a full leaf splits it in two and adds a separator to the parent. Random-key inserts split pages everywhere, leaving them about half full (and writing more WAL). Increasing keys always fill the rightmost page, which databases optimise to split unevenly (fastpath).
- Fill factor leaves free space in pages (
WITH (fillfactor = 90)) for future updates. For heap pages in PostgreSQL, that space enables HOT updates (below). - Deduplication (PostgreSQL 13+) stores repeated keys once with a list of TIDs, which makes low-cardinality indexes much smaller. Bottom-up deletion (14+) removes obsolete versions proactively to avoid splits.
- Bloat: deleted and updated entries leave space that's reused but not returned.
REINDEX CONCURRENTLYrebuilds a bloated index online.
Index-only scans and covering indexes
If an index contains all columns a query needs, the database can answer from the index alone:
CREATE INDEX orders_customer_created_incl ON orders (customer_id, created_at DESC) INCLUDE (status, total_cents);
-- INCLUDE columns are stored in leaf entries but aren't part of the search key (PG 11+, SQL Server)
SELECT created_at, status, total_cents FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20;
-- → Index Only Scan: no heap access … in PostgreSQL, IF the visibility map says those pages are all-visible
PostgreSQL's MVCC twist: an index entry doesn't know whether its row version is visible to your snapshot, so an index-only scan must check the visibility map. Only pages marked all-visible (set by VACUUM) can skip the heap visit (Heap Fetches in EXPLAIN shows how many couldn't). Frequently updated tables that aren't vacuumed promptly get fewer index-only scans. In InnoDB, secondary indexes include the PK, so "covering" means the index columns plus the PK cover the query.
HOT updates
In PostgreSQL every UPDATE creates a new tuple version. Normally that requires new entries in every index of the table, even indexes on unchanged columns, because the new version has a new TID. That's a big write-amplification cost for wide, heavily indexed tables. Heap-Only Tuple (HOT) updates avoid it when:
- No indexed column changed, and
- the new version fits on the same page.
Then the new version is chained from the old one within the page. Indexes still point to the old line pointer, which redirects to the newest version, so no index writes are needed, and the chain is pruned later. Implications:
- Don't index columns that change constantly (
updated_at, counters, status fields on hot rows) unless you query by them. Each such index disables HOT for every update touching that column. - Use a lower fill factor (say 70–90) on update-heavy tables to leave room on each page.
- Monitor
n_tup_hot_updversusn_tup_updinpg_stat_user_tables.
InnoDB updates rows in place (old versions go to undo), and secondary indexes change only when their columns change. That's a different trade-off: no HOT needed, but undo and purge costs instead.
Other index types
| Index | Structure | Supports | Typical uses |
|---|---|---|---|
| Hash | A hash table on disk (WAL-logged and crash-safe since PostgreSQL 10) | Equality only | Rarely better than a B-tree; may be smaller for long keys. MySQL's MEMORY engine and InnoDB's internal adaptive hash index |
| GIN (Generalised Inverted iNdex) | An inverted index: each element (array item, JSON key/value, lexeme, trigram) → a list of rows containing it | "Contains" queries: @>, ?, &&, @@ full-text, trigram LIKE '%x%' |
jsonb, arrays, full-text, pg_trgm. Slower to update (fast-update pending lists help); excellent for reads |
| GiST (Generalised Search Tree) | A balanced tree of bounding predicates (like R-trees: each node covers a region) | Overlap, containment, distance (k-nearest-neighbour ORDER BY point <-> $1), ranges, geometry |
PostGIS geometry, range types, exclusion constraints, full-text (lossy) |
| SP-GiST | Space-partitioned trees (quad-trees, k-d trees, radix tries) | Non-balanced partitioned data | IP addresses, points, text prefixes |
| BRIN (Block Range INdex) | Stores min/max (or a summary) per range of pages (128 by default) | Range queries on columns correlated with physical order | Huge append-only tables (time-series, logs) where created_at increases with insertion order. Tiny: kilobytes for terabytes. Useless if values are randomly distributed |
| Bloom (extension) | A Bloom filter signature per row | Equality on any combination of many columns | Wide tables with arbitrary multi-column filters |
| pgvector HNSW / IVFFlat | Graph or cluster-based approximate nearest neighbour indexes | Vector similarity (<->, <=>) |
Embeddings and semantic search (chapter 63) |
CREATE INDEX events_created_brin ON events USING brin (created_at) WITH (pages_per_range = 64);
CREATE INDEX docs_body_trgm ON docs USING gin (body gin_trgm_ops); -- fast ILIKE '%term%'
CREATE INDEX places_geo ON places USING gist (location); -- PostGIS: ORDER BY location <-> point LIMIT 10
CREATE INDEX bookings_during ON bookings USING gist (room_id, during); -- with btree_gist
Other index variants every engine offers in some form:
- Partial indexes (
WHERE status = 'PENDING'): small, targeted at hot subsets. SQL Server calls them filtered indexes. - Expression indexes (
lower(email)). - Unique indexes.
- Descending and NULLS ordering in indexes.
- Invisible indexes: MySQL's
INVISIBLEand Oracle's invisible indexes test the effect of dropping an index safely. PostgreSQL has no equivalent; usehypopgfor hypothetical indexes.
Every index has a cost: slower writes (each insert, and non-HOT update, touches every index), more WAL, more storage and cache pressure, and more planner work. Unused indexes are pure cost, so find them with pg_stat_user_indexes.idx_scan = 0 (over a representative period, and remembering replicas have separate statistics).
Memory and durability
The buffer cache
Reading a page from disk takes about 100 µs on an SSD (more on networked cloud storage), while reading it from RAM takes about 100 ns. The buffer pool (PostgreSQL shared_buffers, InnoDB innodb_buffer_pool_size) caches pages in memory:
- A lookup table maps (relation, fork, block) → buffer slot.
- Pinning and locking: a backend pins a buffer while using it (so it can't be evicted) and takes short content locks to read or modify it.
- Dirty pages (modified in memory) are written back later by the background writer or checkpointer, never by the committing transaction (which only flushes the WAL).
- Replacement: PostgreSQL uses a clock-sweep algorithm (an approximation of LRU with usage counts) and ring buffers for large sequential scans and VACUUM, so one big scan doesn't flush the whole cache. InnoDB uses an LRU list split into "young" and "old" sublists with midpoint insertion, for the same scan resistance (the same goal as W-TinyLFU in Vol. 3 ch. 53).
- Sizing: InnoDB is usually configured to use most of RAM (70–80%) because it uses
O_DIRECTand bypasses the OS cache. PostgreSQL uses about 25% forshared_buffersand relies on the OS page cache for the rest (double buffering). PostgreSQL 18's asynchronous I/O work is a step toward direct I/O in the future. - The cache hit ratio (
blks_hit / (blks_hit + blks_read)inpg_stat_database) is useful, but a high ratio can hide queries that touch millions of cached pages. Look at buffers per query too.
The write-ahead log in detail
The write-ahead logging rule: a data page change must not reach disk before the WAL record describing it is durable. With that rule, the database can:
- commit quickly: an append-only sequential WAL write plus one fsync, instead of random writes to many data pages;
- recover after a crash: replay WAL records from the last checkpoint (redo);
- replicate: ship the WAL to standbys (chapter 57).
Mechanics:
- LSN (log sequence number): a byte position in the WAL stream. Every data page records the LSN of the last WAL record that changed it, so redo knows whether a record has already been applied.
- Group commit: concurrent commits share one fsync, which is why throughput scales beyond "one fsync per commit" (
commit_delay/commit_siblingstune it). - Checkpoints periodically write all dirty pages and record a redo point. Recovery starts from there, so more frequent checkpoints mean faster recovery but more I/O, especially full-page writes. PostgreSQL triggers them by
checkpoint_timeout(5 minutes by default) ormax_wal_size, and spreads the writes (checkpoint_completion_target = 0.9). - Torn pages: an 8 KB page written with 4 KB device atomicity can be half-written in a crash. PostgreSQL writes a full-page image into the WAL the first time a page changes after each checkpoint (
full_page_writes), so redo can restore a whole page. InnoDB solves the same problem with the doublewrite buffer. Some filesystems and storage (ZFS, atomic-write SSDs) make these unnecessary. - ARIES (IBM, 1992) is the classic recovery algorithm: write-ahead logging, repeating history during redo, and logging changes during undo. InnoDB, SQL Server and DB2 follow it closely, with redo + undo logs. PostgreSQL's no-overwrite MVCC needs redo only, because aborted versions are simply invisible and cleaned up by VACUUM.
- Logical decoding reads the same WAL to produce row-level change streams (chapter 57).
fsync honesty matters. In 2018 PostgreSQL discovered that on Linux a failed fsync could clear the error and drop dirty pages ("fsyncgate"), so later fsyncs reported success. PostgreSQL now panics and recovers from the WAL on fsync failure rather than trusting a retry. Durability depends on every layer below the database (filesystem, controller caches with battery backing, cloud volumes) honouring flushes.
The LSM-tree alternative
Log-structured merge trees
B-trees update pages in place, so random writes go all over the disk. Log-structured merge trees (LSM trees), from the 1996 paper by O'Neil et al., turn writes into sequential appends:
- Writes append to a commit log (durability) and insert into an in-memory sorted memtable.
- When the memtable is full, it's flushed to disk as an immutable sorted file (SSTable).
- Compaction merges SSTables in the background, discarding overwritten values and tombstones (delete markers). Leveled compaction (RocksDB, LevelDB) keeps each level about 10× bigger with non-overlapping files, for better reads and space. Size-tiered compaction (Cassandra's original default) merges similar-sized files, for cheaper writes but more space and read amplification.
- Reads check the memtable, then the SSTables newest-first, using per-file Bloom filters (a cheap "definitely not here" test) and sparse indexes to skip most files.
The trade-off is described by amplification:
| B-tree (in place) | LSM tree | |
|---|---|---|
| Write amplification | Moderate: whole pages rewritten for small changes, plus WAL and full-page images | Data is rewritten during each compaction level (can be 10–30×), but sequentially |
| Read amplification | Low: one tree descent | Higher: several levels or files may be checked (mitigated by Bloom filters and caching) |
| Space amplification | Fragmentation, about 50–70% page fill after random inserts | Obsolete versions until compaction; leveled is better than tiered |
| Write throughput | Limited by random I/O | Very high (sequential writes) |
| Best for | Read-heavy and mixed OLTP, range scans | Write-heavy workloads: time series, logs, events, large key-value stores, wide-column databases |
LSM-based engines include RocksDB (the embedded engine under many systems: MyRocks for MySQL, CockroachDB's predecessor engine, TiKV, Kafka Streams state stores), LevelDB, Pebble (CockroachDB), Cassandra and ScyllaDB, HBase and Bigtable, and InfluxDB/VictoriaMetrics-style time-series stores. MongoDB's WiredTiger engine, by contrast, uses B-trees. Some engines use other structures again: copy-on-write B-trees (LMDB, Btrfs, CouchDB), Bε-trees (buffered B-trees), and log-structured hash tables (Bitcask).
Engines from the language side
Embedded storage engines are a good way to see these structures from application code:
// Rust: an embedded LSM (RocksDB bindings), or fjall (a native Rust LSM); redb is a B-tree alternative
let db = rocksdb::DB::open_default("/var/lib/app/kv")?;
db.put(b"order:42", serde_json::to_vec(&order)?)?;
let raw = db.get(b"order:42")?;
let iter = db.prefix_iterator(b"order:"); // sorted keys → efficient range and prefix scans
// Go: Pebble (CockroachDB's LSM) or bbolt (a B+tree, single-writer, memory-mapped)
db, _ := pebble.Open("/var/lib/app/kv", &pebble.Options{})
defer db.Close()
_ = db.Set([]byte("order:42"), payload, pebble.Sync) // Sync = fsync the WAL before returning
v, closer, err := db.Get([]byte("order:42"))
// Java: RocksDB JNI (used by Kafka Streams state stores), MapDB, Chronicle Map; H2's MVStore is log-structured
try (var options = new Options().setCreateIfMissing(true);
var db = RocksDB.open(options, "/var/lib/app/kv")) {
db.put("order:42".getBytes(UTF_8), payload);
}
// Zig: TigerBeetle, a financial transactions database written in Zig, uses an LSM forest with
// deterministic, statically allocated memory (no allocation after startup): a striking design study.
/* C: SQLite (a B-tree engine with rollback journal or WAL mode), LMDB (a copy-on-write B+tree), LevelDB (C++) */
sqlite3_exec(db, "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;", 0, 0, 0);
SQLite deserves a mention as the world's most deployed database. It's a single-file, embedded B-tree engine in every phone and browser, with a WAL mode that allows concurrent readers with one writer. It's increasingly used server-side for read-heavy apps and edge deployments (Litestream and LiteFS for replication, libSQL/Turso, Cloudflare D1).
Lab: inside the storage layer
PostgreSQL 16 (with pageinspect), SQLite 3 and RocksDB (through the rocksdict Python binding) on a 2-core machine with an SSD.
Experiment 1: how B-trees stay shallow
B-tree on 1,000 bigint keys: 2 levels (root to leaf), 0.0 MB
B-tree on 1,000,000 bigint keys: 3 levels (root to leaf), 22.5 MB
B-tree on 10,000,000 bigint keys: 3 levels (root to leaf), 224.6 MB
Ten thousand times more keys added one level. A leaf page holds about 400 eight-byte keys with their pointers; an internal page holds a similar number of separators, so three levels reach 400³ ≈ 64 million keys. Since the root and internal pages of a busy index stay in memory, a lookup typically costs one disk read (the leaf) plus the heap page. That's why an indexed lookup takes about the same time on a million rows and on a billion, and why index size (here 22 bytes per key) matters more than depth.
Experiment 2: column order and padding
The same six columns (three boolean, three bigint), a million rows, in two orders:
columns (a, b, c, d, e, f) interleaved: 73 MB, row 72 bytes
columns (b, d, f, a, c, e) big first: 57 MB, row 51 bytes
Each bigint must start at an 8-byte boundary, so a 1-byte boolean in front of one wastes 7 bytes of padding; interleaving cost 21 bytes per row and 28% more disk, cache and I/O for identical data. On wide, large tables, order columns from largest alignment to smallest (bigint/timestamptz, then int, then smallint, then boolean, variable-length types last). It's rarely worth reordering an existing table, but it's free when creating one.
Experiment 3: BRIN versus B-tree
Ten million events, one per second, with a time-ordered column (ts, physically in insertion order) and a column of random timestamps over the same 120 days (rnd). Query: count events in a one-hour window. Parallel query off; best of five:
no index: query 416 ms
brin on time-ordered column: index 32 kB, query 1.50 ms
brin on random-order column: index 32 kB, query 742.04 ms
btree on time-ordered column: index 214 MB, query 0.51 ms
btree on random-order column: index 214 MB, query 0.57 ms
A BRIN index stores only the minimum and maximum value of each block range (128 pages by default): 32 kB for 10 million rows, 6,700× smaller than the B-tree, and nearly as fast on the time-ordered column because only a few block ranges can contain the hour. On the random column every block range spans almost the whole period, so BRIN ruled out nothing, and the query was slower than having no index at all (it scanned the whole table plus the index). BRIN suits append-only data queried by its natural order (logs, events, sensor readings, audit trails); B-trees work regardless of physical order, at a large size cost.
Experiment 4: B-tree versus LSM for random writes
Two million writes with random keys, in batches of 10,000 per commit, then 100,000 random point reads:
2,000,000 random-key writes: SQLite B-tree 51.0 s (39,247/s, file 146 MB) | RocksDB LSM 5.1 s (394,648/s)
100,000 random point reads: SQLite B-tree 0.73 s | RocksDB 1.23 s
RocksDB levels: L0 3 files 33 MB (compaction had not yet merged them)
The B-tree had to find and modify the right leaf page for every random key, so as the tree outgrew the cache, writes became random page updates: 10× slower than RocksDB, which appended each batch to its log and an in-memory table and flushed sorted files sequentially. The reads went the other way: SQLite descended one tree, while RocksDB checked its memtable and several level-0 files (Bloom filters skip most, but not for free) and was 1.7× slower. That's the core trade-off: LSM engines (RocksDB, Cassandra, ScyllaDB, the storage layers of CockroachDB, TiDB and YugabyteDB) win on write-heavy workloads and compress well; B-tree engines (PostgreSQL, InnoDB, SQLite, SQL Server) give predictable reads and simpler space management. Background compaction is the LSM's deferred bill: it will rewrite these files several times as they move down the levels (write amplification of 10–30× is common), consuming disk bandwidth that competes with foreground traffic.
Try it yourself
- Use
bt_page_itemson experiment 1's 10-million-key index to print the root page's first few separator keys. - Insert experiment 3's events in random order and rebuild the BRIN index on
ts. What happens to query time, and what doesCLUSTERdo about it? - Repeat experiment 4 with sequential keys. Which engine benefits more?
- Read RocksDB's
rocksdb.statsproperty after a long write-heavy run and compute its write amplification (bytes written by compaction ÷ bytes written by the application).
Revision sheet: storage engine internals
Key ideas
- Pages: fixed-size blocks (8 KB PostgreSQL, 16 KB InnoDB, 4 KB SQLite) with headers, line pointers and tuples; heap (unordered) vs clustered (InnoDB stores rows in the primary-key B-tree); TOAST for large values; alignment and padding.
- B-trees: sorted, balanced, high fan-out; leaf pages linked for range scans; page splits; deduplication (PostgreSQL 13+); covering indexes (
INCLUDE); index-only scans and the visibility map. - Other indexes: hash, GIN (inverted: arrays,
jsonb, full text, trigrams), GiST/SP-GiST (geometry, ranges, nearest neighbour), BRIN (block ranges), partial and expression indexes. - Buffer management: shared buffers plus the OS page cache (double buffering in PostgreSQL), clock-sweep eviction, dirty pages written by the background writer and checkpointer.
- WAL and recovery: log before data, full-page writes after checkpoints, redo on crash; InnoDB's redo and undo logs and doublewrite buffer.
- LSM-trees: memtable + WAL, flushes to immutable SSTables, levelled or tiered compaction, Bloom filters, tombstones; read, write and space amplification trade-offs (RUM conjecture).
- Column stores: column-wise pages, compression, vectorised execution (chapter 62).
Numbers to remember
- Lab: a B-tree held 10 million keys in 3 levels; interleaved booleans and bigints wasted 28% of a table; a BRIN index was 6,700× smaller than a B-tree but slower than no index on random data; RocksDB took random writes 10× faster than SQLite's B-tree and served point reads 1.7× slower.
- Row header 23–24 bytes; B-tree fan-out ≈ 300–400 for bigint keys.
Pitfalls
- Assuming the heap is ordered (it isn't; use
ORDER BY). - B-tree indexes on everything; BRIN on unordered data.
- Ignoring padding in wide tables; storing large blobs in hot tables.
- Random-key inserts into large B-trees (UUIDv4).
- Choosing an LSM store for read-heavy, latency-sensitive workloads without measuring; ignoring compaction capacity.
Glossary
- Heap: a table's unordered row storage.
- Fan-out: the number of children per B-tree page.
- Page split: dividing a full B-tree page when inserting.
- Memtable / SSTable: an LSM's in-memory buffer / immutable sorted file.
- Compaction: merging LSM files and discarding obsolete entries.
- Write amplification: bytes written to storage per byte written by the application.