Skip to content

MVCC, VACUUM & Bloat in PostgreSQL ​

"In PostgreSQL, an UPDATE or DELETE of a row does not immediately remove the old version of the row. This approach is necessary to gain the benefits of multiversion concurrency control (MVCC, see Chapter 13): the row version must not be deleted while it is still potentially visible to other transactions." — PostgreSQL 19 documentation, Routine Vacuuming, §24.1.2

Summary: PostgreSQL never overwrites a row; it writes a new tuple version and leaves the old one for VACUUM, so transaction length becomes disk space, and transaction IDs become a counter that must be frozen before it wraps. Focus: tuple headers (xmin, xmax, cmin/cmax, t_ctid, hint bits), snapshots and visibility, dead tuples and the xmin horizon, HOT, VACUUM/autovacuum and their knobs, bloat measurement and repair, freezing and xid wraparound, and how InnoDB, Oracle and SQL Server keep versions instead. Learning goal: read xmin/xmax/ctid on a live table and explain what you see, find the session or slot that blocks cleanup, tune autovacuum per table, choose between VACUUM, VACUUM FULL, REPACK and pg_repack, and run the wraparound runbook without making it worse.

This page is the complete reference for how PostgreSQL stores row versions and cleans them up. It covers every keyword you meet in production: tuple versions, the tuple header fields, the t_ctid chain, t_infomask hint bits, CLOG/pg_xact, snapshots (xmin:xmax:xip_list), visibility rules, dead tuples, the xmin horizon, long-running and idle in transaction sessions, replication slots and hot_standby_feedback, HOT updates and fillfactor, VACUUM in all its forms, autovacuum's launcher, workers, thresholds and cost throttling, table and index bloat and how to measure it (pgstattuple, pg_stat_user_tables), TOAST, freezing, transaction ID wraparound, multixacts, and the undo-based alternatives in MySQL InnoDB, Oracle and SQL Server. It deliberately does not re-teach its neighbours: which anomalies each isolation level allows is in Isolation Levels; page layout, line pointers, TOAST internals and the free space map file format are in Database Internals; row and table lock modes are in Locks & Concurrency; WAL is in Durability & Crash Recovery.

Page map ​

If you are looking forGo to
The whole topic in three tablesEverything in one minute
Why PostgreSQL keeps old versions at all, and the trade-offWhy MVCC needs a vacuum
Stonebraker 1987, PostgreSQL 6.5Where it comes from
xmin, xmax, cmin, cmax, t_ctid, hint bitsTuple versions and the header
Why an UPDATE writes a whole new rowUPDATE = insert + delete
pg_xact, CLOG, lazy xid assignmentTransaction IDs and the commit log
Snapshot xmin:xmax:xip_list and the visibility decisionSnapshots and visibility
Dead tuples, the xmin horizon, what holds it backDead tuples and the xmin horizon
HOT, fillfactor, n_tup_hot_updHOT updates and fillfactor
VACUUM vs VACUUM FULL vs REPACK vs pg_repackVACUUM in all its forms
Launcher, workers, thresholds, cost delay/limitAutovacuum
Table bloat, index bloat, estimation, pgstattupleBloat
TOAST tables and vacuumTOAST and vacuum
Freezing, age(datfrozenxid), anti-wraparound, failsafeFreezing and xid wraparound
pg_multixact, mxid_ageMultixacts
InnoDB undo, history list length, Oracle "snapshot too old", SQL Server version storePer-engine behaviour
Every knob, every view, every message verbatimMechanics
Tuning, killing idle sessions, rewrites, index bloat, wraparound runbookSolving the classic problems
What to do for which situationChoosing what to do
Monolith → microservices → replicas → scaleIn architecture
Reproduce it in psqlLab
Wrong beliefs, cheat sheet, questions, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

What happens to a row.

StatementWhat PostgreSQL writesOld versionIndex work
INSERTNew tuple, xmin = your xid, xmax = 0noneOne entry per index
DELETENothing new; stamps xmax = your xid on the tupleStays on the page until VACUUMNone now; VACUUM removes entries later
UPDATENew full tuple with new xmin; old tuple gets xmax and t_ctid → newStays, now dead once you commit and no snapshot needs itNew entry in every index, unless HOT
UPDATE (HOT)New tuple on the same page, flagged heap-onlyPruned on the page, even by a SELECTNone
ROLLBACKNothing; the xid is marked aborted in pg_xactThe tuples you wrote are dead immediatelyNone

The words.

TermIn plain wordsWhere you see it
Tuple / row versionOne physical copy of a rowSELECT ctid, xmin, xmax, * FROM t
Dead tupleA version no running snapshot can seepg_stat_user_tables.n_dead_tup, pgstattuple
xmin horizonThe oldest xid any snapshot, session, slot or prepared transaction still needspg_stat_activity.backend_xmin, pg_replication_slots.xmin
BloatSpace held by dead tuples and empty slots beyond what the live data needspgstattuple, wiki estimate query
HOT updateUpdate that stays on the same page and touches no indexn_tup_hot_upd
FreezingMarking old tuples as "visible to everyone forever" so their xid can be recycledage(relfrozenxid), age(datfrozenxid)
WraparoundThe 32-bit xid counter coming back round, so old rows would look like the futureWARNING: database "mydb" must be vacuumed within ... transactions

The three things to do.

SituationDo this
Any applicationKeep transactions short, never do network I/O inside one, set idle_in_transaction_session_timeout (and transaction_timeout on PostgreSQL 17+) per role
A large, hot tablePer-table autovacuum_vacuum_scale_factor / threshold, faster cost settings, lower fillfactor if updates miss HOT
MonitoringAlert on n_dead_tup, last_autovacuum, age(datfrozenxid), the oldest backend_xmin, and replication slot xmin

Why MVCC needs a vacuum ​

A database has to let readers and writers work on the same rows at the same time. One way is locks: the reader waits for the writer. PostgreSQL chose versions instead: a writer creates a new version and readers keep seeing the version that matches their snapshot. The manual's one-line payoff is "reading never blocks writing and writing never blocks reading". The cost is that the old version must stay until nobody can need it, and somebody must come back and remove it. That somebody is VACUUM.

In-place update + undo (InnoDB, Oracle, SQL Server version store)Append a new version in the heap (PostgreSQL)
Table holds only the newest version; history lives in undo or tempdbTable holds every version until VACUUM
Update writes a small undo recordUpdate writes a whole new tuple (plus index entries unless HOT)
Rollback must apply undo, can be slowRollback is instant: the xid is marked aborted
Old readers reconstruct rows by walking undoOld readers read the old tuple directly
Cleanup: purge threads, undo retentionCleanup: VACUUM / autovacuum
Long transaction grows the undo / version storeLong transaction grows tables and indexes (bloat)
Failure mode: undo full, ORA-01555, history list lengthFailure mode: bloat, xid wraparound

The analogy we reuse on this page: a shared office whiteboard where nobody erases. To change a number you cross it out and write the new one beside it, initialling both, so anyone who photographed the board this morning can still match their photo to what is there (the photo is a snapshot). Every evening a cleaner wipes the crossed-out entries, but only those older than the oldest photo anyone is still holding (the xmin horizon). One colleague who took a photo on Monday and keeps it on their desk all week (a long transaction) means the board fills up. The initials are transaction IDs; when the pad of initials runs out and starts again from 1, entries signed long ago would look newer than today's, so the cleaner also stamps very old entries "permanent" (freezing).

Three common misunderstandings, up front ​

  1. "DELETE frees space." It stamps xmax. The space is reusable only after VACUUM, and returned to the operating system only by a rewrite (or when the last pages of the file become empty).
  2. "Autovacuum is on, so I am safe." Autovacuum can run all day and remove nothing if one session idle in transaction or one abandoned replication slot holds the xmin horizon.
  3. "VACUUM FULL is the thorough VACUUM; run it nightly." It rewrites the table under an ACCESS EXCLUSIVE lock that blocks even SELECT, and the table will grow back to its working size. Plain VACUUM, run often, is the goal.

Where it comes from ​

PostgreSQL's storage model is older than its MVCC. In The Design of the POSTGRES Storage System (VLDB 1987), Michael Stonebraker described a Berkeley storage manager in which "no data is ever overwritten" and "updates are turned into insertions". Each record carried the identifier of the transaction that inserted it and of the one that deleted it, named Xmin and Xmax, and an asynchronous process the paper calls "the vacuum cleaner" moved records that were no longer valid off the magnetic disk and into an archive. The archive is gone; the names, the no-overwrite heap and the vacuum survived.

What the Berkeley code did not have was concurrency built on those versions: it used table-level locks. That arrived with PostgreSQL 6.5, released on 9 June 1999. Its release notes list "Multiversion concurrency control/MVCC(Vadim)" and explain the change in one sentence: "MVCC uses the natural multiversion nature of PostgreSQL to allow readers to continue reading consistent data during writer activity."

Later milestones you will see referenced: freezing switched from overwriting xmin with FrozenTransactionId to setting a flag bit in 9.4 (the manual says so in §24.1.5); PostgreSQL 17 added transaction_timeout, removed old_snapshot_threshold (the release notes say it "allowed vacuum to remove rows that potentially could be still visible to running transactions, causing "snapshot too old" errors later"), and gave VACUUM a new memory structure for dead tuple references that is no longer capped at one gigabyte; the current (PostgreSQL 19) manual documents the built-in REPACK command, including REPACK CONCURRENTLY.

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition, a sequence, real scenarios, what each product does, and the fix in SQL, Go and Laravel where there is one.

Tuple versions and the tuple header Must-know ​

In plain words: a "row" in PostgreSQL is a chain of physical copies called tuples. Each copy carries a small header saying which transaction created it and which one ended it.

Common misunderstanding: "ctid is a stable row id." It is the physical address of one version. The manual: "a row's ctid will change if it is updated, or moved by a table-rewriting operation such as VACUUM FULL, CLUSTER, or REPACK. Therefore ctid should not be used as a row identifier."

Definition: every heap tuple has a fixed header ("occupying 23 bytes on most machines", Database Page Layout). The fields that matter for MVCC, also exposed as hidden system columns:

Field / system columnMeaning
t_xmin / xminxid of the inserting transaction
t_xmax / xmaxxid of the deleting or updating transaction, or of a row locker; 0 if none; may hold a multixact id
t_cid / cmin, cmaxCommand id inside the inserting/deleting transaction. Today cmin and cmax "refer to the same field and will always read as the same value", possibly a combocid when one transaction both inserted and deleted the tuple
t_ctid / ctid(block, item) of this version, or of the newer version it was updated to
t_infomask, t_infomask2Flag bits: hint bits (XMIN_COMMITTED, XMIN_ABORTED, XMAX_COMMITTED, XMAX_ABORTED, the names the PostgreSQL wiki uses), frozen, lock-only, HEAP_HOT_UPDATED, HEAP_ONLY_TUPLE, has-nulls, attribute count
UPDATE accounts SET balance = 70 WHERE id = 1 (run by xid 105)B-tree indexkey id = 1TID (0,1)no new entry if HOTHeap page 0lp 1lp 2line pointers (item ids)Version 1 (old)t_xmin = 100 (committed)t_xmax = 105 (deleter)t_ctid = (0,2)balance = 100Version 2 (current)t_xmin = 105t_xmax = 0 (live)t_ctid = (0,2) (itself)balance = 70t_ctid chain: old version points to newert_infomask hint bits (XMIN_COMMITTED, XMAX_COMMITTED ...)are set by the first reader that looks up pg_xactSnapshots taken before xid 105 committed read version 1;later snapshots follow t_ctid and read version 2

The picture shows one UPDATE by xid 105: the index still points at line pointer 1; version 1 got xmax = 105 and t_ctid = (0,2); version 2 is the live row with xmax = 0 and a t_ctid pointing to itself. A snapshot taken before 105 committed follows the index to version 1 and stops there; a later snapshot follows the t_ctid chain to version 2.

text
     T1 (xid 100)                         T2 (xid 105)                          what the heap holds
1    INSERT INTO accounts VALUES (1,100);                                       (0,1) xmin=100 xmax=0
2    COMMIT;
3                                         BEGIN;
4                                         UPDATE accounts SET balance=70        (0,1) xmin=100 xmax=105 ctid->(0,2)
                                            WHERE id=1;                         (0,2) xmin=105 xmax=0
5    SELECT balance FROM accounts;  -- 100 (105 not committed: T1 reads (0,1))
6                                         COMMIT;
7    SELECT balance FROM accounts;  -- 70  (new statement, new snapshot)

Real scenario: a support engineer runs SELECT ctid, xmin, xmax, * FROM orders WHERE id = 42 and sees xmax set on a live row: that is a row lock (SELECT ... FOR UPDATE) or an aborted updater, not a deletion; the t_infomask lock-only bit tells the two apart. A data fix keyed by ctid across two statements silently updates the wrong version after an autovacuum or VACUUM FULL in between. pageinspect's heap_page_items() shows the raw t_infomask when you need to prove which case it is.

ProductWhere version metadata lives
PostgreSQLIn every heap tuple header (xmin, xmax, t_ctid)
MySQL InnoDBHidden 6-byte DB_TRX_ID and 7-byte DB_ROLL_PTR in each clustered-index record; old versions in undo
OracleInterested transaction list (ITL) in the block header; old images in undo segments
SQL Server (RCSI/SNAPSHOT)14-byte versioning tag on the row, pointing into the version store

