Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  PostgreSQL Internals
Engineering~13 min readIntermediate
Deep Dive

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.

01

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.

02

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.

What DML actually does to the heap
INSERTwrites a tuple stamped xmin = my transaction ID ("born at").
UPDATEwrites a whole NEW tuple, stamps the old one xmax ("expired at"). Two versions now coexist.
DELETEjust stamps xmax. The tuple physically remains — invisible to later snapshots.
SELECTsees a tuple iff its birth committed before my snapshot and its expiry didn’t. Visibility is arithmetic on transaction IDs.

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:

visible(t, s)  ⟺  xmin < s  ∧  ( xmax = 0  ∨  xmax ≥ s )

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.

03

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.

→ The scary one: wraparound

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.

04

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 typeReach for it when
B-treeequality + ranges + ordering — 95% of indexes
GINthings-inside-things: JSONB containment, arrays, full-text
GiSTgeometry, ranges, nearest-neighbor
BRINhuge naturally-ordered tables (timestamps) — tiny index, coarse pruning
Partial / expressionindex 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.

05

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.

One mechanism, three features
WAL stream
every change, in order
→
Crash recovery
replay since checkpoint
→
Replication
ship the stream to replicas
→
PITR
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.

06

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.

07

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.

08

The machine in one table

LayerThe one-line truth
Heap8KB pages of row versions; I/O and caching think in pages
MVCCno in-place writes; snapshots via xmin/xmax arithmetic
VACUUMreclaims dead tuples, feeds the visibility map, prevents wraparound
IndexesB-tree → ctid; index-only scans need a clean visibility map
WALsequential log = durability + replication + PITR
Plannercost model on statistics — check estimates vs actuals
Connectionsprocess per connection → pooler is infrastructure
RUN IT YOURSELF

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.

CPython · WebAssembly
By the numbers

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.

StepQuestionArithmeticAnswer
1Dead tuples before autovacuum starts50 + 0.2 × 10,000,0002,000,050
2How long that takes2,000,050 ÷ 500 per second4,000 s, about 67 min
3Heap share that is garbage at trigger time2,000,050 ÷ 12,000,05016.7%: the table is 20% bigger than its live data
4Per-table scale factor 0.0150 + 0.01 × 10,000,000 = 100,050; ÷ 500vacuums every 200 s, under 1% dead
5A 2-hour report holds an old snapshot7,200 s × 5003,600,000 dead tuples no VACUUM may remove
6Forced anti-wraparound vacuum at 2,000 writing txns/s200,000,000 ÷ 2,000100,000 s, about every 28 h
7If freezing never ran at all2,147,483,648 (2^31) ÷ 2,000 ÷ 86,400about 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.

Watch for

Common mistakes

  • An idle transaction left open

    A session in idle in transaction holds the oldest snapshot, so VACUUM runs, finishes, and removes almost nothing (step 5 above). Find these sessions in pg_stat_activity and set idle_in_transaction_session_timeout. Abandoned replication slots and hot_standby_feedback from 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 = $1 on an index of id alone still visits the heap. Add the column with INCLUDE (email) to make the index covering.

  • Running VACUUM FULL on a live table

    It rewrites the whole table under an ACCESS EXCLUSIVE lock, 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 as pg_repack rebuild 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_at means no update can be HOT, so every UPDATE writes a new entry into every index on the table, not just that one. Check n_tup_hot_upd against n_tup_upd in pg_stat_user_tables before adding an index to a hot table.

In the wild

Where this shows up in production and interviews

  • Slow-query triage

    pg_stat_statements ranks 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_feedback stops 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.

Self-check

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.

Frequently asked

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.

▶  Watch it explained

Hash join: joining a billion rows in one pass

PostgreSQL Internals · Engineering · Vibe Engines · 2026
Finished this one? 0 / 209 Handbooks done
NextSQL vs NoSQL Next on the “Data, and where it lives” ladder · rung 3 of 9

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks