PostgreSQL in depth
Learn how Postgres stores, cleans, indexes and copies your rows, so it does not stop taking writes on a Monday morning.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
At 05:35 UTC on 4 February 2019, one database stopped taking writes at Mandrill, Mailchimp's email service for apps. The database was a Postgres shard called shard4. It went into "safety shutdown mode". 1
The cause was transaction ID wraparound. Postgres gives each writing transaction a 32-bit ID. Autovacuum must clean up old IDs in time. On shard4 it had fallen behind or failed, and the IDs hit their limit. 1
The team had seen it coming. In November 2018 they found the IDs at about half their limit during peak load. They added a ticket to set up more monitoring. 1
The fix was slow. Vacuuming the whole shard was estimated to take up to 40 days. Two tables were terabytes in size. Mandrill deletes queued mail after 48 hours, so time mattered. 1
At 19:12 UTC on 5 February, the team truncated those large tables. The vacuum finished about an hour later. Service came back after about 40 hours. By 22:40 they had alerts for wraparound. 1 Sentry had the same outage in 2015. It too ended by truncating one large table. 2
It happens for real
Mailchimp (Mandrill) · 4 Feb 2019Mandrill outage: one Postgres shard stopped writes to avoid transaction ID wraparoundMandrill, Mailchimp's transactional email service, sent only about 80% of queued email for about 40 hours, and its queues were back to normal about 43 hours after the start. All incidents tagged “database”The idea in simple words
Postgres does not change a row in place. An UPDATE writes a new row version and leaves the old one behind. 3 The concurrency control lesson showed why: readers with an older snapshot still need it.
So every busy table creates garbage all the time. An old version that no transaction can see is a dead tuple. VACUUM finds dead tuples and frees their space. 3
VACUUM has a second job that people forget. It marks old rows as "frozen", so their transaction IDs can be reused safely. 3 Skip the first job and you get bloat. Skip the second and Postgres stops writes.
The key idea. In Postgres, every update and delete leaves work for VACUUM. Your job is to keep autovacuum fast enough, and to make sure nothing stops it.
How it works
Step through one update, from new row version to cleanup.
- Order 7 lives in the table's heap as row version v1. Transaction 100 created it, so its xmin is 100. The index points to it.
- Transaction 205 sets status to paid. Postgres does not change v1. It marks v1 with xmax 205 and writes v2. No indexed column changed and the page had room, so this is a HOT update.
- v1 is not garbage yet. A report that started before the update must still see status=new. Postgres keeps v1 for it.
- The report ends. Now no snapshot can see v1. It is a dead tuple. VACUUM, or page pruning during a later read or write, frees its space for new row versions on this page.
- If the update changes an indexed column, or the page is full, it is not HOT. Every index on the table gets a new entry, and VACUUM must later clean the old entries.
Autovacuum and when it falls behind
Autovacuum vacuums a table after enough rows have changed. By default the trigger is 50 rows plus 20% of the table. 7 On a table with 100 million rows, that means about 20 million dead tuples before it starts. By default, 3 workers share the whole server. 7
When it falls behind, dead tuples pile up and the table bloats. Scans read more pages. A long open transaction or a forgotten replication slot can also stop cleanup. 25 3 Watch n_dead_tup and last_autovacuum in pg_stat_all_tables. 9
Transaction ID wraparound, precisely
Transaction IDs (XIDs) are 32 bits. Postgres compares them in a circle: for each ID, two billion are "older" and two billion are "newer". 3 An unfrozen row older than that would suddenly look like it is from the future.
So every table must be vacuumed at least once every two billion transactions. 3 Here are the steps, from the current docs: 3
- A table with unfrozen rows older than
autovacuum_freeze_max_agegets an anti-wraparound autovacuum. The default is 200 million. 7 This runs even if autovacuum is off. - When the oldest XIDs are 40 million transactions from wraparound, PostgreSQL 18 logs
WARNING: database "mydb" must be vacuumed within ... transactions. From version 19 this warning starts at 100 million. 4 5 - At 3 million left, it refuses to start new transactions that need an XID. Reads still work. Writes fail.
To recover, the docs say: end old transactions, resolve prepared ones, drop stale slots, then run a plain VACUUM as a superuser. Single-user mode is usually not needed any more. The one exception: you want to TRUNCATE or DROP a large table instead of vacuuming it. 3
Check how close each database is: 3
SELECT datname, age(datfrozenxid) FROM pg_database
ORDER BY 2 DESC;On a healthy server the age stays below about 200 million, because the anti-wraparound autovacuum starts there. Alert when it stays well above that, for example at 500 million. That is long before the warning. Mandrill's monitoring ticket sat in the backlog. 1
HOT updates
In the diagram, the update was a HOT update (heap-only tuple). It needs two things. No column used by an index changes (BRIN indexes do not count), and the new version fits on the same page. 8 Then no index needs a new entry, though a BRIN summary may be updated. 8
Every B-tree, GIN or GiST index you add makes HOT less likely. To leave room on pages, lower the table's fillfactor: 8
ALTER TABLE orders SET (fillfactor = 80);This applies to pages written from now on. Existing full pages get no room until the table is rewritten. 15
Compare n_tup_hot_upd with n_tup_upd to see your HOT rate. 9
Picking an index type
The indexes lesson covers composite, partial and expression indexes. Here is when to leave the B-tree.
- B-tree: the default. Equality and ranges on sortable values. 10
- GIN: an inverted index for values with many parts, like arrays. 10 It also serves
jsonbcontainment (@>) and key checks. 11 It is the preferred index for full text search. 12 - GiST: a framework for geometric data and "nearest-neighbor" queries. 10
- BRIN: small summaries of block ranges. Best when a column follows the physical row order, like
created_atin an append-only log. 10
CREATE INDEX events_payload_gin
ON events USING GIN (payload jsonb_path_ops);
CREATE INDEX events_created_brin
ON events USING BRIN (created_at);jsonb_path_ops is usually much smaller than the default class. But it does not support the key-exists operators like ?. 11
Reading EXPLAIN (ANALYZE, BUFFERS)
EXPLAIN ANALYZE runs the query and shows real times and row counts next to the estimates. 13 Three checks catch most problems:
- Estimated vs actual rows. The docs call this the most important thing to look for. A big gap means the planner guessed wrong. 13
- Loops. Times and rows are per loop. Multiply by
loopsfor the total. 13 - Buffers. From PostgreSQL 18, ANALYZE turns on buffer counts too. 6 On older versions, add BUFFERS. A "hit" means a read was avoided because the page was already in the cache. 14 A "read" had to ask the operating system, from disk or its cache. Our advice: many buffers (hit plus read) for a few rows often point to bloat or a missing index. Many reads but few hits just mean the data was not in cache.
ANALYZE really runs the statement. Wrap an UPDATE in BEGIN and ROLLBACK. 13
WAL and checkpoints
You met the write-ahead log before. Postgres also runs checkpoints. At a checkpoint it flushes all changed pages and records that point in the WAL. After a crash, it replays only from there. 19
A checkpoint starts every 5 minutes, or sooner when the WAL nears max_wal_size (default 1 GB). 19 After each checkpoint, the first change to a page writes the whole page to the WAL. 19 So frequent checkpoints mean more WAL. By default, Postgres logs a hint when checkpoints caused by WAL volume come less than 30 seconds apart (checkpoint_warning). 18
Physical vs logical replication
Physical streaming replication sends WAL records to a standby as they are made. 20 It copies exact disk blocks, so the standby is a copy of the whole server. 21 It cannot run a different major version. 20
Logical replication sends row changes by table and key, through publications and subscriptions. It can copy a subset of the data, and works across major versions. 21 But it does not copy schema changes. 22 It also does not keep sequence values in step, though version 19 can sync them on request. 22 5
Both can use a replication slot. A slot that nobody reads can keep WAL until the disk fills. 20 It also holds back VACUUM. 3
One process per connection
Postgres starts a new backend process for every connection. 23 The default max_connections is about 100. Raising it allocates more shared memory. 24 So thousands of app connections usually go through a pooler like PgBouncer. Database connection pooling covers this.
Trade-offs
| Choice | Gain | Cost | Use when |
|---|---|---|---|
| Default autovacuum | No tuning work. | Starts late on huge tables. 3 workers in total. 7 | Small and medium tables. |
| Per-table autovacuum settings | Vacuums big, busy tables early. | More vacuum I/O, and settings to maintain. | Tables with many millions of rows and frequent updates. |
Lower fillfactor | More HOT updates, fewer index writes. 8 | Bigger table on disk. | Rows updated often on non-indexed columns. |
GIN on jsonb | Fast containment and key search. 11 | Updating it tends to be slow. 16 | You filter on fields inside documents. |
| BRIN | Very small index. 17 | Poor when values do not follow row order. 10 | Append-only time data. |
| Physical replica | Exact copy, simple failover. 20 | Same major version, whole server only. | High availability and read scaling. |
| Logical replication | Chosen tables, across versions. 21 | No schema changes. Sequences only from version 19. 22 5 | Upgrades and feeding other databases. |
Simple rule: keep the defaults, but watch dead tuples and XID age from day one.
At work: how a senior uses this
- Alert on
age(datfrozenxid)per database. 3 Treat a rising number as a ticket for this week, not the backlog. Mandrill's monitoring ticket waited there. 1 - Set
idle_in_transaction_session_timeout. An idle open transaction holds back VACUUM and causes bloat. 25 - Set
statement_timeoutper app role or session, not inpostgresql.conf, which affects every session. 25 - Set
lock_timeoutin every migration, as in the schema migrations lesson. 25 - Turn on
pg_stat_statements. It needsshared_preload_librariesand a restart, so do it early. 26 Sort bytotal_exec_timeto find what costs most. - Check
pg_replication_slotsfor inactive slots after every replica or CDC change. 3 - For big, busy tables, tune autovacuum per table. Sentry raised workers and removed the cost delay after its outage. 2
- Know which large tables you could truncate in an emergency. Both Mandrill and Sentry recovered that way. 1 2 Once writes have stopped, truncating needs single-user mode. 3
With AI
What to ask the agent
"Write SQL that lists, for each table, dead tuples, the last autovacuum time, the HOT update rate and the age of relfrozenxid. Sort by the worst."
"Here is our EXPLAIN (ANALYZE, BUFFERS) output. Find the node where estimated and actual rows differ most, and explain why."
"We query payload->>'country' and payload @> '{\"tier\":\"gold\"}' on a jsonb column. Propose indexes for each and explain the difference."
What to check yourself
- Every number the agent gives for wraparound matches the docs for your version: 200 million, 40 million (100 million from version 19) and 3 million. Old blog posts give older advice.
- The agent did not suggest
VACUUM FULLas a fix for wraparound. The docs say not to use it there. 3 - A proposed GIN index actually supports the operator in the query.
- Timeouts are set per role or session, with a longer limit for migrations and reports.
EXPLAIN ANALYZEon a write runs inside a transaction that rolls back.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 26 sources and related lessons
- Mailchimp, What We Learned from the Recent Mandrill Outage (opens in a new tab)
A full timeline of a 2019 outage caused by transaction ID wraparound on one Postgres shard. - David Cramer (Sentry), Transaction ID Wraparound in Postgres (opens in a new tab)
The same failure at Sentry in 2015, and the autovacuum settings they changed afterwards. - PostgreSQL documentation: 24.1. Routine Vacuuming (opens in a new tab)
Version 18 page. Dead row versions, freezing, the wraparound limits and warnings, and how to recover. - PostgreSQL documentation: 24.1. Routine Vacuuming (opens in a new tab)
Version 19 page. The wraparound warning now starts at 100 million transactions. - PostgreSQL documentation: E.1. Release 19 (opens in a new tab)
Release notes for version 19, including the new wraparound warning and logical replication of sequence values. - PostgreSQL documentation: E.7. Release 18 (opens in a new tab)
Release notes for version 18, where EXPLAIN ANALYZE started to show buffers by default. - PostgreSQL documentation: 19.10. Vacuuming (opens in a new tab)
Autovacuum settings and their defaults. - PostgreSQL documentation: 66.7. Heap-Only Tuples (HOT) (opens in a new tab)
When an update can skip the indexes, and how fillfactor helps. - PostgreSQL documentation: 27.2. The Cumulative Statistics System (opens in a new tab)
The pg_stat_all_tables view, with dead rows, HOT updates and autovacuum times per table. - PostgreSQL documentation: 11.2. Index Types (opens in a new tab)
What B-tree, Hash, GiST, SP-GiST, GIN and BRIN indexes are each good at. - PostgreSQL documentation: 8.14. JSON Types (opens in a new tab)
Section 8.14.4 on GIN indexes for jsonb and the two operator classes. - PostgreSQL documentation: 12.9. Preferred Index Types for Text Search (opens in a new tab)
Why GIN is the usual index for full text search. - PostgreSQL documentation: 14.1. Using EXPLAIN (opens in a new tab)
Costs, actual times, loops and the BUFFERS option. - PostgreSQL documentation: EXPLAIN (opens in a new tab)
The BUFFERS option: what shared hit, read, dirtied and written mean. - PostgreSQL documentation: ALTER TABLE (opens in a new tab)
Changing a storage parameter such as fillfactor does not rewrite existing pages. - PostgreSQL documentation: 65.4. GIN Indexes (opens in a new tab)
How GIN works, and why updating it tends to be slow. - PostgreSQL documentation: 65.5. BRIN Indexes (opens in a new tab)
Block ranges, why a BRIN index is very small, and when it helps. - PostgreSQL documentation: 19.5. Write Ahead Log (opens in a new tab)
checkpoint_warning and its 30-second default. - PostgreSQL documentation: 28.5. WAL Configuration (opens in a new tab)
What a checkpoint does, its default timing, and full page writes. - PostgreSQL documentation: 26.2. Log-Shipping Standby Servers (opens in a new tab)
Streaming replication, version limits, and replication slots. - PostgreSQL documentation: Chapter 29. Logical Replication (opens in a new tab)
How logical replication differs from physical, and what it is used for. - PostgreSQL documentation: 29.8. Restrictions (opens in a new tab)
What logical replication does not copy, such as schema changes and sequences. - PostgreSQL documentation: 51.2. How Connections Are Established (opens in a new tab)
The process-per-user model and the postmaster. - PostgreSQL documentation: 19.3. Connections and Authentication (opens in a new tab)
max_connections, its default, and why raising it costs shared memory. - PostgreSQL documentation: 19.11. Client Connection Defaults (opens in a new tab)
statement_timeout, lock_timeout and idle_in_transaction_session_timeout. - PostgreSQL documentation: F.32. pg_stat_statements — track statistics of SQL planning and execution (opens in a new tab)
How to turn on the extension and what its columns mean.
Real incident: Mailchimp (Mandrill), 4 Feb 2019: Mandrill outage: one Postgres shard stopped writes to avoid transaction ID wraparound
Case studies: Figma: Horizontally sharding Postgres behind a query proxy · Notion: Sharding Postgres by workspace at Notion · Zerodha: Running billions of rows of reports on plain Postgres
Related: Locking and MVCC in practice · Secondary, composite and special indexes · Replication · Schema migrations without downtime · Transactions and isolation levels
Before this: Transactions and isolation levels and Replication. Related: Concurrency control in practice, Secondary and composite indexes and B-trees and LSM-trees. Next: Database connection pooling.