Fix / how to use it: read it, do not depend on it.

sql
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT ctid, xmin, xmax, cmin, cmax, * FROM accounts WHERE id = 1;
SELECT lp, t_xmin, t_xmax, t_ctid, to_hex(t_infomask) AS infomask
FROM heap_page_items(get_raw_page('accounts', 0));

UPDATE = insert + delete Must-know ​

In plain words: PostgreSQL turns every UPDATE into "mark the old copy deleted, write a full new copy". Changing one int column of a 2 KB row writes a 2 KB tuple.

Common misunderstanding: "Updating a small column is cheap." Without HOT, the update writes a new tuple, a new entry in every index on the table (even indexes on columns you did not change), and WAL for all of it.

Definition: UPDATE = set xmax on the visible version + insert a new version with xmin = your xid + link them through t_ctid. A DELETE is only the first half. The space of the old version is reclaimed later by VACUUM (or by on-page pruning for HOT chains).

text
     session                                   heap pages of a 3-index table
1    UPDATE users SET last_seen = now()        old tuple: xmax set
       WHERE id = 7;                           new tuple written (maybe on another page)
2                                              3 new index entries (pkey, email, last_seen)
3    -- 1,000 logins per second on 1 row       1,000 dead tuples/s + 3,000 dead index entries/s
4    autovacuum (minutes later)                removes dead tuples and their index entries

Real scenario: a last_seen column on the users table, with an index on it for "active users" queries, turns every login into a non-HOT update and bloats all three indexes. A job queue table where each job is updated five times (queued, reserved, running, retry, done) produces five versions per job. An ORM that saves every attribute on save() updates indexed columns that did not change in value; PostgreSQL's HOT check compares values, so unchanged values do not defeat HOT, but a changed updated_at with an index on it does.

ProductWhat an update costs
PostgreSQLNew full tuple + one entry per index (unless HOT) + WAL for both
MySQL InnoDBIn-place change of the clustered record + undo record; secondary indexes change only if their columns change (delete-mark + insert)
OracleIn-place change + undo + redo
SQL ServerIn-place change; with RCSI/SNAPSHOT, also a copy of the old row in the version store

Fix: move hot, frequently changing columns (counters, last_seen) to a narrow side table without indexes on them; batch increments; avoid indexing columns that change on every write. Full code in Hot counters and HOT updates.

Transaction IDs and the commit log Important ​

In plain words: every writing transaction gets a number. Whether that number committed or aborted is written in a separate, compact file, the commit log.

Common misunderstanding: "Every BEGIN consumes a transaction ID." The manual says an xid is assigned "when a transaction first writes to the database"; read-only transactions run with a virtual transaction id (virtualxid) and do not advance the counter.

Definition: xid is 32 bits and appears in xmin/xmax. The commit status of each xid (in progress, committed, aborted, sub-committed) is two bits in pg_xact, historically called CLOG and stored in pg_clog before PostgreSQL 10. The SQL functions expose a 64-bit xid8 (pg_current_xact_id()) that never wraps; the 32-bit value inside tuples does. pg_xact_status(xid8) reports committed, aborted or in progress.

Hint bits. Looking up pg_xact for every tuple would be expensive, so the first reader that learns a tuple's xmin/xmax outcome writes it back into t_infomask (XMIN_COMMITTED, XMIN_ABORTED, XMAX_COMMITTED, XMAX_ABORTED). The official pages read for this topic do not document hint bits; the PostgreSQL wiki does, and warns that this "can result in heavy writes to a database table even though you're just reading from it" (the wiki page predates the rename and still says pg_clog).

text
     loader                                   first reader                        second reader
1    BEGIN; COPY big_table ...; COMMIT;
2                                             SELECT count(*) FROM big_table;
                                               -> checks pg_xact per tuple
                                               -> sets XMIN_COMMITTED hint bits
                                               -> pages dirtied, written out later
3                                                                                 SELECT count(*) ...
                                                                                   -> hint bits set: no pg_xact lookup

Real scenario: the first SELECT after a bulk load is slow and causes write I/O; a read replica (which cannot write hint bits to its WAL-shipped pages in the same way) behaves differently from the primary; with wal_log_hints or data checksums on, setting hint bits can also produce full-page WAL images. Running VACUUM (or VACUUM (FREEZE)) right after a bulk load sets the bits and the visibility map once, under your control.

ProductWhere commit status lives
PostgreSQLpg_xact (CLOG), 2 bits per xid, plus pg_subtrans for subtransactions and pg_multixact for multixacts
MySQL InnoDBTransaction system and undo log headers; readers compare DB_TRX_ID to the read view
OracleTransaction table in the undo segment header; delayed block cleanout plays the hint-bit role
SQL ServerTransaction sequence numbers on versions in the version store

Fix / how to use it:

sql
SELECT pg_current_xact_id();                       -- assigns an xid if this transaction has none
SELECT pg_current_xact_id_if_assigned();           -- NULL in a read-only transaction
SELECT pg_xact_status('123456'::xid8);             -- committed / aborted / in progress
VACUUM (ANALYZE) big_table;                        -- after a bulk load: set hint bits and the visibility map now

Snapshots and visibility Must-know ​

In plain words: a snapshot is a list of "which transactions count as finished for me". Each tuple's xmin and xmax are checked against it to decide whether you see that version.

Common misunderstanding: "A snapshot is a copy of the data." It is three numbers and a list; the data stays in the heap, which is exactly why old versions cannot be deleted while a snapshot that might need them exists.

Definition: pg_current_snapshot() returns xmin:xmax:xip_list. From System Information Functions: xmin is the "Lowest transaction ID that was still active", xmax is "One past the highest completed transaction ID", and xip_list holds the "Transactions in progress at the time of the snapshot". An xid is treated as finished-before-me if it is below xmin, or between xmin and xmax and not in xip_list. A tuple is visible when:

  1. its xmin is committed and finished-before-me (or is my own xid and was inserted by an earlier command, per cmin); and
  2. its xmax is 0, aborted, a lock-only marker, or not finished-before-me (or is my own xid from a later command, per cmax).
Is this tuple visible to my snapshot (xmin:xmax:xip_list)?Tuple header: t_xmin, t_xmax1. Did t_xmin commit (hint bit or pg_xact)?Is it < snapshot xmax and not in xip_list (or my own xid)?noINVISIBLEnot yet bornyes2. Is t_xmax empty (0) or aborted,or only a row lock (lock-only / multixact)?yesVISIBLElive versionno: someone deleted/updated it3. Is t_xmax committed ANDvisible to my snapshot?noyesINVISIBLE (deleted)dead once no snapshot needs itRead Committed: new snapshot per statement. Repeatable Read / Serializable: one snapshot per transaction.

The diagram is the same rule as a flow: first "was it born before my snapshot?", then "was it killed before my snapshot?". Only a tuple that passes the first and fails the second is visible.

How long a snapshot lives is the only isolation-level fact this page needs: under Read Committed each statement takes a new snapshot; under Repeatable Read and Serializable one snapshot is taken at the first statement and kept until the transaction ends. Which anomalies follow from that is in Isolation Levels.

text
     T1 (xid 200)                  T2 (xid 201)            T3 REPEATABLE READ
1    BEGIN;                        BEGIN;
2    UPDATE a SET v=2 WHERE id=1;                          BEGIN ISOLATION LEVEL REPEATABLE READ;
3                                                          SELECT pg_current_snapshot();  -- 200:202:200,201
4    COMMIT;                                               SELECT v FROM a WHERE id=1;    -- 1 (200 in xip_list)
5                                  COMMIT;
6                                                          SELECT v FROM a WHERE id=1;    -- still 1, same snapshot
7                                                          COMMIT;  -- old version of row 1 now removable

Real scenario: a nightly pg_dump runs in one Repeatable Read snapshot for two hours, which keeps every version created in those two hours alive in every table of the database; a BI tool opens a cursor at Repeatable Read and lets the user scroll for an afternoon; a Go service uses sql.LevelRepeatableRead for a report and then uploads files before committing (the "Before" snippet below).

ProductWhat a snapshot isHow long it lives
PostgreSQLxmin:xmax:xip_listStatement (RC) or transaction (RR, Serializable)
MySQL InnoDBRead view: m_low_limit_id, m_up_limit_id, list of active trx idsStatement (RC) or from first consistent read to commit (RR, default)
OracleSCN (system change number)Statement (default) or transaction (SERIALIZABLE, READ ONLY)
SQL ServerTransaction sequence numberStatement (RCSI) or transaction (SNAPSHOT)

Fix / how to use it:

sql
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT pg_current_snapshot();                                   -- e.g. 748:752:748,750
SELECT pg_snapshot_xmin(pg_current_snapshot());
SELECT pg_visible_in_snapshot('750'::xid8, pg_current_snapshot());
COMMIT;

Dead tuples and the xmin horizon Must-know ​

In plain words: an old version becomes garbage only when nobody, anywhere in the cluster, could still need it. The oldest "need" is the horizon; VACUUM removes only what is older.

Common misunderstanding: "My idle session touched a different table, so it cannot bloat this one." The horizon is per database (and for shared catalogs, per cluster). One open snapshot or xid holds back cleanup in every table.

Definition: a tuple whose deleting transaction committed is recently dead while some snapshot could still see it, and dead (removable) once its xmax is older than the xmin horizon. The horizon is the minimum of:

HolderWhere to see itTypical cause
Running and idle in transaction sessionspg_stat_activity.backend_xmin, backend_xid, xact_start, stateLong reports, code that does HTTP inside a transaction, a forgotten BEGIN in psql
Prepared transactions (2PC)pg_prepared_xacts, age(transaction)A transaction manager that crashed between PREPARE and COMMIT PREPARED
Replication slotspg_replication_slots.xmin, catalog_xminA logical decoding consumer (Debezium, CDC) that stopped; a physical slot for a dead replica
Hot standby queries via hot_standby_feedback = onStandby's backend_xmin reported through the walsender (pg_stat_replication.backend_xmin)Long analytics queries on a replica
text
     app worker (pid 4242)                 OLTP traffic                         autovacuum on orders
1    BEGIN;
2    UPDATE jobs SET status='syncing'      -- worker now has an xid
       WHERE id=9;
3    -- calls partner API, waits 40 min    UPDATE orders ... (10k rows/min)
4    -- state = 'idle in transaction'                                           VACUUM orders: 400k dead,
                                                                                 0 removable ("not yet removable")
5    COMMIT;                                                                    next run: 400k removed

Real scenario: a Laravel queued job wraps an ERP call in DB::beginTransaction() (the "Before" snippet below); a Debezium connector is paused for a week and its logical slot pins catalog_xmin, bloating pg_catalog tables and (with xmin) user tables; a replica with hot_standby_feedback = on serves a 6-hour BI query; a developer leaves psql with an open BEGIN over the weekend.

ProductWhat holds old versions aliveWhere you see it
PostgreSQLOldest snapshot/xid, prepared xacts, replication slots, standby feedbackpg_stat_activity, pg_prepared_xacts, pg_replication_slots
MySQL InnoDBOldest read view; undo for it cannot be purgedSHOW ENGINE INNODB STATUS "History list length", information_schema.innodb_trx
OracleUndo needed by the oldest query (bounded by UNDO_RETENTION unless guaranteed)V$UNDOSTAT, V$TRANSACTION
SQL ServerOldest active snapshot transactionsys.dm_tran_active_snapshot_database_transactions, version store DMVs

Fix: find the holder, end it, and prevent it with timeouts. Code in Killing idle and long transactions and Replication slots and standbys.

sql
SELECT pid, usename, application_name, state, xact_start,
       age(backend_xid)  AS xid_age,
       age(backend_xmin) AS xmin_age,
       left(query, 60)   AS last_query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL OR backend_xid IS NOT NULL
ORDER BY greatest(age(backend_xid), age(backend_xmin)) DESC NULLS LAST
LIMIT 10;

HOT updates and fillfactor Must-know ​

In plain words: if an update changes no indexed column and the new version fits on the same page, PostgreSQL skips the indexes entirely and can clean up the old version during normal reads.

Common misunderstanding: "HOT means the row is updated in place." It is still a new tuple. What it saves is the index entries, and the cleanup can happen through page pruning instead of waiting for VACUUM.

Definition: the manual (Heap-Only Tuples) lists two conditions: "The update does not modify any columns referenced by the table's indexes, not including summarizing indexes", and "There is sufficient free space on the page containing the old row for the updated row". Then "New index entries are not needed to represent updated rows", and old versions "can be completely removed during normal operation, including SELECTs, instead of requiring periodic vacuum operations." BRIN is the built-in summarizing index type, so a BRIN index on updated_at does not block HOT. The table storage parameter fillfactor (10–100, default 100) leaves free space on each page for this: per CREATE TABLE, "a smaller fillfactor ... makes heap-only tuple updates more likely".

text
     page 12, fillfactor 100 (full)              page 12, fillfactor 80
1    UPDATE counters SET n=n+1 WHERE id=5        UPDATE counters SET n=n+1 WHERE id=5
2    no room on page 12 -> new tuple on page 97  room on page 12 -> heap-only tuple on page 12
3    new pkey entry -> (97,3)                    no index write; old tuple flagged HOT_UPDATED
4    n_tup_newpage_upd++                         n_tup_hot_upd++
5    dead tuple waits for VACUUM                 next SELECT on page 12 can prune the chain

