Storage engines and indexes: pages, B-trees, LSM-trees, the WAL, index types

How a database keeps rows on disk, survives a crash and finds one row among millions, measured on a real PostgreSQL and a real RocksDB. A child page of Topic: databases. Data as of October 2026. Reading: 42 min, plus 14 in closed details.

The idea in one screen

A storage engine keeps rows in fixed-size pages cached in RAM, makes a commit durable by appending it to a log and flushing that log, and finds rows through an index whose design decides when the write cost is paid: a B-tree pays now, with random in-place page writes; an LSM-tree pays later, by merging sorted files in the background.

Fig. 1: one insert through both engines, in order

  1. Both commit the same way: log, then flush. Each engine appends the change to a sequential log and flushes it; the commit is acknowledged after that flush and nothing else (section 3).
  2. B-tree: change the pages in RAM. The insert changes its table page and one leaf per index in the buffer pool; they are now dirty, and nothing else is written yet.
  3. B-tree: pay at the checkpoint. Where each design pays for its writes: the B-tree at checkpoints (one random 8 KB write per changed page), each page written back to its own place in the table and index files.
  4. LSM-tree: insert into the memtable. The key goes into a sorted table in memory; nothing on disk is read or changed.
  5. LSM-tree: flush now, compact later. A full memtable is written as one sorted file in a single sequential pass. The LSM-tree pays in compaction (every key rewritten once per level it passes through).
  6. Reads go the other way. A B-tree reads about 3 pages from root to leaf; an LSM-tree checks the memtable, then sorted files newest first, skipping most with bloom filters.

Schematic: page, file and key counts in Fig. 1 are drawn to explain; the measured costs are in sections 3, 5 and 7.

You need: the root Topic: databases, Reading sections 1 to 4 (tables, SQL, transactions, why a disk read is slow); what write() and fsync() promise at the operating-system level is Storage and file systems. SQL and keys as a schema question are SQL and data modelling; how the planner chooses an index is Query planning and performance; vector indexes are Vector indexes.

Page
the fixed-size block (8 KB in Postgres) a database reads and writes as a unit.
Buffer pool
the RAM cache of pages.
WAL
write-ahead log: every change appended to a sequential log and flushed before a commit is acknowledged.
Checkpoint
writing every changed page back to its file, so older log can be recycled.
B-tree
a sorted tree of pages, updated in place; the default index.
LSM-tree
log-structured merge-tree: an in-memory table flushed to immutable sorted files that are merged later.
Amplification
bytes written, pages read or bytes stored per unit of useful work (write, read, space).

The running example is the root's chat product: a messages table of a million rows (id, chat_id, role, model, tokens, content, created_at) from the root's script and seed, so the numbers agree: 19,235 pages of 8 KB, 157 MB, a 9.3 MB index on chat_id. measured means on a laptop (Apple M1 Pro, 16 GB, internal SSD, PostgreSQL 16.2 and 18.6, RocksDB through the rocksdict binding, 2026-10-04; a shared machine, so times are plus or minus 30%); illustrative marks drawings made to explain.

PieceThe problem it solvesHow, in one lineWhat it costs
PagesDisks read blocks, not rowsEvery table and index is an array of 8 KB pages; a row lives at (page, slot)Reading one row reads a whole page
Buffer poolDisk is about 1,000 times slower than memoryKeep hot pages in RAM; evict by clock sweepRAM; a working set bigger than RAM changes latency abruptly
Write-ahead log"Saved" must survive a crash; random page writes are slowAppend the change to a log and flush it before acknowledging; write pages laterOne flush per commit (shared by group commit); full-page images after each checkpoint
B-treeFind one key among a billionA sorted tree of pages, hundreds of keys per page: about 4 levels for a billion keysRandom in-place writes; page splits; about 30% empty space under random inserts
LSM-treeWrites faster than a B-tree can absorbBuffer in memory, write sorted files sequentially, merge in the backgroundReads may check several files; compaction rewrites data many times
Index typesNot every question is "equal to" or "between"B-tree by default; GIN for "contains"; GiST and SP-GiST for geometry and ranges; BRIN for huge ordered tablesEach index slows every write and takes space

The one trade-off under all of it: no layout is best at reading, writing and saving space at once (the RUM conjecture), so pick the corner to give up on purpose, then measure it.

The B-tree and LSM lab tab inserts keys into both engines with counters for every page and slot written. The root's Query plans tab measures index against sequential scans, index-only scans, VACUUM and cold against warm cache on 10 million messages; this page links it instead of repeating it.

1. Pages: how a table sits on disk

Disks read blocks, not rows (one random SSD read takes about 100 microseconds, roughly a thousand memory reads), so rows that share a block are fetched for the price of one read. Postgres keeps each table and each index in its own file (messages is base/16384/16460 measured, cut into 1 GB segment files, file layout): an array of 8 KB pages numbered from 0, always read and written whole (page layout). Our million messages fill 19,235 pages; InnoDB uses 16 KB pages and SQLite 4 KB. Each stored row version is a tuple, addressed by its ctid (page, slot): the first message lives at (0,1), and indexes store ctids to jump straight to a page.

Fig. 2: a page fills from both ends. Page 0 of messages, from pageinspect (page_header, heap_page_items) measured

  1. An 8 KB page. Page 0 of messages to scale: 8,192 bytes, drawn as 8 rows of 1,024 from the back. Every table and index file is an array of these, read and written whole.
  2. The header, 24 bytes. The LSN of the last change to the page, a checksum, and two offsets: lower, where free space starts, and upper, where tuples start.
  3. Line pointers grow forward. One 4-byte pointer per tuple, from byte 24: 52 line pointers, 208 bytes, so lower = 232 (24 + 52 x 4, where free space starts).
  4. Tuples grow backward from the end. Slot 1 is at the far end (offset 8,040, 152 bytes) and each new tuple goes just before the previous one: 52 tuples, 7,872 bytes, upper = 320 (where tuples start).
  5. Free space is the gap. 88 bytes between lower and upper; the page is full when they meet. Pages hold between 34 and 58 messages, 52 on average.
  6. A ctid is page plus slot. (0,1) is page 0, line pointer 1, which holds the tuple's offset and length. The 4-byte line pointers let Postgres move a tuple inside its page without changing its ctid, so no index needs updating.
  7. Inside a tuple. A header (xmin 732, xmax 0, t_ctid pointing to itself), then 128 bytes of the row's data; the header is the next paragraph.

Each tuple starts with a 23-byte header (padded to 24): xmin and xmax, the transactions that created and deleted or replaced this version (0 if none), which decide who can see it (MVCC, owned by Transactions and concurrency); t_ctid, its own address or its replacement's; and infomask flags (has nulls, hint bits caching whether xmin and xmax committed). So a message with about 90 bytes of data takes about 120 to 200 bytes on the page, and a single-bigint table uses 36 to 40 bytes per 8-byte value derived (24 + 8, aligned, plus 4).

Explore page 0: click a stripe or a slot to decode it (all 52 slots, the raw pageinspect rows)
Header, 24 bytes52 line pointers, 208 bytesFree, 88 bytes52 tuples, 7,872 bytes

Page size 8,192. Click a stripe; slot 1 is at the far right.

An update is a new tuple

