Eight Kilobytes
Eight Kilobytes
Chase Pierce
First edition · PostgreSQL 18 · 2026-10-05
Publisher: Flagon
Start reading · Print the whole book
Almost everything about PostgreSQL performance comes down to one number: 8,192. That’s the size of a page, the unit Postgres reads, writes, and caches. A fast query touches few pages. A slow one touches many, or waits on someone else who is. Once you can see the pages, most of the mystery goes away.
You’ve probably met the symptoms already. The dashboard that was instant at launch and crawls now. The migration that “does nothing” and took the site down anyway. The table that keeps growing faster than the data in it. And the standing offer to fix all of it with a bigger instance. This book is the alternative to that offer.
Count the pages, then earn the bigger box
The book starts at the bytes on disk and works up: how rows are stored and changed, how indexes and the planner find them, how to change a schema without an outage, and how to run Postgres in production. Along the way it builds two habits. Before you add an index, raise a setting, or blame the ORM, ask how many pages the work touches. And before you buy a bigger database, or a second one, use up the cheap fixes and prove in numbers that you’ve outgrown them.
That includes knowing where Postgres stops. On the same two million events, two column stores kept the data in under a fifth of the bytes and answered about ten times faster than a tuned Postgres. The book shows how far one Postgres goes, and the signal that tells you it’s time for something else.
It’s written for application developers who use Postgres every day, often through an ORM. You need basic SQL, not internals.
Every claim that matters comes with a check
Every query ran against PostgreSQL 18, on a sample schema you can load in a minute, and every claim that matters comes with a lab check you can rerun on your own machine. Each chapter is a short essay you can read on its own; deep dives hold the machinery and the full measurements for when you want them.
Free, and written in the open
Read it here, chapter by chapter, or download the whole thing as a PDF. It’s versioned in git like everything else we publish, so when Postgres changes, the book does too. If something’s wrong or unclear, that’s a bug: open an issue or send a fix.
Contents
Figures
- Figure 2-1 — One server, many databases, a process per connection. Each connection gets its own backend process, which works in one database; inside it, schemas hold the tables. Beside the backends, the server runs its own processes, and roles and settings belong to the whole server.
- Figure 3-1 — A page lives in one of three places. A hit in shared_buffers is a memory lookup; a miss, which EXPLAIN calls "read", costs a system call and a copy if the kernel has the page cached, and a trip to the device if it doesn't. Postgres can't tell those last two apart.
- Figure 4-1 — Line pointers from the front, tuples from the back. The two grow toward each other, and the page is full when they meet.
- Figure 5-1 — Finding a page is one hash lookup. The tag lands in one of 128 separately locked partitions. A hit pins the buffer and is done; a miss has to evict a victim, maybe write it out, and read the page in.
- Figure 5-2 — The hand takes a point from every buffer it passes. It skips pinned buffers and evicts the first one it finds at zero. A page read constantly is back at 5 before the hand returns, so it never gets there.
- Figure 6-1 — An update is an insert plus a stamp. The old version stays in slot 1, stamped with the updater's XID and a ctid pointing at (0,4); the new version is a complete copy in slot 4. Four tuples now hold three rows.
- Figure 7-1 — HOT keeps the new version where the indexes can already find it. A cold update puts the new version on another page and adds an entry to every index. A HOT update writes it on the same page, chained from the old one through t_ctid, and no index changes; after pruning, lp1 becomes a redirect to the new version.
- Figure 8-1 — A commit waits for the log, not the pages. The update dirties a page in shared_buffers and appends a WAL record. COMMIT waits only until that record is flushed to the sequential WAL; the checkpointer or background writer writes the page to the data files later.
- Figure 8-2 — Recovery starts at the redo point. A checkpoint begins at its redo point, writes the dirty pages, and logs its checkpoint record when done. Everything before the redo point is already in the data files, so after a crash, replay starts there.
- Figure 8-3 — Every checkpoint resets the images. The first change to a page after a checkpoint carries a full 8 KB image of it; later changes to that page are small records. After the next checkpoint, the first change pays again.
- Figure 11-1 — InnoDB finds rows by key, Postgres by address. In InnoDB the table is the primary key B-tree, so a secondary index entry holds the key and every row found through it descends that tree again. In Postgres every index, the primary key included, points straight at a page in the heap.
- Figure 13-1 — Increasing keys append; random keys scatter. New identity or UUIDv7 keys all land on the rightmost leaf, which stays in memory. UUIDv4 keys land on any leaf, a full leaf splits 50/50, and pages settle around 70 percent full against 90 for appends.
- Figure 17-1 — A lookup reads one page per level, then the heap. The primary key of events is 1 root page, 19 internal pages and 5,465 leaves over a heap of 35,173 pages, so finding a row reads three pages in the tree and one in the heap.
- Figure 21-1 — Find the node, then fix the estimate or the work. If estimated and actual rows differ 10x or more, fix the statistics or the query that misleads them; if the rows are right, fix the index, the shape or the prices. Reach for enable_* and hints only at the end.
- Figure 22-1 — OFFSET counts from the front; keyset starts at the bookmark. OFFSET 1000000 reads 1,000,020 index entries and 21,422 pages to show 20. The keyset query seeks to where the last page ended and reads the next 20 in 5 pages, the same on every page.
- Figure 25-1 — The second write wins, silently. Both transactions read 100, and tx2 waits for tx1's row lock, then writes a value computed from that stale read. The balance ends at 80, and tx1's spend is lost with no error.
- Figure 25-2 — One waiting lock stops every query. The migration waits for the idle reporting transaction, and every query after it, even a plain read, waits behind the migration. When reporting commits, the migration runs in a millisecond and the line drains.
- Figure 32-1 — Recovery is a base backup plus replay. Restore the base backup, then replay archived WAL forward until recovery_target_time. Replay stops just before the 14:02 mistake and the server opens there.
- Figure 38-1 — A replica replays the primary's WAL forever. The walsender streams WAL to the standby's walreceiver, the startup process replays it into pages, and the standby reports its LSN positions back to pg_stat_replication. It takes reads and refuses writes with 25006.
- Figure 39-1 — Deleting a month is work; dropping one is a file. The delete left 164,383 dead tuples and wrote 32 MB of WAL, and the vacuum after it wrote another 12 MB. Detaching and dropping the month's partition unlinks its files and wrote under 150 KB.
- Figure 40-1 — The shard key decides who does the work. A query that names account_id goes to the one shard holding that account, where its rows sit together. A query without it goes to every shard, and the results are merged.
Tables
- Table 1-1 — The machine comes first; then jump to what hurts
- Table 1-2 — One ordinary SaaS schema runs through every chapter
- Table 2-1 — A handful of psql commands cover this book
- Table 3-1 — Memory is cheap; everything else is expensive
- Table 3-2 — Round trips cost more than queries
- Table 4-1 — A row costs more than its columns
- Table 5-1 — Your query shouldn't be the one writing dirty pages
- Table 5-2 — Big operations get a ring
- Table 7-1 — A cold update pays for every index
- Table 7-2 — Every column an index mentions is indexed
- Table 7-3 — Leave room on the page, or every update moves
- Table 7-4 — Leave room on the page, or every update moves
- Table 7-5 — A long transaction turns HOT off
- Table 7-6 — Bottom-up index deletion is the safety net
- Table 8-1 — wal_compression is a cheap win
- Table 8-2 — Commit means flush
- Table 9-1 — Four promises, four mechanisms
- Table 9-2 — Only serializable rules out every anomaly
- Table 10-1 — The defaults are wrong for big tables
- Table 10-2 — Wraparound stops writes before anything is corrupted
- Table 11-1 — Where rows and old versions live decides the rest
- Table 11-2 — Secondary lookups cost two descents in InnoDB
- Table 11-3 — Integer division truncates, and NULLs sort last
- Table 11-4 — Most MySQL idioms have a direct Postgres equivalent
- Table 12-1 — Integers run out sooner than you think
- Table 12-2 — Pick a collation provider whose order never changes
- Table 13-1 — Random keys write nearly four times the WAL
- Table 13-2 — Random keys write nearly four times the WAL
- Table 13-3 — Every id format trades order against what it leaks
- Table 14-1 — Store each fact once
- Table 14-2 — The insert pays for every check
- Table 14-3 — History is a table you design
- Table 15-1 — Each model is one shape, made fast
- Table 15-2 — Entity-attribute-value is a trap
- Table 15-3 — Closure tables store every ancestor pair
- Table 16-1 — Contrib is the safest shelf, though some of it is obsolete
- Table 16-2 — A crashing extension drops every connection, so vet it
- Table 17-1 — Every index is a tax on writes
- Table 18-1 — Beyond the B-tree
- Table 18-2 — For containment, jsonb_path_ops beats the default
- Table 18-3 — GIN filters trigrams; GiST ranks by similarity
- Table 18-4 — A thousandth of the size, nearly the same pages
- Table 18-5 — The operator picks the index type
- Table 20-1 — Every price is relative to one sequential page
- Table 20-2 — Extended statistics measure columns together
- Table 21-1 — The 5% rule is wrong in both directions
- Table 21-2 — Join order is a search, and searches get expensive
- Table 22-1 — OFFSET reads every row it skips
- Table 23-1 — Store the tsvector; don't index the expression
- Table 23-2 — Search extensions put BM25 in the index
- Table 23-3 — ef_search trades latency for recall
- Table 24-1 — The primary is your most expensive CPU
- Table 24-2 — A row trigger costs about a microsecond a row
- Table 25-1 — Row locks live in the row, not in pg_locks
- Table 26-1 — Pick the index build that matches the table's traffic
- Table 26-2 — Pick the index build that matches the table's traffic
- Table 26-3 — Run a concurrent build alone, untimed, and check it's valid
- Table 26-4 — Widening a type is free; most other type changes rewrite
- Table 28-1 — Transaction pooling breaks session state
- Table 29-1 — Ask one question
- Table 30-1 — Context decides reload or restart
- Table 30-2 — Autovacuum's defaults suit small tables and slow disks
- Table 30-3 — Cheap logging answers most 3 a.m. questions
- Table 32-1 — Write down RPO and RTO first
- Table 32-2 — pg_dump leaves out roles; dump them separately
- Table 32-3 — pg_upgrade --link is fast and one-way
- Table 33-1 — The app never owns its tables
- Table 34-1 — Some jobs stay yours whoever runs the box
- Table 34-2 — Some jobs stay yours whoever runs the box
- Table 34-3 — The provider adds its own gate on CREATE EXTENSION
- Table 34-4 — Throttled I/O shows as flat IOPS and rising latency
- Table 34-5 — Failover is DNS, and your pool has to notice
- Table 35-1 — Know the shape and you know the tradeoffs
- Table 35-2 — Superuser access and retention rule services out
- Table 36-1 — 10. Scale out only for the signal that asks for it
- Table 36-2 — Eight changes, in the playbook's order
- Table 36-3 — Eight changes, in the playbook's order
- Table 37-1 — Measure before you buy anything
- Table 37-2 — Precompute what you show
- Table 38-1 — Synchronous commit costs a round trip
- Table 38-2 — Streaming for failover, logical for a job
- Table 39-1 — Range fits time; list and hash have narrow jobs
- Table 39-2 — Retention: detach, then drop
- Table 39-3 — Every partition a query can't prune costs planning time
- Table 39-4 — Every partition a query can't prune costs planning time
- Table 40-1 — Each option moves the hard parts somewhere else
- Table 40-2 — Each option moves the hard parts somewhere else
- Table 41-1 — Column stores keep a tenth of the bytes
- Table 41-2 — Postgres read every page for every query
- Table 41-3 — Column stores were about ten times faster, and still faster on one core
- Table 41-4 — Column stores were about ten times faster, and still faster on one core
- Table 41-5 — Rollups and a column extension close much of the gap
- Table 41-6 — Know the signal before you need it
Parts
| Part | Chapters |
|---|---|
| Front matter | 1–2 |
| The machine | 3–11 |
| Designing for it | 12–16 |
| Finding rows fast | 17–24 |
| Changing it | 25–27 |
| Running it | 28–36 |
| Scaling out | 37–41 |
| Back matter | 42–44 |
About this edition
© 2026 Flagon, Inc. All rights reserved. This English web edition reproduces the first edition of Eight Kilobytes: PostgreSQL from the page up, published 2026-10-05, with examples run against PostgreSQL 18. The original book text and figures are available online at Flagon. The book’s license permits online reading and reserves republication rights to Flagon, Inc.; this project records the source and version explicitly.
The lab kit and its MIT-licensed source files remain available from the original Eight Kilobytes lab.
1 Before you start
Here are two queries against the same table, on the same server, a few seconds apart:
The first touched 4 pages. The second touched 35,173.
Both return almost nothing, both look simple, and an ORM would generate either without complaint. One is how a database idles at 3% CPU. The other is how someone gets paged at 2 a.m.
That gap is why this book exists.
Count the pages
Most PostgreSQL advice arrives as folklore. Add an index. Raise shared_buffers. Run vacuum. Each is right some of the time, and without a model of the server you can’t tell which time this is.
The model is smaller than you’d think. Postgres stores everything (tables, indexes, the bookkeeping beside them) in 8 KB pages, and it reads, writes and caches whole pages. A slow query nearly always did one of two things: touched far more pages than it needed, or made far more round trips than it needed.
So the first habit this book builds is one sentence long: count the pages.
- When you design a table, ask how many rows fit on a page.
- When you add an index, ask how many pages a lookup touches before and after.
- When you read a plan, read the
Buffers:line first. It counts pages. - When a table grows faster than its data, ask what is sitting in those pages that you didn’t put there.
You don’t need to think about bytes all day. You need a feel for what fits in 8 KB, because nearly every performance property of Postgres follows from it. Hence the title.
Earn the bigger box
The second habit is about money. When a database gets slow, the easiest thing to buy is a bigger one, and it works, for a while. Then the data catches up, and you’re paying more every month for the same problem.
An index costs nothing per month. A rewritten query costs an afternoon. A pooler, a vacuum setting, or a smaller row costs a little reading. So we hold one opinion harder than any other in this book: use up the cheap fixes before you buy hardware, and when you do upgrade, prove the need in numbers (Earn the bigger box). Every chapter is, one way or another, a cheap fix and the evidence that it worked.
Start with one database, and leave on evidence
A growing product collects databases: a cache, a document store, a queue, a search engine, a vector store. Each brings its own backups, upgrades, failure modes, and pager, and its data has to stay in sync with all the others.
Postgres covers most of that list from one server, in the same transaction as the rest of your data. Documents go in jsonb. A queue is a table and for update skip locked. Full-text search and vectors live next to the rows they describe. Time series fit BRIN and monthly partitions, and maps run on PostGIS. It’s one size that fits most, and most reaches further than you’d guess (You don’t need another database (yet)).
Most isn’t all, and this book says where the line is. On the same two million events, two column stores kept the data in under a fifth of the bytes and answered about ten times faster than a tuned Postgres, and still at least twice as fast on one core. Search relevance at scale, streams, global writes, and very large vector sets have lines of their own (Where Postgres loses).
So we start every product on one Postgres, and add a second system only for a property we can name and a number that proves we need it, with Postgres still the source of truth. It’s the bigger box again, applied to architecture: start grounded, and leave on evidence.
Every claim comes with a proof
You shouldn’t take a database book’s word for anything, this one included. So every claim that matters ships with its evidence.
Every query here ran against a real PostgreSQL 18 server, on a sample schema you can load in a minute. The plans are real plans, the sizes are real sizes, and when a chapter says an index helps, it shows the pages read before and after. Prove it boxes sit next to the claims that matter. Each holds the exact check from that chapter’s lab script, a lab.prove(...) that fails loudly if the claim isn’t true, so you can rerun the evidence instead of trusting us.
That’s also how the book stays honest. When Postgres changes, a check fails, and the chapter gets fixed.
You know SQL; this is what’s underneath it
You write application code and use Postgres every day, through an ORM or by hand. You know select, join, group by, insert and update. Maybe you recently became “the database person” because someone had to.
What you lack is a model of what’s underneath: why an update makes a table bigger, why last month’s fast query is slow now, why the planner ignores the index you just built. Without it, tuning is guessing. Every internal concept is explained the first time it appears. No C, no source code, no production experience required.
Read it at two depths
Every chapter is two books in one. The simple track is a short essay: the argument, the one piece of evidence that proves it, and what to do. Read only that, in every chapter, and you get the whole book. The deep dives hold the internals, the full measurements, and the edge cases, each one placed right after the paragraph it deepens.
On the site, the Simple / Deep dive switch at the top of a chapter sets the depth for the whole book; in Simple mode each deep dive folds to one line you can open on its own. On paper, every deep dive is printed, set apart so you can skip it, and each Prove it box prints as the claims its checks make, plus the lab file that holds them.
Why I wrote this
I’m Chase Pierce, and I started Flagon to build software, and a company, in the open.
I don’t have a war story about how I got here. I picked Postgres for plain reasons and kept picking it. Over MySQL, because it does more: transactional schema changes, richer types, and an extension system that lets the database grow into what you need. Over Oracle and SQL Server, because it’s open source, runs anywhere, and has no license to count cores against. Those reasons have held up on every project since.
What never held up was the advice around it. The book I wanted didn’t exist in one place. Internals books assume you want to work on the server itself. Tuning guides hand you settings without the model that explains them. Blog posts are right for someone’s workload, on someone’s version, in some year. I wanted the model, the evidence, and the opinions together, written for the person who just inherited the database. So I wrote it, and made every claim carry a check, because a claim you can’t rerun is one more piece of folklore.
The rest of the book says “we”. That’s Flagon’s voice, and it’s also you and me at the same terminal, looking at the same plan. When we hold an opinion, we say so plainly and show the numbers behind it. When you find a mistake, it’s a bug: open an issue or send a fix.
The machine comes first; then jump to what hurts
| Part | What it covers |
|---|---|
| The machine | Latency, pages, the buffer cache, MVCC, HOT updates, the write-ahead log, ACID, vacuum, and how all of it differs from MySQL |
| Designing for it | Types, keys, constraints, data models, extensions |
| Finding rows fast | Indexes, EXPLAIN, the planner, query patterns, search, functions |
| Changing it | Locks, migrations that keep the site up, bulk loading |
| Running it | Connections, benchmarking, configuration, monitoring, backups, security, managed services, a playbook for slow databases |
| Scaling out | Scaling up first, replication, partitioning, sharding, and where Postgres loses |
First comes a primer, Know the nouns first: a crash course in SQL and the server’s vocabulary: tables, queries, updates, joins, indexes, databases, schemas, roles, the catalog. Skip it if search_path and pg_class are old friends. The machine is the foundation. If you read nothing else, read Everything is a page and Updates are inserts; almost every later chapter leans on them. Then jump to whatever is hurting. A slow query ruining your week? Start with Read the plan, not the clock. Coming from MySQL? Postgres is not MySQL flags the habits that don’t transfer.
Every chapter ends with “The short version” and “Further reading”.
Every example ran on PostgreSQL 18
The book targets PostgreSQL 18. Almost every example ran on 18.6; the few chapters that needed a third-party image pinned another minor release and say so (Citus in Shard last on 18.4, pg_duckdb in Where Postgres loses on 18.1). Most of it applies to any release from 13 on, and newer features are tagged with the version that introduced them, like MERGE (PostgreSQL 15+). Page layout, MVCC, vacuum, the planner and the write-ahead log have changed in detail, not in shape.
Output from psql and EXPLAIN sits in its own block right after the query that produced it, trimmed with ... where long. Some of it will differ on your machine, and that’s expected:
- Transaction IDs, OIDs and file names are assigned by the server as it runs. Yours will differ; the relationships between them won’t.
- Timings depend on hardware and load. Ours ran on a laptop, inside Docker, next to other workloads, and a few labs that write heavily turn on
synchronous_commit = offto finish faster (they say so), so treat every millisecond as rough. - Buffer counts and row counts are the evidence. For a given data set and plan, they come out the same every time. A whole query’s count can run a few dozen pages past the table itself, for the catalog and other small reads: a full scan of the 35,173-page
eventsheap reports about 35,249. - Sizes are the binary values
pg_size_prettyreports: the 288,137,216-byteeventsheap is 275 MB, not 288.
Callouts flag what you must not miss. Read every warning; each one describes a way to take down a production database.
Run your own PostgreSQL 18
You need Docker, and bash: any Linux or macOS terminal, or Git Bash or WSL on Windows. The lab kit is a small Compose project: PostgreSQL 18 with the example data, plus one script per chapter that turns the chapter’s claims into checks. Download it and run a chapter:
A chapter’s number or name works too (./lab 3, ./lab storage), and ./lab alone lists them all. The first run starts the server and builds the example database, which takes about a minute. Each run gets a fresh copy of the data, prints PROVED: for every claim that holds, and stops at the first one that doesn’t. ./lab all runs every chapter and lists any that failed; the lab page explains the rest.
The server listens only on your machine, at 127.0.0.1:5418, if you’d rather use a GUI client. A few chapters (replication, sharding, the MySQL comparison) need more than one server; for those, ./lab starts the extra containers and removes them afterwards.
The kit’s postgres user is a superuser. That matters: some of the book’s best tools (pageinspect above all, which reads the raw bytes of a page) are superuser-only by default, and managed services generally don’t give you one. When you’re finished, docker compose down -v throws it all away.
One ordinary SaaS schema runs through every chapter
Every chapter uses the same small SaaS schema: accounts, their users, the projects they own, and a large table of events (deploys, builds, comments, alerts, logins) that grows forever. It’s deliberately ordinary, and big enough for the planner to make real decisions and for mistakes to cost something you can measure:
| Table | Rows | Heap size | Columns worth knowing |
|---|---|---|---|
| accounts | 1,000 | 72 KB | plan |
| users | 100,000 | 9 MB | account_id, email (unique together) |
| projects | 20,000 | 1.5 MB | account_id, owner_id, archived_at |
| events | 2,000,000 | 275 MB | account_id, project_id, user_id, kind, payload (jsonb), created_at |
Every table has a bigint identity id and a created_at. The data is generated from a fixed random seed and dated back from one fixed moment, October 6, 2026, so your plans, counts and dates will match ours.
Two things are intentional, so don’t “fix” them yet:
eventshas no secondary indexes, only its primary key. The indexing chapters add them one at a time, so you can see exactly what each one buys.- Only one foreign key column is indexed, and only by accident.
users.account_idleads theunique (account_id, email)constraint’s index; no other referencing column has one. Postgres doesn’t index referencing columns for you, and that’s one of the most common mistakes in real schemas. Constraints, chosen on purpose shows what it costs.
The whole seed is seed.sql in the kit: five extensions, four tables, and an insert per table. The interesting part is the generator. Here is events and the statement that fills it:
setseed makes random() return the same sequence every run, so the same projects get the same events. created_at is spread evenly over the year before October 6, 2026, and the order by inserts rows in time order, which is why recent events sit together at the end of the table (a fact the latency and indexing chapters lean on). The repeated array entries skew the mix: deploys and builds are common, comments, alerts and logins an eighth each, and a quarter of statuses are failed. The final vacuum analyze leaves every page marked all-visible and the planner’s statistics fresh.
The kit loads it into a database called book (about 345 MB) and marks it as a template. Copying a template is far cheaper than rerunning the seed, so explore in a copy:
Many chapters update every row, delete half a table, or add and drop indexes. Never touch book itself (the kit doesn’t even allow connections to it). When you’ve made a mess in scratch, drop database scratch and copy again.
Break things here, not in production
Some examples are destructive on purpose: they update millions of rows, hold transactions open, or delete half a table to watch vacuum work. Run them on your disposable server, never on a database anyone depends on. Where a technique is meant for production (a migration pattern, a monitoring query, a setting), the text says so, with what it locks and what it costs.
After a short primer on the nouns, the first stop is the hardware, because a page costs wildly different amounts of time depending on where it is when you ask for it.
The short version
- Nearly every Postgres performance question reduces to pages touched and round trips made. Count the pages.
- Use up the cheap fixes before you buy hardware, and prove the need in numbers when you do. Earn the bigger box.
- Start on one Postgres. Add a second system only for a property you can name and a number that proves you need it.
- Read the
Buffers:line of a plan before the timing. Buffer and row counts are repeatable; milliseconds aren’t. - Every claim that matters has a Prove it check. Rerun it instead of trusting us.
- Read the simple track for the argument; open a deep dive when you want the internals or the full measurements.
- Get the lab kit for a disposable PostgreSQL 18 with the example data in a template called
book. - Rerun any chapter’s evidence with
./lab <chapter>from the kit’s folder; the Prove it boxes show the checks. - Work in a copy (
create database scratch template book) and drop it when you’ve made a mess.
Further reading
- PostgreSQL 18 documentation, PGDG. The reference this whole book leans on; learn to find your way around it.
- PostgreSQL 18 release notes, PGDG. The source for every “(PostgreSQL 18+)” tag in the book.
- Versioning policy, PGDG. Five-year support windows, and how long your major version has left.
- psql reference, PGDG. The client behind every example; its backslash commands repay an hour of reading.
- Set returning functions, PGDG. How
generate_seriesbuilds the seed, and how to build your own test data.
2 Know the nouns first
This book argues about pages, plans, and locks. Those arguments assume some SQL and a handful of Postgres nouns. If you’ve written select, insert, and update against Postgres and know what a schema is, skim the headings below and move on; you lose nothing. If you haven’t, this primer is your crash course: the least you need to follow every chapter after it.
Fair warning about what comes next: the rest of the book assumes everything here and goes deep fast, down to the bytes on disk, because that’s where the answers to “why is this slow?” live. Every claim in this chapter runs against the lab server, like the rest of the book, so even the basics come with proof.
A table is rows that share the same columns
Postgres keeps your data in tables. A table has named, typed columns, and every row holds one value for each column, or NULL, which means “no value” (not zero, and not an empty string). Here’s the book’s biggest table, events:
Read it line by line and you’ve met most of what a schema says. bigint is a large integer, text is a string of any length, jsonb is a JSON document, and timestamptz is a moment in time. not null forbids NULL, and default fills in a value when you don’t give one. The id is the primary key: a value no other row shares, which Postgres numbers for you, so any row can be found by it. Each references line is a foreign key: account_id must name a row that exists in accounts.
events holds two million rows, every one with the same seven columns. A table is the shape; the rows are the data.
01-basicsSELECT asks, and changes nothing
You read with select. Name the columns you want, the table they come from, and a where clause that keeps only the rows you care about; order by sorts them and limit stops early:
Two more words cover most reports. count(*) counts rows, and group by counts them per value:
A select never changes anything. It doesn’t even take a transaction ID (XID), the number Postgres stamps on every change. That doesn’t make it free. The whole book is about how many pages a select has to read to answer you.
01-basicsINSERT adds a row, and in Postgres so does UPDATE
Three statements change data. insert adds rows, update changes them, and delete removes them. Here they are on notes, a scratch table with an id and a body:
Always give update and delete a where. Without one, they apply to every row in the table, and Postgres won’t ask whether you meant it.
Here’s the first thing that makes Postgres Postgres. An update doesn’t change the row where it sits. It writes a complete new copy of the row, on the same page if there’s room, and marks the old copy as replaced. A delete marks the row dead and leaves it in place. Both old copies stay on the page until vacuum, a background cleanup, clears them. On a one-row table, one update left two copies on the page, and after the delete there were still two copies of a row the table no longer has.
That one fact explains why tables grow, why vacuum exists, and why a busy table can be twice the size of its data. The book calls it Updates are inserts, and it comes back in nearly every chapter.
01-basicsJOIN puts the tables back together
A good schema stores each fact once: a user’s email lives in users, an account’s plan in accounts. A join brings them back together by matching rows across tables, almost always on a foreign key:
The u and a are short names for the tables, and on says which rows match: here, the account whose id is the user’s account_id. User 295 belongs to account 296. A plain join keeps only rows that match on both sides; left join keeps every row on the left, with NULLs where nothing matched.
01-basicsAn index makes one read cheap and every write dearer
Ask for one user by email, and without help Postgres reads the whole users table to find it: 1,126 pages for one row. (The unique (account_id, email) constraint has an index, but it’s sorted by account first, so finding an email through it means searching it once per account, and the planner reads the table instead.) An index is a separate, sorted structure that points at rows, like the index at the back of a book. Build one on email and the same lookup reads 4 pages:
Indexes aren’t free. Every insert, and every update that changes an indexed column, has to update each index too. So index the columns your queries actually search on, not every column you have. The B-tree does the heavy lifting shows how an index finds a row in a handful of pages.
01-basicsThat’s enough SQL to follow the book. The rest of this chapter is the server underneath it.
One server runs many databases, and they don’t share tables
A Postgres server is one data directory and the processes running on it. The documentation calls it a cluster, which has nothing to do with several machines; it’s one server. It holds many databases. The lab server has four:
A connection picks one database and sees only that one. Try to read another and Postgres refuses:
That’s a design decision, not a missing feature: each database has its own tables, its own catalog, and its own extensions. Roles, tablespaces, and the server’s configuration file are the exceptions, shared by the whole server. If two parts of your app need to join their data, they belong in one database, in two schemas.
create database copies template1 unless you name another template; template0 is a pristine spare. The lab marks book as a template too, which is why create database scratch template book is far cheaper than loading the data again.
01-basicsEvery connection is its own process
When your app connects, the server starts a new operating-system process to serve it, a backend, and that process lives until the connection closes. Ten connections are ten processes, each with its own memory. That one fact explains why connections are expensive, why max_connections is a ceiling and not a capacity, and why every production app ends up behind a pooler (Connections aren’t free).
The server runs its own processes too. On the lab server, beside the one client:
Most of the book is about what those do: the WAL writer flushes the write-ahead log in the background, the checkpointer and background writer write changed pages back to their files, the autovacuum launcher starts vacuum workers, and the io workers (PostgreSQL 18+) do reads on the backends’ behalf.
01-basicsSchemas are folders, and search_path picks the one you meant
Inside a database, tables live in schemas: named folders, one level deep. Every new database has one called public, and if you’ve never created another, everything you own is in it. public.invoices and billing.invoices are two different tables.
When you write a bare invoices, Postgres looks through the schemas named in search_path, in order, and uses the first match. Put billing first and the same query reads a different table. That’s convenient for organizing a big schema. It’s also how a function can end up calling something you didn’t write, which is why the security chapter pins search_path on every function that runs with elevated rights.
01-basicsA role is a user, a group, or both
Postgres has one kind of principal, the role. A role with the LOGIN attribute is what you’d call a user; a role without it is a group; and any role can be a member of another and inherit its privileges. Every table has an owner role, which can do anything to it, and every other role gets only what it’s granted.
The habit to build now: your application should connect as a role that owns nothing and isn’t a superuser, so a bug in the app can’t drop a table. Trust no tenant shows the setup.
01-basicsEvery statement runs in a transaction
Postgres never runs a statement outside a transaction. Send one update on its own and Postgres wraps it in a transaction that commits when the statement finishes; that’s autocommit, and it’s what your driver does unless you say begin. Two statements sent that way are two transactions, each paying for its own commit.
Inside begin and commit, everything lands together or not at all, and in Postgres “everything” includes schema changes. A create table rolled back is gone, so a migration that runs in one transaction and fails leaves nothing half-done (ACID, honestly). It also means a long transaction holds everything it touched, locks included, until it ends. You’ll meet that open transaction again and again in this book.
01-basicsThe server describes itself in tables
Everything Postgres knows about your schema lives in ordinary tables you can query, the system catalog. pg_class lists every table and index, pg_attribute their columns, pg_roles the roles, pg_settings every setting. The pg_stat_ views count what the server has been doing. psql’s backslash commands, like \d events, are queries over these tables.
The catalog already counts pages for you:
That’s the planner’s picture of events: 35,173 pages and about two million rows, updated by vacuum and analyze. That page count is the number this whole book keeps returning to.
01-basicsA setting has a value, a source, and a scope
Postgres has a few hundred settings, like work_mem, the memory one sort may use (4 MB by default). Each one has a value, a place that value came from, and a scope. The configuration file sets the server’s default. alter database and alter role override it for one database or one role. set changes it for your session, and set local for one transaction, after which it snaps back.
You’ll use the narrow scopes most. A report that needs more memory for one big sort should set local work_mem inside its transaction, not raise it for every connection on the server. show work_mem reads the current value, and pg_settings tells you where it came from (The settings that matter).
01-basicsExtensions arrive with one command
An extension adds types, functions, operators, or index methods to one database with create extension. Some ship with Postgres (the “contrib” modules); others you install on the server first. The lab database has the five this book leans on: pg_stat_statements to rank queries, pageinspect to read raw pages, pgstattuple and pg_buffercache to measure tables and the cache, and pg_trgm for text search.
Managed services allow a fixed list, so check it before you design around one (Extensions worth knowing).
01-basicsYour data is files you never touch
Under it all, every table and index is a file in the server’s data directory, named by numbers, not by your table names:
288,137,216 bytes is 35,173 pages of 8,192 bytes, the same count the catalog gave. Postgres reads and writes those files a page at a time, and that’s where the rest of the book begins. Everything is a page opens one up.
Never edit, copy, or delete anything in the data directory by hand, least of all pg_wal. The server is the only thing that understands those files, and a copy taken from under a running server is not a backup.
01-basicsA handful of psql commands cover this book
Every example in the book ran in psql, the command-line client that ships with Postgres. GUI clients work fine, but a handful of backslash commands are worth knowing by heart:
| Command | Does |
|---|---|
\d name | describes a table: columns, indexes, constraints |
\dt, \di, \dn, \du | lists tables, indexes, schemas, roles |
\x | prints wide rows vertically, one column per line |
\timing | prints each statement’s time |
\e | opens the last query in your editor |
Add \? for the rest. When a backslash command shows you something useful, \set ECHO_HIDDEN on prints the catalog query behind it, which is the fastest way to learn the catalog.
The short version
- A table is rows that share typed columns. The primary key finds a row; a foreign key points at one in another table.
selectreads and changes nothing. In Postgres anupdatewrites a new copy of the row, and adeleteleaves the old row in place, until vacuum clears them.- An index turned 1,126 pages into 4 for one lookup, and every write pays to keep it current.
- One server holds many databases that can’t query each other; inside one, schemas are folders and
search_pathpicks among them. Roles are shared by the whole server, and apps should connect as one that owns nothing. - Every connection is a process with its own memory, which is why connections cost what they do.
- Every statement runs in a transaction. Schema changes roll back too, and an open transaction holds what it touched.
- The catalog is queryable tables, settings have scopes (use the narrowest), and tables are files of 8 KB pages you never touch by hand.
Further reading
- The SQL Language, PostgreSQL documentation. The manual’s own tutorial: tables, queries, joins, and updates, one short page each.
- Architectural Fundamentals, PostgreSQL documentation. The two-page version of the process model, from the tutorial.
- Schemas, PostgreSQL documentation. Schemas,
search_path, and the usage patterns the manual recommends. - Database Roles, PostgreSQL documentation. Roles, attributes, and membership.
- System Catalogs, PostgreSQL documentation. Every catalog table, column by column, for when
\disn’t enough. - psql, PostgreSQL documentation. Every backslash command and variable.
3 Where the time goes
An endpoint that lists a team’s projects takes 180 ms in production. You copy the query from the logs, run it in psql, and it finishes in 0.4 ms. Again: 0.3 ms. The database is clearly fine.
Then you count. The endpoint doesn’t run one query. It runs one to fetch 100 projects, one per project for the owner, and one per project for the latest deploy. That’s 201 queries, each fast on the server, each crossing the network and back. At half a millisecond per round trip, the network alone costs 100 ms before the database does any work.
Nothing in that story is slow. It’s counted wrong. Know roughly what each kind of operation costs and you can estimate a query, an access pattern, or a loop in your code before you measure it.
Memory is cheap; everything else is expensive
You can’t estimate a query until you know what its parts cost. Here is the latency ladder for a database. Rows marked “measured” come from the lab kit on our laptop; the rest are orders of magnitude, not guarantees.
| Operation | Typical latency |
|---|---|
| CPU L1 cache reference | about 1 ns |
| Main memory (RAM) reference | about 100 ns |
| Read an 8 KB page from the OS page cache | 4 to 5 µs (measured) |
| Random read from local NVMe | tens of µs |
| Round trip within one availability zone | 100 to 500 µs |
| Random read from network block storage | under 0.5 ms to several ms |
| Round trip across availability zones | about 0.5 to 2 ms |
| Durable write (fsync) on our laptop SSD | 0.65 ms quiet, 18 ms busy (measured) |
| Round trip across regions | 30 to 150 ms |
Three lessons drive almost every database decision. Memory is cheap; everything else is expensive, so the first question about any query is how many pages it touches, and where they are. The network isn’t free, even nearby: a same-zone round trip costs about as much as a network disk read. And durability is the slowest thing on every write, which is why the write-ahead log exists.
The CPU, memory, SSD and network rows follow the classic ladder in Numbers Every Programmer Should Know By Year (1 ns L1, 100 ns RAM, 16 µs SSD random read, 500 µs datacenter round trip, 150 ms California to the Netherlands and back). The network storage row comes from AWS’s own volume type documentation: io2 Block Express volumes average under 500 µs per I/O, and general-purpose gp3 volumes promise “single-digit millisecond” latency. Cross-zone round trips depend on the provider and the zones; AWS says only that its zones are within 100 km of each other, so measure yours. One disk can also swing widely with load: our laptop’s fsync measured 0.65 ms quiet and 18 ms while other containers hammered the same disk.
A query is pages and round trips
A rough model, good enough for most decisions:
For a typical application query the CPU term is small and the first two dominate. To see the page term, take the two queries from the preface and ask Postgres to report what it did:
That’s a query plan, and you’ll read hundreds in this book. Four rules get you through them until Read the plan, not the clock covers the rest. Each line is a step, a node; the most indented runs first and feeds the one above. actual rows is what a node produced, per loop. Buffers: counts the 8 KB pages it touched: hit means the page was already in Postgres’s memory, read means Postgres had to ask the operating system. And read that line first: timings bounce with cache and load, page counts don’t. (PostgreSQL 18 shows it by default; before 18, write explain (analyze, buffers).)
Four pages, all in memory: three in the primary key index (the B-tree chapter shows its shape) and one in the table, holding the row.
02-latencyNow a filter on a column with no index:
35,173 pages to find 85 rows: every page of the table. It still took only about 30 ms, because three processes shared the work and the “read” pages came from the operating system’s memory, not the disk.
Four pages against 35,173, both “simple”. Once an hour in a report, 30 ms is fine. On every page view, it’s the most expensive thing your database does. The skill here is noticing the ratio.
The scan’s count is the same on every run: 35,173 is every page of events, and 85 is how many events project 4242 has.
02-latencyNeither plan asked for buffers; PostgreSQL 18 reports them anyway. The lab checks that against the JSON form of a plain explain (analyze).
02-latencyRun the primary key lookup on a fresh copy and the first execution shows a few more pages, read rather than hit, while Postgres loads the index’s metadata page and the path down the tree. Run it again and it settles at four.
A page lives in one of three places
When Postgres needs a page, it looks in three places, each far slower than the last: a desk, a filing cabinet across the room, a warehouse across town.
shared_buffers is Postgres’s own cache of pages, shared by every server process. The default is 128 MB, tiny on purpose; the usual production starting point is about 25% of RAM (The settings that matter). The buffer cache decides what stays shows how it chooses what to keep.
The OS page cache is the kernel’s cache of file contents, in whatever RAM is otherwise free. Every page Postgres reads also lands there, so a hot page can sit in both caches at once. That double buffering is why shared_buffers isn’t set to 90% of RAM.
“Read” does not mean “from disk”
In a plan, read means “not in shared_buffers, so Postgres asked the kernel”. Whether the kernel went to the device, Postgres can’t see. The clock can: the lab kit turns on track_io_timing, which adds an I/O Timings line. Here are 2,000 primary key lookups scattered across the table:
3,139 pages read in 15.0 ms: about 5 µs per page (4 to 5 µs across our runs). No storage device does random reads that fast; those pages came from the OS page cache. Tens of microseconds or more per page means a device.
The query behind those numbers:
Don’t divide the sequential scan’s numbers instead. In PostgreSQL 18 a sequential scan reads ahead through asynchronous I/O and combines neighboring pages into larger reads (up to io_combine_limit, 128 KB by default), so most of its I/O time overlaps with other work and the per-page figure means little. Random reads, one page at a time, are the honest test.
02-latencyBig scans don’t flush the cache
You might expect that full scan of the 275 MB events table to push everything else out of a 128 MB cache. It doesn’t. A big sequential scan recycles a small private ring of buffers (2,304 KB in PostgreSQL 18 with default settings), so one report can’t evict the pages your application lives on (Big operations get a ring).
Every commit waits for the disk
Reads can be cached. Commits can’t, not if they must survive a crash. On commit, Postgres writes a record to its write-ahead log and waits for the disk to confirm it’s durable. That wait is an fsync, and your hardware sets its price: about 0.65 ms on our quiet laptop SSD, 18 ms with other containers writing to the same disk, and well under a millisecond on good server storage.
A client that commits one row at a time pays one flush per row. At 0.65 ms that’s about 1,500 commits per second at the very best; at 18 ms, about 55. So 10,000 rows in 10,000 transactions cost 10,000 flushes, and in one transaction, one.
Batch your writes (Load it fast), and for write-heavy systems buy storage with fast fsync before fast reads. Commit means flush measures the commit rate, and the two ways around the wait: many sessions sharing one flush, and not waiting at all.
Postgres has a server setting called fsync. Setting it to off makes benchmarks look wonderful and turns any crash or power loss into possible silent corruption of the whole cluster, not just the last few transactions. synchronous_commit = off is the safe version of the idea, and you can set it per session or per transaction: a crash may lose commits from the last fraction of a second (at most three times wal_writer_delay, 600 ms by default), but the database stays consistent.
pg_test_fsync ships with Postgres. Run it on the volume where your data lives; in the lab kit, open a shell with docker compose exec postgres bash first:
fdatasync is the server’s wal_sync_method on Linux: 0.65 ms here. Unsynced writes ran at 2.6 to 2.9 million per second across our runs. That gap, three orders of magnitude, is the price of durability.
IOPS are capped by reads in flight, not by what you paid
Every read that misses both caches, and every commit, lands on storage. If you’re on a managed service, your data most likely lives on network block storage: a volume that looks like a local disk but sits on servers down the hall, so every cache miss is a network request. That storage is sold by three numbers that are easy to confuse: latency (how long one I/O takes), IOPS (I/Os per second), and throughput (bytes per second).
Queue depth, the number of I/Os in flight, connects them: IOPS achieved = I/Os in flight / latency. A process that waits for one 1 ms read at a time gets 1,000 IOPS, however many you paid for. (That’s Little’s law; it holds for the line at the post office too.) Big scans can keep many reads in flight; an index lookup that misses the cache is one round trip to the storage servers.
Do the arithmetic. AWS gp3 starts at 3,000 IOPS and 125 MiB/s: about 3,000 random cold page reads per second, for every connection combined. Buy faster volumes when you’ve measured that you’re I/O bound, never instead of an index. On a managed service this is usually the first ceiling you hit (The volume is your bottleneck now).
On gp3’s baseline of 3,000 IOPS and 125 MiB/s:
- Random page reads: 3,000 IOPS times 8 KB is about 24 MB/s. Index lookups on a big table that doesn’t fit in memory are capped at about 3,000 cold pages per second, across all connections.
- Sequential scans: the 275 MB
eventstable read cold at 125 MiB/s takes about 2.2 seconds. A 100 GB table takes over 13 minutes, and a nightly report doing that saturates the volume for everyone else.
Provisioned-IOPS volumes (io1/io2-style) sell more IOPS and lower, steadier latency at a higher price.
Burst credits have exact numbers too. A gp2 volume under 1 TiB bursts to 3,000 IOPS on a balance that lasts at least 30 minutes at full burst, and many smaller instance types can drive their maximum EBS performance for 30 minutes at least once every 24 hours before falling back to a baseline that can be several times lower. gp3 volumes don’t burst; they hold their provisioned numbers.
Burst credits run out in the middle of the job
gp2 volumes and many smaller instance types run on burst credits: fast for a while, then back to a much lower baseline when the credits run out. Testing goes fine, and so does the first half hour of a heavy job; then latency climbs with no change in traffic. If an I/O cliff lines up with time under load rather than with load, check your burst balance before your queries.
Local NVMe is fast and dies with the host
Local NVMe reads in tens of microseconds and dies with the host. Use it only with replication and backups built for losing a node at any moment (Local NVMe: fast, and gone with the host). Network volumes survive the host and charge you latency on every miss.
Size RAM to the working set
The most effective hardware decision for Postgres is enough RAM for your working set: the pages your workload touches over, say, an hour. Not the whole database; the part that’s used.
All of events is 318 MB with its index. But suppose the application mostly shows the last week. Events arrive in time order, so the latest 7 days sit together at the end of the table: 675 pages, about 5 MB, smaller than users. That’s the common shape: a big tail that’s rarely read and a hot head that’s read constantly. Your working set is the hot head of each table, plus the index pages that find it, plus whatever periodic jobs touch.
If the working set fits in RAM (shared_buffers plus the OS page cache), almost every read takes microseconds. If it doesn’t, every query becomes a storage-latency query, and no amount of IOPS will make it feel like memory. RAM is usually cheaper than IOPS, and much cheaper than engineering time.
How big everything is, heap and indexes:
A row’s ctid is its physical address, a page number and a slot (A line pointer lets a tuple move without changing its address takes it apart); casting it to a point pulls out the page number. The sample data ends on October 6, 2026, so we measure back from the newest event rather than from now():
02-latencyWatch it run shows how to measure what your cache is serving.
Round trips cost more than queries
Back to the endpoint from the start. Timed end to end with pgbench, the load generator that ships with Postgres (pgbench is already installed), a primary key lookup took 78 µs, trip included, with client and server on one laptop. Another host in the same zone adds roughly 100 to 500 µs per query; another zone, up to a couple of milliseconds; another region, 30 ms or more.
Now the N+1 math. A page showing 100 projects that loads each owner separately runs 101 queries:
| Where the app runs | Round trip | 101 queries | 2 queries |
|---|---|---|---|
| Same host | 0.08 ms | 8 ms | 0.2 ms |
| Same zone | 0.5 ms | 51 ms | 1 ms |
| Other zone | 1.5 ms | 152 ms | 3 ms |
| Other region | 60 ms | 6 s | 120 ms |
The queries didn’t get slower. Only the distance changed. That’s why N+1 bugs are invisible on a laptop and painful in production, and why moving the database to “a better region” without moving the app makes everything slower.
The ORM version looks innocent:
Fetch them in one query instead, with a join or an array parameter:
Fetching 100 rows by primary key this way took about a millisecond, in one round trip. Most ORMs can ask for it (“eager loading”, “includes”, “preload”); Queries that age well covers the SQL side.
100 rows, 213 pages, one round trip. (written counts dirty pages this backend had to write out before it could reuse their buffers, on a server busy with other labs; Your query shouldn’t be the one writing dirty pages explains it.)
02-latencyThe per-query number came from a two-line script, lookup.sql (100 µs per query on a busy run):
A new connection costs several round trips before it runs anything, so use a pool (Connections aren’t free). Transactions add trips too: begin, each statement, and commit are separate unless your driver pipelines them, so a five-statement transaction is at least seven. Pipelining sends several queries without waiting for each result (libpq has supported it since PostgreSQL 14, and several drivers expose it), which cuts latency for chatty workloads without restructuring queries.
Estimate before you measure
You can now estimate most queries without running them. Three same-zone round trips touching 50 cached pages: about 1.5 ms, nearly all network. 2,000 uncached pages on a network volume: 2 seconds, and more CPUs won’t help. A batch job committing every row on a disk with 2 ms fsync: 500 rows per second, at most.
When something is slow, ask which term is large: round trips, pages, or where the pages came from. The rest of the book shrinks each one, starting with the pages themselves.
The short version
- Query time is roughly round trips times network latency, plus pages touched times the cost of wherever those pages live: microseconds in memory, up to milliseconds on a network volume.
- Read the
Buffers:line of a plan first; page counts repeat, timings don’t.readmeans “missed shared_buffers”, not “came from disk”. - A commit waits for one WAL flush, whatever it contains. Batch rows into transactions, and measure your fsync with
pg_test_fsync. - Size RAM to the working set, not the whole database. On cloud volumes, IOPS achieved is I/Os in flight divided by latency; watch burst credits.
- N+1 queries cost round trips, not server time. Fetch related rows in one query, and keep the app in the same region and zone as the database.
Further reading
- Resource consumption settings, PGDG. The primary source for
shared_buffers,work_memand the I/O settings, includingio_method. - WAL reliability, PGDG. What a durable commit requires from the disk, and how write caches can lie.
- pg_test_fsync, PGDG. Measure your own fsync latency before choosing storage.
- Amazon EBS volume types, AWS. Real IOPS, throughput and latency figures for network block storage; the General Purpose SSD page documents gp3 baselines and gp2 burst credits.
- Numbers Every Programmer Should Know By Year, Colin Scott. The latency ladder, adjustable by year.
4 Everything is a page
Here are two tables with the same six columns, holding the same million rows:
The only difference is the order the columns were declared in. One is 27% bigger than the other: 27% more pages to scan, cache, back up, and replicate, forever.
Postgres doesn’t really store tables. It stores pages, and a table is whatever fits in them. Picture the page and you can say how many bytes any row takes, and how to make it take fewer. We’ll go from the outside in, mostly through pageinspect, an extension that reads raw pages from SQL.
A table is a file of pages
Every table and index is one or more ordinary files in the server’s data directory. You can ask which:
16764 is the database’s ID and 16644 the table’s relfilenode, the name of its file (yours will differ). From a shell in the container (docker compose exec postgres bash, then cd /var/lib/postgresql/18/docker):
As Know the nouns first showed, 288,137,216 bytes divided by 8,192 is exactly 35,173. The file is nothing but pages, one after another, numbered from 0. (Past 1 GB, a table continues in 16644.1, 16644.2, and so on.)
03-storageAnything that rewrites a whole table (truncate, vacuum full, some alter tables) writes a fresh file under a new name, so never assume the name is stable.
A table is more than its main file
events had three files, not one. Each is a fork with its own job: main holds the rows, _fsm is the free space map, and _vm is the visibility map; both maps get sections below. Unlogged tables add an empty _init fork that’s copied over them after a crash.
That’s why the honest answer to “how big is this table?” is rarely the main file alone:
pg_relation_size is the main fork only. pg_table_size adds the other forks and the table’s TOAST storage (below), and pg_total_relation_size adds every index. Use the total.
Every page has the same layout
Every one of those 35,173 pages is laid out like this. It’s the most important picture in this book:
It works like a notebook page with a table of contents written from the top and the entries written from the bottom up.
A 24-byte page header records the page’s last change, a checksum, and where the free space starts and ends. Line pointers, 4 bytes each, grow from the front; each points at a tuple. Tuples grow from the back; a tuple is one version of a row, as stored on the page. The page is full when the two meet. (Indexes keep bookkeeping in the special space at the end; table pages leave it empty.)
This page has 56 rows. A 24-byte header plus 56 line pointers at 4 bytes each ends at 248: that’s lower. Tuples start at 384 (upper), leaving 136 bytes free, not enough for another row. special is 8192: no special space. flags is 4, the “all visible” flag you’ll meet with the visibility map.
03-storageA line pointer lets a tuple move without changing its address
The line pointer lets Postgres move a tuple within its page, to compact free space, without changing its address. That address is the row’s ctid, a page number and a line pointer number, and every table has it as a hidden column:
(0,1) means page 0, line pointer 1. Indexes store ctids: when an index lookup finds id = 2, what it finds is “page 0, slot 2”. Following a ctid to its table page is the fourth read in the four-page lookup from A query is pages and round trips.
A row’s ctid changes whenever the row is updated (Updates are inserts shows why) and whenever the table is rewritten. Use it to inspect; never store it or hand it to an application.
In InnoDB the table is the primary key B-tree. A Postgres table is a heap: rows go wherever there’s room, and every index, the primary key included, points at a ctid (Postgres is not MySQL).
8 KB is a compile-time choice, and you should keep it
Eight kilobytes isn’t a law of nature. It’s a constant, BLCKSZ, fixed when Postgres is compiled (./configure --with-blocksize, a power of two from 1 to 32 KB), and every file in the data directory is written in it. A server built for 16 KB pages can’t open a data directory made with 8 KB ones, and pg_upgrade won’t cross between them. A running server tells you what it was built with, and no setting changes it:
Bigger pages sound like fewer pages to count, and for some work they are. A sequential scan makes fewer, larger reads; an index fits more keys per page, so the tree is a little shallower; and wide rows stay inline longer, because the threshold for compressing and moving big values (TOAST, below) scales with the page.
But Postgres reads and caches whole pages, and sometimes logs them whole, so everything else gets worse. At 32 KB, a lookup that wants one row pulls four times the bytes into memory. The same shared_buffers holds a quarter as many pages, so your hot rows share the cache with four times as many cold neighbors. And the first change to a page after a checkpoint logs the whole page, so each of those full-page images can be up to four times the size.
So we keep 8 KB, and so should you. Managed services don’t let you choose it anyway. Every lever in this book changes how many rows fit on a page without a custom build: column order, narrower types, fillfactor, TOAST, and the right index. Larger pages pay off mainly for scan-heavy analytics on a server you compile yourself, and that’s the workload where a column store wins anyway (Where Postgres loses).
03-storageWe didn’t build a 32 KB server for this book, so this box is reasoning from how pages are used, not a lab run. The limits that scale with BLCKSZ:
- TOAST starts compressing a row at about a quarter of a page, roughly 2 KB here (Large values are compressed, then moved out of the row).
- Index entries can’t exceed about a third of a page, which is the error you hit indexing a long text column.
- The visibility map keeps two bits per page, so each bit covers more rows, and one changed row clears the bit for more of its neighbors.
- Full-page images in WAL are one page each, so bigger pages mean a bigger burst after every checkpoint.
Two neighbors are separate compile-time constants: wal_block_size (also 8 KB) and the 1 GB file segment size, which is why a big table continues in 16644.1. pg_controldata prints all three for a data directory, and tools that read raw pages, such as pageinspect, take their sizes from the server.
03-storageA row costs more than its columns
Open a page and count what each row actually stores. heap_page_items decodes every tuple on a page:
Tuple 1 is 144 bytes at offset 8048, ending exactly at the end of the page; tuple 2 sits right below it. Each starts with a 23-byte tuple header.
The header’s two most important fields are t_xmin, the transaction that inserted this version, and t_xmax, the one that deleted or locked it (0 if none). They’re the heart of Postgres’s concurrency control and get a chapter of their own (Updates are inserts). Here, every row was inserted by transaction 766, the seed, and none has been deleted. t_ctid is the tuple’s own address, or its newer version’s. t_hoff says the column values start at byte 24, after the header and a byte of alignment, in declaration order, end to end.
Twenty-four bytes of header and a 4-byte line pointer, on every row. A row of two integers is mostly overhead.
The whole header:
| Field | Size | What it is |
|---|---|---|
| t_xmin | 4 bytes | ID of the transaction that inserted this version |
| t_xmax | 4 bytes | ID of the transaction that deleted or locked it, or 0 |
| t_cid | 4 bytes | Command number within the transaction |
| t_ctid | 6 bytes | This tuple’s address, or the address of its newer version |
| t_infomask2 | 2 bytes | Number of columns, plus a few flags |
| t_infomask | 2 bytes | Status flags |
| t_hoff | 1 byte | Offset where the column data starts |
t_infomask on row 1 is 2306, and pageinspect (PostgreSQL 13+) decodes it:
The row has variable-width columns, its inserting transaction is known to have committed, and it has no valid deleter. The last two are hint bits, cached answers that A read can write explains.
Then the data. The first eight bytes are id, the integer 1, least significant byte first, as on any x86 or 64-bit ARM machine:
The next eight, a903..., are account_id: 0x03a9 is 937, exactly what select account_id from events where id = 1 returns.
03-storageNULLs cost one bit
A NULL takes no space in the data area. A row with any NULL carries a null bitmap in its header instead: one bit per column, 0 for NULL. In projects, an unarchived project has a NULL archived_at:
Rows 1 and 3 aren’t archived: their fifth bit is 0, and they’re 8 bytes shorter than row 2, which stores its timestamp. One bit instead of eight bytes. (Up to 8 columns, the bitmap fits in a spare byte of the header. Past 8, a row with any NULL needs a longer bitmap, which can push the start of its data from byte 24 to byte 32.)
03-storageColumn order is free space
Now the mystery from the start of the chapter. CPUs read a value fastest at an address that’s a multiple of its size, so Postgres lines values up that way: a bigint or timestamptz starts at a multiple of 8 bytes, an integer or date at a multiple of 4, a smallint at a multiple of 2, and a boolean anywhere. When an 8-byte column follows one that ended at an odd offset, Postgres pads the gap. Picture a parking lot where trucks may only park at every eighth line: let a motorbike take the first space, and the next seven go empty.
Here are the two tables from the start, column by column. pg_column_size says a padded row is 72 bytes and a packed one 52:
It compounds: each tuple also starts at a multiple of 8 on the page (so packed’s 52 bytes occupy 56), and each needs a line pointer. That’s 107 rows per page against 136, and 9,346 pages against 7,353.
The rule that falls out:
- Fixed-width 8-byte columns first:
bigint,timestamptz,double precision. - Then 4-byte ones:
integer,real,date. - Then 2-byte, then 1-byte:
smallint,boolean. - Variable-length columns (
text,jsonb,numeric) last. Short values need no alignment, so they pack tightly at the end.
For a few thousand rows, not at all. For a narrow table headed for hundreds of millions (events, logs, join tables, metrics), spend five minutes on it when you write the create table; reordering later means rewriting the table.
The two tables, loaded with the same million rows:
With 8,168 usable bytes per page after the header, and a 4-byte line pointer per row:
03-storageEvery type’s alignment is in pg_type.typalign: c (any byte), s (2), i (4) or d (8). uuid is a surprise: 16 bytes, but c, so it needs no padding.
The example schema does fine. An events row is the header, four 8-byte ids with no padding, kind as short text, payload as small jsonb, and created_at, which may pick up a few bytes of padding after the two variable-length columns. Measured rows are 136 to 144 bytes, about 66 of them JSON. The JSON is the cost worth watching; Types are a contract discusses when to promote a field out of jsonb into a real column.
Large values are compressed, then moved out of the row
A row must fit in an 8 KB page, yet a text value can be up to 1 GB. TOAST (The Oversized-Attribute Storage Technique) squares the two. When a row about to be stored is larger than about 2 KB (2,032 bytes with 8 KB pages, so at least four rows fit on a page), Postgres works through its variable-length columns, largest first:
- Compress the value in place.
- If the row is still too big, move the value into the table’s own TOAST table, cut into chunks of just under 2 KB, leaving an 18-byte pointer behind.
In a test table, 100,000 repeated characters compressed to 1,156 bytes and never left the row. 32,000 characters of random hex didn’t compress, so they moved out in 17 chunks, leaving a 50-byte row behind. Reading that value back means an index lookup in the TOAST table and 17 more tuple fetches, invisible in your SQL.
What that means for your queries:
select *isn’t free on wide tables. A list view that doesn’t show a document’s body shouldn’t fetch it, and most ORMs fetch every column unless told otherwise.- Changing a toasted value rewrites all of it. Change one key in a big
jsonbdocument and Postgres stores the whole document again. Keep a hot counter out of the document; better still, give it a narrow table of its own (Move hot counters to a narrow table). - Medium values are the awkward case. A 1 to 2 KB value isn’t toasted and makes every row large, so only a handful fit per page.
A table with one text column, filled with a short string, repeated characters (very compressible), and random hex (barely compressible):
Rows 4 and 5 left 50-byte tuples on the table’s page (a 24-byte header, 8 for id, and the 18-byte pointer). Their chunks are rows in the TOAST table that reltoastrelid in pg_class names:
The threshold is exact: a 2,028-byte row is stored as is, a 2,038-byte one is compressed. And pg_column_toast_chunk_id (PostgreSQL 17+) shows the update rule: an update to another column keeps the same TOAST pointer and copies nothing, while changing the value stores all 17 chunks again.
03-storage03-storage03-storageCompression is per column. The default is pglz; since PostgreSQL 14 you can choose lz4 (if the server was built with it, as most packaged builds are), which is generally much faster with similar ratios:
The same 100,000 characters that pglz stored in 1,156 bytes take 411. The setting applies only to newly stored values; if you store a lot of compressible text or JSON, default_toast_compression = lz4 server-wide is a reasonable choice.
Each column also has a storage strategy (plain, main, external, extended; text and jsonb default to extended, compress then move). Set external with alter table ... alter column ... set storage for data that’s already compressed, like images: compressing again wastes CPU, and substring operations can fetch only the chunks they need.
The toast_tuple_target storage parameter sets how small Postgres tries to make a row once toasting has started. It doesn’t move the trigger: in PostgreSQL 18 toasting still starts at a row over about 2 KB, whatever the parameter says. (The CREATE TABLE reference describes it as the minimum length that triggers toasting, but the server code checks the fixed threshold.) So a lower target leaves a 1.5 KB row alone, and once a row does cross 2 KB, moves more of its medium-sized columns out of line, trading smaller rows for more TOAST lookups.
03-storageFillfactor leaves room for updates
By default Postgres fills table pages completely; the fillfactor storage parameter tells inserts to stop earlier and leave room on each page. That room is for updates, which write a new version of the row and are much cheaper when it fits on the same page, so choosing the value is part of Leave room on the page, or every update moves.
Inserts find room without scanning the table
How does an insert find a page with room? Not by scanning the table. The _fsm fork records roughly how much each page has free, one byte per page in steps of 32 bytes: page 0 of events, with 136 bytes free, is recorded as 128 (after setting aside 4 for a line pointer). Finding a page with room takes a few reads. Vacuum updates the map, which is when space from deleted rows becomes reusable. When no page has room, the table grows at the end.
03-storageTwo bits per page let scans and vacuum skip work
Two bits per page are why an index-only scan can skip the table, and why vacuuming a big, mostly static table is cheap. The last fork, _vm, is the visibility map: two bits for each page of the table.
- all-visible: every row on the page is visible to every transaction, now and in the future.
- all-frozen: every row on the page is frozen, safe from transaction ID wraparound forever (Old rows must be frozen before the XID counter wraps).
The pg_visibility extension summarizes it:
Every page is all-visible, because the seed ended with vacuum analyze. Two parts of Postgres lean on this map. Index-only scans skip the table page when it’s all-visible and answer from the index alone (The B-tree does the heavy lifting). Vacuum skips all-visible pages (Vacuum is not optional). Any change to a page clears its bit; vacuum sets it again once every transaction can see the change.
The bit lives in two places: the map, and flag 4 in the page header.
03-storageCount pages before you create the table
Put the pieces together and you can predict a table’s size before it exists:
8,168 is the page’s 8,192 bytes minus its 24-byte header. events rows average about 139 bytes, so about 57 fit on a page, and 2,000,000 rows need about 35,100 pages. The real table has 35,173. Do that in your head the next time someone proposes a table that will take 50 million rows a month: how many pages, how many hot, and does it fit in memory?
Page count drives everything that follows, starting with which of those pages get to stay in memory. And every update and delete changes it, in ways that surprise most people the first time they look.
The short version
- A table is a file of 8 KB pages, plus forks for the free space map and visibility map. Ask
pg_total_relation_sizehow big it really is. - 8 KB is fixed when Postgres is built (
block_size, read-only). Change how many rows fit on a page with the schema, not a custom build. - Every row carries a 24-byte header and a 4-byte line pointer. Small rows are mostly overhead.
- A ctid is a physical address (page, slot) that changes on every update. Never store it.
- NULLs cost one bit, not the width of the column.
- Order columns from 8-byte fixed-width types down to 1-byte types, variable-length last. The wrong order cost 27% more space here.
- Values over about 2 KB are compressed, then moved to a TOAST table. Don’t
select *wide columns you don’t need. - Fillfactor leaves room on each page for updates; the HOT chapter covers choosing it.
Further reading
- Database page layout, PGDG. The 8 KB page, line pointers, and every tuple header field, from the source of truth.
- TOAST, PGDG. Thresholds, storage strategies, and compression options.
- Free space map and visibility map, PGDG. The two small forks that make inserts and vacuum fast.
- pageinspect, PGDG. Every function used in this chapter, and more.
- Heap table structure, Hironobu Suzuki, The Internals of PostgreSQL. A diagram-first companion explanation of the same layout.
5 The buffer cache decides what stays
Read a nine-page table once and Postgres gives each of its pages one point. Read it again: two points. By the fifth read every page has five, and there the counting stops. Those points, and a hand that goes round the cache taking them away, decide which pages stay in memory and which go. That’s the whole eviction policy, and it fits in a sentence.
A page costs microseconds or milliseconds depending on where it is (A page lives in one of three places). This chapter is the machinery that decides where it is. After that comes the memory each connection keeps for itself, which is what actually runs servers out of RAM. Everything below runs on the lab kit’s default 128 MB of shared_buffers, inspected with the pg_buffercache extension.
shared_buffers is an array of pages
shared_buffers is one big array of 8 KB slots, called buffers, allocated in shared memory at startup. Every process reads and writes pages through it. The default 128 MB is 16,384 buffers.
Think of a coat check: numbered hooks, each with a ticket. Each buffer’s ticket is a 64-byte descriptor: a tag naming the page it holds (which file, which fork, which block), how many processes are using it right now, a usage count, and whether it was changed in memory and not yet written (dirty). pg_buffercache shows one row per buffer with those fields decoded; the examples below read it through cached, a small view over pg_buffercache that keeps only this database’s tables and names them.
pg_shmem_allocations (PostgreSQL 13+) lists the pieces:
Buffer Blocks is the 128 MB of pages (plus 4 KB for alignment). Buffer Descriptors is exactly 1 MB: 16,384 descriptors padded to 64 bytes each, one CPU cache line, so two processes updating neighboring descriptors don’t fight over the same line.
The cached view joins pg_buffercache to pg_class. It filters on the database as well as the file number, because databases cloned from the same template start with the same file numbers:
The whole server is shared memory: shared_buffers plus the WAL buffers, lock tables, and the rest. show shared_memory_size reports 152 MB on the kit, the number to plan RAM and Linux huge pages around (Memory: budget it before you tune it; shared_memory_size_in_huge_pages, PostgreSQL 15+, says 76 here).
04-buffersFinding a page takes a hash lookup
A backend that wants block 7 of users doesn’t search 16,384 descriptors. It hashes the tag and looks it up in the buffer mapping table, a shared hash table from tag to buffer:
A hit is a quick lookup in one of 128 separately locked partitions, so backends rarely wait for each other. A miss does real work. When many sessions wait on BufferMapping (An active session with no wait event is on a CPU), they’re all missing at once: a working set that doesn’t fit, not a lock to tune.
A pin means “in use”
Before a backend touches a page, it pins the buffer. A pinned buffer can’t be evicted, so the page stays put while it’s read. Pins are short, but they last as long as a query sits on a page: an open cursor, or a slow client that stopped reading halfway, keeps its page pinned. That matters to vacuum. Vacuum can only clean a page nobody has pinned, so a parked cursor makes it skip the page or wait on a BufferPin event (Vacuum is not optional).
Open a cursor on accounts, fetch one row, and cached shows blocks 0, 1 and 2 each pinned by one backend. The cursor holds block 0, where its row came from. Blocks 1 and 2 are pinned too: since PostgreSQL 17, sequential scans read through a “read stream” that pins a few pages ahead so their I/O can already be in flight. While the pins exist, pg_buffercache_evict() (PostgreSQL 17+, superuser, for testing) refuses to evict those buffers. Commit, and the same call succeeds.
04-buffersUsage counts climb with every read
Each pin also bumps the buffer’s usage count, up to 5: the cache’s memory of how popular a page is. Evict accounts (nine pages), scan it, and count:
One scan, one point per page. Five scans, five points, and there it stays.
04-buffersThe clock sweep picks the victim
When a backend misses and every buffer is taken, something has to go. Postgres doesn’t keep a least-recently-used list (maintaining one on every hit would need a global lock). It runs a clock sweep:
A page read once survives one pass of the hand. A page read constantly is back at 5 long before the hand returns, so it never reaches zero. Two consequences:
- One pass over cold data can’t push out the hot set. Cold pages arrive at count 1 and leave first, where a strict least-recently-used cache would evict everything older.
- Popularity is relative to churn. The hand moves as fast as backends miss. Miss a lot and it spins, and even popular pages fall out between visits. More misses cause more misses; that’s how a working set that outgrows the cache falls off a cliff.
Start from an empty cache: pg_buffercache_evict_all() (PostgreSQL 18, for testing only; never on a server you care about) throws out every unpinned page. Read accounts five times so its pages sit at 5. Then flood the cache: pg_prewarm reads the first 20,000 pages of events through the normal path, more than the 16,384 buffers there are.
Over 3,600 of the flood’s own pages are already gone, evicted by its newer ones, while the nine accounts pages survived, a point lighter per pass of the hand. Which older flood pages go depends on where the hand stood (on our runs, sometimes all of the first thousand, sometimes none). The shape doesn’t change.
pg_buffercache_usage_counts() (PostgreSQL 16+) gives the distribution server-wide. On the shared lab server, while a dozen labs ran at once, 13,578 of 16,384 buffers sat at 0 or 1 and 295 at 5: a cache too small for, or swept by, work that reads everything once. A cache doing its job on a steady workload has a fat tail at 4 and 5.
04-buffersYour query shouldn’t be the one writing dirty pages
An update changes the page in its buffer and marks it dirty; the data file isn’t touched. The change is already recorded in the write-ahead log, which must reach disk before the page does (Checkpoints put a limit on recovery). The page reaches the file later, written by one of three kinds of process:
| Who | When | Ideal share |
|---|---|---|
| Checkpointer | Every checkpoint writes all dirty buffers | Most writes |
| Background writer | Continuously, ahead of the clock hand | Some |
| Any backend | When the victim it picked is dirty | Few |
Watch the last row. A backend that picks a dirty victim must write it before reusing the buffer, and its query waits. When backends write a steady share of pages, shared_buffers is too small for the write load. pg_stat_io (PostgreSQL 16+) counts writes by process type (pg_stat_io catches backends writing dirty pages (PostgreSQL 16+)).
Update 50 accounts and cached shows two dirty pages on our runs: the one holding the old row versions and the one that received the new ones (Updates are inserts explains why there are two).
The checkpointer writes every buffer that was dirty when a checkpoint began, so recovery can start there. The background writer wakes every 200 ms (bgwriter_delay), finds dirty buffers the clock is about to reach, and writes up to 100 of them: at most 4 MB per second with the defaults. A backend writes when it has no choice; pg_buffercache_evict() shows the rule, flushing a dirty buffer before evicting it:
On our shared test server, one backend that ran a single scan while other labs bulk-loaded data had to write 2,909 other sessions’ dirty pages to make room.
04-buffersBig operations get a ring
A nightly report reading 275 MB through a 128 MB cache would flood it, if nothing stopped it. Something does. Operations that touch many pages once get a buffer ring: a small private set of buffers they recycle instead of taking new ones from the clock, so they evict their own pages, not yours.
| Operation | Ring | Size with defaults |
|---|---|---|
| Sequential scan of a table bigger than shared_buffers / 4 | bulkread | 256 KB, plus room for in-flight I/O: 2,304 KB in PostgreSQL 18 |
| VACUUM and ANALYZE | vacuum | vacuum_buffer_usage_limit, 2 MB (the setting is PostgreSQL 16+; 17 raised its default from 256 KB) |
| COPY FROM and CREATE TABLE AS | bulkwrite | 16 MB |
The scan threshold is a quarter of shared_buffers, 4,096 pages here. Scan events (35,173 pages) and users (1,126) once each from an empty cache, with parallel workers off:
The small table is cached whole. The big one went through its ring and left under 288 buffers behind, the size of one 2,304 KB ring (the exact count varies run to run).
Writes hold a surprise: insert ... select gets no ring. Load the same 2,000,000 integers both ways and COPY leaves one 16 MB ring in the cache, 2,048 pages, having written its own pages as it went. insert ... select leaves all 8,850 pages in shared_buffers, 69 MB of a 128 MB cache, with its dirty buffers for someone else to write. For a backfill into a new table, COPY or create table as is the polite way to load.
A ring stops one operation from evicting everyone else’s pages. It does nothing for the I/O: the report still reads all 35,173 pages, and because its pages don’t stay, the next run reads them all again. If a big scan runs often enough to matter, it needs an index or a summary table, not a bigger cache.
No ring is larger than an eighth of shared_buffers. The PostgreSQL 18 bulk-read ring is bigger than the classic 256 KB because asynchronous reads need buffers to land in: 8 KB times io_combine_limit (16) times effective_io_concurrency (16) on top, 288 buffers in all. The backend’s own I/O counters (pg_stat_get_backend_io(), PostgreSQL 18) show the full scan above reused buffers over 35,000 times in the bulkread context. With parallel workers, each worker gets its own ring.
The write experiment:
copied is 62 pages longer: COPY extends the file many pages at a time, and its last batch is still empty. Because a ring buffer full of new rows is dirty, COPY writes its own pages as it recycles them. That’s deliberate: a bulk load pays for its own writes instead of handing them to the background writer and to every other backend’s evictions.
04-buffersTemporary tables live in local buffers
Temporary tables never enter shared_buffers. Each session caches them in private local buffers, temp_buffers (8 MB by default), and a bigger temp table is read from its file on every scan. The setting can only be raised before the session first touches a temp table, so if your application builds big ones (reports, imports, staging), set it per role: alter role reporting set temp_buffers = '64MB'.
14 MB through 8 MB of buffers: every later scan reads all 1,792 pages again, because a sequential pass always evicts the page it will need next. (The first scan also set hint bits and wrote the pages back.) Raising the setting now fails:
In a fresh session with set temp_buffers = '32MB' first, the same scan shows Buffers: local hit=1792.
04-buffersThe OS page cache is the second tier
A miss in shared_buffers may still hit the kernel’s page cache. Rings send big scans there on every run, so that second tier is what makes a repeated report survivable, and it’s one reason to keep shared_buffers near a quarter of RAM rather than most of it (shared_buffers starts at 25% of RAM, not 80%).
A big table at usage 1 needs an index, not memory
Everything above is visible from SQL. This query ranks the current database’s tables and indexes by how much of the cache they hold:
Read it with the clock in mind. A table at a high percentage with average usage near 5 is your hot set, earning its place. A big table holding a large share of the cache at usage 1 is being read once and replaced: a candidate for an index, not more memory. The query walks every buffer, so run it on demand; pg_buffercache_usage_counts() (PostgreSQL 16+) is the cheap server-wide check, and most buffers at 0 or 1 means churn.
Warm the cache after a restart
A restart empties shared_buffers, and so does a failover to a replica that cached different pages. For the next hour every query that used to hit memory goes to the OS cache or the disk; on network storage, it can be the slowest hour of the week. pg_prewarm (a contrib extension) loads a relation on demand: select pg_prewarm('users') loaded all 1,126 pages, and the next full scan was all hits.
autoprewarm restores the last cache
Choosing tables by hand is guesswork. autoprewarm, part of the same extension, records what was in the cache and puts it back after a restart:
A background worker saves the list of cached blocks every 5 minutes and at shutdown, and loads them back at startup while the server accepts connections. It runs on standbys too, so after a failover the new primary starts from its own warm list. It costs one small file every few minutes; turn it on (managed services may not let you: Extensions come from an allowlist).
It works on indexes too (users_pkey is 276 pages) and takes a fork and a block range. Prewarmed pages get no special treatment: they start at usage count 1, and prewarming a table bigger than shared_buffers is the flood from earlier. Two other modes skip shared_buffers, 'read' and 'prefetch', for relations too big for it that still fit in RAM. autoprewarm’s list is a small text file, autoprewarm.blocks, one line per block; select autoprewarm_dump_now() saves it on demand.
04-bufferseffective_cache_size is a hint, not memory
effective_cache_size allocates nothing. It tells the planner how much data is probably cached, in both tiers, and a bigger value makes index scans look cheaper. Set it to 50 to 75% of the machine’s RAM (effective_cache_size is a hint: set it to 50% to 75% of RAM).
At 1 MB the planner assumes nearly every page fetched through the index is a fresh random read, and sorts a sequential scan instead. At 4 GB it walks the index. Nothing about memory changed; any session can set it. The cost model itself is in The planner is guessing.
Backend memory is private
Everything so far was shared. Each backend also has private memory, allocated as it works and invisible to other processes: a megabyte or two idle, a hundred or more mid-query (Memory: 1.5 MB idle, 109 MB mid-sort measured both). Two things decide most of it: working memory for queries, and caches of the system catalogs.
The biggest memory context names the culprit
Postgres allocates in memory contexts, arenas arranged in a tree, and frees a whole context when its job ends, a query’s when the query finishes. pg_backend_memory_contexts (PostgreSQL 14+) shows your own backend’s tree; for another, say a pooled connection that has grown to 2 GB, pg_log_backend_memory_contexts(pid) writes its tree to the server log. The biggest context names the culprit.
work_mem is per node, and you can see it
work_mem (4 MB by default) limits each sort or hash step of a plan, not each query. A merge join with two sorts holds two allowances at once: we caught a query with two Sort nodes holding just over 4 MB each. Add a hash join and that’s a third, at twice work_mem with the default hash_mem_multiplier. Multiply by connections, and that’s why we keep work_mem modest globally and raise it per role or per transaction (work_mem: multiply before you raise it).
Open the join as a cursor and fetch one row, so both sorts have finished and are held in memory:
Each sort sits at its own work_mem limit; the rest of each 300,000-row input spilled to temp files.
04-buffersThe catalog caches only grow
To plan a query, a backend needs the table’s definition, and it caches what it reads from the system catalogs for as long as the connection lives. Here’s one connection that ran a trivial query against each of 1,000 small tables:
About 9 KB per table and its index, in every backend that touched them, and discard all, which poolers run between clients, gives none of it back. With 10,000 partitions and 200 pooled connections, that’s gigabytes of RAM that show up in no plan.
Recycle connections: give pooled server connections a maximum lifetime (PgBouncer’s server_lifetime defaults to 3,600 seconds). An hour of growth is bounded; a month isn’t. And if tenants map to schemas, don’t route every tenant through every connection (Trust no tenant covers shared-table tenancy).
The source’s README for memory contexts says CacheMemoryContext is never reset or deleted: it holds the relcache (one entry per table or index opened) and the catcache (rows of the catalogs themselves).
04-buffersThe short version
- shared_buffers is an array of 8 KB buffers. The clock sweep evicts the first unpinned buffer at usage count 0, taking a point from each it passes: hot pages keep earning points, pages read once go after one pass.
- Changes dirty buffers in memory. The checkpointer should write most of them; backends that write their own victims are waiting on I/O. Check
pg_stat_io. - Big scans, VACUUM, and COPY or
create table asuse small rings and can’t flush your cache.insert ... selectdoesn’t, so prefer COPY orcreate table asfor bulk loads. - Temp tables use per-session
temp_buffers; set it per role if you build big ones. - See what’s cached with
pg_buffercache; turn on autoprewarm to come back warm after a restart or failover. effective_cache_sizeis a planner hint that can change plans; it allocates nothing.work_memis per sort or hash node, and catalog caches grow with every table a connection touches and never shrink. Cap connection lifetime in the pooler.
Further reading
- src/backend/storage/buffer/README, PostgreSQL source. The buffer manager’s own design notes: pins, content locks, the mapping partitions, clock sweep, and the rings.
- pg_buffercache, PGDG. Every column and function, including the summary, usage-count, and eviction functions and their version notes.
- pg_prewarm, PGDG. The prewarm modes and the autoprewarm settings.
- Resource consumption settings, PGDG.
shared_buffers,temp_buffers,work_mem,vacuum_buffer_usage_limit, and the background writer settings. - src/backend/utils/mmgr/README, PostgreSQL source. How memory contexts work and which ones live how long.
6 Updates are inserts
The users table in the example database is 9 MB. Run one statement against it:
Now it’s 18 MB, and its indexes grew from 8 MB to 12 MB. You changed no row’s size and added no rows, and the table doubled. Run vacuum and it’s still 18 MB.
None of this is a bug. It’s how Postgres lets many transactions read and write the same data without making readers wait for writers. The technique is multiversion concurrency control (MVCC), and its central rule fits in three words: updates are inserts. Once you see it in the pages, bloat, slow updates, vacuum that can’t keep up, and transaction ID wraparound stop being mysterious.
Readers never wait for writers
Picture a report that sums every account’s balance and takes ten seconds. Halfway through, another transaction moves money from an account the report hasn’t reached to one it has already counted. If the report reads whatever is on the page when it gets there, the money vanishes from its total.
One fix is locking: the report locks what it reads, and writers wait. Correct, and miserable. Postgres takes another route: it never overwrites a row in place. An update writes a new version of the row and leaves the old one where it is, marked with who replaced it. A reader that started before the update keeps seeing the old version; one that starts after sees the new one. Nobody waits.
The bill comes later: old versions pile up until nobody can need them, and vacuum has to clean them up. That pile is the bloat.
Every write gets a transaction ID
Two numbers in every row’s header are where the trouble in the rest of this book starts: bloat, vacuum work, and wraparound all trace back to them.
Every transaction that changes data gets a transaction ID (XID) from a server-wide counter at its first write; read-only transactions never take one. Every row version carries two of them in its header (A row costs more than its columns): xmin, the transaction that inserted it, and xmax, the one that deleted, replaced, or locked it (0 if none). Every events row has xmin 766, the seed, and xmax 0; select xmin, xmax, * from events shows them on any table.
(Our server was busy while we ran this chapter, so the XIDs below are large and jump between steps. Yours will differ.)
An update writes a whole new row
To watch versions being made, we need a page small enough to read in full. A per-account usage counter fits, the kind of row an application updates constantly:
Three rows, in slots 1 to 3 of page 0, inserted by transaction 869572. Now increment account 1’s counter. RETURNING with old and new (PostgreSQL 18+) shows both versions’ addresses:
The row moved to a new slot. The page now holds four tuples for three rows: the old version, still in slot 1 byte for byte, stamped with the updater’s XID and pointing at (0,4), and a complete new copy in slot 4:
That’s the whole mechanism: an update inserts a new version and stamps the old one “replaced by 869576, see (0,4)”.
Every update writes a full new copy, however little changed. Increment a 4-byte counter in a 1 KB row and a new 1 KB tuple lands on the page. That’s why wide, frequently updated rows are expensive in Postgres, and why a hot counter belongs in its own narrow table, like account_usage.
HEAP_HOT_UPDATED on slot 1 and HEAP_ONLY_TUPLE on slot 4 mark this as a HOT update, the kind the HOT section below explains.
05-mvccThe lab also updates a counter in a row of about 1 KB and reads the new tuple’s length off the page: over 1,000 bytes. The write-ahead log is kinder. When the new version lands on the same page, Postgres logs only the bytes that changed, under 100 in our test, unless the record carries a full-page image or the server runs with wal_level = logical (Write it down first).
05-mvccA version is dead only when no snapshot can see it
Update account 1 twice more and its chain grows to (0,1) to (0,4) to (0,5) to (0,6): six tuples for three rows, three of them dead weight.
A version no transaction can ever see again is a dead tuple. “Ever” matters: a replaced version is dead only once every transaction that might still read it has finished. The oldest snapshot still running (a fixed view of what had committed, below) sets the xmin horizon: versions that died before it can go; the rest must stay. That line decides how much vacuum can clean, as the section on long transactions shows.
Dead tuples are removed two ways. Pruning happens on the fly, when a query reads a nearly full page: cheap, one page at a time, no index work. Vacuum does the full job, index entries included (Vacuum is not optional).
After vacuum account_usage, account 1’s three dead versions are gone and slot 1 is a redirect to slot 6, because the primary key index still points at (0,1). Tuples move; addresses don’t. That’s what the line pointer from A line pointer lets a tuple move without changing its address is for.