Real scenario: session tables, counters, status columns of job queues and last_login_at are the classic HOT candidates; one index on updated_at "for the admin panel" destroys HOT for the whole table; pg_stat_user_tables shows n_tup_hot_upd near n_tup_upd when you got it right, and n_tup_newpage_upd counts updates that had to move to another page.

ProductEquivalent
PostgreSQLHOT + fillfactor + page pruning
MySQL InnoDBNot needed: in-place update; secondary indexes untouched unless their columns change. MERGE_THRESHOLD and page fill are separate concerns
OraclePCTFREE reserves block space for row growth (avoids row migration)
SQL ServerFILLFACTOR on indexes (leaf page free space), not for version placement

Fix:

sql
ALTER TABLE page_stats SET (fillfactor = 80);   -- applies to new pages; rewrite to apply to existing ones
DROP INDEX IF EXISTS page_stats_updated_at_idx; -- or replace by BRIN if you need it for ranges
SELECT relname, n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd,
       round(100.0 * n_tup_hot_upd / nullif(n_tup_upd, 0), 1) AS hot_pct
FROM pg_stat_user_tables ORDER BY n_tup_upd DESC LIMIT 10;

VACUUM in all its forms Must-know ​

In plain words: plain VACUUM marks dead space as reusable while the table stays online. VACUUM FULL, CLUSTER and REPACK build a new, compact copy of the table and swap it in. pg_repack is an extension that does the rewrite with only short locks.

Common misunderstanding: "After VACUUM the file is smaller." Plain VACUUM returns space to the operating system only "in the special case where one or more pages at the end of a table become entirely free and an exclusive table lock can be easily obtained". Otherwise the free space is kept for future inserts and updates.

Definition:

CommandWhat it doesLockGives disk back to OSExtra disk
VACUUMRemoves dead tuples and their index entries, updates FSM and visibility map, freezes old tuplesSHARE UPDATE EXCLUSIVE (reads and writes continue; blocks DDL and another VACUUM)Only trailing empty pages (TRUNCATE option / vacuum_truncate, needs a brief ACCESS EXCLUSIVE)None
VACUUM (FREEZE)Plain VACUUM that freezes every eligible tupleSameSameNone
VACUUM FULLRewrites table and rebuilds all indexesACCESS EXCLUSIVE for the whole run (blocks SELECT)YesAbout the table + indexes size
CLUSTERRewrite in index orderACCESS EXCLUSIVEYesSame
REPACK (current manual)Rewrite, optionally USING INDEX to clusterACCESS EXCLUSIVEYesSame
REPACK (CONCURRENTLY)Online rewrite; lock "held only while swapping the table and index files"Short ACCESS EXCLUSIVE at the endYesSame
pg_repack extensionBuilds a copy, captures concurrent changes with a trigger into a log table, swapsShort ACCESS EXCLUSIVE at start and end; table needs a PRIMARY KEY or not-null unique indexYesSame
TRUNCATEDrops all rows at onceACCESS EXCLUSIVEYesNone ("strict MVCC semantics are violated")
1. UPDATE / DELETEstamps t_xmax on old version2. Recently deadsome snapshot may still need it3. Dead tupleolder than the xmin horizonThe xmin horizon is held back by:long or idle in transaction sessionsreplication slots (xmin, catalog_xmin)hot_standby_feedbackprepared transactions4. VACUUM (autovacuum)scan heap, drop index entries,free line pointers, freeze old xidslock: SHARE UPDATE EXCL.5. Maps updatedfree space map (_fsm)visibility map (_vm): all-visible6. Space reusednext INSERT / UPDATE findsroom via the FSM; file staysShrink the file:VACUUM FULL, REPACK,pg_repack (rewrite)Bloat = the gap between steps 1 and 4 growing faster than vacuum can close it.

The cycle diagram is the whole life of the space: an UPDATE/DELETE leaves a recently dead tuple; when it passes the xmin horizon it is dead; VACUUM removes it and its index entries and records the free space in the free space map (_fsm fork) and all-visible pages in the visibility map (_vm fork); later inserts and updates reuse the space. Only the side path (VACUUM FULL, REPACK, pg_repack) makes the file smaller.

text
     plain VACUUM on a 10 GB table, 30% dead     VACUUM FULL on the same table
1    phase: scanning heap (collect dead TIDs)    ACCESS EXCLUSIVE taken: all queries on the table wait
2    phase: vacuuming indexes (remove entries)   new file written: ~7 GB (+ indexes)
3    phase: vacuuming heap (free line pointers)  indexes rebuilt
4    phase: truncating heap (if tail empty)      old files dropped, lock released
5    file still 10 GB, 3 GB free inside         file 7 GB; app was down for the whole run

Real scenario: after deleting 80% of an audit table, the file stays 200 GB until a rewrite; a team runs VACUUM FULL in a "maintenance window" and the window runs past the deadline while the checkout table is locked; pg_repack fails because the table has no primary key; a disk at 85% cannot fit a rewrite of its largest table.

ProductReclaim space onlineShrink file
PostgreSQLVACUUM / autovacuumVACUUM FULL, CLUSTER, REPACK [CONCURRENTLY], pg_repack
MySQL InnoDBPurge (automatic)OPTIMIZE TABLE / ALTER TABLE ... FORCE (online DDL rebuild)
OracleAutomatic (undo); space reused in segmentALTER TABLE ... SHRINK SPACE, MOVE ONLINE
SQL ServerGhost cleanup task, version store cleanupALTER INDEX ... REBUILD (ONLINE = ON), DBCC SHRINKFILE
SQLitePRAGMA auto_vacuum, freelistVACUUM (rewrites the file)

Fix: let plain VACUUM keep up; schedule rewrites only for one-off recovery. See Reclaiming space.

Autovacuum Must-know ​

In plain words: a background launcher wakes up regularly, picks a database, and starts worker processes that VACUUM and ANALYZE tables whose changes passed a threshold.

Common misunderstanding: "Autovacuum is slow, so turn it off and vacuum at night." The manual: "It is unwise to disable the daemon completely unless you have an extremely predictable workload", and anti-wraparound autovacuum runs even when it is disabled.

Definition: "There is a persistent daemon process, called the autovacuum launcher, which is in charge of starting autovacuum worker processes for all databases." It tries to start one worker per database every autovacuum_naptime (default 1min), with at most autovacuum_max_workers (default 3) at once. A table is vacuumed when

text
dead tuples > Minimum(autovacuum_vacuum_max_threshold,
                      autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuples)
defaults:              100,000,000                     50     +      0.2              * reltuples

or when inserts since the last vacuum exceed autovacuum_vacuum_insert_threshold (1000) + autovacuum_vacuum_insert_scale_factor (0.2) × reltuples × fraction not frozen, or when age(relfrozenxid) passes autovacuum_freeze_max_age. Speed is limited by cost-based throttling: each page hit costs vacuum_cost_page_hit (1), miss vacuum_cost_page_miss (2), dirtied vacuum_cost_page_dirty (20); after accumulating autovacuum_vacuum_cost_limit (default -1, meaning vacuum_cost_limit = 200) the worker sleeps autovacuum_vacuum_cost_delay (default 2 ms). The limit "is distributed proportionally among the running autovacuum workers", so adding workers alone does not add throughput.

text
     time   events on orders (10M rows)                      autovacuum
1    00:00  vacuumed; n_dead_tup = 0                          threshold = 50 + 0.2*10M = 2,000,050
2    04:00  n_dead_tup = 1.2M (12%)                           below threshold: nothing
3    07:30  n_dead_tup = 2.0M                                 worker starts VACUUM orders
4    07:30-  scans 10M rows with cost_limit 200/3 workers     sleeps 2 ms every ~67 cost units
5    09:10  finishes; space reusable; table already 20% bigger

Real scenario: a 500M-row events table waits for 100M dead tuples before the max threshold kicks in; an ANALYZE cron every minute keeps cancelling autovacuum because they conflict on SHARE UPDATE EXCLUSIVE (the manual warns this "can effectively prevent autovacuums from ever completing"); all three workers are stuck on three huge tables while small hot tables bloat; on managed services the cost limit is the first thing support asks you to raise.

ProductBackground cleanupMain knobs
PostgreSQLAutovacuum launcher + workersautovacuum_max_workers, autovacuum_naptime, autovacuum_vacuum_scale_factor, autovacuum_vacuum_threshold, autovacuum_vacuum_cost_delay, autovacuum_vacuum_cost_limit
MySQL InnoDBPurge coordinator + purge threadsinnodb_purge_threads (1 if ≤16 logical CPUs, else 4), innodb_purge_batch_size (300), innodb_max_purge_lag (0 = no throttling)
SQL ServerGhost cleanup, version store cleanup threadMostly automatic
OracleUndo is reused automaticallyUNDO_RETENTION, undo tablespace size

Fix: per-table settings for large or hot tables, faster cost settings globally. See Autovacuum tuning per table.

Bloat: table and index Must-know ​

In plain words: bloat is the empty or dead space inside the files that the live data does not need. Some of it is healthy (room for the next updates); a lot of it means vacuum fell behind.

Common misunderstanding: "n_dead_tup is the bloat." It counts dead tuples waiting for vacuum (an eventually consistent estimate). After VACUUM it drops to near zero, but the free space inside the file, which is what makes scans slow and backups large, stays.

Definition: the manual's target state: "each table occupies space equivalent to its minimum size plus however much space gets used up between vacuum runs". Table bloat is free plus dead space far above that. Index bloat is sparse B-tree pages: VACUUM removes dead index entries and can recycle completely empty pages, but a B-tree does not merge half-empty pages back together, so indexes on monotonically increasing keys with old-row deletions, or indexes hit by non-HOT updates, stay large until REINDEX.

How to measure, from cheapest to exact:

MethodCostWhat you get
pg_stat_user_tables (n_live_tup, n_dead_tup, last_autovacuum, autovacuum_count)FreeDead tuples waiting; when vacuum last ran
Bloat estimation query (PostgreSQL wiki, from check_postgres)Cheap, uses statistics"a loose estimate of table growth activity only"
pgstattuple_approx('t')Reads pages not all-visibleApproximate dead_tuple_percent, approx_free_percent
pgstattuple('t')Reads every pageExact tuple_percent, dead_tuple_percent, free_percent
pgstatindex('idx')Reads the whole indexavg_leaf_density (about 90 on a fresh B-tree), leaf_fragmentation
text
     day   orders size   pgstattuple free%  dead%    what happened
1    1     8 GB          10                 1        steady state
2    3     8 GB          12                 18       report job held a snapshot 30 h; vacuum could not remove
3    4     11 GB         35                 2        job killed; vacuum freed the space, file did not shrink
4    5     11 GB         30                 1        new rows reuse the free space; no growth for weeks
5    -     7.5 GB        3                  0        after pg_repack (only if the 3.5 GB matters)

Real scenario: a sequential scan of a 40 GB table that has 4 GB of live data; an index on created_at of a queue table where old rows are deleted from the left and new ones added on the right, leaving a long tail of near-empty pages; backups and replicas that take 3× longer because of dead space; shared_buffers full of half-empty pages.

ProductWhere bloat shows upMeasure
PostgreSQLHeap, indexes, TOAST tablespgstattuple, pgstatindex, wiki estimate
MySQL InnoDBUndo tablespaces (history), fragmented clustered index after deletesinformation_schema.INNODB_TABLESTATS, DATA_FREE in information_schema.TABLES
SQL ServerVersion store in tempdb (or PVS with ADR), index fragmentationsys.dm_db_index_physical_stats, sys.dm_tran_version_store_space_usage
OracleUndo tablespace growth; segment space below high water markDBMS_SPACE, segment advisor

Fix: measure exactly before rewriting; rewrite indexes with REINDEX CONCURRENTLY, tables with pg_repack or REPACK CONCURRENTLY. See Index bloat and Reclaiming space.

sql
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT * FROM pgstattuple('orders');           -- exact, reads every page
SELECT * FROM pgstattuple_approx('orders');    -- skips all-visible pages
SELECT avg_leaf_density, leaf_fragmentation FROM pgstatindex('orders_created_at_idx');

TOAST and vacuum Good to know ​

In plain words: large values (long text, JSONB, bytea) are stored out of line in a separate TOAST table that has its own dead tuples, its own vacuum and its own bloat.

Common misunderstanding: "If I update a row with a big JSONB column but do not change the JSONB, the JSONB is copied." Unchanged out-of-line TOAST values are not rewritten; the new heap tuple points to the same TOAST chunks. But changing any part of the big value writes all of its chunks again.

Definition: every table with a TOAST-able column has a pg_toast.pg_toast_<oid> relation (pg_class.reltoastrelid). Autovacuum treats it as its own table (storage parameters toast.autovacuum_*); VACUUM (PROCESS_TOAST false) skips it, and per the manual PROCESS_TOAST "is required when the FULL option is used". Freezing also needs the TOAST table: the manual's age query takes the greater of age(c.relfrozenxid) and age(t.relfrozenxid) for exactly this reason. Storage format details are in Database Internals.

text
     update pattern on documents(body jsonb ~200 KB)    heap                 TOAST table
1    UPDATE documents SET title='x' WHERE id=1          new 300-byte tuple   no new chunks
2    UPDATE documents SET body = body || '{"a":1}'      new tuple            ~100 new chunks, old 100 dead
3    1,000 such updates per minute                      small                100k dead chunks/min

Real scenario: a table looks small in pg_relation_size but pg_total_relation_size is 50× larger because of TOAST bloat; a JSONB "state" document updated on every event; an anti-wraparound vacuum of a big TOAST table that nobody watched.