Postgres never overwrites a row in place: an UPDATE writes a new tuple and stamps the old one's xmax. If the new version lands on another page, every index needs a new entry, even when no indexed column changed. A HOT update (heap-only tuple) avoids that: when no indexed column changed and the new version fits on the same page, the old tuple points to the new one and the indexes are untouched (HOT). Predict before you switch: on a full page, where can the new version go?

The same one-row update: on a full page every index gets a new entry; with room on the page, none do

measured PostgreSQL 16.2. Full table: message 60 at (1,8) got xmax = 735 and a t_ctid pointing to (19234,35), the end of the table. Copy with fillfactor = 90 (inserts stop at 90% full, keeping 10% of each page for updates): the old tuple (0,10) was flagged "HOT updated", the new (0,48) "heap only", and n_tup_hot_upd = 1 against 0 on the full table. A lower fillfactor is the standard setting for tables updated often.

HOT over time: dead tuples with and without an index on the updated column (measured on a sibling)

Running Postgres in production (section 5) updated a 100,000-row table 1,500 times a second; with no index on the updated columns, HOT updates and on-the-spot pruning kept dead tuples in the low thousands, under the autovacuum trigger (50 + 0.2 x 100,000 = 20,050); after one index on the updated column (last_message_at), every update was a full one and dead tuples rose to the trigger in a sawtooth measured there.

The visibility map, and big values

The visibility map (_vm) keeps two bits per page, all-visible and all-frozen (VM): VACUUM skips all-visible pages, and an index-only scan can skip the table page only when its bit is set. After a VACUUM, 19,234 of 19,235 pages were all-visible; deleting rows on pages 0 and 1 cleared their bits measured: hence slow index-only scans on a table that is not vacuumed (the root's Query plans tab, case 7). Values over about 2 KB are compressed or moved out of line (TOAST), so SELECT * on long LLM answers pays extra page reads.

Big values (TOAST) and the free space map (depth)

A tuple must fit in a page, so a row wider than about 2 KB has its large values compressed and, if still too big, cut into chunks in a side table: TOAST (threshold "normally 2 kB", values up to 1 GB, TOAST; pglz by default, lz4 since Postgres 14 via default_toast_compression). Two 13 KB assistant answers measured: a repetitive one compressed to 186 bytes and stayed in the page; one of hexadecimal hashes barely compresses, so its 13,199 bytes went to the TOAST table (16 KB). Long LLM answers are this case: SELECT * pays the extra page reads even when you do not need the text.

The free space map (_fsm, one byte per page in 32-byte steps, 56 KB for our 19,235 pages measured) lets an insert find a page with room (FSM). VACUUM keeps it up to date.

What pages cost
One 150-byte row costs a whole 8 KB page, so rows read together should live together (section 8); about 24 + 4 bytes of every row are bookkeeping; updates leave dead tuples that only VACUUM reclaims (Running Postgres in production owns VACUUM tuning).

2. The buffer pool, and the operating system's cache under it

Opening chat 42000 touches about a dozen pages (the root measured 12 for its 6 messages); at about 100 microseconds per SSD read, a busy server would spend its time re-reading the same popular pages, the top of every index and the newest messages. The buffer pool keeps them in RAM: 8 KB slots plus a hash table from (file, page) to slot. In Postgres it is shared_buffers, 128 MB by default; the docs suggest 25% of RAM on a dedicated server and say more than 40% is unlikely to help, "because PostgreSQL also relies on the operating system cache" (resource settings). A hit is a memory lookup; a miss evicts a victim (writing it first if dirty, changed since read) and reads the page in.

Exact least-recently-used order would need a lock on a shared list for every access, so Postgres uses a clock sweep (buffer manager README): each buffer has a usage count, raised by one on every access up to 5 (BM_MAX_USAGE_COUNT in buf_internals.h); a hand walks round the buffers taking one point from each, and evicts the first at zero. Predict: after twenty requests, which pages are still cached?

Fig. 3: the clock sweep, then the real pool

  1. Eight empty buffers. Each has a usage count (the green blocks, 0 to 5) and the hand (red) points at the next buffer to examine. illustrative Eight buffers and a scripted list of requests: the index root and an inner page are asked for often, table pages once each. The rule is the real one.
  2. Requests 1 to 8: misses fill empty buffers. Each table page is read from disk into an empty buffer with usage count 1; the root and the inner page are hit again and climb.
  3. Requests 9 to 15: the pool fills. Every buffer is taken; the root reaches the cap of 5, the inner page 4.
  4. Request 16: the first sweep. The pool is full, so the hand walks round taking one point from each buffer it passes and evicts the first at zero: table page T1, read once. The root and the inner page lose points but survive.
  5. Requests 17 to 22: a page read once is gone after one sweep. Each new table page evicts the next table page that was read once; the index root and the inner page keep surviving because they are used often. In all, 10 hits and 12 disk reads.
  6. The real pool. The real pool has 16,384 buffers at 128 MB. On the real server after a mixed workload, the 611 buffers in use had usage counts 1: 154, 2: 122, 3: 90, 4: 54, 5: 191 measured with pg_buffercache: a quarter touched once, a hot set of 191 (index upper levels, catalog pages) at the cap.
  7. A big scan uses a ring. A private ring of 32 buffers, recycled for the whole table, so the rest of the pool keeps its pages (next paragraph).

A big scan must not flush the cache. A sequential scan of a table larger than a quarter of shared_buffers reuses a private ring of 256 kB (32 buffers); VACUUM uses 2 MB and bulk writes 16 MB (README, freelist.c). On the 157 MB table with a 128 MB pool, after a restart measured: a full scan read all 19,235 pages and left exactly 32 cached; a second scan found those 32 and "read" the other 19,203 again, both in about 74 ms because the operating system's cache served them (the root's Query plans tab, case 8, measures a truly cold read).

That is double buffering: a Postgres read is a normal file read, so the OS keeps its own copy in its page cache (Storage and file systems owns it) and a page can be cached twice. Postgres leans on that, hence the modest 25%.

InnoDB's other road, effective_cache_size, and Postgres 18's asynchronous I/O (depth)

The planner's effective_cache_size (default 4 GB) tells Postgres how much the two caches hold together. InnoDB takes the other road: a large buffer pool (up to 80% of memory on a dedicated server) and, since MySQL 8.4, O_DIRECT on Linux so its reads bypass the OS cache (InnoDB buffer pool, 8.4 defaults). Postgres 18 added asynchronous I/O (io_method, default worker, or io_uring on Linux builds), which lets a scan queue many reads at once (PG 18 release notes).

What the cache costs, and the cliff
RAM. The hit ratio is the strongest single predictor of OLTP latency and it does not degrade smoothly: while the working set (the pages your traffic touches) fits in RAM almost every access is a hit; beyond that a fraction of accesses pay a disk read, a hundred to a thousand times slower, and p99 latency changes character. Watch blks_hit against blks_read in pg_stat_database.

3. The write-ahead log: what is written, when, and what it costs

A commit must survive a power cut the moment the database says "saved", but writing every changed page in place at commit means several random writes, and a crash halfway leaves some pages new and some old. So every change first becomes a WAL record (subsystem, page, just enough bytes to redo it) appended to one sequential stream, the write-ahead log, kept as 16 MB files in pg_wal/. A record's byte position is its LSN (log sequence number, such as 0/111CFEA0). Each page header stores the LSN of the last record that changed it, and a dirty page may not be written until the log is flushed up to that LSN: the whole "write-ahead" rule (WAL internals). One new message, read back with pg_walinspect (page images off) measured:

