Chapter 06

MVCC, vacuum and operations

Everything in this chapter is invisible until it is the only thing that matters. Knowing it is the difference between "the database is slow" and "the database is bloated because a connection has been idle in transaction for six hours".

⏱ 18 min readLevel: intermediate → advanced

MVCC — how PostgreSQL avoids read locks

A row with three versions showing xmin and xmax, two sessions with different snapshots, and autovacuum reclaiming dead tuples
An UPDATE writes a new version. Readers never block writers, and writers never block readers.
The consequence that surprises people

An UPDATE is physically an insert plus a delete mark. That is why updating every row in a 10 GB table temporarily needs 20 GB, and why a heavily updated table needs vacuum more than a heavily inserted one.

Isolation levels

LevelPreventsNotes
READ COMMITTED (default)Dirty readsEach statement sees a fresh snapshot
REPEATABLE READ+ non-repeatable reads and phantomsSnapshot fixed at first statement; may raise a serialization error
SERIALIZABLEAll anomaliesTrue serialisability via SSI — you must retry on failure
retrying is part of using SERIALIZABLE
BEGIN ISOLATION LEVEL SERIALIZABLE;
  -- ...
COMMIT;
-- ERROR: could not serialize access due to read/write dependencies
-- SQLSTATE 40001 → the application must retry the whole transaction

Locks and deadlocks

who is blocking whom
SELECT blocked.pid            AS blocked_pid,
       blocked.query          AS blocked_query,
       blocking.pid           AS blocking_pid,
       blocking.query         AS blocking_query,
       now() - blocked.query_start AS blocked_for
FROM   pg_stat_activity blocked
JOIN   pg_stat_activity blocking
       ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
WHERE  cardinality(pg_blocking_pids(blocked.pid)) > 0;

-- terminate a runaway session
SELECT pg_cancel_backend(12345);     -- polite: cancels the query
SELECT pg_terminate_backend(12345);  -- forceful: drops the connection
Deadlocks are almost always an ordering problem

Two transactions lock rows A then B, and B then A. Fix it by always acquiring locks in a deterministic order — for example ORDER BY id before updating a batch. PostgreSQL detects the cycle and kills one transaction, so the application must handle SQLSTATE 40P01 and retry.

Vacuum and bloat

is autovacuum keeping up?
SELECT relname,
       n_live_tup,
       n_dead_tup,
       round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum,
       last_autoanalyze
FROM   pg_stat_user_tables
WHERE  n_dead_tup > 1000
ORDER  BY dead_pct DESC NULLS LAST;
tune it per table, not globally
-- a hot, heavily updated table: vacuum far more eagerly than the 20% default
ALTER TABLE customer_order SET (
  autovacuum_vacuum_scale_factor  = 0.02,
  autovacuum_analyze_scale_factor = 0.01,
  autovacuum_vacuum_cost_delay    = 2
);
The two things that break vacuum

Long-running transactions. Vacuum cannot remove a row version any open snapshot might still need. One reporting query left running for hours prevents cleanup across the entire database.

Idle in transaction. An application that opens a transaction and then waits on an HTTP call holds the same horizon open. Set idle_in_transaction_session_timeout = '60s'.

find the culprit
SELECT pid, state, now() - xact_start AS xact_age, left(query, 60)
FROM   pg_stat_activity
WHERE  state IN ('idle in transaction', 'active')
  AND  now() - xact_start > interval '5 minutes'
ORDER  BY xact_age DESC;

Connection pooling

LayerToolSizing
ApplicationHikariCPStart at (cores × 2) + spindles — usually 10–20, not 200
MiddlePgBouncerTransaction pooling; needed above a few hundred clients
Databasemax_connections100–200; more processes is not more throughput
A bigger pool is usually slower

Past the point where the database saturates CPU and disk, extra connections add context switching and lock contention while every query gets slower. If hikaricp.connections.pending is high, fix the slow query rather than raising the ceiling.

Backups and replication

logical backup — fine up to a few hundred GB
pg_dump -Fc -Z6 -d oms -f oms-$(date +%F).dump    # custom format, compressed
pg_restore -d oms_restored --clean --if-exists oms-2026-08-17.dump
ApproachRecovery pointUse when
pg_dumpLast dumpSmall databases, moving between versions
Base backup + WAL archive (PITR)Any secondProduction. Recover to just before the bad migration.
Streaming replicaSecondsHigh availability and read scaling — not a backup
Logical replicationTable-levelZero-downtime major upgrades, selective sync
A replica is not a backup

DELETE FROM customer_order; replicates in milliseconds. Only point-in-time recovery protects against human error — and a backup you have never restored is a hypothesis, not a backup. Test the restore on a schedule.

Production checklist

  • ☐ Managed service, or a documented HA setup with automatic failover.
  • ☐ Point-in-time recovery enabled, and a restore tested this quarter.
  • ☐ shared_buffers, work_mem and random_page_cost tuned for the hardware.
  • ☐ pg_stat_statements and auto_explain enabled.
  • ☐ idle_in_transaction_session_timeout and statement_timeout set.
  • ☐ lock_timeout set in every migration.
  • ☐ Autovacuum tuned per hot table; bloat monitored.
  • ☐ Application connects as a least-privilege role, not the schema owner.
  • ☐ TLS required; no superuser login from the application.
  • ☐ Alerts on replication lag, connection saturation, disk, and transaction-id age.

A table has 2 million live rows and 14 million dead ones. Autovacuum is running. What is the most likely cause?

Vacuum can only remove versions no snapshot can still see. One old transaction pins the horizon and dead tuples accumulate no matter how often vacuum runs. Find it in pg_stat_activity and add an idle_in_transaction_session_timeout.