By the Numbers / Postgres
Postgres runs on a handful of numbers: an 8 KiB page, a 23-byte row header, a 32-bit transaction counter, a price of 4.0 for a random read. Learn those and most production surprises stop being surprises. This page works each one out from the source and gives you a calculator to push on it.
Version: PostgreSQL 19.0, released 2026-11-19, the current major release. Constants read from REL_19_STABLE src/include at commit f53b834 (2026-11-25, after the 19.0 tag; no constant on this page differs). Defaults assume a 64-bit build with 8 KiB pages.
PG 19 · storage/bufpage.h · storage/itemid.h · access/htup_details.h · access/heaptoast.h
Start with an empty row: no columns, no data. It still takes 28 bytes. That is a 23-byte header, padded to 24, plus a 4-byte pointer that tells the page where the row lives.
That sounds like nothing until you multiply it. At 10 billion rows it comes to 280 GB, about sixty DVDs of pure bookkeeping. In a table of two bigints, the bookkeeping is bigger than the 16 bytes of data it describes.
In 1986 Michael Stonebraker and Lawrence Rowe at Berkeley published the design for POSTGRES. The name meant "after Ingres," the database they had built before it. One of its stranger ideas was that the database would never overwrite a row. Each row would carry the ID of the transaction that created it and the one that deleted it, so old versions stayed readable. Postgres still works this way forty years later, and those IDs are most of the header.
Tables and indexes both live in 8 KiB pages. A page is the smallest thing Postgres reads, writes, caches or logs.
A page fills from both ends. Row pointers grow forward from a 24-byte page header, and rows grow backward from the end. When the two meet, the page is full. The animation at the top of this page shows it happening.
Each column has to start at an address its type can read in one step. An 8-byte column, like a bigint or a timestamp, starts at a multiple of 8. Put a 1-byte boolean in front of it and you lose 7 bytes to padding. Then the whole row is rounded up to a multiple of 8.
Reordering costs nothing. Load "Badly ordered events" in the tool, then press "Reorder for alignment." The same columns fit 15% more rows per page.
Rows bigger than about a quarter of a page get special treatment. Past 2,032 bytes, Postgres compresses the largest values. If that is not enough, it moves them to a side table and leaves a short pointer behind. The mechanism is called TOAST, short for The Oversized-Attribute Storage Technique. In 19 its default compression switched from pglz to lz4, which the release notes call the more efficient of the two.
Page header (PageHeaderData, 24 bytes): pd_lsn 8, pd_checksum 2, pd_flags 2, pd_lower, pd_upper and pd_special 2 each, pd_pagesize_version 2, pd_prune_xid 4. Heap pages have no special space; B-tree pages use 16 bytes of it.
Line pointer (ItemIdData, 4 bytes): a 15-bit offset, a 2-bit state and a 15-bit length.
Row header (HeapTupleHeaderData, 23 bytes): t_xmin, t_xmax and t_cid/t_xvac at 4 each, t_ctid 6, two 2-byte infomasks, and the 1-byte t_hoff. Data starts at t_hoff, MAXALIGNed to 24. The null bitmap begins at byte 23, so with up to 8 columns it fits in the padding; with 9 to 72 columns, a NULL pushes t_hoff to 32.
Alignment (typalign in pg_type.dat): 8 for int8, float8 and timestamptz; 4 for int4 and date; 2 for int2; 1 for bool and uuid. A variable-length value with at most 126 bytes of payload gets a 1-byte header and no alignment; a longer one gets a 4-byte header and 4-byte alignment.
TOAST: the toaster works until the row fits TOAST_TUPLE_TARGET (2,032 unless toast_tuple_target is set). Each moved value leaves an 18-byte pointer and is stored as 1,996-byte chunks, four chunk rows per TOAST page. The lz4 default applies when the server is built with LZ4 (toast_compression.h).
Smil check: 10 × 109 rows × 28 B = 2.8 × 1011 B = 280 GB; a single-layer DVD holds 4.7 GB, so about 60 of them.
Toy assumptions: every column non-null; numeric stored as a 9-byte short varlena (an 8-byte payload, up to about 12 digits); text and jsonb payloads incompressible, so the toaster goes straight to out-of-line storage; a freshly loaded page with no dead rows.
PG 19 · access/nbtree.h · access/itup.h · nbtree/README · optimizer/cost.h
Look up one row in a billion-row table by its bigint primary key. Postgres reads four index pages and one table page, and usually only the last one or two come from disk.
An index entry on a bigint key costs 20 bytes, so one page holds a few hundred of them. Each level of the tree multiplies the reach by that much again.
Four levels reach 8.4 billion rows, and ten billion needs a fifth. Growing from a million rows to a billion adds just one level.
Rudolf Bayer and Edward McCreight came up with the B-tree in 1970 at Boeing's research labs, and they never settled in print what the B stands for. Postgres uses a 1981 refinement by Philip Lehman and S. Bing Yao that lets readers keep walking the tree while writers split pages. The first sentence of the README in Postgres's B-tree source folder says so.
The top of the tree is tiny. In a billion-row bigint index, everything above the leaves fits in under 100 MB, so it stays in memory. A lookup usually pays for one leaf page and one table page from storage. Set the cache size in the tool and watch which levels miss.
The planner prices a random page read at 4.0 and a sequential one at 1.0. That is the random_page_cost setting. The docs explain that real random reads cost far more than 4×, but most of them are expected to hit cache.
SSDs closed most of the gap between random and sequential reads, and many people set random_page_cost between 1.1 and 2.0 on fast local SSDs practice, not docs. That is a bigger change than it looks. At 4.0, an index scan wins only when you want less than about 0.56% of the table. At 1.1 it wins up to about 2%.
A B-tree entry is an 8-byte IndexTupleData (a 6-byte heap address plus 2 bytes of t_info) followed by the key, MAXALIGNed, plus a 4-byte line pointer. Each page loses 24 bytes to its header and 16 to BTPageOpaqueData (sibling links, level, flags, cycle ID). An int8 key costs 16 + 4 = 20 bytes, so a full page holds 8,152 / 20 ≈ 407.
CREATE INDEX fills leaves to BTREE_DEFAULT_FILLFACTOR = 90 and inner pages to BTREE_NONLEAF_FILLFACTOR = 70, and ascending inserts split at the same targets. Random inserts settle leaves near 69% full, the ln 2 result for random B-tree insertion. Suffix truncation (12) keeps inner keys short; deduplication (13) stores repeated keys once. The largest entry is BTMaxItemSize = 2,704 bytes.
Toy assumptions: one key column, unique keys (no deduplication), every level filled evenly. Break-even uses 100 rows per table page, one filter condition, and an uncorrelated index where each matching row costs a random page, ignoring the planner's correction for pages read twice. The real planner moves toward sequential cost as pg_stats.correlation approaches ±1.
PG 19 · postmaster/autovacuum.c · access/transam/varsup.c · c.h · docs: routine vacuuming · 19 release notes
On 20 July 2015, Sentry was down for most of the US working day because its database had run out of transaction IDs. In February 2019 the same wall hobbled Mailchimp's Mandrill for about 40 hours, after a hashing imbalance sent extra writes to one shard of its Postgres store.
Both outages trace back to the 1986 design from the first section.
Postgres never overwrites a row, so an UPDATE writes a new version and marks the old one dead. The dead row keeps its space until vacuum clears it.
Vacuum is older than Postgres itself. Stonebraker's 1987 storage design included a background process he called the vacuum cleaner. Its job was to move old row versions off magnetic disk onto write-once optical disks, so you could query the database's past. The optical archive never made it into Postgres. The vacuum did, and it picked up a second job: protecting the transaction counter.
Every write gets a 32-bit transaction ID, and only about 2.1 billion of them can count as "the past" at once. At 10,000 write transactions a second, that lasts two and a half days. Read-only queries don't use IDs. Every write does, and so does every subtransaction that writes.
Vacuum can only freeze rows that nothing still needs to see. A transaction left open for days, a replication slot nobody reads, or a forgotten prepared transaction will hold freezing back. Vacuum keeps running and gets nowhere, which is how a healthy-looking database ends up refusing writes. Switch the tool to "Freezing blocked" to watch the countdown.
Autovacuum visits a table once its dead rows pass 20% of the table, plus 50. On a 10-billion-row table that meant waiting for 2 billion dead rows, so Postgres 18 capped the trigger at 100 million. Try your own table sizes in the second tool.
Some updates make almost no mess. If you don't change an indexed column and the new version fits on the same page, Postgres does a HOT (heap-only tuple) update. It adds no index entries, and Postgres can clean it up by tidying that one page. Pages fill all the way by default, so leaving room with a lower fillfactor is how you earn HOT updates.
In 19 the first warning comes when 100 million IDs are left, up from 40 million. 19 also adds parallel autovacuum, which is off by default (autovacuum_max_parallel_workers is 0 in the source), and a scoring system that decides which tables autovacuum visits first.
TransactionId is a uint32 (c.h); the wrap limit is the oldest frozen ID plus 231 − 1, and the warn and stop limits sit 100,000,000 and 3,000,000 below it (varsup.c). Defaults run three autovacuum workers (up to 16 slots since 18), with a 2 ms cost delay for every 200 cost units. The visibility map's all-frozen bit (9.6) lets aggressive vacuums skip frozen pages, and 18 added eager freezing of all-visible pages during normal vacuums, capped by vacuum_max_eager_freeze_failure_rate = 0.03. HOT also tolerates changes to columns covered only by BRIN indexes, since 16.
Smil check: 231 / 10,000 per second = 214,748 s ≈ 2.5 days.
Toy assumptions: one table holds the cluster's oldest frozen ID; IDs burn at a constant rate; a vacuum that starts at age A finishes with the table frozen up to its start ID minus vacuum_freeze_min_age (50M), so age drops to 50M plus whatever burned while it ran. "Blocked" means something holds back the horizon, so vacuum runs but cannot advance.
Row size is the padded row, header included. HOT headroom counts new versions that fit in the space fillfactor left free, before the page has to be tidied; each needs its row plus a 4-byte pointer.
PG 19 · access/xlogrecord.h · access/transam/xlog.c · pg_config_manual.h · docs: WAL configuration
Change 120 bytes in a row and Postgres can write 8 KiB to its log, nearly 70 times more. It happens on the first change to each page after a checkpoint. Later changes to that page cost only themselves, until the next checkpoint starts the count again.
The 1987 POSTGRES design had no write-ahead log at all. It never overwrote data, so Stonebraker reasoned there was nothing to replay after a crash. Postgres added a write-ahead log later, and with it a problem the old design never had: torn pages.
An operating system can write an 8 KiB page as two 4 KiB pieces. If the power fails between them, the page is half old and half new, and no log record can repair that. So after each checkpoint, Postgres logs a full copy of every page the first time it changes, and recovery starts from that clean copy.
That means log volume depends mostly on how many different pages you touch between checkpoints, and much less on how many changes you make.
Longer gaps between checkpoints mean less log but slower recovery. Recovery starts from the last checkpoint that finished, and each checkpoint spreads its writes over 90% of the gap. So a crash at the worst moment replays almost two gaps' worth of log.
The 5-minute timer usually isn't what sets the gap. The default max_wal_size of 1 GB triggers a checkpoint after about 520 MB of log (33 segments of 16 MiB). In the tool's default workload, that forces a checkpoint every 13 seconds.
By default, a commit doesn't return until its log is on disk. On storage that takes 1 ms to flush, one connection can't commit more than about a thousand times a second. Many connections do better, because one flush covers every commit waiting behind it. Turning synchronous_commit off removes the wait. A crash can then lose the last fraction of a second of commits, but it can't corrupt anything.
The free space between pd_lower and pd_upper is left out of a full-page image, and wal_compression can shrink the rest; in 19, on picks the best method available rather than always pglz. 19 also reports full-page-image bytes in pg_stat_wal and in EXPLAIN (ANALYZE, WAL). commit_delay (microseconds, default 0) can hold a flush briefly once at least commit_siblings (5) other transactions are active. With synchronous commit off, the loss window is at most 3 × wal_writer_delay, which defaults to 200 ms.
Smil check: (8,192 + 120) / 120 ≈ 69.
Toy assumptions: updates land uniformly on the hot set; each log record, header included, is 120 bytes; each full-page image costs 8,192 bytes (hole removal and compression make it smaller); index pages ignored; one transaction per update. The curves show the timer alone; the dots include the max_wal_size trigger. Redo speed varies by an order of magnitude with cache state and storage, so measure your own.
PG 19 · optimizer/cost.h · utils/selfuncs.h · optimizer/path/costsize.c · docs: row estimation
Ask Postgres for rows where city = 'SF' AND state = 'CA'. It knows 1% of rows have city SF and 2% have state CA. It assumes the two are unrelated, multiplies, and expects 0.02%. The real answer is 1%, so the estimate is off by 50×, and every join above that step inherits the mistake.
In 1979 Patricia Selinger and her team at IBM's San Jose lab described how System R picked a query plan: estimate the cost of each option and take the cheapest. Every serious SQL optimizer still works this way. When a column had no index to tell System R about its values, it guessed that an equality test kept 1 row in 10. Postgres's fallback guess is 1 in 200, and both systems guess that an inequality keeps a third.
One bad guess is survivable. The trouble is that a join's estimate is built by multiplying the estimates beneath it. If each of ten joins is off by 2× in the same direction, the estimate at the top is off by about 1,000×.
This isn't theoretical. In 2015 Viktor Leis and colleagues tested real optimizers, Postgres included. Every one routinely produced large errors that grew with the number of joins, and those errors hurt plans far more than any flaw in the cost formulas.
CREATE STATISTICS tells the planner that two columns move together, like city and state, but only within one table. For everything else, 19 adds pg_plan_advice, a module that lets you pin or nudge plan choices when you can't fix the estimates. 19 also turns JIT compilation off by default, because the cost estimates that switched it on turned out to be unreliable.
Costs are counted in units of one sequential page read: seq_page_cost 1.0, random_page_cost 4.0, cpu_tuple_cost 0.01, cpu_index_tuple_cost 0.005, cpu_operator_cost 0.0025, parallel_setup_cost 1000, parallel_tuple_cost 0.1, effective_cache_size 4 GB.
Without usable statistics (selfuncs.h): equality 0.005, inequality 1/3, range 0.005, pattern match 0.005, 200 distinct values. With statistics, estimates come from each column's most-common-values list and histogram, sized by default_statistics_target = 100. An equijoin's selectivity is about 1 / max(nd1, nd2). Past join_collapse_limit = 8 the planner stops reordering explicit joins, and at geqo_threshold = 12 FROM items it switches to a genetic search.
Toy assumptions: each join's estimate is off by the same factor q. "Same direction" multiplies qk. "Random direction" makes each factor q or 1/q with equal odds and reports the 95th-percentile spread, exp(1.645·√k·ln q). The correlated-pair preset puts a 50-fold underestimate at the scan and makes every join above it accurate, so the 50 is simply inherited.
PG 19 · utils/misc/guc_parameters.dat · docs: resource consumption · Queues by the Numbers: pool sizing
Open 500 connections and have each one run a query with three sorts. At the default 4 MB per sort, that is 6 GB of memory before Postgres counts anything else.
Postgres starts a separate operating-system process for every connection. Each process keeps its own caches of table and catalog details and its own query plans. How much that takes depends on how many tables it touches no fixed figure in the docs.
On top of that, work_mem is a budget for each sort or hash step, in each process, rather than a limit per query. A query with three such steps can use three budgets. Hash steps get double, and parallel workers are separate processes with budgets of their own. Going over a budget spills to disk instead of failing, so one big query is rarely the problem. The total across every process is.
In 1961 John Little proved that the average number of jobs inside a system equals how fast they arrive times how long each one stays, whatever the arrival pattern. Queues by the Numbers gives the law its own section. For Postgres it answers the question every connection pool raises: how many connections are doing work right now?
The answer is usually far fewer than are open. Most clients sit idle between queries, so a connection pooler in transaction mode can serve thousands of them through a few dozen server processes. Queues by the Numbers sizes a pool from both ends. The floor keeps checkouts from waiting. The ceiling is about twice the database's cores, and past it extra connections just fight each other. The second tool here gives the floor for one pool.
work_mem 4 MB; hash_mem_multiplier 2.0 (since 15); max_parallel_workers_per_gather 2; max_connections 100; shared_buffers 128 MB; maintenance_work_mem 64 MB. In 19, max_locks_per_transaction doubled from 64 to 128, and because the lock table is now sized differently, matching an old capacity means doubling an old setting. Measure a backend's real footprint with pg_backend_memory_contexts or its proportional set size, since resident size double-counts shared buffers.
Smil check: 500 × 3 × 4 MB = 6,000 MB ≈ 6 GB.
Toy assumptions: every connection runs the same query at the same moment and fills every budget, which is the worst case, not the usual one. shared_buffers is set to 25% of RAM. The 5 MB private baseline is a placeholder varies widely.
Toy assumptions: an M/M/c queue, with random arrivals, exponential service times and each pooled connection as a server. It assumes query time does not grow with concurrency, which stops being true once active connections outnumber the cores doing the work. Queues by the Numbers adds fleets of app instances and a p99 target.
Generic model · docs: file_copy_method · OpenZFS performance tuning (recordsize) · docs: page layout · docs: WAL reliability
Copy a 1 TB database in under a second. Since Postgres 18 you can: set file_copy_method = clone and run CREATE DATABASE with STRATEGY = FILE_COPY on a filesystem that supports cloning. It takes about the same fraction of a second for a gigabyte as for a terabyte, because nothing is copied until someone writes.
That is copy-on-write. A new branch shares every block with its parent and costs nothing at first. Each write to a shared block gives the writer its own copy. Storage grows with the number of different blocks changed since the fork. For overwrites of shared blocks, a branch can never grow past the size of the data it shares with its parent. New rows add new blocks on top of that.
Postgres writes 8 KiB pages. If your storage copies in 8 KiB units, a page write costs 8 KiB. If it copies 128 KiB records, a common filesystem default, one random page write copies 128 KiB. That is sixteen times as much, until every record in the working set has been copied once. Appending new rows barely notices, because new pages fill new units in order.
Each of these counts as a change on a branch, even though your app never asked for it:
initdb has turned on data checksums by default since 18. That logs the first hint-bit change to each page after a checkpoint as a full-page copy.A plain filesystem snapshot of a running database is safe only if it captures the data directory and the log at the same instant. Otherwise, wrap it in pg_backup_start and pg_backup_stop.
Toy assumptions: each page write hits one uniformly random page of the hot set (or a new page, for appends); copy units line up with pages; units smaller than 8 KiB behave like 8 KiB because PostgreSQL rewrites whole pages; the change-record line assumes 150 bytes per write and never rebuilds pages. "Parent also writing" assumes the parent changes the same hot set at the same rate, independently.
Guess first, then reveal. The answers come from the same code as the calculators above, so you can go back and see how each one was worked out.
Release notes for each major version: postgresql.org/docs/release · 19.0 · 18.0
Most of the numbers on this page are older than the features built around them. The 8 KiB page and the 32-bit transaction ID are old design choices that the project has kept. HOT updates, the freeze map, deduplication, the vacuum failsafe, the autovacuum cap and async I/O all work around those limits. None of them removes one.
19 keeps the pattern. It adds REPACK to replace VACUUM FULL and CLUSTER (both stay for compatibility), and its concurrent mode rebuilds a table without blocking reads or writes. The row format doesn't change.
None of these shipped in 19. This is where things stand in November 2026. Cards marked "my reading" summarize mailing-list and commitfest activity, not a release note.
Egor Rogov, PostgreSQL 14 Internals (Postgres Professional, 2023). The closest thing to a field guide to the code. It covers pages, MVCC, vacuum, the buffer cache, WAL, locking and every index type, and traces each one down to the structures in this page's asides. The English PDF is free; a Russian edition updated for version 18 appeared in 2026.
Hironobu Suzuki, The Internals of PostgreSQL (interdb.jp, online). A free, heavily illustrated tour. It is especially good on heap pages, concurrency control and the query processor, and its diagrams show what this page's byte lists only describe.
Martin Kleppmann and Chris Riccomini, Designing Data-Intensive Applications, 2nd edition (O'Reilly, 2026). Read this to see where Postgres sits among other databases. It compares log-structured and page-oriented storage, snapshot isolation and replication, and explains the trade-offs behind each.
Joseph Hellerstein, "Looking Back at Postgres" (2019). A short essay from inside the Berkeley project. It covers which of Stonebraker's ideas lasted, which were dropped, and how a research prototype became the database most of us run.
Last verified: 2026-11-26
The calculators are deliberately simple models with their assumptions stated beside them. The constants are exact for a default PostgreSQL 19 build on a 64-bit platform.
MusicChordsRhythmBluesJazz HarmonySynthesisMIDIVoiceSoftwareQueuesInfrastructureThe GridData CentersEarthHurricanesEarthquakesStartupsFounder Equity