ProductLarge values
PostgreSQLTOAST table per relation, vacuumed separately
MySQL InnoDBOff-page LOB pages; old LOB versions also need purge
SQL ServerLOB pages; only the changed fragment goes to the version store
OracleLOB segments with their own undo/retention (RETENTION, PCTVERSION)

Fix: keep frequently changing fields out of big documents; check both sizes.

sql
SELECT c.relname,
       pg_size_pretty(pg_relation_size(c.oid))            AS heap,
       pg_size_pretty(pg_relation_size(c.reltoastrelid))  AS toast,
       pg_size_pretty(pg_total_relation_size(c.oid))      AS total
FROM pg_class c WHERE c.relkind = 'r' AND c.reltoastrelid <> 0
ORDER BY pg_relation_size(c.reltoastrelid) DESC LIMIT 10;

Freezing and xid wraparound Must-know ​

In plain words: transaction IDs are 32-bit and wrap around. Before an old row's xmin becomes "the future", VACUUM must mark it frozen. If vacuum cannot keep up, PostgreSQL first warns, then refuses new write transactions.

Common misunderstanding: "Wraparound means data corruption; the fix is single-user mode and VACUUM FULL." Modern PostgreSQL stops assigning xids long before data could be lost, and the manual's runbook says single-user mode is "no longer necessary, and should be avoided" and VACUUM FULL "requires an XID and will therefore fail".

Definition: xids are compared modulo 2^32, so "for every normal XID, there are two billion XIDs that are "older" and two billion that are "newer"". PostgreSQL reserves FrozenTransactionId, "always considered older than every normal XID"; since 9.4 freezing sets a flag bit and keeps the original xmin. The knobs:

KnobDefaultMeaning
vacuum_freeze_min_age50 millionTuples older than this get frozen when VACUUM visits their page
vacuum_freeze_table_age150 millionAbove this age(relfrozenxid), VACUUM runs aggressively (visits every page not all-frozen); capped at 95% of autovacuum_freeze_max_age
autovacuum_freeze_max_age200 millionForces an anti-wraparound autovacuum, "even if autovacuum is disabled"
vacuum_failsafe_age1.6 billionVACUUM drops cost delay, skips index vacuuming and uses all of shared buffers to finish
vacuum_max_eager_freeze_failure_rate0.03How much eager freezing a normal vacuum may attempt on all-visible pages
Warning point100 million xids before wraparoundWARNING: database "mydb" must be vacuumed within 99985967 transactions
Stop point3 million xids before wraparoundERROR: database is not accepting commands that assign new transaction IDs to avoid wraparound data loss in database "mydb"

age(relfrozenxid) per table and age(datfrozenxid) per database (the minimum of its tables) tell you where you are. An anti-wraparound autovacuum shows in pg_stat_activity as autovacuum: VACUUM ... (to prevent wraparound) and is not cancelled by conflicting lock requests, so a ALTER TABLE that needs ACCESS EXCLUSIVE will now queue behind it, and everything else queues behind the ALTER.

text
     age(datfrozenxid)   what PostgreSQL does
1    0 .. 150M            normal vacuums freeze opportunistically (tuples older than 50M)
2    150M                 next VACUUM of the table is aggressive
3    200M                 anti-wraparound autovacuum forced, not interrupted by lock conflicts
4    1.6B                 failsafe: no throttling, index vacuuming skipped
5    ~2.1B - 100M         WARNING on every xid assignment
6    ~2.1B - 3M           ERROR: no new xids; read-only transactions still work; VACUUM still runs

Real scenario: a 5 TB append-only table whose anti-wraparound vacuum takes 30 hours and saturates I/O at 2 a.m.; a forgotten prepared transaction that kept datfrozenxid from moving for months; a stopped logical replication slot that holds xmin; a write burst of 1,000 xid/s (86M/day) that reaches 200M in two and a half days, so anti-wraparound vacuums are routine on such systems, not an emergency.

ProductCounter widthWraparound handling
PostgreSQL32-bit xid in tuples (64-bit xid8 in functions)Freezing via VACUUM; warnings at 100M left, stop at 3M left
MySQL InnoDB48-bit (6-byte DB_TRX_ID)Not a practical concern
OracleSCN, a much wider counterNo freezing step
SQL Server64-bit transaction sequence numbersNot a concern
CockroachDB, SpannerHybrid logical / TrueTime timestampsNot a concern; old versions removed after gc.ttlseconds (CockroachDB)

Fix: monitor age, keep autovacuum fast enough, and know the runbook in Wraparound emergency.

sql
SELECT datname, age(datfrozenxid) AS xid_age, mxid_age(datminmxid) AS mxid_age,
       round(100.0 * age(datfrozenxid) / 2000000000, 1) AS pct_to_stop
FROM pg_database ORDER BY age(datfrozenxid) DESC;

SELECT c.oid::regclass AS table_name,
       greatest(age(c.relfrozenxid), age(t.relfrozenxid)) AS xid_age,
       pg_size_pretty(pg_total_relation_size(c.oid)) AS size
FROM pg_class c LEFT JOIN pg_class t ON c.reltoastrelid = t.oid
WHERE c.relkind IN ('r', 'm') ORDER BY 2 DESC LIMIT 20;

Multixacts Good to know ​

In plain words: when several transactions lock the same row at once (shared locks, foreign key checks), there is room for only one id in xmax, so PostgreSQL stores a "group id" there, a multixact, and keeps the member list elsewhere.

Common misunderstanding: "Only xids wrap around." Multixact ids are also 32-bit and also need freezing; their member storage can grow large too.

Definition: the manual: lock information "is encoded as a "multiple transaction ID", or multixact ID for short, whenever there is more than one transaction concurrently locking a row", stored in pg_multixact. Knobs mirror the xid ones: vacuum_multixact_freeze_min_age (5 million), vacuum_multixact_freeze_table_age (150 million), autovacuum_multixact_freeze_max_age (400 million), vacuum_multixact_failsafe_age (1.6 billion). Check mxid_age(relminmxid) and mxid_age(datminmxid). "MXID exhaustion will only block a subset of write transactions, specifically those that involve row locks that require an MXID", and "replication slots do not directly hold back multixact cleanup".

text
     T1                                        T2                                   row 7 xmax
1    INSERT INTO order_items (order_id=7)                                           xid of T1 (FK check: KEY SHARE lock)
2                                              INSERT INTO order_items (order_id=7) multixact 900 = {T1, T2}
3    COMMIT;                                   COMMIT;                              multixact 900 stays until frozen/replaced

Real scenario: a parent table referenced by a busy child table (every child insert takes FOR KEY SHARE on the parent row); SELECT ... FOR SHARE in a reservation flow; savepoints in ORMs combined with row locks.

ProductMultiple lockers on one row
PostgreSQLMultixact id in xmax, members in pg_multixact
MySQL InnoDBLock structures in memory (lock system), not on the row
OracleITL slots in the block header
SQL ServerLock manager in memory

Fix: monitor mxid_age; avoid FOR SHARE where FOR UPDATE or no lock works; index foreign keys so checks are cheap. Lock modes themselves are in Locks & Concurrency.

Per-engine behaviour ​

MVCC in MySQL InnoDB vs PostgreSQL: undo vs in-heap versions ​

InnoDB updates the clustered-index record in place and writes the previous image to an undo log in a rollback segment. From the MySQL 8.4 manual: each row has "A 6-byte DB_TRX_ID field" for the last writer and "A 7-byte DB_ROLL_PTR field called the roll pointer" that "points to an undo log record written to the rollback segment". A reader whose read view should not see the latest change follows the roll pointer and rebuilds the older version. Insert undo is discarded at commit; update undo is kept until no read view needs it. Deleted rows are delete-marked and physically removed by purge.

"The History list length is typically a low value, usually less than a few thousand, but a write-heavy workload or long running transactions can cause it to increase, even for transactions that are read only." — MySQL 8.4 Reference Manual, Purge Configuration

PostgreSQL heapInnoDB undo
Where old versions liveIn the table pages, next to current onesIn undo tablespaces (rollback segments)
Cost of an updateNew full tuple; new index entries unless HOTIn-place change plus a smaller undo record
RollbackNothing to undo; the aborted xid is just invisibleApply undo records (long rollback after a big update)
Reading old dataDirect; old tuple is on the pageRebuild from the undo chain (slow with long chains)
Reading current dataMay have to skip dead versions until vacuumedAlways the newest record first
CleanupVACUUM / autovacuumPurge threads (innodb_purge_threads)
Backlog metricn_dead_tup, xmin horizon ageHistory list length (SHOW ENGINE INNODB STATUS)
What a long transaction growsTables and indexes (bloat)Undo tablespaces; reads slow down walking versions
Counter wraparound32-bit xid, needs freezing48-bit trx id, no freezing
Secondary indexPoints to heap TID; dead entries until vacuumPoints to primary key; delete-marked entries purged

The MySQL manual gives the same warning PostgreSQL does, in different words: "commit transactions regularly, including transactions that issue only consistent reads. Otherwise, InnoDB cannot discard data from the update undo logs". When purge falls behind, innodb_max_purge_lag (default 0, no limit) imposes "a delay ... on INSERT, UPDATE, and DELETE operations to allow time for purge operations to catch up". See MySQL Storage Engines and Storage Engines.

Oracle: undo segments and "snapshot too old" ​

Oracle also updates in place and keeps before-images in undo segments. A long query that needs a before-image that has already been overwritten fails with ORA-01555: snapshot too old: rollback segment number string with name "string" too small; Oracle's action text: "If in Automatic Undo Management mode, increase undo_retention setting. Otherwise, use larger rollback segments". UNDO_RETENTION is a minimum retention in seconds (ignored for a fixed-size undo tablespace, which Oracle auto-tunes), and RETENTION GUARANTEE makes it hard, at the price of failing DML when undo is full. So Oracle chooses the opposite failure to PostgreSQL: the old reader dies; the table never bloats. PostgreSQL had an opt-in version of this, old_snapshot_threshold, removed in PostgreSQL 17.

SQL Server: the version store ​

With READ_COMMITTED_SNAPSHOT or ALLOW_SNAPSHOT_ISOLATION on, SQL Server copies the previous committed row image to the version store on every modification. Microsoft's guide: "If accelerated database recovery (ADR) is enabled on a database, the version store is created in that database. Otherwise, the version store is created in the tempdb database." A background thread removes versions no active transaction needs; a long snapshot transaction prevents that. When tempdb fills, the longest-running snapshot transactions are made victims (message 3967 in the error log, 3966 when the victim reads), and under ADR a full persistent version store (PVS) makes version-generating UPDATE and DELETE fail.

What each database really does ​

ProductOld versions live inCleanupLong-transaction symptomKey metric / knob
PostgreSQLHeap pages (in-table), TOASTVACUUM / autovacuumTable and index bloat; xid agen_dead_tup, backend_xmin, age(datfrozenxid)
MySQL InnoDBUndo tablespacesPurge threadsHistory list length, undo growth, slow readsinnodb_purge_threads, innodb_max_purge_lag
OracleUndo segmentsAutomatic reuse after retentionORA-01555 snapshot too oldUNDO_RETENTION, RETENTION GUARANTEE
SQL ServerVersion store (tempdb, or PVS in the database with ADR)Version cleanup threadtempdb / PVS growth, errors 3966/3967sys.dm_tran_version_store_space_usage
SQLiteNo MVCC for writers; WAL mode keeps old pages in the WAL for readersCheckpointWAL file grows while a reader holds an old end markPRAGMA wal_checkpoint, wal_autocheckpoint
MongoDB (WiredTiger)Update chains in cache, history store on diskEviction, history store cleanupCache pressure; transactions aborted after transactionLifetimeLimitSeconds (60 s)WiredTiger cache stats
CockroachDBMVCC versions per key in PebbleMVCC GC after gc.ttlsecondsOld versions kept for the TTL (and protected timestamps for backups/changefeeds)gc.ttlseconds
RedisNo MVCC (single-threaded command execution)n/an/an/a

Mechanics ​

Every knob in one table ​