RecordBytesWhat it says
Heap INSERT135put this tuple in page 8132 of messages
Btree INSERT_LEAF64add id 1000001 to the primary-key leaf page 2744
Btree INSERT_POST66add this ctid to chat 42000's existing entry in the chat_id index (a posting list, section 5)
Transaction COMMIT34transaction committed
Total299about twice the size of the row itself

Fig. 4: the same insert, in order

  1. Three pages change in RAM. The insert puts the tuple in page 8132 of messages and adds entries to primary-key leaf 2744 and chat_id leaf 478, all in the buffer pool; nothing is written to disk yet.
  2. One record per change goes to the log. The four records of the table above, 299 bytes in all, appended to the WAL buffers in memory. Bar height is bytes.
  3. The commit flushes the log, then answers. The WAL is written to its 16 MB file in pg_wal/ and flushed; only then does the client get COMMIT. That flush is the cost of a commit: 6.0 ms per single-client commit on this laptop (below).
  4. The pages wait in RAM. Each page header stores the LSN of the last record that changed it, and a dirty page may not be written until the log is flushed up to that LSN.
  5. A checkpoint writes them back. Later, each dirty page is written to its own place in its file: three random 8 KB writes for one insert. Then older log can be recycled.
  6. After a checkpoint, the first change logs the whole page. The same insert just after a CHECKPOINT logged 8,202 + 1,873 + 7,529 + 34 = 17,638 bytes, 59 times as much: three full-page images. Why, next.

Checkpoints, and why the first change after one is expensive

A checkpoint writes every dirty page to its file and records "everything before this LSN is on disk", so older WAL can be recycled and recovery starts there; Postgres starts one every checkpoint_timeout (5 minutes) or after max_wal_size (1 GB) of WAL, spread over 90% of the interval (checkpoint_completion_target 0.9, WAL settings); setting them in operation, and why pg_wal/ grows, is Running Postgres in production section 1. The subtle part: disks write 512-byte or 4 KB sectors, so a power cut during an 8 KB page write can leave a torn page, half new and half old, that no small delta can repair. So with full_page_writes on (the default) the first change to each page after a checkpoint logs the whole page, a full-page image (FPI), and later changes only deltas (full_page_writes; InnoDB uses a doublewrite buffer instead). Predict: 1,000 updates of random rows right after a checkpoint, how much WAL?

They wrote 19.3 MB of WAL, 50 times the 0.39 MB without page images, and 0.50 MB when repeated once those pages had been imaged. Access pattern matters more than settings: writes on few pages (appends, inserts in key order) pay few images; writes scattered over many pages pay one per page per checkpoint. wal_compression = pglz cut it to 6.2 MB (lz4 and zstd since Postgres 15). Longer checkpoint intervals mean fewer images but more WAL to replay after a crash.

Scattered writes after a checkpoint pay one whole-page image per page: 50 times the WAL

measured PostgreSQL 16.2, the 1M-message table with its primary key and chat_id index. Top: one insert just after a CHECKPOINT, page images off and on (the 17,638 bytes are three page images, with the empty middle of each page left out, plus the commit). Bottom: 1,000 updates of random messages (977 different table pages) just after a CHECKPOINT, then the same 1,000 again.

Do not turn full_page_writes off
The docs warn that turning it off "might lead to either unrecoverable data corruption, or silent data corruption, after a system failure". It is safe only on storage that guarantees atomic 8 KB writes (for example ZFS, which is copy-on-write). Use wal_compression and checkpoint tuning instead.

fsync, group commit and synchronous_commit

write() only copies bytes into the OS page cache; fsync() (or fdatasync(), Postgres's default on Linux, wal_sync_method) waits until the device says they are stored. A commit waits for the WAL flush and nothing else; the checkpointer and background writer write data pages later. One flush covers everything written before it, so transactions committing together share it: group commit ("one fsync of the WAL file may suffice to commit many transactions", WAL introduction; commit_delay can wait a few microseconds to gather more). synchronous_commit = off acknowledges before the flush: a crash can lose the last transactions, at most three times wal_writer_delay (3 x 200 ms), but it "does not create any risk of database inconsistency"; they vanish whole (synchronous_commit).

With the flush, one client waits 6 ms per commit, so at most about 165 commits a second; 32 clients share flushes and reach 2,603 (16 times more for 32 times the clients); without waiting, 7,504 and 71,439. Choose per transaction: SET LOCAL synchronous_commit = off for a page view or a token-usage event, never for spending credits. The other values (local, remote_write, remote_apply) set how long a commit waits for replicas (Running Postgres in production owns replication).

The flush, not the update, is the cost of a commit; 32 clients share it

measured pgbench, 20 s per run, each transaction one UPDATE of a random user's credit row, real flushes (on macOS the default does not empty the drive's own cache; fsync_writethrough does, and was used), loopback connection. The root measured the same shape with pgbench's default script: 148 and 2,133 per second with the flush.

Correction to the old page
The old page said stable storage is "10,000 times slower than memory" and put an enterprise-SSD fsync at "0.1 to 1 ms". It depends on the hardware: an SSD with power-loss protection acknowledges a flush in about 1.6 to 12 microseconds (its capacitor-backed cache counts as stable), a consumer SSD takes about 0.9 to 3 ms, network block storage about 0.7 ms (the root's notes and the system design page's Numbers to know tab). This laptop: 6.0 ms per single-client commit measured.
The same log, reused: replicas, point-in-time recovery, change data capture (links)

The same log is reused far beyond crash safety: shipped to another server it keeps a replica current; replayed to a chosen moment it restores a backup to that moment (point-in-time recovery); decoded by another program it becomes a stream of changes (change data capture, as Debezium does). Redo log, journal, binlog, commit log and oplog are the same idea in other products. Running Postgres in production owns backups and replication; Queues, streams and async work owns change data capture.

When fsync fails: the 2018 Linux surprise and Postgres's PANIC (depth)

In 2018 PostgreSQL developers found that on Linux a failed fsync could drop the dirty pages and report success on the next call, so "retry the fsync" could silently lose data (LWN, "PostgreSQL's fsync() surprise", 2018-04-18; the kernel side is Storage and file systems). Since the February 2019 minor releases (11.2 and the back branches), Postgres instead stops with a PANIC on a failed data-file flush and recovers from the WAL on restart; data_sync_retry (default off) controls it (error handling settings, 11.2 notes).

Recovery replays the log forward from the checkpoint's redo point until the first broken record


PostgreSQL 16.2, 2026-10-04. Redo starts at 0/111CFEA0 and the log ends at 0/119D8C88, 8,227 kB later (in the drawing, orange records carry page images and green ones deltas, an illustrative mix: most of these records carried page images; the checkpoint itself was logged at 0/111CFF50, just after its redo point). The LSN comparison of step 3 makes replay safe to repeat if the server crashes again during recovery (xlogutils.c).

4. Crash recovery, step by step, on a real crash

