Storage: pages, heaps, tuples and the buffer pool
Every row lives in an 8 KB page, every page passes through one cache, and most slow queries are a story about which pages were not in it
A freshly loaded table has 2 000 000 rows at about 109 rows per 8 KB page. You run UPDATE orders SET total_cents = total_cents + 1 WHERE id BETWEEN 1 AND 100000. Roughly how many pages does the table have afterwards?
Every table and every index in Postgres is a file of fixed-size blocks, 8 KB each. Every read of a row is a read of one of those blocks into a shared cache, and every write is a modification of a cached block that reaches the disk later. If you can picture one page and one cache, you can predict the cost of almost any query. If you cannot, EXPLAIN output is a list of numbers with no story.
This chapter opens a page with pageinspect, follows a row version through an update, then sizes the cache and watches the hit ratio move. The tools are the ones you will use in production: pageinspect, pg_buffercache, pg_stat_io and pg_statio_user_tables.
The page
A heap page is 8 192 bytes, set at compile time (BLCKSZ; nobody changes it). Its layout has four regions:
The page header is 24 bytes: pd_lsn (8 bytes: the WAL position of the last change to this page, which the WAL chapter uses), pd_checksum (2), pd_flags (2), pd_lower (2), pd_upper (2), pd_special (2), pd_pagesize_version (2) and pd_prune_xid (4). The two offsets you care about are pd_lower, where the line-pointer array ends, and pd_upper, where tuple data begins. The space between them is the page’s free space. When they meet, the page is full.
Line pointers (ItemIdData, 4 bytes each) grow forwards from the header. Each holds an offset into the page, a length, and two flag bits (normal, unused, dead, or redirect). Tuples grow backwards from the end. A tuple’s address, its ctid, is (block number, line pointer index), and it is what every index entry stores. The indirection is deliberate: when Postgres compacts a page it moves tuple bytes around, but line pointers never move, so every index entry stays valid without touching the index. Heap pages have no special space; B-tree pages use it for sibling links and flags, which the next chapter reads.
A page can hold at most 291 tuples: (8192 - 24) / (4 + 24), the smallest possible tuple with no columns. Real rows are wider. The shop’s orders row is 72 bytes including its header (64 when shipped_at is NULL), so about 109 fit per page and the 2 000 000-row table is 18 382 pages, or 144 MB. Those two numbers, pages and bytes, are the ones to keep in your head; pg_relation_size('orders') gives the bytes and dividing by 8192 gives the pages.
The tuple
Each row version carries a 23-byte header, padded to 24 so the data starts on an 8-byte boundary:
| field | bytes | meaning |
|---|---|---|
t_xmin |
4 | transaction id that inserted this version |
t_xmax |
4 | transaction id that deleted or updated it; 0 if none |
t_cid / t_xvac |
4 | command id within the transaction (shared field) |
t_ctid |
6 | this tuple’s own ctid, or the ctid of the newer version after an update |
t_infomask2 |
2 | column count and flags (HOT updated, heap-only tuple) |
t_infomask |
2 | flags: has nulls, xmin committed, xmax committed, and so on |
t_hoff |
1 | offset to the first column |
Then an optional null bitmap (one bit per column, present only when some column is null), then the columns, each aligned to its type’s requirement. A bigint after a text of 7 bytes wastes bytes to padding; column order affects row size, and a table of int4, int8, int4, int8 is wider than the same columns as int8, int8, int4, int4.
Two things follow from xmin and xmax. First, an update is an insert plus a mark: the new version gets xmin = your xid, the old version gets xmax = your xid and t_ctid pointing to the new one. Nothing is overwritten. Second, deciding whether you can see a tuple means comparing its xmin and xmax against your snapshot and against the commit log (pg_xact). The first visit to a tuple after its transaction commits has to look that up; it then sets a hint bit (HEAP_XMIN_COMMITTED in t_infomask) so the next reader does not. That is why a SELECT after a large load dirties pages: it is writing hint bits. The MVCC chapter builds everything on this.
Wide columns do not go in the page. When a row would exceed TOAST_TUPLE_THRESHOLD (about 2 KB), Postgres compresses its variable-length columns and, if the row is still too wide, moves them to the table’s TOAST table in chunks of about 2 000 bytes, leaving an 18-byte pointer in the row. A text column of 5 MB costs the main row 18 bytes and the query that does not select it never touches the chunks. A query that does pays for the TOAST table and its index too, which show up in pg_statio_user_tables as toast_blks_read and tidx_blks_read. The per-column strategy is PLAIN, EXTENDED (default: compress, then move out), EXTERNAL (move out, do not compress; substrings are faster) or MAIN; the compressor is pglz or, if compiled in, lz4 via default_toast_compression. The maximum value is 1 GB.
Fill factor and free space
A table’s fillfactor (default 100) is how full INSERT is allowed to leave a page. At 100 a freshly loaded page has no free space, which is what the Predict question depends on. At 70 each page keeps 30% free for later versions of its own rows, which is what makes HOT updates possible (next chapter). You set it with ALTER TABLE orders SET (fillfactor = 70); it applies to new pages, so existing ones change only on a rewrite (VACUUM FULL or CLUSTER).
Postgres finds free space through the free space map (FSM), a separate fork of the table (orders_fsm) that records, in 1/256-page units, how much is free on each page. An insert consults it; VACUUM updates it. The visibility map (orders_vm) is a third fork with two bits per page: all tuples visible to everyone, and all tuples frozen. Index-only scans and vacuum both read it. pageinspect can open any fork: get_raw_page('orders', 'fsm', 0).
The buffer pool
Postgres does not read pages directly from disk into a query. Every page goes through shared buffers, an array of 8 KB slots in shared memory sized by shared_buffers (default 128 MB, that is 16 384 slots; set only at server start). A backend that needs a page asks the buffer manager. If the page is in a slot, that is a hit: a hash-table lookup and a pin, under a microsecond. If not, it is a read: the manager picks a slot to evict, writes it out if it is dirty, and reads the page in. The read is a pread() from the file, which the kernel satisfies from its own page cache if it can (tens of microseconds) or from the device (around 100 microseconds on NVMe, 5 to 10 milliseconds on a spinning disk).
Eviction is clock sweep. Each slot has a usage count, raised on every hit up to a maximum of 5. A hand moves around the array; at each slot it decrements the count, and the first slot it finds at zero and unpinned is the victim. A page that is used often keeps getting its count raised faster than the hand can lower it. A page scanned once gets a 1 and is gone the next time the hand passes. It is an approximation of LRU that needs no list manipulation on a hit, which matters when hundreds of backends share the array.
CREATE EXTENSION pg_buffercache;
SELECT * FROM pg_buffercache_usage_counts(); -- how many slots at each count 0..5
SELECT * FROM pg_buffercache_summary(); -- used, unused, dirty, pinned
Two refinements change what you measure. First, a sequential scan of a table larger than a quarter of shared_buffers does not use the main pool. It allocates a 256 KB ring (32 slots) and recycles pages within it, so a one-off report scan of a 100 GB table does not evict your hot working set. The cost is that the scanned table also does not stay cached. VACUUM and COPY use rings too. pg_stat_io labels these as context = 'bulkread', 'vacuum' and 'bulkwrite', against 'normal' for everything else. Second, dirty pages are written by the background writer ahead of the clock hand (bgwriter_delay 200 ms, bgwriter_lru_maxpages 100 per round) and by checkpoints, so that a backend evicting a page rarely has to write it first. When it does, that is a write stall inside a read, and pg_stat_io counts it as a writes row for client backend.
Two caches, not one
Postgres reads files through the kernel, so a page that is in shared buffers is usually also in the kernel page cache. Memory is spent twice. The documentation’s advice follows from that: start at 25% of RAM for shared_buffers on a dedicated machine, and expect no gain above about 40%. The remaining RAM is the second tier. A read that misses shared buffers but hits the OS cache costs tens of microseconds, not hundreds; pg_stat_io.read_time (which needs track_io_timing = on) is the only Postgres-side view of which one you hit, because a cheap “read” is an OS-cache hit.
The planner knows about the second tier through effective_cache_size (default 4 GB), which does not allocate anything: it tells the planner how much of an index to assume is cached when costing index scans. Set it to shared buffers plus the OS cache you expect, usually 50 to 75% of RAM.
Measuring the hit ratio
Two views answer “how often did we go to disk”. pg_statio_user_tables is per table:
SELECT relname, heap_blks_read, heap_blks_hit,
round(100.0 * heap_blks_hit / nullif(heap_blks_hit + heap_blks_read, 0), 1) AS hit_pct,
idx_blks_read, idx_blks_hit, toast_blks_read
FROM pg_statio_user_tables ORDER BY heap_blks_read DESC LIMIT 10;
pg_stat_io (Postgres 16 and later) is per backend type, object and context, and is the one that explains the ring buffer:
SELECT backend_type, context, reads, hits, evictions, reuses, writes
FROM pg_stat_io
WHERE object = 'relation' AND (reads > 0 OR hits > 0)
ORDER BY backend_type, context;
hits / (hits + reads) is the hit ratio. evictions is how often the clock hand threw out a page from the main pool; reuses is how often a ring recycled one of its own slots. Reset both views for an experiment with SELECT pg_stat_reset_shared('io') and, per database, pg_stat_reset() (which also resets autovacuum’s counters, so run ANALYZE afterwards on a real system). Counters since server start are the useful production number; a ratio under 99% on an OLTP database with a working set that should fit is the symptom to chase.
The ratio lies in one well-known way. A table scanned through the ring buffer shows a hit ratio near zero and may be perfectly healthy: the pages came from the OS cache. The fix for the measurement is to look at context and read_time, not at the ratio alone.
What goes wrong
The working set stops fitting. A table grows, or bloats with dead versions, until the pages a typical query touches no longer stay in shared buffers between calls. The query plan has not changed; EXPLAIN (ANALYZE, BUFFERS) shows shared read where it used to show shared hit, and latency moves from 2 ms to 200 ms. The GitLab incidents above had this shape. pg_buffercache tells you which relations hold the pool; the fix is more memory, less bloat, or a smaller working set through a better index.
A batch job flushes the pool. A query that touches a large table through an index (not a sequential scan, so no ring) pulls millions of pages through the main pool at usage count 1 and the hand evicts your hot pages to make room. The next morning’s first requests are slow. pg_stat_io.evictions spiking during the batch is the signature.
Hint bits and checksums write on read. The first SELECT after a large load sets hint bits on every page it visits, dirtying them, and with data_checksums on, each becomes a full-page WAL record on the next modification after a checkpoint. A read-only report produces gigabytes of WAL. VACUUM after the load sets the bits in one pass.
Double counting memory. Someone sets shared_buffers to 90% of RAM “because it is the cache”. The OS cache starves, every checkpoint write and WAL write goes to a cold kernel, and the machine swaps under a work_mem spike. 25% is the starting point for a reason.
Everything runs in psql unless the step says otherwise. The atlas role is the container’s superuser, which the extensions need.
1. Open page zero of orders.
CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE EXTENSION IF NOT EXISTS pg_buffercache;
SELECT * FROM page_header(get_raw_page('orders', 0));
SELECT pg_relation_size('orders') / 8192 AS pages, pg_size_pretty(pg_relation_size('orders')) AS bytes;pagesize 8192, version 4, special 8192 (no special space on a heap page), an lsn like 0/1A3B2C0, and lower and upper a few hundred bytes apart or less: the page is nearly full because the loader filled it to fillfactor 100. The table is 18 382 pages, 144 MB, at scale 1 (lower 460, upper 480 on page 0). If lower is 24 + 4 × (number of tuples), the arithmetic from the chapter holds; the next step checks it.2. Read the line pointers and tuple headers.
SELECT count(*) AS tuples_on_page_0 FROM heap_page_items(get_raw_page('orders', 0));
SELECT lp, lp_off, lp_len, t_xmin, t_xmax, t_ctid, t_hoff
FROM heap_page_items(get_raw_page('orders', 0)) ORDER BY lp LIMIT 5;lp_off descending as lp rises (tuples fill from the end of the page), lp_len 72 (64 for an order with no shipped_at, whose NULL takes no bytes), t_xmax 0 (live), t_ctid equal to (0,lp) (this version is the newest), and t_hoff 24. All rows share one t_xmin: the loader’s transaction. The 4-byte pointers at the front and the 72-byte tuples at the back are the two halves of the diagram.3. Update one row and find both versions.
SELECT ctid, xmin, xmax FROM orders WHERE id = 1;
BEGIN;
UPDATE orders SET total_cents = total_cents + 1 WHERE id = 1;
SELECT ctid, xmin, xmax, pg_current_xact_id() FROM orders WHERE id = 1;
SELECT lp, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('orders', 0)) WHERE lp = 1;
ROLLBACK;
SELECT ctid, xmin, xmax FROM orders WHERE id = 1;ctid (0,1), xmax 0. Inside the transaction the row’s ctid becomes something like (18381,87): a page at the end of the table, because page 0 had no room. The old tuple at (0,1) now shows t_xmax equal to your transaction id and t_ctid pointing at the new location. After ROLLBACK the row reads as (0,1) again with xmax still set: the old version is live because the transaction that set xmax aborted, and the new version at the end of the table is dead. Nothing was erased in either direction. VACUUM will remove the dead version later; that is the next-but-one chapter.4. Hit ratio at the default shared_buffers.
Start from an empty pool, because the load you ran left thousands of orders pages in it: in a shell, docker compose restart db, then reconnect psql.
SHOW shared_buffers;
SELECT pg_stat_reset_shared('io');
\timing on
SELECT count(*) FROM orders;
SELECT count(*) FROM orders;
\timing off
SELECT backend_type, context, reads, hits, evictions, reuses
FROM pg_stat_io WHERE object = 'relation' AND (reads > 0 OR hits > 0);
SELECT count(*) AS orders_pages_in_pool FROM pg_buffercache WHERE relfilenode = pg_relation_filenode('orders');shared_buffers is 128MB. At scale 1 count(*) runs as a parallel scan, so the I/O is split between a client backend row (the leader, about a third) and a background worker row (the two workers). Added together, reads is about 36 800, two full scans of 18 382 pages, all in context bulkread, with hits near zero and reuses almost equal to reads: the table (144 MB) is bigger than a quarter of the pool (32 MB), so each process scanned through a small ring of buffers and recycled its own slots. orders_pages_in_pool is a couple of hundred at most, the rings’ worth. The second scan is as fast as the first or faster because the pages came from the OS page cache, which Postgres cannot see: a low hit ratio, no slow query. At scale 0.1 the table is 14 MB, under the threshold, so you see context normal, the second scan all hits, and 1 839 pages in the pool: skip to the break and do the eviction there instead.5. Grow the pool and scan again.
This needs a restart: shared_buffers is read at server start. Run the first line in psql, the rest in a shell in labs/databases.
ALTER SYSTEM SET shared_buffers = '1GB';docker compose restart db
docker compose exec db psql -U atlas shop -c "SHOW shared_buffers" \
-c "SELECT pg_stat_reset_shared('io')" \
-c "SELECT count(*) FROM orders" -c "SELECT count(*) FROM orders" \
-c "SELECT backend_type, context, reads, hits, evictions, reuses FROM pg_stat_io WHERE object = 'relation' AND (reads > 0 OR hits > 0)" \
-c "SELECT count(*) AS orders_pages_in_pool FROM pg_buffercache WHERE relfilenode = pg_relation_filenode('orders')"1GB. Summed over the client backend and background worker rows, the first scan reads about 18 400 pages in context normal (the table is now under a quarter of the pool, so no ring), the second scan adds about 18 400 hits and no reads, and orders_pages_in_pool is 18 382: the whole table is resident. Hit ratio went from about 0% to about 50% over the two scans and would approach 100% with more. The same table, the same query, the same plan; one knob and a restart changed where the bytes came from. Put it back when you are done: ALTER SYSTEM RESET shared_buffers; then docker compose restart db.shared_buffers still at 1 GB and orders resident, evict it by hand and time the next scan: SELECT count(*) FILTER (WHERE pg_buffercache_evict(bufferid)) FROM pg_buffercache WHERE relfilenode = pg_relation_filenode('orders'); then \timing on and SELECT count(*) FROM orders;. pg_stat_io shows about 18 400 fresh reads, yet the scan takes about the same time as a fully cached one, because the kernel still has every page. Restarting the container does not change that: the page cache belongs to the kernel of the machine Docker runs on, not to the container. Defeat the kernel too: docker compose restart db, then drop that kernel’s page cache (on Linux sync; echo 3 | sudo tee /proc/sys/vm/drop_caches; on Docker Desktop, whose kernel is in a VM, docker run --rm --privileged alpine sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches'). The first scan after that is several times slower with the identical reads count. Two caches, one counter. In production the first number is the only one you can see from SQL, and it does not tell you which of the two you missed; track_io_timing = on and read_time do.You run the shop's Postgres on a dedicated 64 GB machine with NVMe storage. The database is 200 GB on disk; the hot working set, measured with pg_buffercache over a week, is about 14 GB of heap and index pages. Checkpoints currently write 3 GB each. How do you set shared_buffers?
- BOOK PostgreSQL 14 Internals Egor Rogov, 2023
Free PDF. Part I chapter 'Pages and Tuples' is this chapter's page and tuple sections with pageinspect output for every claim; Part II 'Buffer Cache' walks the clock sweep, the rings and the background writer. Version 14, but nothing here changed in 17 except the pg_stat_io view. Read: Part I 'Pages and Tuples'; Part II 'Buffer Cache'.
- BOOK Database Internals Alex Petrov, 2019
Chapters 3 and 4 cover slotted pages, cell layout, and the buffer-management design space (eviction policies, pinning, dirty-page handling) across engines, so you can see what is Postgres and what is universal. Skip the distributed half for now. Read: chapters 3 ('File Formats') and 4 ('Implementing B-Trees'), and chapter 5 on buffer management.
- DOC Database Page Layout
The authoritative field-by-field table for PageHeaderData, ItemIdData and HeapTupleHeaderData, with sizes. Use it next to heap_page_items output to decode what you see.
- DOC TOAST
The thresholds, the four storage strategies, the compression options and the 1 GB limit. Short; read the whole page before you store documents in a table.
- DOC pageinspect
Every function used in the lab and the B-tree ones used in the next chapter, with their columns. Keep it open while you work; the column names are not guessable.
- DOC pg_stat_io
The column definitions and, more useful, the meaning of each context value (normal, vacuum, bulkread, bulkwrite). This is the view that explains a low hit ratio that is not a problem.
- DOC Resource Consumption: Memory
The shared_buffers paragraph with the 25% and 40% figures, huge_pages, and the background writer knobs. The Decide above is this page applied.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.