ParameterDefault (PostgreSQL 19 docs)ScopeWhat it changes
autovacuumonserverDaemon on/off (anti-wraparound runs anyway)
autovacuum_max_workers3server (reload)Concurrent workers; slots reserved by autovacuum_worker_slots (typically 16)
autovacuum_naptime1minserverDelay between runs per database
autovacuum_vacuum_threshold50server, per tableBase dead-tuple count
autovacuum_vacuum_scale_factor0.2server, per tableFraction of reltuples added
autovacuum_vacuum_max_threshold100,000,000server, per tableCap on the computed threshold
autovacuum_vacuum_insert_threshold / _insert_scale_factor1000 / 0.2server, per tableInsert-driven vacuums (freezing, visibility map)
autovacuum_analyze_threshold / _scale_factor50 / 0.1server, per tableWhen to ANALYZE
autovacuum_vacuum_cost_delay2 msserver, per tableSleep after reaching the cost limit
autovacuum_vacuum_cost_limit-1 (uses vacuum_cost_limit = 200)server, per tableCost units before sleeping, shared among workers
vacuum_cost_delay0 (manual VACUUM unthrottled)sessionThrottle for manual VACUUM
vacuum_cost_page_hit / _miss / _dirty1 / 2 / 20serverCost accounting
autovacuum_work_mem / maintenance_work_mem-1 / 64MBserverMemory for dead tuple references (fewer index passes)
vacuum_freeze_min_age50 millionsession, per table (autovacuum_freeze_min_age)Freeze cutoff
vacuum_freeze_table_age150 millionsession, per tableAggressive vacuum trigger
autovacuum_freeze_max_age200 millionserver start, per table (lower only)Forced anti-wraparound autovacuum
vacuum_failsafe_age1.6 billionsessionFailsafe mode
autovacuum_multixact_freeze_max_age400 millionserver startMultixact forced vacuum
vacuum_truncateonserver, per tableTruncate empty tail pages (needs brief ACCESS EXCLUSIVE)
log_autovacuum_min_duration10minserver, per tableLog slow autovacuum runs (0 = log all)
idle_in_transaction_session_timeout0 (off)session, role, databaseKill sessions idle inside a transaction (SQLSTATE 25P03)
transaction_timeout0 (off), PostgreSQL 17+session, role, databaseKill any transaction longer than this (SQLSTATE 25P04)
statement_timeout0 (off)session, roleCancel long statements (57014)
hot_standby_feedbackoffstandbyStandby reports its xmin to the primary
max_standby_streaming_delay30sstandbyHow long replay waits before cancelling conflicting queries
max_slot_wal_keep_size-1 (unlimited)serverInvalidate slots that retain too much WAL
idle_replication_slot_timeout0 (off)serverInvalidate slots idle longer than this at checkpoint
fillfactor (table storage parameter)100per tableFree space reserved per page for HOT

VACUUM options and phases ​

VACUUM [ ( option [, ...] ) ] [ table [ (columns) ] ] with options FULL, FREEZE, VERBOSE, ANALYZE, DISABLE_PAGE_SKIPPING, SKIP_LOCKED, INDEX_CLEANUP { AUTO | ON | OFF }, PROCESS_MAIN, PROCESS_TOAST, TRUNCATE, PARALLEL n, SKIP_DATABASE_STATS, ONLY_DATABASE_STATS, BUFFER_USAGE_LIMIT. The command-line wrapper is vacuumdb (--jobs, --min-xid-age, --analyze-in-stages).

text
pg_stat_progress_vacuum.phase, in order:
1  initializing
2  scanning heap               -> heap_blks_scanned, dead tuple references collected
3  vacuuming indexes           -> once per index, repeated if memory for dead TIDs fills up
4  vacuuming heap              -> line pointers freed, FSM updated
5  cleaning up indexes
6  truncating heap             -> only if the tail of the file is empty
7  performing final cleanup    -> visibility map, pg_class stats, relfrozenxid advanced

Views and functions you will use ​

View / functionColumns that matter
pg_stat_user_tablesn_live_tup, n_dead_tup, n_mod_since_analyze, n_ins_since_vacuum, n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd, last_vacuum, last_autovacuum, vacuum_count, autovacuum_count
pg_stat_activitypid, state (idle in transaction, idle in transaction (aborted)), xact_start, backend_xid, backend_xmin, backend_type (autovacuum worker)
pg_stat_progress_vacuumphase, heap_blks_total, heap_blks_scanned, index_vacuum_count, indexes_total, indexes_processed
pg_replication_slotsslot_name, slot_type, active, xmin, catalog_xmin, inactive_since, wal_status
pg_stat_replicationbackend_xmin (from hot_standby_feedback), lag columns
pg_prepared_xactsgid, prepared, transaction
pg_class / pg_databaserelfrozenxid, relminmxid, reltuples, relpages, relallvisible, relallfrozen / datfrozenxid, datminmxid
Functionsage(xid), mxid_age(xid), pg_current_snapshot(), pg_current_xact_id(), pg_xact_status(), pg_terminate_backend(pid), pg_cancel_backend(pid), pg_drop_replication_slot(name)

Messages you will see ​

The two wraparound messages are copied from the manual (§24.1.5); the others are the server and tool texts as they appear in logs and clients.

MessageMeaningAction
WARNING: database "mydb" must be vacuumed within 99985967 transactions + HINT: To avoid transaction ID assignment failures, execute a database-wide VACUUM in that database.Under 100 million xids leftRunbook now, while writes still work
ERROR: database is not accepting commands that assign new transaction IDs to avoid wraparound data loss in database "mydb"Under 3 million leftRunbook; read-only works, VACUUM works
FATAL: terminating connection due to idle-in-transaction timeout (SQLSTATE 25P03)idle_in_transaction_session_timeout firedFix the code path; retry from the start
FATAL: terminating connection due to transaction timeout (SQLSTATE 25P04)transaction_timeout firedSame
ERROR: canceling statement due to conflict with recovery (SQLSTATE 40001)Standby replay needed to remove versions your query useshot_standby_feedback, longer max_standby_streaming_delay, or run elsewhere
ERROR: canceling autovacuum task (log)A lock request conflicted with a normal autovacuumStop frequent conflicting DDL/ANALYZE
autovacuum: VACUUM public.t (to prevent wraparound) (pg_stat_activity.query)Anti-wraparound run; not cancellable by lock conflictsLet it finish; do not queue DDL behind it
ORA-01555: snapshot too old (Oracle)Needed undo overwrittenRaise undo retention / size, shorten query
History list length 1234567 (MySQL SHOW ENGINE INNODB STATUS)Purge backlogFind the old transaction in innodb_trx

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Big table vacuumed too rarelyPer-table thresholdsALTER TABLE ... SET (autovacuum_vacuum_scale_factor = 0.01, ...)Precise, no restartMust be maintained per table
Autovacuum too slow everywhereRaise cost limit / lower delayautovacuum_vacuum_cost_limit = 2000Fewer backlogsMore I/O during vacuum
Cleanup blockedKill the horizon holderpg_terminate_backend, drop slot, rollback preparedImmediateThat session's work is lost
Cleanup blocked again next weekTimeouts per roleidle_in_transaction_session_timeout, transaction_timeoutSelf-healingLong legit jobs need their own role
Table bloated after a one-off eventOnline rewritepg_repack, REPACK CONCURRENTLYSmaller file, online2× disk, extension/PK needed, load
Index bloatREINDEX CONCURRENTLYPer indexOnlineWaits for old transactions; two table scans
Hot counterHOT-friendly schema + batchingSide table, fillfactor, no index on counterFar fewer dead tuplesSlight staleness
Delete-heavy historyPartitioningDROP/DETACH old partitionsNo dead tuples at allSchema and query changes
Wraparound nearRunbookHolders → plain VACUUM of oldest tablesRestores writesHours on large tables

Autovacuum tuning per table ​

Rule: change global settings for speed, per-table settings for frequency. A 200M-row table with the default 0.2 scale factor waits for 40M dead tuples.

sql
-- Global (postgresql.conf or ALTER SYSTEM; reload)
ALTER SYSTEM SET autovacuum_vacuum_cost_limit = 2000;     -- shared by workers
ALTER SYSTEM SET autovacuum_vacuum_cost_delay = '2ms';
ALTER SYSTEM SET autovacuum_max_workers = 6;              -- reload is enough in recent versions
ALTER SYSTEM SET log_autovacuum_min_duration = '1s';
SELECT pg_reload_conf();

-- Per table: vacuum after ~1% change instead of 20%
ALTER TABLE orders SET (
  autovacuum_vacuum_scale_factor = 0.01,
  autovacuum_vacuum_threshold    = 10000,
  autovacuum_analyze_scale_factor = 0.02,
  autovacuum_vacuum_cost_limit   = 4000      -- excluded from worker balancing
);
-- Append-only table: freeze early so the anti-wraparound run has little to do
ALTER TABLE events SET (autovacuum_freeze_min_age = 0, autovacuum_vacuum_insert_scale_factor = 0.05);
-- TOAST table has its own settings
ALTER TABLE documents SET (toast.autovacuum_vacuum_scale_factor = 0.02);

-- Verify
SELECT relname, reloptions FROM pg_class WHERE reloptions IS NOT NULL;

Go: a monitor that flags tables whose dead tuples exceed their own effective threshold.

go
// DueTables lists tables whose dead tuples exceed the default autovacuum
// threshold, ignoring per-table overrides for brevity.
func DueTables(ctx context.Context, db *sql.DB) ([]string, error) {
	rows, err := db.QueryContext(ctx, `
		SELECT s.relname
		FROM pg_stat_user_tables s
		JOIN pg_class c ON c.oid = s.relid
		WHERE s.n_dead_tup > current_setting('autovacuum_vacuum_threshold')::int
		      + current_setting('autovacuum_vacuum_scale_factor')::float8 * c.reltuples
		ORDER BY s.n_dead_tup DESC`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []string
	for rows.Next() {
		var name string
		if err := rows.Scan(&name); err != nil {
			return nil, err
		}
		out = append(out, name)
	}
	return out, rows.Err()
}

Laravel: keep per-table settings in a migration so they live in version control.

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        DB::statement('ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.01, autovacuum_vacuum_threshold = 10000)');
        DB::statement('ALTER TABLE page_stats SET (fillfactor = 80)');
    }

    public function down(): void
    {
        DB::statement('ALTER TABLE orders RESET (autovacuum_vacuum_scale_factor, autovacuum_vacuum_threshold)');
        DB::statement('ALTER TABLE page_stats RESET (fillfactor)');
    }
};

Killing idle and long transactions ​

Find, end, prevent. pg_cancel_backend cancels the current query (useless for an idle session); pg_terminate_backend ends the session and rolls its transaction back.

sql
-- Find: sessions idle in transaction for more than 5 minutes
SELECT pid, usename, application_name, now() - state_change AS idle_for, age(backend_xmin) AS xmin_age
FROM pg_stat_activity
WHERE state IN ('idle in transaction', 'idle in transaction (aborted)')
  AND now() - state_change > interval '5 minutes';

-- End them
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction' AND now() - state_change > interval '5 minutes';

-- Prevent, per role (not per pooled connection)
ALTER ROLE app_web    SET idle_in_transaction_session_timeout = '15s';
ALTER ROLE app_web    SET transaction_timeout = '60s';          -- PostgreSQL 17+
ALTER ROLE app_report SET idle_in_transaction_session_timeout = '5min';

The manual's reason for the idle timeout: "an open transaction prevents vacuuming away recently-dead tuples that may be visible only to this transaction; so remaining idle for a long time can contribute to table bloat." With PgBouncer in transaction mode, set these on the role, because SET on a pooled server connection leaks to other clients (see Connection Pooling).

Go: before and after. The report holds a Repeatable Read snapshot while it uploads files, and the view counter rewrites the same row once per event:

go
// Package before shows two habits that feed table bloat in PostgreSQL: a
// reporting transaction that stays open while it does slow, unrelated work,
// and a hot counter that is rewritten once per event.
package before

import (
	"context"
	"database/sql"
)

type Order struct {
	ID         int64
	TotalCents int64
}

// ExportDailyReport takes one REPEATABLE READ snapshot and keeps it for as
// long as the uploads take. Every row version that any other session makes
// obsolete in the meantime must stay on disk: VACUUM may not remove a
// version this snapshot could still read.
func ExportDailyReport(ctx context.Context, db *sql.DB, upload func(context.Context, Order) error) error {
	tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
	if err != nil {
		return err
	}
	defer tx.Rollback()

	rows, err := tx.QueryContext(ctx,
		`SELECT id, total_cents FROM orders WHERE created_at >= now() - interval '1 day'`)
	if err != nil {
		return err
	}
	var orders []Order
	for rows.Next() {
		var o Order
		if err := rows.Scan(&o.ID, &o.TotalCents); err != nil {
			rows.Close()
			return err
		}
		orders = append(orders, o)
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return err
	}

	// Network calls, PDF rendering, retries: minutes of work that need no
	// database at all, done while the snapshot is still pinned.
	for _, o := range orders {
		if err := upload(ctx, o); err != nil {
			return err
		}
	}

	// A closing query "for consistency" is the excuse for keeping tx open.
	var n int
	if err := tx.QueryRowContext(ctx,
		`SELECT count(*) FROM orders WHERE created_at >= now() - interval '1 day'`).Scan(&n); err != nil {
		return err
	}
	return tx.Commit()
}

// CountPageViews writes one new heap tuple per event. Ten thousand views of
// one page leave ten thousand dead versions of the same row behind, and an
// index on updated_at turns every one of them into a non-HOT update.
func CountPageViews(ctx context.Context, db *sql.DB, views <-chan int64) error {
	for pageID := range views {
		if _, err := db.ExecContext(ctx,
			`UPDATE page_stats SET hits = hits + 1, updated_at = now() WHERE page_id = $1`,
			pageID); err != nil {
			return err
		}
	}
	return nil
}

After: connections start with statement_timeout and idle_in_transaction_session_timeout as runtime parameters, the report reads first and works afterwards, counters are flushed in batches, and a health file reads dead tuples, autovacuum recency, age(datfrozenxid) and the oldest backend_xmin:

go
// Package after keeps transactions short, lets the server enforce that with
// timeouts, and batches hot counters so fewer row versions are created.
package after

import (
	"context"
	"database/sql"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/stdlib"
)

// Open returns a *sql.DB whose every pooled connection starts with these
// settings. RuntimeParams are sent in the startup message, so they apply to
// all connections, not just the one a SET statement happened to run on.
func Open(dsn string) (*sql.DB, error) {
	cfg, err := pgx.ParseConfig(dsn)
	if err != nil {
		return nil, err
	}
	cfg.RuntimeParams["application_name"] = "report-worker"
	cfg.RuntimeParams["statement_timeout"] = "30s"
	// A session left idle inside a transaction is terminated, which releases
	// its snapshot and its xid and lets VACUUM move on.
	cfg.RuntimeParams["idle_in_transaction_session_timeout"] = "15s"
	return stdlib.OpenDB(*cfg), nil
}

