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".
MVCC — how PostgreSQL avoids read locks
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
| Level | Prevents | Notes |
|---|---|---|
READ COMMITTED (default) | Dirty reads | Each statement sees a fresh snapshot |
REPEATABLE READ | + non-repeatable reads and phantoms | Snapshot fixed at first statement; may raise a serialization error |
SERIALIZABLE | All anomalies | True serialisability via SSI — you must retry on failure |
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
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
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
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;
-- 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 );
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'.
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
| Layer | Tool | Sizing |
|---|---|---|
| Application | HikariCP | Start at (cores × 2) + spindles — usually 10–20, not 200 |
| Middle | PgBouncer | Transaction pooling; needed above a few hundred clients |
| Database | max_connections | 100–200; more processes is not more throughput |
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
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
| Approach | Recovery point | Use when |
|---|---|---|
pg_dump | Last dump | Small databases, moving between versions |
| Base backup + WAL archive (PITR) | Any second | Production. Recover to just before the bad migration. |
| Streaming replica | Seconds | High availability and read scaling — not a backup |
| Logical replication | Table-level | Zero-downtime major upgrades, selective sync |
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_memandrandom_page_costtuned for the hardware. - ☐
pg_stat_statementsandauto_explainenabled. - ☐
idle_in_transaction_session_timeoutandstatement_timeoutset. - ☐
lock_timeoutset 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.