Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Postgres internals: UPDATE never updates, and a janitor keeps it working.
The world's default database has a strange secret at its core: it never modifies data in place. Updates write copies, deletes delete nothing, and a background janitor cleans up the corpses. From that one design choice — MVCC — flows almost everything operators fight with and everything that makes Postgres brilliant. Here's the machine, layer by layer.
The heap: tables are bags of 8KB pages
A table is a heap — a file of fixed 8KB pages, each holding row versions (tuples) plus a small item-pointer directory. Rows have no inherent order; a row's physical address (the ctid: page number + slot) is where indexes point. Values too big for a page get sliced into a side table by TOAST — which is why a 5MB JSON blob doesn't wreck the page geometry of its neighbors.
Hold onto the page as the unit of thought: I/O happens in pages, the buffer cache holds pages, and the planner prices queries in page reads. "How many pages will this touch?" is the question behind nearly every performance mystery below.
MVCC: every row is a row version
Concurrent readers and writers are the defining database problem. Locking readers against writers murders throughput; Postgres chose Multi-Version Concurrency Control instead: keep multiple versions of each row, let every transaction see its own consistent snapshot.
All of visibility is one predicate on two integers. A tuple stamped (xmin, xmax) is visible to a snapshot s exactly when it was born in your past and hasn't expired in your past:
Take two snapshots at different times over the same logical row and this predicate hands each a different physical version — that's snapshot isolation, and it needs no locks. It also explains dead tuples exactly: once every live snapshot has moved past a tuple's xmax, nothing can select it again, so it is pure garbage. The runnable model below is this predicate plus a tiny heap; watch an UPDATE serve an old and a new reader at once and leave one dead tuple behind.
The prize: readers never block writers, writers never block readers — a long analytics query and a burst of updates coexist peacefully, each in its own snapshot. The price: expired versions — dead tuples — accumulate in the heap, and every index entry pointing at them lives on too. Someone has to clean up.
VACUUM: the janitor with two jobs
VACUUM walks tables reclaiming dead tuples so their space gets reused, and maintains the visibility map (which pages are all-visible — crucial for index-only scans, next section). Autovacuum triggers it per table when dead tuples cross thresholds. When churn outruns it, you get bloat: tables and indexes physically far larger than their live data, wasting cache, slowing scans — the classic silent Postgres degradation. Watch pg_stat_user_tables.n_dead_tup; tune autovacuum more aggressive, not less, on hot tables.
Transaction IDs are 32-bit and circular. VACUUM's second job is freezing old tuples so their age stops mattering. If autovacuum is disabled or perpetually starved, Postgres will eventually force an aggressive freeze — and in the worst case shut down to protect data. When a DBA looks pale and says "wraparound," this is the story.
Indexes: B-trees, heap trips, and the free lunch
The default index is a B-tree mapping key → ctid. But an index hit isn't the end: the tuple's visibility lives in the heap, so a normal index scan does index then heap — two page trips. The visibility map earns its keep here: if the index covers every column the query reads and the target page is marked all-visible, Postgres can skip the heap trip entirely — an index-only scan, the fastest read Postgres has. (Well-vacuumed tables make them possible; bloated ones don't.)
| Index type | Reach for it when |
|---|---|
| B-tree | equality + ranges + ordering — 95% of indexes |
| GIN | things-inside-things: JSONB containment, arrays, full-text |
| GiST | geometry, ranges, nearest-neighbor |
| BRIN | huge naturally-ordered tables (timestamps) — tiny index, coarse pruning |
| Partial / expression | index only the rows or the transform you actually query |
MVCC's tax collects here too: every UPDATE creates index entries for the new version in every index — unless nothing indexed changed and the new tuple fits the same page (a HOT update). Fewer indexes and non-indexed churn columns = more HOT = less bloat.
WAL: one log, three superpowers
Writing dirty 8KB pages to random disk locations on every commit would be slow and torn-write fragile. Postgres instead appends every change to the write-ahead log — sequential, fsynced before commit returns. Data pages are updated lazily in memory and flushed at checkpoints.
every change, in order
replay since checkpoint
ship the stream to replicas
base backup + WAL to any second
Crash? Replay WAL from the last checkpoint — perfect recovery. Replicas? They're just servers replaying your WAL live (streaming replication), or logically decoding it (logical replication, CDC). Point-in-time recovery? A base backup plus archived WAL replayed to any chosen second. Durability, HA and backups: one log.
The planner: a cost model, not a mind-reader
SQL says what; the planner picks how: which indexes, which join algorithm (nested loop for tiny inner sides, hash join for big unsorted ones, merge join for pre-sorted inputs), which order. It prices candidate plans with statistics — histograms and distinct-counts per column, refreshed by ANALYZE — and picks the cheapest estimate.
Which is why every slow-query investigation is the same ritual: EXPLAIN ANALYZE, then compare estimated rows vs actual rows. Off by 1000×? The stats are stale or the column correlations exceed what histograms capture — and the planner chose a nested loop for a million rows. Seq scan on a "should be indexed" query? Often correct: past ~5-10% selectivity, reading the whole table sequentially beats a million random heap trips. The planner is rarely wrong given its inputs; fix the inputs.
Connections and memory: why the pooler is mandatory
Postgres forks an OS process per connection — robust isolation, expensive arithmetic: each backend carries megabytes, and creation isn't cheap. A serverless app opening 2,000 lambda connections meets reality fast. Hence PgBouncer (or a built-in pooler): thousands of client connections multiplexed onto a few dozen real backends, in transaction-pooling mode. Treat it as part of Postgres, not an optimization.
Memory in one line each: shared_buffers — Postgres's own page cache (classic advice: ~25% of RAM; the OS page cache handles the rest); work_mem — per sort/hash operation, not per connection, so big values multiply frighteningly under concurrency; maintenance_work_mem — feed VACUUM and index builds generously.
The machine in one table
| Layer | The one-line truth |
|---|---|
| Heap | 8KB pages of row versions; I/O and caching think in pages |
| MVCC | no in-place writes; snapshots via xmin/xmax arithmetic |
| VACUUM | reclaims dead tuples, feeds the visibility map, prevents wraparound |
| Indexes | B-tree → ctid; index-only scans need a clean visibility map |
| WAL | sequential log = durability + replication + PITR |
| Planner | cost model on statistics — check estimates vs actuals |
| Connections | process per connection → pooler is infrastructure |
Watch MVCC serve two readers one row
This is Postgres's visibility rule as runnable code: visible() is the exact xmin < snap ∧ (xmax = 0 ∨ xmax ≥ snap) predicate, and a tiny heap does INSERT/UPDATE by stamping txids instead of overwriting. A row is inserted by txid 100; a long-running report (snapshot 150) starts; txid 200 debits it. The old snapshot still reads balance=100 while a fresh snapshot reads balance=90 — the same logical row, two physical versions, zero locks — and the superseded version is now a dead tuple waiting for VACUUM. Change the snapshot numbers and see who sees what.
Worked example: when does autovacuum actually run?
An orders table holds 10 million live rows. It takes 500 updates a second, none of them HOT, so each one leaves a dead tuple. Autovacuum vacuums a table once n_dead_tup exceeds 50 + 0.2 × reltuples (the default threshold and scale factor). The workload is illustrative; the defaults are Postgres’s own.
| Step | Question | Arithmetic | Answer |
|---|---|---|---|
| 1 | Dead tuples before autovacuum starts | 50 + 0.2 × 10,000,000 | 2,000,050 |
| 2 | How long that takes | 2,000,050 ÷ 500 per second | 4,000 s, about 67 min |
| 3 | Heap share that is garbage at trigger time | 2,000,050 ÷ 12,000,050 | 16.7%: the table is 20% bigger than its live data |
| 4 | Per-table scale factor 0.01 | 50 + 0.01 × 10,000,000 = 100,050; ÷ 500 | vacuums every 200 s, under 1% dead |
| 5 | A 2-hour report holds an old snapshot | 7,200 s × 500 | 3,600,000 dead tuples no VACUUM may remove |
| 6 | Forced anti-wraparound vacuum at 2,000 writing txns/s | 200,000,000 ÷ 2,000 | 100,000 s, about every 28 h |
| 7 | If freezing never ran at all | 2,147,483,648 (2^31) ÷ 2,000 ÷ 86,400 | about 12.4 days to the wraparound horizon |
Step 4 is the standard fix for big hot tables: ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.01). A percentage threshold that suits a 10,000-row table lets a 10-million-row table rot for an hour. Step 5 is the trap the tuning cannot fix: VACUUM may only remove tuples that are dead to every open snapshot, so one long transaction pins the garbage until it ends. Steps 6 and 7 count only transactions that write, because read-only ones never take an xid. That is why a write-heavy cluster meets wraparound and a read-heavy one rarely does.
Common mistakes
- An idle transaction left open
A session in
idle in transactionholds the oldest snapshot, so VACUUM runs, finishes, and removes almost nothing (step 5 above). Find these sessions inpg_stat_activityand setidle_in_transaction_session_timeout. Abandoned replication slots andhot_standby_feedbackfrom a busy replica pin the horizon in the same way. - Expecting an index-only scan the index cannot serve
A clean visibility map is necessary but not enough. Every column the query reads must be in the index.
SELECT email … WHERE id = $1on an index ofidalone still visits the heap. Add the column withINCLUDE (email)to make the index covering. - Running VACUUM FULL on a live table
It rewrites the whole table under an
ACCESS EXCLUSIVElock, so every read and write waits until it finishes. Plain VACUUM makes space reusable without blocking. To actually shrink a bloated table online, tools such aspg_repackrebuild it beside the original and swap. - Raising work_mem globally
The limit applies to each sort or hash node in each backend, not to each server. 100 connections each running a query with 4 such nodes at 256 MB can claim 100 GiB. Raise it per session or per role for the reports that need it.
- Indexing the column every update touches
An index on
updated_atmeans no update can be HOT, so every UPDATE writes a new entry into every index on the table, not just that one. Checkn_tup_hot_updagainstn_tup_updinpg_stat_user_tablesbefore adding an index to a hot table.
Where this shows up in production and interviews
- Slow-query triage
pg_stat_statementsranks queries by total time.EXPLAIN (ANALYZE, BUFFERS)then shows pages found in shared buffers versus pages read from disk, which is the page-as-unit thinking from section 01, as numbers. - Change data capture
Debezium and logical replication read decoded WAL through a replication slot. A slot whose consumer stops keeps every WAL segment since its position, until the disk fills. Monitor slot lag, and since Postgres 13 cap it with
max_slot_wal_keep_size. - Read replicas
A streaming replica replays the primary’s WAL, including VACUUM’s cleanup. A long query on the replica that still needs those rows gets cancelled with a conflict error.
hot_standby_feedbackstops the cancels by telling the primary to keep the rows, which moves the bloat to the primary. - The interview version
Expect “why is
COUNT(*)slow?” (each tuple’s visibility must be checked, so it scans, unless an index-only scan on a well-vacuumed table can stand in), “why does this update-heavy table keep growing?” (dead tuples, autovacuum thresholds, long transactions) and “why put a pooler in front?” (a process per connection). Each answer is one layer of the table in section 08.
Check yourself
A report starts at 09:00 and is still running at 11:00. Autovacuum processes a hot table at 10:00. What can it remove?
Only tuples that were already dead to the 09:00 snapshot. Every version expired after 09:00 might still be visible to the report, so VACUUM must keep it. Dead tuples pile up until the report ends, which is why long transactions show up as bloat.
COMMIT returned, and the server crashed 30 seconds later before the data page was flushed. Is the row lost?
No. The WAL record was fsynced before COMMIT returned, and crash recovery replays WAL from the last checkpoint and rebuilds the page. The exception is synchronous_commit = off, which returns before the flush and can lose the last moments of commits (but never corrupts the database).
EXPLAIN ANALYZE shows a nested loop where the estimate was 10 rows and the actual was 500,000. What do you fix first?
The estimate, not the join. Run ANALYZE on the tables involved. If the filter combines correlated columns (such as city and postcode), the per-column histograms multiply them as if independent and underestimate, so add CREATE STATISTICS on that column pair. With a right estimate the planner picks the hash join on its own.
A status column flips on every row many times a day and has its own index. Updates are slow and indexes bloat. What change helps most?
Drop or rethink that index. While an indexed column changes, no update can be HOT, so each flip writes a new entry into every index. Without it, a lower fillfactor (say 90) leaves room on each page so the new version fits beside the old one, and updates become HOT.
Quick answers
What is MVCC?
No in-place changes: UPDATE writes a new version, DELETE marks. Transactions see snapshot-consistent versions via xmin/xmax — readers and writers never block each other.
Why VACUUM?
To reclaim dead tuples, maintain the visibility map (index-only scans) and freeze old transaction IDs against wraparound. Starve it and you get bloat.
What does the WAL buy?
Crash recovery, streaming replication and point-in-time recovery — all from one sequential, fsynced change log.
Why PgBouncer?
Process-per-connection makes direct high concurrency ruinously expensive; a pooler multiplexes thousands of clients onto dozens of backends.
Hash join: joining a billion rows in one pass
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- Concurrency, Locks & Isolation LevelsHow overlapping operations stay correct — race conditions, optimistic vs pessimistic locking, the four isolation levels and their anomalies, MVCC, and distributed locks with fencing tokens. Part of System Design Fundamentals.Read →
- Partitioning, Sharding & ReplicationHow one dataset becomes many — range vs hash partitioning, consistent hashing and virtual nodes, hot partitions, replication topologies, replication lag, and quorums. Part of System Design Fundamentals.Read →
- The SQL HandbookWhat the database does underneath your SELECT — the relational model and keys, joins (inner/left/right/full), indexes and B-trees, the query planner and reading EXPLAIN, transactions and ACID, isolation levels and the anomalies they prevent, normalization vs denormalization, and the pitfalls (N+1, missing indexes, SELECT *).Read →
- SQL vs NoSQLFramed as a war, it’s really a menu. Relational databases give you schema, joins and ACID; NoSQL is an umbrella of document/key-value/wide-column/graph stores that drop some of that for flexibility and horizontal scale. The relationships-vs-scale core difference, the CAP trade-off, and why to start relational.Read →
- PostgreSQL vs MySQLBoth are excellent free relational databases you can build a company on, so the choice is about character, not capability: Postgres prizes correctness, rich types and advanced features; MySQL prizes simplicity and read-heavy speed. The real differences, when each wins, and why Postgres became the modern default.Read →
- OLTP vs OLAPOne storage-layout decision explains the whole comparison: row-oriented OLTP makes fetching one record cheap, column-oriented OLAP makes aggregating one column across millions of rows cheap. Why you can’t run heavy analytics well on your production database.Read →