type Order struct {
	ID         int64
	TotalCents int64
}

// ExportDailyReport reads what it needs in one statement, outside any
// explicit transaction, and only then does the slow work. Under the default
// READ COMMITTED level the snapshot lives exactly as long as the query.
func ExportDailyReport(ctx context.Context, db *sql.DB, upload func(context.Context, Order) error) error {
	orders, err := loadOrders(ctx, db)
	if err != nil {
		return err
	}
	for _, o := range orders {
		if err := upload(ctx, o); err != nil {
			return err
		}
	}
	return nil
}

func loadOrders(ctx context.Context, db *sql.DB) ([]Order, error) {
	rows, err := db.QueryContext(ctx,
		`SELECT id, total_cents FROM orders WHERE created_at >= now() - interval '1 day'`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var orders []Order
	for rows.Next() {
		var o Order
		if err := rows.Scan(&o.ID, &o.TotalCents); err != nil {
			return nil, err
		}
		orders = append(orders, o)
	}
	return orders, rows.Err()
}

// CountPageViews aggregates views in memory and flushes them once per
// interval: one new row version per page per flush instead of one per view.
// With no index on hits or updated_at, each flush can be a HOT update.
func CountPageViews(ctx context.Context, db *sql.DB, views <-chan int64, every time.Duration) error {
	pending := map[int64]int64{}
	tick := time.NewTicker(every)
	defer tick.Stop()

	for {
		select {
		case pageID, ok := <-views:
			if !ok {
				return flush(ctx, db, pending)
			}
			pending[pageID]++
		case <-tick.C:
			if err := flush(ctx, db, pending); err != nil {
				return err
			}
			pending = map[int64]int64{}
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}

func flush(ctx context.Context, db *sql.DB, pending map[int64]int64) error {
	if len(pending) == 0 {
		return nil
	}
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()
	for pageID, n := range pending {
		if _, err := tx.ExecContext(ctx,
			`UPDATE page_stats SET hits = hits + $2, updated_at = now() WHERE page_id = $1`,
			pageID, n); err != nil {
			return err
		}
	}
	return tx.Commit()
}
go
package after

import (
	"context"
	"database/sql"
	"time"
)

type TableHealth struct {
	Table          string
	LiveTuples     int64
	DeadTuples     int64
	HotUpdates     int64
	Updates        int64
	LastAutovacuum sql.NullTime // NULL until autovacuum has processed the table
}

type DatabaseAge struct {
	Name          string
	FrozenXIDAge  int64 // transactions since datfrozenxid; wraparound is at ~2 billion
	OldestXminAge sql.NullInt64
	OldestXactFor sql.NullString
}

// TablesByDeadTuples reads the cumulative statistics view. The counts are
// estimates, cheap to read, and good enough to alert on.
func TablesByDeadTuples(ctx context.Context, db *sql.DB, limit int) ([]TableHealth, error) {
	rows, err := db.QueryContext(ctx, `
		SELECT schemaname || '.' || relname, n_live_tup, n_dead_tup,
		       n_tup_hot_upd, n_tup_upd, last_autovacuum
		FROM pg_stat_user_tables
		ORDER BY n_dead_tup DESC
		LIMIT $1`, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var out []TableHealth
	for rows.Next() {
		var t TableHealth
		if err := rows.Scan(&t.Table, &t.LiveTuples, &t.DeadTuples,
			&t.HotUpdates, &t.Updates, &t.LastAutovacuum); err != nil {
			return nil, err
		}
		out = append(out, t)
	}
	return out, rows.Err()
}

// CurrentDatabaseAge reports how close the database is to forced
// anti-wraparound vacuums, and which session is holding the xmin horizon back.
func CurrentDatabaseAge(ctx context.Context, db *sql.DB) (DatabaseAge, error) {
	var a DatabaseAge
	err := db.QueryRowContext(ctx, `
		SELECT d.datname, age(d.datfrozenxid),
		       (SELECT max(age(backend_xmin)) FROM pg_stat_activity
		         WHERE datname = d.datname),
		       (SELECT (now() - xact_start)::text FROM pg_stat_activity
		         WHERE datname = d.datname AND xact_start IS NOT NULL
		         ORDER BY xact_start LIMIT 1)
		FROM pg_database d
		WHERE d.datname = current_database()`).
		Scan(&a.Name, &a.FrozenXIDAge, &a.OldestXminAge, &a.OldestXactFor)
	return a, err
}

// Alert is a deliberately simple rule set; tune the numbers to your workload.
func Alert(t TableHealth, a DatabaseAge, now time.Time) []string {
	var msgs []string
	if t.LiveTuples > 0 && t.DeadTuples > t.LiveTuples/5 {
		msgs = append(msgs, t.Table+": dead tuples exceed 20% of live tuples")
	}
	if t.LastAutovacuum.Valid && now.Sub(t.LastAutovacuum.Time) > 24*time.Hour && t.DeadTuples > 0 {
		msgs = append(msgs, t.Table+": no autovacuum in 24h")
	}
	if a.FrozenXIDAge > 1_000_000_000 {
		msgs = append(msgs, a.Name+": datfrozenxid older than 1 billion transactions")
	}
	return msgs
}

The Go angle: BeginTx returns a *sql.Tx pinned to one pooled connection until Commit or Rollback, and nothing stops you from passing it into code that does HTTP. Never hold a *sql.Tx across non-database I/O, and defer tx.Rollback() immediately. db.Exec("SET ...") changes one random pooled connection; use pgx RuntimeParams, the DSN, or ALTER ROLE. A Go-side terminator for a cron job:

go
// TerminateIdle ends sessions idle in a transaction longer than limit and
// returns how many were terminated. Requires pg_signal_backend or superuser.
func TerminateIdle(ctx context.Context, db *sql.DB, limit time.Duration) (int, error) {
	var n int
	err := db.QueryRowContext(ctx, `
		SELECT count(pg_terminate_backend(pid))
		FROM pg_stat_activity
		WHERE state LIKE 'idle in transaction%'
		  AND now() - state_change > make_interval(secs => $1)`,
		limit.Seconds()).Scan(&n)
	return n, err
}

Laravel: before and after. The job writes a status, which assigns the transaction an xid, then waits on a partner API with retries before committing:

php
<?php

// app/Jobs/SyncInvoiceToErp.php
namespace App\Jobs;

use App\Models\Invoice;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

final class SyncInvoiceToErp implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $invoiceId) {}

    public function handle(): void
    {
        DB::beginTransaction();

        try {
            $invoice = Invoice::with('lines')->findOrFail($this->invoiceId);

            // The first write assigns this transaction an xid. From here until
            // COMMIT, VACUUM cannot remove any row version that became dead
            // after this transaction started, in any table of the database.
            $invoice->update(['erp_status' => 'syncing']);

            // A slow partner API, a two-minute timeout and three retries:
            // the session sits "idle in transaction" the whole time.
            $response = Http::timeout(120)
                ->retry(3, 5000)
                ->post(config('services.erp.url').'/invoices', $invoice->toArray())
                ->throw();

            $invoice->update([
                'erp_status' => 'synced',
                'erp_reference' => $response->json('id'),
            ]);

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();

            throw $e;
        }
    }
}

After: read, call the API with no transaction open, write in a DB::transaction closure that lasts milliseconds; an Artisan command reports dead tuples, xid age and the sessions holding the horizon:

php
<?php

// app/Jobs/SyncInvoiceToErp.php
namespace App\Jobs;

use App\Models\Invoice;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

#[Tries(3)]
#[Timeout(150)]
final class SyncInvoiceToErp implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $invoiceId) {}

    public function handle(): void
    {
        // 1. Read. Each statement gets its own snapshot under READ COMMITTED;
        //    nothing is held once the query returns.
        $invoice = Invoice::with('lines')->findOrFail($this->invoiceId);
        $payload = $invoice->toArray();

        // 2. Talk to the outside world with no transaction open.
        $response = Http::timeout(120)
            ->post(config('services.erp.url').'/invoices', $payload)
            ->throw();

        // 3. Write, in a transaction that lasts milliseconds.
        DB::transaction(function () use ($invoice, $response) {
            $invoice->update([
                'erp_status' => 'synced',
                'erp_reference' => $response->json('id'),
            ]);
        });
    }
}

// app/Console/Commands/VacuumHealth.php
namespace App\Console\Commands;

use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[Signature('db:vacuum-health {--limit=10}')]
#[Description('Report dead tuples, autovacuum recency, xid age and the oldest open transaction')]
final class VacuumHealth extends Command
{
    public function handle(): void
    {
        $tables = DB::select(<<<'SQL'
            SELECT schemaname || '.' || relname AS "table",
                   n_live_tup, n_dead_tup,
                   round(100.0 * n_dead_tup / greatest(n_live_tup + n_dead_tup, 1), 1) AS dead_pct,
                   n_tup_hot_upd, n_tup_upd, last_autovacuum
            FROM pg_stat_user_tables
            ORDER BY n_dead_tup DESC
            LIMIT ?
            SQL, [(int) $this->option('limit')]);

        $this->table(
            ['table', 'live', 'dead', 'dead %', 'HOT upd', 'upd', 'last autovacuum'],
            array_map(fn ($row) => (array) $row, $tables),
        );

        [$age] = DB::select(
            'SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database WHERE datname = current_database()'
        );
        $this->line("datfrozenxid age for {$age->datname}: {$age->xid_age} transactions");

        $oldest = DB::select(<<<'SQL'
            SELECT pid, state, application_name,
                   (now() - xact_start)::text AS open_for,
                   age(backend_xmin) AS xmin_age
            FROM pg_stat_activity
            WHERE backend_xmin IS NOT NULL OR backend_xid IS NOT NULL
            ORDER BY xact_start NULLS LAST
            LIMIT 5
            SQL);

        $this->table(
            ['pid', 'state', 'application', 'open for', 'xmin age'],
            array_map(fn ($row) => (array) $row, $oldest),
        );

        // Autovacuum is forced at autovacuum_freeze_max_age (200 million by default).
        if ($age->xid_age > 1_000_000_000) {
            // fail() prints the message and exits with code 1, so cron or CI notices.
            $this->fail('Transaction ID age is above 1 billion: investigate before PostgreSQL does.');
        }
    }
}

The Laravel angle: DB::transaction() keeps the boundary in one visible block; manual DB::beginTransaction() spreads it across a method and is where long transactions hide. Laravel 13's database configuration has no key for statement_timeout or idle_in_transaction_session_timeout, so set them on the role. #[Timeout] on a job kills the PHP worker; PostgreSQL only notices when the socket closes. DB::whenQueryingForLongerThan() flags slow queries, not slow gaps between them, which is what bloats tables. A scheduled cleanup, if you cannot fix the code yet:

php
<?php

// routes/console.php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schedule;

Schedule::call(function () {
    DB::select(<<<'SQL'
        SELECT pg_terminate_backend(pid)
        FROM pg_stat_activity
        WHERE state LIKE 'idle in transaction%'
          AND now() - state_change > interval '10 minutes'
          AND usename = 'app_worker'
        SQL);
})->everyFiveMinutes()->name('terminate-idle-transactions')->withoutOverlapping();

Replication slots and standbys ​

A slot keeps WAL and (for logical slots, catalog_xmin; for physical slots with feedback, xmin) holds the horizon even when nothing is connected.

sql
SELECT slot_name, slot_type, active, inactive_since,
       age(xmin) AS xmin_age, age(catalog_xmin) AS catalog_xmin_age, wal_status
FROM pg_replication_slots ORDER BY greatest(age(xmin), age(catalog_xmin)) DESC NULLS LAST;

SELECT pg_drop_replication_slot('debezium_orders');   -- only if the consumer is gone for good

ALTER SYSTEM SET max_slot_wal_keep_size = '50GB';      -- slot invalidated instead of filling the disk
ALTER SYSTEM SET idle_replication_slot_timeout = '2d';
SELECT pg_reload_conf();

hot_standby_feedback "can be used to eliminate query cancels caused by cleanup records, but can cause database bloat on the primary for some workloads." The trade is: off means long replica queries get canceling statement due to conflict with recovery; on means they hold back VACUUM on the primary exactly as if they ran there. For long analytics, prefer a logical replica or a separate warehouse, or cap replica queries with statement_timeout. Replica topologies are in Replication & Failover.

Reclaiming space: VACUUM FULL, REPACK and pg_repack ​

Decide with exact numbers first (pgstattuple), then pick the least locking tool that fits.

sql
-- 1. Is it worth it? (free + dead > ~30-40% and the space is not reused soon)
SELECT pg_size_pretty(table_len) AS size, dead_tuple_percent, free_percent FROM pgstattuple('audit_log');

-- 2a. Built-in online rewrite (current manual)
REPACK (CONCURRENTLY) audit_log;

-- 2b. Extension (needs CREATE EXTENSION pg_repack and a PK or not-null unique index)
--     shell: pg_repack --dbname=app --table=public.audit_log --jobs=2 --wait-timeout=60

-- 2c. Offline rewrite in a real maintenance window only
SET lock_timeout = '5s';          -- fail fast instead of queueing every query behind the lock
VACUUM (FULL, VERBOSE, ANALYZE) audit_log;