We took a checkpoint, inserted 1,000 messages in one committed transaction, killed the server with kill -9 and restarted it measured. The rows went into gaps on many old pages, so they generated 8.4 MB of WAL, mostly page images. Step through what the server did; highlighted lines are what it printed.

  1. Notice the crash. On start Postgres reads the control file pg_control, sees the server was not shut down cleanly, and finds the last checkpoint record ("database system was interrupted ... automatic recovery in progress").
  2. Go to the redo point. The checkpoint record names the LSN from which changes might be missing from the data files: "redo starts at 0/111CFEA0" (WAL internals: "performs the REDO operation by scanning forward from the WAL location indicated in the checkpoint record").
  3. Replay each record. A record with a full-page image overwrites the page with it, which also repairs a torn page. A delta record is applied only if the page's stored LSN is older than the record's; otherwise the change is already on disk and is skipped.
  4. Find the end of the log. Each record carries a CRC checksum; the first record that is missing or fails its check marks the end: "invalid record length at 0/119D8C88: expected at least 24, got 0" is the normal end, not an error. Transactions whose commit record was not reached never become visible.
  5. Checkpoint and open. An end-of-recovery checkpoint wrote the 1,015 pages the replay had rebuilt, and the server accepted connections. All 1,000 committed rows were there; the restart took 0.22 seconds for 8.4 MB of log.
What recovery costs
Time proportional to the WAL written since the last checkpoint: a max_wal_size of tens of GB on a write-heavy server means minutes of replay, the other side of fewer checkpoints and fewer page images. Recovery protects committed transactions against a crash, not against a lost disk or a bad DELETE: that takes backups and replicas.

5. B-trees: the default index

Chat 42000's 6 messages are scattered over 19,235 pages; without an index the database reads every page (the root measured 19,349 page reads and 28 ms). A B-tree (strictly a B+tree, the variant relational databases use) reaches them in a handful of reads, stays correct under concurrent inserts, and also answers "between" and "in order". Its nodes are pages: leaf pages hold the keys in sorted order, each with its row's ctid, linked to their right neighbour so a range scan walks sideways; internal pages hold separator keys and downlinks ("keys below 25,047 are under page 3"); the root is the page at the top, and page 0, the metapage, says where it is.

Fig. 5: finding chat 42000, then a split

  1. Three levels. The chat_id index on the million messages. The metapage (page 0) says the root is page 289, at level 2, so the tree has 3 levels: the root, 4 internal pages and 1,130 leaf pages (one tile here stands for about 28).
  2. Root (page 289): 4 entries. Separators 25,047, 50,199 and 75,331 split the key space in four; 42000 falls in the second range, so go to page 288.
  3. Internal page (page 288): 285 entries, each a separator and a downlink; binary search leads to leaf page 478.
  4. Leaf page (page 478): 92 entries. Key 42000 appears once, followed by a list of 6 ctids: (7973,10), (8004,13), (8077,46), (8146,16), (8202,45), (8240,8).
  5. Table pages: 6 different pages, one per message, because the chat's messages arrived at different times: 3 index pages and 6 table pages instead of 19,235 (drawn by page number, 140 pages to a row).
  6. A full leaf splits. illustrative A new page takes the upper half of a full leaf and the parent gets a separator for it; a full parent splits too, and a root split adds a level, so every leaf stays at the same depth.
  7. Key order decides how full the leaves are. The same million bigint keys made a primary key of 2,733 leaf pages, 90% full, when inserted in order, and 3,760 pages, 66% full, in random order (measured, below).

measured the 1M-row chat_id index, from pageinspect (bt_metap, bt_page_stats, bt_page_items); keys are stored little-endian: bytes d7 61 00 00 00 00 00 00 are 0x61d7 = 25,047.

List the real entries of each page on the path (pageinspect rows)
Concurrency: high keys and right links (Lehman and Yao) (depth)

Postgres follows Lehman and Yao's 1981 design: each page also stores a high key (an upper bound for its contents) and a right-sibling link, so a reader that arrives at a page just split can step right instead of waiting for a lock (nbtree README).

Fan-out: why a billion rows need about four levels

The children per internal page, the fan-out, keeps the tree shallow. A bigint entry is an 8-byte header plus the key, rounded up to 8 bytes, plus a 4-byte line pointer: 20 bytes. A page has 8,152 usable bytes (8,192 minus a 24-byte header and a 16-byte trailer), so about 407 entries fit; Postgres fills leaves to 90% when it builds an index or appends at the right edge (367 entries) and internal pages to 70% (about 285) (B-tree fillfactor, nbtree.h):

levels = 1 + ⌈logf(N / l)⌉
N
number of keys
l
keys per leaf page (367 for bigint at 90% fill)
f
fan-out of internal pages (about 285 for bigint at 70% fill)

