MVCC: how readers and writers don’t block
A report reads a table for ten minutes while the app keeps updating it, and neither waits for the other. Postgres manages that by keeping old copies of rows next to new ones. Here is what is really on the page, how each transaction picks its copy, and why something has to come back later to throw the old ones away.
01 Readers that never wait
In Transactions and what isolation levels stop you met snapshots: each transaction sees the data as it was at one moment. This page opens that up. If a writer changed rows in place, a reader would have to wait for the writer, or see half-finished work. Postgres does neither. A plain SELECT never waits for an UPDATE, and an UPDATE never waits for a SELECT.
The trick is multi-version concurrency control (MVCC). A change never overwrites a row. It adds a new version and marks the old one as replaced. Each reader then picks the version that was current at its snapshot. Writers still wait for other writers on the same row; that is the subject of Row locks and deadlocks.
02 Every row version carries two transaction ids
Every transaction that writes gets a number, its transaction id (xid), handed out in order. Each row version stores two of them in hidden system columns. You can select them by name:
| Column | Means |
|---|---|
| xmin | the transaction that created this version |
| xmax | the transaction that deleted or replaced it; 0 if none (a row lock writes it too; see **Row locks and deadlocks**) |
| ctid | where the version lives: (page, slot on that page) |
Both rows were inserted by one transaction, 732, and nobody has replaced them. This and the listings below are real runs on Postgres 16; your xids will be different numbers.
03 An UPDATE writes a new version
Now update account 1 and look again. The row has moved: it is in slot 3, with a new xmin. The pageinspect extension shows what is really on the page, including versions no query would return:
Slot 1 still holds balance 100, now stamped xmax 733 and pointing forward to (0,3). A DELETE is the same move without the new version: it only sets xmax. A ROLLBACK undoes nothing on the page either. Postgres just records the transaction as aborted, and every version it wrote becomes invisible from then on.
04 A snapshot decides which version you see
A snapshot is three things: the lowest xid still running (xmin), the next xid not yet handed out (xmax), and the list of xids running in between. Here session B (756) is open, a third session’s 757 has committed, and the snapshot reads 756:758:756:
For each version a query meets, Postgres asks two questions with that snapshot. It looks up whether a transaction committed in the commit log, pg_xact, and caches the answer on the row as hint bits so later readers skip the lookup.
| Check | Visible when |
|---|---|
| Was it created in time? | `xmin` committed, is below the snapshot’s `xmax`, and is not in its running list (or it is my own transaction) |
| Was it already gone? | `xmax` is 0, or that transaction aborted, or it is not yet committed as far as my snapshot is concerned |
| Result | visible only if the answer to the first is yes and to the second is “not gone” |
At most one version of a row passes both checks for any snapshot. At READ COMMITTED each statement takes a fresh snapshot; at REPEATABLE READ the first statement’s snapshot holds until the end. That is the whole difference between them for reads.
05 Two readers, one writer, drawn
Here is one update with a long reader alongside. The table is the real heap page from a run with autovacuum switched off, so you can see the dead version wait for VACUUM.
- just written
- not committed yet
- what A’s read used
- dead to new snapshots
- removed by VACUUM
- free slot
Account 1 holds 100. Its row is one version on heap page 0, in line pointer 1, stamped xmin 749: the transaction that inserted it. xmax 0 means nobody has deleted or replaced it. Slot 3 on the page is still free.
06 Why VACUUM exists
Nothing in the update path deletes old versions, because some snapshot might still need them. Every UPDATE and DELETE leaves a dead tuple behind. VACUUM is the job that finds versions no snapshot can see any more, frees their space for reuse, and removes the index entries that point at them.
You can watch a table double. 100,000 rows, autovacuum off, one UPDATE of every row:
The update wrote 100,000 new versions, so the file doubled. VACUUM did not shrink it, but it marked the dead space free, and the second update reused that space instead of growing again. Only VACUUM FULL gave the space back to the operating system, by rewriting the table.
ACCESS EXCLUSIVE lock the whole time: no reads, no writes. Treat it as maintenance downtime.Autovacuum runs VACUUM for you. In Postgres 16 it visits a table once its dead tuples pass autovacuum_vacuum_threshold (50) plus autovacuum_vacuum_scale_factor (0.2) times its row count: about 20% of a big table. VACUUM also freezes old versions. Xids are 32 bits, so the counter wraps round, and an xid more than about 2 billion in the past would start to look like the future. Before that happens, old versions are marked “frozen”: visible to everyone, whatever their xmin says.
07 When it bites
One session left idle in transaction stops VACUUM removing any row version newer than its snapshot, in every table of that database. Find them with SELECT pid, state, xact_start, backend_xmin FROM pg_stat_activity WHERE state = 'idle in transaction'; and set idle_in_transaction_session_timeout.
UPDATE jobs SET heartbeat = now() WHERE id = $1; -- every secondHot rows that are updated constantlyEach update is a new version. A small table updated thousands of times a minute can bloat far past its live size if autovacuum cannot keep up. Lower autovacuum_vacuum_scale_factor for that table, and keep indexed columns out of the update so it stays HOT.BEGIN ISOLATION LEVEL REPEATABLE READ; -- 2-hour reportLong reports on the primaryA long snapshot keeps every version made since it began. Run long reports on a replica; but note that hot_standby_feedback = on sends the replica’s oldest snapshot back to the primary, with the same effect.SELECT count(*) FROM orders;count(*) is not storedDifferent snapshots see different row counts, so there is no single number to keep. Postgres must check visibility of each version, or use the visibility map in an index-only scan. For a rough figure, read reltuples from pg_class.WARNING: database "app" must be vacuumed within ... transactionsTransaction id wraparoundIf freezing falls far behind, Postgres warns, and as a last resort refuses new xids until a VACUUM finishes. Autovacuum forces a freezing pass when a table’s oldest xid passes autovacuum_freeze_max_age (200 million by default). Do not turn autovacuum off.CREATE INDEX ON items (qty);An index on a column you updateHOT updates only work when no indexed column changes and the page has room. Index the busy column and every update also writes new entries into every index on the table.