Scheduling rules: run one table at a time; check free disk ≥ table + indexes; run at low write load (pg_repack's trigger log and REPACK CONCURRENTLY must apply concurrent changes); set lock_timeout so the final lock does not stall traffic; never use a rewrite to fix wraparound (the REPACK page: "it is not a good way to prevent transaction ID or multixact ID wraparound"). Go runs it as an ordinary statement with a long context; Laravel as an Artisan command:

go
// RepackTable runs an online rewrite with its own deadline and a short lock timeout.
func RepackTable(ctx context.Context, db *sql.DB, table string) error {
	conn, err := db.Conn(ctx)
	if err != nil {
		return err
	}
	defer conn.Close()
	if _, err := conn.ExecContext(ctx, `SET lock_timeout = '5s'`); err != nil {
		return err
	}
	_, err = conn.ExecContext(ctx, `REPACK (CONCURRENTLY) `+pgx.Identifier{table}.Sanitize())
	return err
}
php
<?php

// app/Console/Commands/RepackTable.php
namespace App\Console\Commands;

use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[Signature('db:repack {table}')]
final class RepackTable extends Command
{
    public function handle(): void
    {
        $table = $this->argument('table');
        $before = DB::selectOne('SELECT pg_total_relation_size(?::regclass) AS bytes', [$table])->bytes;

        DB::statement("SET lock_timeout = '5s'");
        DB::statement('REPACK (CONCURRENTLY) '.DB::getQueryGrammar()->wrapTable($table));

        $after = DB::selectOne('SELECT pg_total_relation_size(?::regclass) AS bytes', [$table])->bytes;
        $this->info("{$table}: {$before} -> {$after} bytes");
    }
}

Index bloat and REINDEX CONCURRENTLY ​

REINDEX CONCURRENTLY rebuilds "without taking any locks that prevent concurrent inserts, updates, or deletes", at the price of two table scans and waiting for existing transactions. If it fails it leaves an _ccnew index marked invalid; drop it and retry.

sql
SELECT indexrelid::regclass AS index, pg_size_pretty(pg_relation_size(indexrelid)) AS size,
       (pgstatindex(indexrelid::regclass::text)).avg_leaf_density
FROM pg_index JOIN pg_class ON pg_class.oid = indexrelid
WHERE indrelid = 'orders'::regclass AND relam = (SELECT oid FROM pg_am WHERE amname = 'btree');

REINDEX INDEX CONCURRENTLY orders_created_at_idx;
REINDEX TABLE CONCURRENTLY orders;                       -- every index, one at a time
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;   -- leftovers after a failure

Hot counters and HOT updates ​

sql
CREATE TABLE page_counters (page_id bigint PRIMARY KEY, hits bigint NOT NULL DEFAULT 0)
  WITH (fillfactor = 70, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 1000);
-- no index on hits; one UPDATE per page per flush, not per view
UPDATE page_counters SET hits = hits + $2 WHERE page_id = $1;

The Go "after" snippet above batches increments in memory and flushes once per interval. In Laravel, aggregate in Redis and flush on a schedule:

php
<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

// On each view: Redis::hincrby('page_hits', (string) $pageId, 1);

// Every minute (routes/console.php, Schedule::call):
$hits = Redis::hgetall('page_hits');
Redis::del('page_hits');
DB::transaction(function () use ($hits) {
    foreach ($hits as $pageId => $n) {
        DB::update('UPDATE page_counters SET hits = hits + ? WHERE page_id = ?', [(int) $n, (int) $pageId]);
    }
});

Delete-heavy tables: partition instead of vacuum ​

Logs, events and job history that are deleted by age should be partitioned by time; dropping a partition creates no dead tuples. Details in Partitioning & Sharding. For job queues that delete processed rows, keep the table small and let autovacuum run very often (autovacuum_vacuum_scale_factor = 0, threshold of a few thousand).

sql
ALTER TABLE events DETACH PARTITION events_2026_01 CONCURRENTLY;
DROP TABLE events_2026_01;

Wraparound emergency ​

The order comes from the manual (§24.1.5). Do not stop the server, do not enter single-user mode, do not run VACUUM FULL or VACUUM FREEZE.

sql
-- 0. Where are we?
SELECT datname, age(datfrozenxid), mxid_age(datminmxid) FROM pg_database ORDER BY 2 DESC;

-- 1. Old prepared transactions: commit or roll back
SELECT gid, prepared, age(transaction) FROM pg_prepared_xacts ORDER BY age(transaction) DESC;
ROLLBACK PREPARED 'gid-from-above';

-- 2. Long-running transactions
SELECT pid, age(backend_xid), age(backend_xmin), state, xact_start FROM pg_stat_activity
WHERE backend_xid IS NOT NULL OR backend_xmin IS NOT NULL ORDER BY 2 DESC NULLS LAST;
SELECT pg_terminate_backend(12345);

-- 3. Old replication slots
SELECT slot_name, age(xmin), age(catalog_xmin), active FROM pg_replication_slots;
SELECT pg_drop_replication_slot('stale_slot');   -- a replica still using it must be rebuilt

-- 4. Plain VACUUM, oldest tables first, as superuser, unthrottled
SET vacuum_cost_delay = 0;
VACUUM (VERBOSE, INDEX_CLEANUP OFF) big_old_table;    -- skip index work, like the failsafe
-- or the whole database in parallel from a shell:
--   vacuumdb --all --min-xid-age=1000000000 --jobs=4 --verbose

-- 5. Afterwards: fix autovacuum settings and the monitoring that missed it

The manual says the VACUUM "should be performed by a superuser, else it will fail to process system catalogs, which prevent it from being able to advance the database's datfrozenxid". Go and Laravel have no special role here beyond alerting early: the health.go and VacuumHealth snippets above alert when age(datfrozenxid) passes one billion, long before the 100-million-left warning.

Choosing what to do ​

SituationRecommendationExtra techniqueReason
OLTP web appDefaults + idle_in_transaction_session_timeout per roletransaction_timeout, alerts on backend_xmin ageMost bloat comes from one forgotten transaction
One huge hot tablePer-table scale factor 0.005–0.02Higher per-table cost limitDefault 20% waits too long
Counters / last_seenSide table, no index on the counter, fillfactor 70–90Batch incrementsHOT and fewer versions
Job queue tableSmall table, aggressive autovacuum, SKIP LOCKEDDelete or partition processed jobsConstant churn
Append-only eventsPartition by timeautovacuum_freeze_min_age = 0, insert-based vacuumNo dead tuples; freezing done early
Long analyticsReplica without feedback, or a warehousestatement_timeout on replicasKeep the primary's horizon free
CDC / logical replicationMonitor slot catalog_xmin agemax_slot_wal_keep_size, idle_replication_slot_timeoutAbandoned slots bloat silently
Table already bloated oncepg_repack or REPACK CONCURRENTLY once, then fix the causeCheck disk headroomRewrites are recovery, not maintenance
Bloated indexREINDEX CONCURRENTLYpgstatindex before and afterOnline
age(datfrozenxid) above 1 billionFind holders, plain VACUUM unthrottledvacuumdb --min-xid-ageRestore headroom before the warning
MySQL InnoDB history list length growingFind old transaction in information_schema.innodb_trxinnodb_purge_threads, innodb_max_purge_lagSame root cause, different file

In architecture: from a single process to a distributed system ​

MVCC turns transaction duration into storage cost. Every design decision below follows from that one sentence.

Monolith: one process, one database ​

The simplest correct usage: short request transactions, no HTTP calls inside them, one role per workload with its own timeouts. Example: a Laravel monolith with app_web (idle_in_transaction_session_timeout = 15s) and app_worker (5min), queued jobs that read, call the API, then write in a short DB::transaction (the "After" snippet). The admin "export CSV" button streams with a cursor in its own short-lived Read Committed statement rather than holding a Repeatable Read transaction across the download (see Cursors & Streaming).

Modular monolith and multiple databases ​

Modules that share one PostgreSQL cluster share one horizon per database: the reporting module's two-hour transaction bloats the orders module's tables. Give heavy modules their own database (the horizon is per database for user tables) or their own replica, own role, own timeouts, and own per-table autovacuum settings in their migrations. Example: billing and catalog in separate databases on the same cluster, so a billing reconciliation job cannot hold back vacuum of catalog.products.

Microservices: no transaction spans services ​

Because long transactions are expensive, a workflow that spans services must not hold a database transaction open while waiting for another service. The flow becomes: Order service writes orders + an outbox row in one short transaction → relay publishes OrderPlaced → Payment service consumes, writes its own short transaction → publishes PaymentCaptured → Order service updates status. Each step is milliseconds of database time. Outbox tables are themselves high-churn (insert, mark sent, delete), so they need aggressive autovacuum or partitioning (see Outbox Pattern and Saga Pattern). CDC-based relays (Debezium) add a logical replication slot, which is one more horizon holder to monitor (Change Data Capture).

Distributed data: replicas, caches and distributed SQL ​

  • Physical replicas: VACUUM on the primary produces cleanup WAL that conflicts with long standby queries. Either cancel them (max_standby_streaming_delay) or hold the primary's horizon (hot_standby_feedback). There is no third option on the same replica.
  • Logical replicas and CDC: slots hold catalog_xmin; a consumer down for a weekend can bloat catalogs and fill the disk with WAL.
  • Caches: a cache in front of a hot row reduces reads, not versions; to reduce versions batch the writes (counters in Redis, flushed periodically).
  • Distributed SQL: CockroachDB keeps MVCC versions per key and garbage-collects them after gc.ttlseconds; backups and changefeeds set protected timestamps that act like PostgreSQL's horizon holders. Spanner keeps versions for its version retention period to serve stale reads. Same trade, different knob. See Distributed SQL.

Scaling path: 1×, 10×, 100× ​

  • 1×: defaults, timeouts per role, a dashboard with n_dead_tup, last_autovacuum, age(datfrozenxid), oldest backend_xmin.
  • 10×: per-table autovacuum for the top ten tables, autovacuum_vacuum_cost_limit raised, autovacuum_max_workers 5–8, HOT-friendly schema for counters, partition append-only tables, alert on anti-wraparound runs lasting hours.
  • 100×: write rate makes anti-wraparound vacuums routine: freeze early (insert-based vacuum, low autovacuum_freeze_min_age on append-only partitions), keep partitions small enough to vacuum in minutes, run analytics off the primary without feedback, consider sharding hot tables (Billion-Row Tables, Partitioning & Sharding). Track xid consumption per day as a capacity metric.

Lab ​

PostgreSQL 17 or later in Docker, two psql terminals. Expected outputs in comments are the deterministic parts (exact xids and sizes will differ on your machine).

Setup.

bash
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
# terminal A and B:  docker exec -it pg psql -U postgres
sql
CREATE EXTENSION pgstattuple;
CREATE EXTENSION pageinspect;
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100), (2, 100);
CREATE TABLE bloat (id int PRIMARY KEY, payload text) WITH (autovacuum_enabled = false);
INSERT INTO bloat SELECT g, repeat('x', 200) FROM generate_series(1, 100000) g;
VACUUM ANALYZE bloat;

Experiment 1: watch xmin, xmax and ctid.

