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
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.
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.
| Piece | The problem it solves | How, in one line | What it costs |
|---|---|---|---|
| Pages | Disks read blocks, not rows | Every table and index is an array of 8 KB pages; a row lives at (page, slot) | Reading one row reads a whole page |
| Buffer pool | Disk is about 1,000 times slower than memory | Keep hot pages in RAM; evict by clock sweep | RAM; a working set bigger than RAM changes latency abruptly |
| Write-ahead log | "Saved" must survive a crash; random page writes are slow | Append the change to a log and flush it before acknowledging; write pages later | One flush per commit (shared by group commit); full-page images after each checkpoint |
| B-tree | Find one key among a billion | A sorted tree of pages, hundreds of keys per page: about 4 levels for a billion keys | Random in-place writes; page splits; about 30% empty space under random inserts |
| LSM-tree | Writes faster than a B-tree can absorb | Buffer in memory, write sorted files sequentially, merge in the background | Reads may check several files; compaction rewrites data many times |
| Index types | Not 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 tables | Each 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.
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
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).
Page size 8,192. Click a stripe; slot 1 is at the far right.
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?
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.
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 (_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.
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.
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
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%.
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).
blks_hit against blks_read in pg_stat_database.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:
| Record | Bytes | What it says |
|---|---|---|
| Heap INSERT | 135 | put this tuple in page 8132 of messages |
| Btree INSERT_LEAF | 64 | add id 1000001 to the primary-key leaf page 2744 |
| Btree INSERT_POST | 66 | add this ctid to chat 42000's existing entry in the chat_id index (a posting list, section 5) |
| Transaction COMMIT | 34 | transaction committed |
| Total | 299 | about twice the size of the row itself |
Fig. 4: the same insert, in order
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).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.
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.
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).
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.
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.
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).
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).
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.
pg_control, sees the server was not shut down cleanly, and finds the last checkpoint record ("database system was interrupted ... automatic recovery in progress").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.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
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.
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).
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):
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).
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).
PostgreSQL 16.2, one bigint column, index built after loading; the last column is the formula's prediction.
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).
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.
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).
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).
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.UNIQUE (B-tree docs, unique indexes).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
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:
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.
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).
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.
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
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.
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 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.
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.
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.
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%).
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).
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:
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.
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.
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.
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):
| Type | How it works | Answers | Use it for | Do not use it when |
|---|---|---|---|---|
| B-tree | Sorted 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 UNIQUE | Values over about 2.7 KB; containment questions |
| Hash | Hash of the value into buckets; stores the 4-byte hash, not the value | = only | Equality on long values (URLs, long text) where a B-tree entry would be big | You need ranges, sorting or uniqueness; usually a B-tree is as good. Crash-safe only since Postgres 10 (PG 10 notes) |
| GIN | Inverted index: each element (word, array item, JSON key and value) maps to a posting list of rows | @> contains, ? key exists, && overlaps, @@ full-text match | jsonb documents, arrays of tags, full-text search | Write-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) |
| GiST | Balanced tree of bounding predicates (boxes, ranges) that may overlap; lossy, rechecked | Overlaps, 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-GiST | Space-partitioned trees whose regions do not overlap: quadtrees, k-d trees, radix tries | Points, IP ranges, text prefixes | Data with natural non-overlapping partitions (inet, points) | Data that clusters unevenly in ways the partitioning cannot split |
| BRIN | For each range of 128 table pages, the min and max of the column (BRIN) | Ranges on a column that follows the physical order | Huge append-only tables queried by time: logs, events, messages by created_at | The column is not correlated with row position (measured below: useless) |
| bloom (contrib) | One bloom filter signature per row (bloom) | = on any combination of many columns | Ad hoc equality filters over many columns | Ranges; 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.
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.
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).
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":
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).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.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.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).
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.
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).
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.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 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.
Optional: everything here is reference that the sections above point to.
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.
| Setting | Default | What pros do, and why |
|---|---|---|
shared_buffers | 128 MB | About 25% of RAM on a dedicated server, as the docs suggest; rarely above 40% (double buffering, section 2). |
max_wal_size, checkpoint_timeout | 1 GB, 5 min | Common 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_compression | off | lz4 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, fsync | on, on | Leave on. Turning either off risks corruption after a crash. |
synchronous_commit | on | On globally; SET LOCAL synchronous_commit = off in transactions whose loss after a crash is acceptable (events, logs). |
Table fillfactor | 100 | 70 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) | worker | Leave 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 none | Buffer pool up to about 80% of RAM on a dedicated server (InnoDB parameters). |
| RocksDB | 64 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.
SELECT * on tables with long textThe 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).
| Operation | Old page | Now | Why it matters here |
|---|---|---|---|
| L1 cache reference | 1 ns | about 1 ns (0.98 ns measured on the system design page) | The unit |
| Main memory reference | 100 ns | about 70 to 100 ns | A buffer pool hit |
| Read 1 MB sequentially from memory | 50 μs | corrected: 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 SSD | 50 to 100 μs | about 100 μs (102 μs at queue depth 1, consumer drive) | A buffer pool miss; why the working set must fit in RAM |
| fsync | 0.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 laptop | The floor on commit latency per connection; why group commit exists |
| Read 1 MB sequentially from NVMe | 200 to 500 μs | unconfirmed (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, warm | 0.5 to 2 ms | corrected: 0.061 ms inside the server (root), 0.067 ms over loopback (system design page); a network round trip adds 0.5 ms or so | If 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.
Insert the same keys into a small B-tree and a small LSM-tree and watch what each one writes. Pages here hold a handful of keys instead of hundreds, so a few hundred inserts show what millions do on a real server. The rules are the real ones: a B-tree splits a full page in two (or keeps the left page 90% full when appending at the right edge, as Postgres does), a checkpoint writes each dirty page once, and the first change to a page after a checkpoint logs a full-page image; an LSM-tree fills a memtable, flushes it as a sorted run, and merges runs by leveled or tiered compaction. Sizes are in key slots, not bytes. illustrative The measured versions of the same counters, on a real Postgres and a real RocksDB, are in the Reading tab's sections 3, 5 and 7.
Try: insert 1,000 ascending keys, note the B-tree's page writes and fill, press Reset, then insert 1,000 random keys: fill drops to about 70% and page writes multiply, which is the measured UUID v4 story of section 5. Then switch the LSM to tiered: fewer slots written, more runs to probe. Use Overwrite to see an LSM keep stale versions until compaction.
Write amplification counts every slot written to storage per key inserted: for the B-tree, page writes at checkpoints plus full-page images in the log plus one log record per insert; for the LSM-tree, one log record per insert plus every slot written by flushes and compactions. Space amplification is slots on disk per live key. Read cost is pages read (B-tree height) or sorted runs searched for one lookup; with bloom filters a run is searched only when its filter says "maybe" (false-positive rate 0.82% at 10 bits per key, formula in section 6).
Insert keys into both engines; splits, flushes, compactions, write and space amplification. About 2 minutes to read, 10 to play.
The from-zero overview this page deepens. Its Query plans tab measures index against sequential scans, index-only scans, VACUUM, and cold against warm cache on 10M messages; its Database atlas tab compares about 50 products including every LSM and B-tree engine named here; its SQL playground runs SQL in the browser. About 27 minutes plus the tabs.
Queries, joins, schema design, migrations (including building indexes without blocking writes). Child page, about 48 minutes.
MVCC in depth: what xmin and xmax decide, isolation anomalies, locks. Child page, about 43 minutes.
EXPLAIN, statistics, why the planner picks a bad plan, sargable predicates; owns the old page's planner section. Child page, about 45 minutes.
VACUUM and bloat, backups and point-in-time recovery from the WAL, replication, upgrades, pooling. Child page, about 43 minutes.
Column stores, Parquet, zone maps and MergeTree in depth (section 12 here is the summary). Child page, about 46 minutes.
Key-value, document, wide-column (Cassandra's LSM in use), time-series, graph. Child page, about 46 minutes.
Inverted indexes, BM25, ANN indexes (HNSW, IVF, DiskANN), pgvector; owns the old page's ANN section, HNSW paper and ANN-Benchmarks. Child page, about 33 minutes.
Every cache layer above the buffer pool, eviction and invalidation. Child page, about 43 minutes.
Read replicas, sharding Postgres, distributed SQL (many of which run on LSM engines such as RocksDB or Pebble). Child page, about 45 minutes.
Its Numbers to know tab owns the full latency list (memory, SSD, fsync, network). About 21 minutes.
Working sets, cache hit rates under load, and when the disk becomes the bottleneck. Child page.
Change data capture from the WAL, the outbox pattern. Child page.
Alex Petrov, O'Reilly 2019. Part I (storage engines) is the clearest walk through B-tree mechanics, page layout and LSM compaction. Start here. About 9 h 25 min (Part I about 5 h).
Kleppmann and Riccomini, O'Reilly, March 2026. The storage and retrieval chapter covers the same ground at a higher altitude, with judgement about when each engine wins (the chapter number in the 2nd edition is unconfirmed). About 1 h 30 min for the chapter.
Hironobu Suzuki, free online. Chapters on the heap, the buffer manager, the WAL and VACUUM, with diagrams of real structures. About 6 h for the storage chapters.
The primary source for sections 1 to 4. About 1 h.
How Postgres's B-tree handles concurrency, splits, deduplication and deletion, from the people who wrote it. About 45 min.
Markus Winand, free. Practical indexing: composite order, covering indexes, functions in predicates, reading plans. About 4 h.
Athanassoulis et al., EDBT 2016: the six-page paper behind section 7. About 30 min.
Luo and Carey, VLDB Journal 2020: compaction strategies, bloom filters and cost analysis. About 1 h 30 min.
O'Neil, Cheng, Gawlick and O'Neil, Acta Informatica 1996: the original paper. About 1 h.
How a production LSM engine sizes levels and picks files, with diagrams. About 30 min.
Andy Pavlo's course; the lectures on storage, buffer pools, B+trees and logging and recovery are the best free videos on this page's material. About 6 h for those lectures.
Colin Scott's version of Jeff Dean's list, with a slider for the hardware year (extrapolated, not measured; see the Numbers section). About 10 min.
Measurements: PostgreSQL 16.2 (the pgserver wheel's build, plus contrib modules built from the 16.2 source) and 18.6 (built from source), and RocksDB through rocksdict, on an Apple M1 Pro laptop on 2026-10-04; every script is in the page's src/measure/ and each run takes under 15 minutes. The old page's facts, where each now lives, and the corrections are listed in src/coverage.json; the 2026-10-24 rebuild's knowledge ledger is src/ledger.json.