The top one or two levels are touched by every lookup, so they stay cached: a lookup on a big table costs one or two physical reads, not four (the old page's "3 to 4 page reads for a large table plus one heap fetch, mostly cached" holds; the root measured 12 page touches, all cache hits, for the 6-row chat).

Predict the levels for a billion bigint keys, then drag; wider keys cost levels sooner

Defaults reproduce the measurement independently: 367 keys per leaf and 3 levels at 1M bigint rows, as Postgres reported. At 100 million rows Postgres built 4 levels with a root of only 4 entries, room for about 71 times more keys, so a billion rows need 4 levels derived. A 36-character text key (a UUID stored as text) fits 141 entries per leaf instead of 367: 59.1 MB at 1M rows against 22.5 MB for bigint (text counted as 1 length byte plus the characters; collation and compression also matter).

Measured depth at 1,000 to 100 million rows (table)

PostgreSQL 16.2, one bigint column, index built after loading; the last column is the formula's prediction.

Inserting: splits, and why random keys waste space

An insert walks down to its leaf and adds the entry in order. A full leaf splits: a new page takes the upper half and the parent gets a separator for it; a full parent splits too, and a root split adds a level (the tree grows at the top, so every leaf stays at the same depth). Fig. 5 (step 6) shows one split; the B-tree and LSM lab runs thousands. When the new key is the largest, Postgres keeps the left page at the fillfactor (90%) instead of half, because an increasing key never inserts there again (nbtree.h: "The fillfactor is applied during index build and when splitting a rightmost page"). Random keys split pages in the middle and half-empty pages fill only partly before splitting again: the classic result is about 69% average fill (ln 2).

The same million keys in random order need 38% more leaf pages

measured PostgreSQL 16.2, 1M bigint keys. Random order ended 66% full on average (close to the textbook 69%) and took 1.6 times as long, with everything still in memory.

Primary keys: bigint, UUID v4 or UUID v7

This matters most for the primary key, which every row inserts into. A UUID is a 16-byte identifier generated anywhere without coordination: version 4 is random, so consecutive rows land on random leaves; version 7 starts with a timestamp, so new rows go to the right edge like a sequence (RFC 9562, 2024; Postgres 18 added uuidv7(), PG 18 release notes).

A random key leaves the primary-key index a third emptier, and bigger, than a time-ordered one

measured PostgreSQL 18.6, 3M rows inserted in batches of 100,000 into a table whose only index is the primary key, 128 MB buffer pool. The UUID v4 index ended 68% full against 90% for v7, so it is 1.33 times the size; it wrote 9% more WAL and took 1.4 times as long. Part of the gap to bigint is generating UUIDs, not the index. The 126 MB index still almost fits the 128 MB pool; a random-key index several times larger than memory also waits for a disk read per insert (section 11: about 12 times slower).

SQL and data modelling (section 7) turns this into a key choice and measures the three key types at 1M and 10M rows: random UUID v4 keys cost a bigger index and more WAL than v7 for the same rows. On InnoDB the penalty is larger, because the primary key orders the whole table (section 8).

Duplicates, dead entries, skip scan and size limits (depth)
  • Deduplication (Postgres 13): when many rows share a key, the leaf stores the key once followed by a sorted list of ctids, a posting list (PG 13 notes; deduplicate_items, on by default). Chat 42000's entry is one 56-byte item holding 6 ctids. On a column with 4 distinct values (model), the index is 7.0 MB with deduplication and 27.1 MB without (3.9 times larger) measured.
  • Bottom-up deletion (Postgres 14): an update that is not HOT adds a new entry to every index even when the key did not change. Before splitting a page full of such versions, Postgres checks which entries point to dead row versions and deletes them, so version churn does not bloat the index (PG 14 notes, B-tree deletion).
  • Skip scan (Postgres 18): an index on (a, b) used to be nearly useless for a query on b alone. Postgres 18 can "skip" through the distinct values of a, one small descent per value (PG 18 notes: "allows multi-column btree indexes to be used in more cases such as when there are no restrictions on the first or early indexed columns"). An index on (model, created_at), four models, a one-hour window on created_at measured: Postgres 16 read the whole index, 4,382 pages (54.4 ms as it chose, 23.8 ms forced onto the index); Postgres 18 used an Index Only Scan with 9 index searches, 46 pages, 0.26 ms.
  • Limits: an index entry cannot exceed about a third of a page (2,704 bytes), so long text needs a hash or expression index; an index can have up to 32 columns; only B-trees can enforce UNIQUE (B-tree docs, unique indexes).
What a B-tree costs
Every insert dirties a leaf; random keys dirty pages all over the file (random writes, more page images, about 30% empty space), and every index on a table repeats this for every row. Skip it for a column you never search by, a tiny table, a huge append-only table queried by time (BRIN, section 9, was about 3,000 times smaller), or a write stream faster than random page writes can absorb (an LSM-tree, next).

6. LSM-trees: write first, sort later

Suppose the chat product logs every token-usage event, hundreds of thousands a second, keyed by a random request id. A B-tree turns each into a random leaf read and write plus a page image after each checkpoint, while flash and disks are far faster at long sequential writes. The LSM-tree (log-structured merge-tree, O'Neil, Cheng, Gawlick and O'Neil, Acta Informatica, 1996; memtable and SSTable are names from Google's Bigtable paper, OSDI 2006) maintains an index with sequential writes only:

Fig. 6: the LSM-tree's write path, then the measured RocksDB run

  1. Log it, then the memtable. Append the change to a write-ahead log, exactly as Postgres does, so a crash loses nothing; then insert it into a sorted structure in memory (RocksDB uses a skip list). Nothing on disk is read or changed.
  2. Flush. When the memtable is full (64 MB by default in RocksDB, 8 MB in the run below) it is written in one sequential pass as an immutable sorted file, an SSTable (sorted string table): key-value blocks, an index of the blocks, and a bloom filter. A new memtable takes over.
  3. Compact. Background threads merge-sort files together, keeping only the newest version of each key and dropping deleted ones, so the number of files stays bounded. Here level 0 reaches 4 files and is merged into the level below, whose overlapping files are rewritten.
  4. The levels, measured. After loading 4,000,000 keys into RocksDB (section 7 has the setup): 5 files in L5 and 63 in L6, each level about 10 times the one above; levels 1 to 4 stayed empty at this size (dynamic level sizes, the default since RocksDB 8.4). One box is one file.
  5. The bill. The application wrote 476 MB; RocksDB wrote 476 MB of log, 512 MB of flushes and 1,890 MB of compaction: a write amplification of 5.05, or 6.05 with the log. The 4,000,000 overwrites that followed: 6.21.
  6. Read. Look in the memtable, then in the files from newest to oldest, stopping at the first hit; per-file bloom filters and block indexes avoid most disk reads. A lookup of an absent key read 0.01 data blocks with the filters and 4.43 without.
  7. Tiered instead. Universal (tiered) compaction on the same workload left its files in levels 0, 1, 4 and 6 (1, 12, 23 and 60 files) and held 1.71x the space, against 1.10x for leveled; the next subsection compares the two.

Compaction is the real design choice

Files on disk are grouped in levels: level 0 holds freshly flushed files, which may overlap in key range; deeper levels are larger. How files move down is the compaction strategy:

Leveled (RocksDB's default)

Each level from 1 down is one sorted run, split into files with no overlap, each level about 10 times the one above (RocksDB: level 0 compacts at 4 files, level 1 is 256 MB, multiplier 10, options.h). A file pushed down is merged with the overlapping files there, rewriting them. Few runs to search, little wasted space, many rewrites: RocksDB's tuning guide works an example to a write amplification of "approximately 1 + 2 + 10 + 10 + 10 = 33" (tuning guide). Cassandra calls it LCS.

Tiered (RocksDB "universal", Cassandra STCS)

Runs of similar size accumulate; when there are enough, they merge into one bigger run ("waits for several sorted runs with similar size and merge them together", universal compaction). Each key is rewritten fewer times, but a read may search many runs and old versions take space until merged. Size-tiered is still Cassandra's default (cassandra.yaml); Cassandra 5.0 added a Unified Compaction Strategy that can behave like either (Cassandra compaction).

The textbook costs of leveling and tiering (formulas)

With size ratio T between levels, L levels and B entries per page, Luo and Carey give the textbook costs: writing an entry costs O(T·L/B) I/O under leveling and O(L/B) under tiering; a point lookup without bloom filters searches O(L) runs under leveling and O(T·L) under tiering (LSM survey, VLDB Journal 2020, section 2.3). Section 7 measures both on RocksDB.

Bloom filters: skipping files that cannot hold the key

A bloom filter is a bit array plus k hash functions. Adding a key sets k bits; asking "is x here?" checks x's k bits: any 0 is a certain no; all 1 is maybe (other keys may have set them). With m bits for n keys the false-positive rate is about

p ≈ (1 − e−k n / m)k, best at k = (m/n) ln 2

At 10 bits per key the best k is 6.9; with k = 7, p = 0.82% derived (RocksDB's wiki: "9.9 bits per key (1% false positive rate)", RocksDB bloom filter). A lookup for a key that does not exist then costs under 0.01 file reads per level instead of one. Bloom filters cannot help a range scan ("all keys between a and b" must visit every run), the LSM-tree's weak spot.

Each extra bit per key cuts false positives by about 38% (p ≈ 0.62 to the power of the bits per key, at the best k), for 125 kB more memory per million keys

Deletes are writes: tombstones

Files are immutable, so a delete writes a tombstone, a marker saying "this key is gone". The old value stays on disk until a compaction carrying the tombstone reaches its level, and until then every read of that range steps over the tombstones. RocksDB's DeleteRange writes one range tombstone for a whole key range (DeleteRange). That is why using a Cassandra table as a queue (insert, read, delete, repeat) is a classic failure: the live rows are few, the tombstones many, and reads slow down before compaction catches up.

Cassandra's tombstone settings (depth)

Cassandra keeps tombstones for gc_grace_seconds, 864,000 (10 days) by default, so a replica that was down can still learn about the delete (CREATE TABLE); it warns when a query reads 1,000 tombstones and aborts at 100,000 (cassandra.yaml). NoSQL in practice covers Cassandra in use.

What an LSM-tree costs
Compaction rewrites data many times (section 7) and competes with queries for disk and CPU; reads may search several runs and range scans cannot use bloom filters; old versions and tombstones take space until merged. The characteristic failure: compaction falls behind a write burst, level 0 piles up, reads slow, and the engine throttles or stops writes (RocksDB write stalls); alert on pending compaction bytes, not just disk space. Its home is ingest-heavy key-value and time-series streams (Cassandra, ScyllaDB, RocksDB inside many systems; the root's Database atlas tab lists the products), not read-mostly data with range queries or small data.

7. The RUM trade-off, measured

Every way of storing and indexing data pays three overheads: extra Reads beyond the data asked for, extra Update work beyond the bytes changed, and extra Memory or space beyond the data itself. The RUM conjecture: "designing access methods that set an upper bound for two of the RUM overheads, leads to a hard lower bound for the third overhead which cannot be further reduced" (Athanassoulis et al., EDBT 2016). They are measured as amplification factors: write amplification, bytes written to storage per byte the application wrote (log, pages, compaction rewrites); read amplification, pages or files read per lookup; space amplification, bytes on disk per byte of live data.

Each design sits near the corner it optimises and pays on the far side

Placement is qualitative, from this page's measurements: a B-tree bounds reads (3 pages) and space and pays on updates (up to 307x for scattered updates after a checkpoint); leveled LSM bounds space (1.10x) and pays rewrites; tiered LSM rewrites less at scale but needed 1.71x the space and searches more runs; BRIN is tiny (73.7 kB for 10M rows) and reads whole 128-page ranges. An index pays space and update cost to cut reads; compression pays CPU to cut space.

Measured on two real engines

RocksDB through the rocksdict Python binding, statistics on measured: 4,000,000 unique random 16-byte keys with 100-byte values (464 MB of data), then 4,000,000 overwrites of random existing keys; memtable 8 MB, level 1 32 MB, ratio 10, no compression, bloom filters 10 bits per key; 100,000 lookups of present and of absent keys.

Leveled compaction wrote 5.0x on load and 6.2x on overwrite (flushes plus compaction over the bytes the application wrote; the write-ahead log adds 1 more) and kept 1.10x space; universal (tiered) wrote about as much at this size but held 1.71x. Bloom filters at work: an absent-key lookup read 0.01 data blocks on average with them and 4.43 without; the measured false-positive rate was 0.97% per filter checked (formula: 0.82%).

How the RocksDB factors were computed (method)

Space amplification is SST bytes on disk after the overwrites divided by the SST bytes of the same unique keys fully compacted (the leveled run after loading); RocksDB's own live-data estimate was unreliable under universal compaction. Write amplification counts memtable flushes plus compaction writes divided by the bytes the application wrote.

Postgres on the 1M-message table measured: write amplification depends on where the writes land far more than on the engine.

Logical bytes are the rows without their 24-byte headers (128 bytes per message on average, from pgstattuple). Append: WAL plus the table and index files (251 MB + 158 MB + 22.5 MB), 3.4x. Updates: WAL (19.3 MB) plus the 2,448 pages the checkpoint will write back, counted as one write each (the number of page images, a lower bound), 307x. Read amplification for a point lookup is the tree height (3 here) plus one table page per row; the table's space amplification is about 1.23x (headers, alignment, free space).

Correction to the old page
The old page gave B-tree write amplification as "easily 10x to 40x", LSM leveled as "roughly 10x to 30x", and space amplification as 1.3x (B-tree), 1.1x (leveled) and "up to 2x or more" (tiered), without sources. One number misleads: Postgres measured about 3.4 times for appends and about 300 times for scattered updates after a checkpoint; leveled RocksDB about 5 to 6 times, growing with the levels the data spans (half a gigabyte sits in two levels here; RocksDB's worked example reaches 33). Tiered wrote about as much at this size but needed 1.7 times the space against 1.1; its write saving appears as data spans more levels (Luo and Carey: L against T times L). Quote amplification with its workload.
How to use this
Name the corner you give up: a ledger read and updated by key wants bounded reads (B-tree); an event firehose wants cheap writes (LSM, or an append-only Postgres table with BRIN); a cold archive wants little space (columnar, compressed, section 12). Then measure write amplification on your workload: on flash it sets how fast drives wear out and how much I/O compaction or checkpoints take from queries.

8. Heap tables and clustered tables: where the row itself lives

Opening chat 42000 read 6 table pages for 6 messages because rows sit in arrival order. If the table itself were sorted by chat, those messages would share one page. Two designs decide this:

Heap plus indexes (Postgres)

The table is a heap: rows go wherever there is room, in no particular order. Every index, the primary key included, is a separate B-tree whose leaves point to ctids. All indexes are equal, and a row's address changes only when a non-HOT update moves it (then every index gets a new entry, section 1). CLUSTER can sort the table once by an index, but new rows are not kept in order.

Index-organised (InnoDB, SQLite)

The table is the primary-key B-tree: its leaves hold whole rows in key order, a clustered index. InnoDB clusters on the primary key, or the first unique non-null index, or a hidden 6-byte row id; every secondary index stores the primary key, not a page address, so a secondary lookup walks two B-trees (InnoDB index types). SQLite tables are B-trees keyed by rowid; WITHOUT ROWID tables cluster on the primary key (SQLite docs).

In InnoDB a primary key of (chat_id, id) puts each chat's messages together, so reading a chat is one or two leaf pages, which Postgres lacks; but a random primary key (UUID v4) scatters every insert across the whole table, and every secondary index carries the full 16-byte key. In Postgres the key's order barely affects the table and a secondary lookup costs the same as a primary-key one; it can approximate clustering for a read-heavy path with a covering index (section 10) or partitioning.

In a heap every index points at row addresses; in a clustered table the primary-key tree holds the rows and other indexes point at the key

illustrative Two indexes on the same few messages. Left: Postgres, where any index costs one descent plus one table page per row. Right: InnoDB, where a primary-key range is one walk along the leaves, but a secondary lookup descends two trees.

What clustering costs
Primary-key range reads get cheap and secondary lookups dearer (two descents), and the primary key now decides physical layout: changing it rewrites the table. Heap tables pay one table-page read per matching row unless the index covers the query.

9. Index types in Postgres, and when to use each

A B-tree answers questions about order: equal, less than, between, sorted by. Many real questions are not: "messages whose metadata contains {"tool": "search"}", "documents containing refund", "users within 5 km", "bookings that overlap this range", "the last hour of a 10-billion-row event table". Postgres gives each kind of question its own structure, an access method (index types):

TypeHow it worksAnswersUse it forDo not use it when
B-treeSorted tree of pages (section 5)=, <, >, BETWEEN, IN, IS NULL, ORDER BY, LIKE 'abc%' (with C collation or text_pattern_ops)Almost everything; the default; the only one that can be UNIQUEValues over about 2.7 KB; containment questions
HashHash of the value into buckets; stores the 4-byte hash, not the value= onlyEquality on long values (URLs, long text) where a B-tree entry would be bigYou need ranges, sorting or uniqueness; usually a B-tree is as good. Crash-safe only since Postgres 10 (PG 10 notes)
GINInverted index: each element (word, array item, JSON key and value) maps to a posting list of rows@> contains, ? key exists, && overlaps, @@ full-text matchjsonb documents, arrays of tags, full-text searchWrite-heavy tables (one row inserts many entries); new entries wait in a pending list (fastupdate, up to gin_pending_list_limit, 4 MB) that searches must also read (GIN)
GiSTBalanced tree of bounding predicates (boxes, ranges) that may overlap; lossy, recheckedOverlaps, contains, within distance, nearest (ORDER BY <->)Geometry (PostGIS), range types, exclusion constraints ("no two bookings of a room overlap")Plain scalar equality or order
SP-GiSTSpace-partitioned trees whose regions do not overlap: quadtrees, k-d trees, radix triesPoints, IP ranges, text prefixesData with natural non-overlapping partitions (inet, points)Data that clusters unevenly in ways the partitioning cannot split
BRINFor each range of 128 table pages, the min and max of the column (BRIN)Ranges on a column that follows the physical orderHuge append-only tables queried by time: logs, events, messages by created_atThe column is not correlated with row position (measured below: useless)
bloom (contrib)One bloom filter signature per row (bloom)= on any combination of many columnsAd hoc equality filters over many columnsRanges; a few known query shapes (use B-trees)

Only B-trees always support index-only scans; GiST and SP-GiST support them for some operator classes; the others never do. Multicolumn indexes exist for B-tree, GiST, GIN and BRIN (index-only scans, multicolumn). Vector indexes (pgvector's HNSW and IVFFlat) are another access method, owned by Vector indexes; full-text ranking and vector search as a database feature are Search and vector databases.

Correction to the old page
The old page called GiST "historically the ANN index in early pgvector". It was not: pgvector's first release (0.1.0, 2021-04-20) shipped IVFFlat, and HNSW arrived in 0.5.0 (2023-08-28); it has never used GiST (pgvector changelog).

On a time-ordered column, BRIN reads about as many pages as a B-tree from an index 3,047 times smaller

measured PostgreSQL 16.2, 10,000,000 messages (1.58 GB) where created_at grows with row position, warm cache, one worker. BRIN returns whole 128-page ranges whose rows are rechecked one by one. On a shuffled copy of 2M rows, where created_at no longer follows the row order, the same one-hour query through BRIN read 38,602 pages, more than the whole table of 38,592 pages, and took 230 ms against 150 ms for a plain sequential scan: every block range spans almost all dates.

Hash against B-tree measured: a hash index on chat_id is 33.1 MB against 9.3 MB for the B-tree, because deduplication stores each chat once with a list of rows while a hash index stores one entry per row; both found chat 42000 by touching 12 pages. Hash indexes pay off only for long keys that deduplication cannot help.

Bitmap scans: how two single-column indexes combine (depth)

Postgres has no stored bitmap index, but it builds bitmaps on the fly: a bitmap index scan collects the matching ctids from an index into a bitmap of pages, two such bitmaps can be combined with AND or OR, and a bitmap heap scan then reads each needed page once, in file order. That is why two single-column indexes can still answer WHERE a = 1 AND b = 2 reasonably, and why the plans in the root's Query plans tab often show "Bitmap Heap Scan". Analytical stores do keep bitmap indexes (one bitmap per distinct value of a low-cardinality column).

10. Index shapes: multicolumn, partial, expression, covering

Beyond the type, the shape of an index decides which queries it serves (Use The Index, Luke is the best practical guide). Multicolumn (composite): CREATE INDEX ON messages (chat_id, created_at) sorts by chat, then by time within a chat. The rule is equality columns first, then the range or sort column, because after the first range condition the rest of the index is not ordered by the later columns (multicolumn indexes, concatenated keys). Predict which order reads fewer entries for "chat 42000, after 10:00":

  • Partial: CREATE INDEX ON messages (tokens) WHERE role = 'assistant' AND tokens > 1000 indexes only the rows a known query looks for (long answers, unprocessed jobs, active users). Measured: 95,287 of 1M rows qualify; the partial index is 680 kB against 7.1 MB for an index on tokens over all rows (partial indexes).
  • Expression: CREATE INDEX ON users (lower(email)) indexes a computed value, so WHERE lower(email) = ... can use it; wrapping a column in a function hides it from an ordinary index (expression indexes). Why a predicate can or cannot use an index is the planner's story, owned by Query planning and performance.
  • Covering (INCLUDE, Postgres 11): CREATE INDEX ON messages (chat_id) INCLUDE (role, tokens) stores extra columns in the leaves without sorting by them, so a query that needs only those columns is an index-only scan, skipping the table pages (if the visibility map allows, section 1). Measured: fetching role and tokens of chat 42000 touched 12 pages with the plain index and 7 with the covering one, at the price of a 40.6 MB index instead of 9.3 MB.

Equality first: the matching entries are one contiguous run; range first: they are scattered through the range

illustrative 24 index entries of four chats, sorted as each index sorts them. Highlighted: entries the scan must read; outlined: the 3 it returns. (chat_id, created_at) also serves WHERE chat_id = 42000 ORDER BY created_at and WHERE chat_id = 42000 alone; before Postgres 18 it barely served WHERE created_at > ... alone (skip scan, section 5, now helps when the first column has few distinct values).

What shapes cost
Each is one more index to maintain on every write. Wider entries (INCLUDE, long expressions) mean fewer entries per page and a deeper, bigger index. A partial index is used only when the query's WHERE clause implies the index's condition, so a query written differently silently misses it.

11. What indexes cost on writes, measured

The root warns that every index slows writes. By how much: the same million messages copied with one INSERT ... SELECT into an empty table with 0, 1, 3 and 6 indexes, three times each, 128 MB buffer pool measured. Predict which index is the expensive one.

An index on an increasing key (the primary key, created_at) is cheap: a sequential stream of leaf pages and its share of WAL. The expensive one has random-order keys and outgrows memory: the B-tree on content (random-looking text, 144 MB against a 128 MB buffer pool) turned an insert of about 10 seconds into about 2 minutes, because each row needs a random leaf page that is probably not cached. Single-row inserts through a connection (pgbench, 4 clients, commit not waiting for the flush) showed no trend, between about 12,600 and 23,500 per second across 0 to 6 indexes: microseconds of index work hide behind the round trip until the indexes stop fitting in memory. Index cost is invisible in a small benchmark and decisive at scale.

Cheap until one index has random keys and outgrows memory: then 10 seconds become 2 minutes

PostgreSQL 16.2, shared_buffers 128 MB, median of 3 runs (1.7, 2.1, 10.6 and 129.8 seconds; the 6-index runs took 92.5, 129.8 and 135.2). WAL grew from 185 MB with no index to 864 MB with six, and index files to 261 MB. Index names: pkey (id), chat_created (chat_id, created_at), created (created_at), model_tokens, role_chat, content (the message text, random-looking, 30 to 130 characters).

Find indexes nobody uses
SELECT indexrelid::regclass, idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) FROM pg_stat_user_indexes ORDER BY idx_scan, pg_relation_size(indexrelid) DESC; An index with idx_scan = 0 after weeks of normal traffic (and not backing a constraint) is pure write cost; check replicas too, since the counters are per server (statistics views). Build new indexes with CREATE INDEX CONCURRENTLY so writes are not blocked.

12. Column stores, in one section

Everything above keeps a row's columns together, which suits "fetch this chat". Analytics reads one or two columns of every row ("total tokens per model over a year"), so a column store keeps each column in its own compressed chunks: on the root page the same aggregate needed 94 times fewer bytes from Parquet than from the Postgres heap measured there. Column stores skip blocks by sort order and zone maps (min and max per block, BRIN's idea) rather than B-trees, and their storage is LSM-shaped. Analytics: columnar engines, DuckDB and the lakehouse owns the details.

ClickHouse's MergeTree as an example (depth)

ClickHouse's MergeTree writes each insert as an immutable sorted part and merges parts in the background, with a sparse primary index of one entry per 8,192 rows (MergeTree). Because skipping depends on how data was sorted when it was written, sort order matters more there than any index added later. The analytics page covers Parquet layout, encodings, DuckDB and the lakehouse.

Depth: production settings, common mistakes, numbers, all terms

Optional: everything here is reference that the sections above point to.

Settings in production, October 2026 (per-setting table)

Current versions: PostgreSQL 18.6 (2026-08-13) is the latest release; 19 reached Release Candidate 1 on 2026-10-15, with general availability targeted for 2026-11-19 (RC 1 announcement; versioning). MySQL 8.4 is the long-term-support line. RocksDB's defaults are those in its options.h. The settings below are the ones this page's mechanisms point to; each says whether it is a documented default or common practice.

SettingDefaultWhat pros do, and why
shared_buffers128 MBAbout 25% of RAM on a dedicated server, as the docs suggest; rarely above 40% (double buffering, section 2).
max_wal_size, checkpoint_timeout1 GB, 5 minCommon practice on write-heavy servers: raise both (several GB, 15 to 30 min) so checkpoints come from the timer, not WAL volume; fewer full-page images, longer crash recovery (sections 3 and 4). Check checkpoints_req against checkpoints_timed; tuning them on a live server is Running Postgres in production section 1.
wal_compressionofflz4 or zstd (Postgres 15+) when page images dominate the WAL; costs a little CPU (measured: pglz cut the images to a third).
full_page_writes, fsyncon, onLeave on. Turning either off risks corruption after a crash.
synchronous_commitonOn globally; SET LOCAL synchronous_commit = off in transactions whose loss after a crash is acceptable (events, logs).
Table fillfactor10070 to 90 on tables with frequent updates, so updates stay HOT; watch n_tup_hot_upd against n_tup_upd.
Primary key-bigint GENERATED ALWAYS AS IDENTITY, or uuidv7() (Postgres 18) when ids must be created outside the database; avoid random UUID v4 keys on large tables.
New indexes-CREATE INDEX CONCURRENTLY; drop indexes with idx_scan = 0; check B-tree health with amcheck and size with pgstattuple.
io_method (18)workerLeave the default unless measured; io_uring needs a Linux build with liburing.
InnoDB (MySQL 8.4)buffer pool 128 MB; O_DIRECT on Linux; change buffering noneBuffer pool up to about 80% of RAM on a dedicated server (InnoDB parameters).
RocksDB64 MB memtable, leveled, dynamic level sizes (default since 8.4)Bloom filters at about 10 bits per key; alert on pending compaction bytes and write stalls.

Operating these settings (vacuum, bloat, upgrades, backups) is Running Postgres in production; reading plans and finding slow queries is Query planning and performance.

Common mistakes, each with the section that shows why (ten)
Random UUID v4 primary keys on a big, growing table
Every insert lands on a random leaf page: more page images in the WAL, about 30% empty space, cache misses once the index outgrows memory (section 5 measured it). Use a sequence or UUID v7.
Indexing every column "just in case"
Each index is paid on every insert and non-HOT update; one random-order index that does not fit in memory made a bulk insert about 12 times slower here (section 11). Index what queries search by, then measure.
Composite index columns in the wrong order
(created_at, chat_id) cannot serve "this chat, newest first" well; (chat_id, created_at) can. Equality columns first, then the range or sort column (section 10).
Expecting index-only scans on a table that is never vacuumed
Without the visibility map's all-visible bits, an index-only scan still visits the table pages (section 1; the root's Query plans tab, case 7).
Turning off fsync, full_page_writes or synchronous_commit globally for speed
The first two risk corruption; the third loses the last instant of commits for every table, money included. Use group commit, wal_compression, and per-transaction synchronous_commit instead (section 3).
SELECT * on tables with long text
Long values are TOASTed: fetching them costs extra page reads and decompression. List the columns you need (section 1).
BRIN on a column that does not follow the row order
Each block range then spans almost the whole value range and nothing is skipped (section 9 measured it). BRIN suits append-only time columns.
Using an LSM store as a queue, and ignoring compaction debt
Deletes become tombstones that reads must step over; compaction that falls behind a write burst ends in write stalls (section 6).
Benchmarking with data that fits in memory
Everything is a cache hit and index costs vanish (section 11's single-row inserts). Test at production size, or at least with data larger than shared_buffers and the OS cache.
A huge shared_buffers
Postgres also relies on the OS page cache; above about 40% of RAM the docs say it is unlikely to help, and checkpoints have more dirty pages to write (section 2).
Numbers to keep in mind for storage, corrected against measurements (table)

The old page's latency table, re-based on measurements (the root's notes and the system design page's Numbers to know tab, which owns the full list). Rows about networks, caches, vectors and LLMs moved to the pages that own them (listed under the table).

OperationOld pageNowWhy it matters here
L1 cache reference1 nsabout 1 ns (0.98 ns measured on the system design page)The unit
Main memory reference100 nsabout 70 to 100 nsA buffer pool hit
Read 1 MB sequentially from memory50 μscorrected: 18.3 μs measured on an M1 Pro, one thread (classic list: 250 μs)Why scanning cached pages is cheap
Random 4 KB read from an NVMe SSD50 to 100 μsabout 100 μs (102 μs at queue depth 1, consumer drive)A buffer pool miss; why the working set must fit in RAM
fsync0.1 to 1 ms (enterprise SSD)corrected: 1.6 to 12 μs with power-loss protection; 0.9 to 3 ms consumer SSD; 0.74 ms network block storage; 6.0 ms per commit on this laptopThe floor on commit latency per connection; why group commit exists
Read 1 MB sequentially from NVMe200 to 500 μsunconfirmed (depends on the drive; consumer NVMe drives advertise several GB/s, which would be 0.2 to 0.5 ms)Why a well-laid-out scan can beat scattered index lookups
Postgres indexed single-row read, warm0.5 to 2 mscorrected: 0.061 ms inside the server (root), 0.067 ms over loopback (system design page); a network round trip adds 0.5 ms or soIf you see 50 ms, look for a missing index, a cold cache or N+1 queries

Moved: same-datacentre and cross-region round trips and S3 first-byte times to the system design page's Numbers to know tab; Redis GET (corrected there to about 0.14 ms on loopback, vendor figure) to Caching; HNSW query time to Search and vector databases; LLM time to first token to Topic: inference-and-serving. The habit the old table taught still holds: multiply the number of page reads, flushes or round trips by the cost of one and compare with what you measured; if they disagree, you are optimising the wrong layer.

All terms on this page (glossary)