sql
-- A
SELECT ctid, xmin, xmax, * FROM accounts WHERE id = 1;   -- (0,1) | 750 | 0 | 1 | 100
BEGIN;
UPDATE accounts SET balance = 70 WHERE id = 1;
SELECT ctid, xmin, xmax, * FROM accounts WHERE id = 1;   -- (0,3) | 751 | 0 | 1 | 70   (new version)
-- B (A has not committed)
SELECT ctid, xmin, xmax, * FROM accounts WHERE id = 1;   -- (0,1) | 750 | 751 | 1 | 100 (old version, xmax = A's xid)
-- A
COMMIT;
SELECT lp, t_xmin, t_xmax, t_ctid FROM heap_page_items(get_raw_page('accounts', 0));
-- lp 1: t_xmax = 751, t_ctid = (0,3)   lp 3: t_xmax = 0, t_ctid = (0,3)

Experiment 2: HOT vs non-HOT.

sql
SELECT pg_stat_reset_single_table_counters('accounts'::regclass);
UPDATE accounts SET balance = balance + 1;              -- balance is not indexed -> HOT
CREATE INDEX accounts_balance_idx ON accounts (balance);
UPDATE accounts SET balance = balance + 1;              -- indexed column changes -> not HOT
SELECT pg_sleep(1);
SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_user_tables WHERE relname = 'accounts';
-- n_tup_upd = 4, n_tup_hot_upd = 2 (if the first two versions fit on the page)

Experiment 3: create bloat and measure it with pgstattuple.

sql
SELECT pg_size_pretty(pg_relation_size('bloat'));                -- note this size
UPDATE bloat SET payload = repeat('y', 200);                      -- every row: new version
SELECT pg_size_pretty(pg_relation_size('bloat'));                -- about double
SELECT dead_tuple_percent, free_percent FROM pgstattuple('bloat'); -- dead ~50%
VACUUM bloat;
SELECT dead_tuple_percent, free_percent FROM pgstattuple('bloat'); -- dead ~0, free ~50%: space reusable, file same size
UPDATE bloat SET payload = repeat('z', 200);
SELECT pg_size_pretty(pg_relation_size('bloat'));                -- grows little or not at all: free space reused
VACUUM FULL bloat;
SELECT pg_size_pretty(pg_relation_size('bloat'));                -- back to about the size noted at the start

Experiment 4: hold a transaction and watch n_dead_tup not drop. A bare BEGIN at Read Committed holds nothing; the holder must have a snapshot or an xid.

sql
-- B: hold a snapshot
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM accounts;          -- snapshot taken now and kept
-- A
UPDATE bloat SET payload = 'a' WHERE id <= 10000;
VACUUM (VERBOSE) bloat;                 -- the tuples line counts ~10000 dead but not yet removable
SELECT pg_sleep(1);
SELECT n_dead_tup FROM pg_stat_user_tables WHERE relname = 'bloat';   -- ~10000, still there
SELECT pid, state, backend_xmin, age(backend_xmin) FROM pg_stat_activity WHERE backend_xmin IS NOT NULL;
-- B's row: state 'idle in transaction', backend_xmin not null
-- B
COMMIT;
-- A
VACUUM bloat;
SELECT pg_sleep(1);
SELECT n_dead_tup FROM pg_stat_user_tables WHERE relname = 'bloat';   -- 0

Experiment 5: idle in transaction timeout.

sql
-- B
SET idle_in_transaction_session_timeout = '5s';
BEGIN; SELECT pg_current_xact_id();     -- now holds an xid
-- wait 6 seconds, then:
SELECT 1;   -- FATAL: terminating connection due to idle-in-transaction timeout

Experiment 6: watch age() climb. Each pg_current_xact_id() in its own transaction consumes one xid.

sql
SELECT age(datfrozenxid) FROM pg_database WHERE datname = current_database();   -- e.g. 760
DO $$ BEGIN FOR i IN 1..1000 LOOP PERFORM pg_current_xact_id(); COMMIT; END LOOP; END $$;
SELECT age(datfrozenxid) FROM pg_database WHERE datname = current_database();   -- ~1000 higher
SELECT age(relfrozenxid) FROM pg_class WHERE relname = 'bloat';                 -- also ~1000 higher
VACUUM (FREEZE) bloat;
SELECT age(relfrozenxid) FROM pg_class WHERE relname = 'bloat';                 -- near 0

Common misconceptions ​

BeliefReality
"DELETE frees disk space."It stamps xmax. VACUUM makes the space reusable; only a rewrite or an empty file tail returns it to the OS.
"VACUUM FULL is the better VACUUM; run it regularly."It takes ACCESS EXCLUSIVE for the whole run and the table regrows. Tune autovacuum instead; rewrite once, online, when needed.
"Autovacuum running means bloat is handled."One idle in transaction session, prepared transaction or stale replication slot makes it remove nothing.
"Read-only transactions cannot cause bloat."A Repeatable Read or Serializable snapshot holds the horizon for its whole life, in every table of the database.
"n_dead_tup = 0 means no bloat."It counts dead tuples not yet vacuumed; free space left behind by vacuum is invisible to it. Use pgstattuple.
"Updating one small column is cheap."Without HOT, a full new tuple plus one entry in every index.
"Lower fillfactor always helps."Only for tables updated in place without index changes; it wastes space on insert-only tables.
"Disable autovacuum on big tables and vacuum at night."Spikes bloat the table between runs, and anti-wraparound autovacuum runs anyway, at the worst time.
"Wraparound means single-user mode and VACUUM FULL."The manual says neither: end holders, then plain VACUUM. VACUUM FULL needs an xid and fails.
"hot_standby_feedback is free."It moves the replica's long queries' cost onto the primary as bloat.
"Killing the query (pg_cancel_backend) frees the horizon."An idle in transaction session has no query; use pg_terminate_backend or let the timeout fire.
"InnoDB has no such problem."It has the same one in the undo log: history list length grows and purge lags behind a long transaction.
"REINDEX locks the table so we cannot do it online."REINDEX CONCURRENTLY blocks no writes; it is slower and waits for old transactions.

Cheat sheet ​

TopicRemember
UPDATE= new tuple + xmax on the old one + t_ctid link
Visibilityxmin committed and before my snapshot, xmax empty/aborted/after my snapshot
Snapshotxmin:xmax:xip_list; per statement in RC, per transaction in RR/Serializable
Horizon holdersbackend_xmin/backend_xid, prepared xacts, slot xmin/catalog_xmin, standby feedback
HOTNo indexed column changed + room on the page; raise room with fillfactor
Triggerdead > min(100M, 50 + 0.2 × reltuples); lower scale factor per big table
Speedautovacuum_vacuum_cost_limit up, cost_delay down; limit is shared by workers
Rewritepg_repack / REPACK CONCURRENTLY online; VACUUM FULL only offline
Index bloatpgstatindex → REINDEX INDEX CONCURRENTLY
Measuren_dead_tup estimate; pgstattuple exact; wiki query loose
Freezingmin age 50M, table age 150M, forced at 200M, failsafe 1.6B
Wraparound stop100M left warns, 3M left blocks writes; runbook: prepared → long xacts → slots → VACUUM
Timeoutsidle_in_transaction_session_timeout (25P03), transaction_timeout (25P04, 17+) per role
InnoDBUndo log + purge; watch history list length
Oracle / SQL ServerUndo + ORA-01555 snapshot too old / version store in tempdb or PVS

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — You run UPDATE t SET note = 'x' WHERE id = 1 on a table with three indexes, none on note. How many index entries are written if the page has room? If it does not? Good to know ​

Answer

Answer: With room on the page it is a HOT update: zero index entries. Without room the new tuple goes to another page and every one of the three indexes gets a new entry.

2 — What does xmax set on a live, visible row usually mean? Good to know ​

Answer

Answer: A row lock (FOR UPDATE/FOR SHARE, lock-only bit in t_infomask, possibly a multixact) or an updater/deleter that aborted. A committed deleter would make the row invisible.

3 — A session shows state = 'idle in transaction' and backend_xmin is null but backend_xid is set. Does it hold back vacuum? Good to know ​

Answer

Answer: Yes. A running xid counts toward the xmin horizon: other sessions' snapshots list it in xip_list, so the horizon cannot advance past it and versions deleted after it started stay "recently dead".

4 — Why does VACUUM on a 10 GB table with 3 GB dead leave a 10 GB file? Must-know ​

Answer

Answer: Plain VACUUM makes space reusable inside the file and only truncates fully empty pages at the end. Shrinking needs a rewrite (VACUUM FULL, REPACK, pg_repack).

5 — With defaults, when is a 50-million-row table autovacuumed? Important ​

Answer

Answer: After 50 + 0.2 × 50M ≈ 10,000,050 dead tuples (below the 100M cap), or on insert/age triggers.

6 — Why does adding autovacuum workers not make vacuum faster overall? Important ​

Answer

Answer: autovacuum_vacuum_cost_limit is shared proportionally among running workers; total I/O budget stays the same unless the limit is raised (or per-table limits are set).

7 — What are the four steps of the manual's wraparound runbook, and what must you not run? Good to know ​

Answer

Answer: Resolve old prepared transactions; end long-running transactions; drop old replication slots; run plain VACUUM (database-wide or oldest tables first) as superuser. Do not use VACUUM FULL (needs an xid), VACUUM FREEZE (more work than needed) or single-user mode.

8 — A replica with hot_standby_feedback = on runs a 4-hour query. What happens on the primary? Important ​

Answer

Answer: The replica reports its xmin; the primary's horizon is held back for 4 hours, so dead tuples accumulate (bloat) as if the query ran on the primary.

9 — How does InnoDB's equivalent of a long transaction show up, and where? Good to know ​

Answer

Answer: Purge cannot discard update undo needed by the oldest read view; "History list length" in SHOW ENGINE INNODB STATUS grows, undo tablespaces grow, and reads walk longer version chains.

10 — What is the difference between n_dead_tup and pgstattuple's free_percent? Good to know ​

Answer

Answer: n_dead_tup estimates dead tuples not yet removed. free_percent is space already freed (by vacuum) but still in the file. A table can have n_dead_tup = 0 and 60% free space.

11 — Why is ctid unsafe as a row identifier between two statements? Important ​

Answer

Answer: Any update creates a new version at a new ctid, and VACUUM FULL, CLUSTER or REPACK move every row.

Glossary ​

TermMeaning
MVCCMultiversion concurrency control: readers see a consistent version while writers create new ones
Tuple versions (tuple / row version)One physical copy of a row in a heap page
xminxid of the transaction that inserted the tuple (t_xmin)
xmaxxid that deleted/updated or locked the tuple, or a multixact id (t_xmax)
cmin / cmaxCommand id within the inserting/deleting transaction; one shared field, may hold a combocid
t_ctid chain (t_ctid / ctid)Physical (block, item) address; points to the newer version after an update
t_infomaskTuple flag bits: hint bits, frozen, lock-only, HOT flags
Infomask hint bitsXMIN_COMMITTED, XMIN_ABORTED, XMAX_COMMITTED, XMAX_ABORTED cached commit status in t_infomask
xid32-bit transaction id, assigned at the first write
xid864-bit non-wrapping xid used by functions like pg_current_xact_id()
Virtual transaction idId of a transaction that has not written; does not consume an xid
CLOG / pg_xactCommit log: 2 bits of status per xid (pg_clog before PostgreSQL 10)
Snapshotxmin:xmax:xip_list deciding which xids count as finished
xip_listTransactions in progress when the snapshot was taken
Visibility rulesxmin committed-before-snapshot and xmax not committed-before-snapshot
Dead tupleVersion invisible to every possible snapshot; removable by VACUUM
Recently deadDeleted version some snapshot may still need; "not yet removable"
xmin horizonOldest xid still needed by any snapshot, session, slot or prepared transaction
backend_xmin / backend_xidpg_stat_activity columns: a session's snapshot xmin and its own xid
Idle in transactionSession state: transaction open, no query running
Long-running transactionsTransaction whose snapshot or xid is old enough to block cleanup
Replication slotServer-side marker that retains WAL and, via xmin/catalog_xmin, old versions for a consumer
hot_standby_feedbackStandby setting that reports its oldest xmin to the primary
Prepared transactionTwo-phase-commit transaction after PREPARE TRANSACTION; holds its xid until resolved
HOT (heap-only tuple)Update on the same page with no index change; prunable without VACUUM
Page pruningOn-page removal of dead HOT chain members during normal access
fillfactorTable/index storage parameter: % of page filled on insert
VACUUMRemoves dead tuples and index entries, updates FSM/VM, freezes old tuples
VACUUM FULLRewrites table and indexes under ACCESS EXCLUSIVE
REPACKBuilt-in rewrite command in the current manual; CONCURRENTLY locks only at the swap
pg_repackExtension for online rewrites using a trigger and log table; needs a PK or unique not-null index
CLUSTERRewrite ordered by an index
Autovacuum launcherPersistent process that starts workers per database every autovacuum_naptime
Autovacuum workerProcess that runs VACUUM/ANALYZE on one database's tables
autovacuum_vacuum_scale_factor / autovacuum_vacuum_thresholdFraction of rows and base count of dead tuples that trigger vacuum
autovacuum_vacuum_cost_delay / autovacuum_vacuum_cost_limitSleep and budget for cost-based throttling
Free space map (FSM)_fsm fork recording free space per page for reuse
Visibility map (VM)_vm fork with all-visible and all-frozen bits per page; enables index-only scans and skipping
BloatDead and free space far beyond the working margin
Table bloat / index bloatBloat in the heap / in index pages (B-trees do not shrink by themselves)
Table bloat estimationStatistics-based query (wiki, check_postgres); loose
pgstattupleExtension: exact tuple-level and index statistics (pgstattuple, pgstattuple_approx, pgstatindex)
n_dead_tup / last_autovacuumpg_stat_user_tables columns: estimated dead tuples; time of last autovacuum
REINDEX CONCURRENTLYOnline index rebuild that blocks no writes
TOAST and vacuum (TOAST)Out-of-line storage for large values in a separate, separately vacuumed table
FreezingMarking tuples as older than every normal xid (flag bit since 9.4)
FrozenTransactionIdSpecial xid 2, older than every normal xid
vacuum_freeze_min_ageAge above which VACUUM freezes tuples (50M)
Aggressive vacuumScan of every page not all-frozen; advances relfrozenxid
relfrozenxid / datfrozenxidOldest unfrozen xid per table / database; age() measures distance
Anti-wraparound vacuum (anti-wraparound autovacuum)Forced at autovacuum_freeze_max_age; "(to prevent wraparound)"; not cancelled by locks
vacuum_failsafe_ageAge (1.6B) where VACUUM drops throttling and skips index work
xid wraparound32-bit counter cycling so unfrozen old rows would appear to be in the future
MultixactId in xmax standing for several row lockers; members in pg_multixact
mxid_ageAge of a multixact id (relminmxid, datminmxid)
Undo logInnoDB/Oracle storage of before-images used for rollback and consistent reads
Rollback segmentInnoDB/Oracle structure holding undo logs
PurgeInnoDB background removal of delete-marked rows and undo no longer needed
History list lengthInnoDB backlog of undo pages awaiting purge
Read viewInnoDB's snapshot
Snapshot too oldOracle ORA-01555: needed undo already overwritten
UNDO_RETENTIONOracle minimum undo retention in seconds
SQL Server version storeSQL Server row versions in tempdb, or persistent version store (PVS) with ADR
idle_in_transaction_session_timeoutTerminates sessions idle inside a transaction (25P03)
transaction_timeoutPostgreSQL 17+ cap on transaction duration (25P04)

References ​

Built by Morteza Negahi