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 for | Go to |
|---|---|
| The whole topic in three tables | Everything in one minute |
| Why PostgreSQL keeps old versions at all, and the trade-off | Why MVCC needs a vacuum |
| Stonebraker 1987, PostgreSQL 6.5 | Where it comes from |
xmin, xmax, cmin, cmax, t_ctid, hint bits | Tuple versions and the header |
| Why an UPDATE writes a whole new row | UPDATE = insert + delete |
pg_xact, CLOG, lazy xid assignment | Transaction IDs and the commit log |
Snapshot xmin:xmax:xip_list and the visibility decision | Snapshots and visibility |
| Dead tuples, the xmin horizon, what holds it back | Dead tuples and the xmin horizon |
HOT, fillfactor, n_tup_hot_upd | HOT updates and fillfactor |
| VACUUM vs VACUUM FULL vs REPACK vs pg_repack | VACUUM in all its forms |
| Launcher, workers, thresholds, cost delay/limit | Autovacuum |
Table bloat, index bloat, estimation, pgstattuple | Bloat |
| TOAST tables and vacuum | TOAST and vacuum |
Freezing, age(datfrozenxid), anti-wraparound, failsafe | Freezing and xid wraparound |
pg_multixact, mxid_age | Multixacts |
| InnoDB undo, history list length, Oracle "snapshot too old", SQL Server version store | Per-engine behaviour |
| Every knob, every view, every message verbatim | Mechanics |
| Tuning, killing idle sessions, rewrites, index bloat, wraparound runbook | Solving the classic problems |
| What to do for which situation | Choosing what to do |
| Monolith → microservices → replicas → scale | In architecture |
| Reproduce it in psql | Lab |
| Wrong beliefs, cheat sheet, questions, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
What happens to a row.
| Statement | What PostgreSQL writes | Old version | Index work |
|---|---|---|---|
INSERT | New tuple, xmin = your xid, xmax = 0 | none | One entry per index |
DELETE | Nothing new; stamps xmax = your xid on the tuple | Stays on the page until VACUUM | None now; VACUUM removes entries later |
UPDATE | New full tuple with new xmin; old tuple gets xmax and t_ctid → new | Stays, now dead once you commit and no snapshot needs it | New entry in every index, unless HOT |
UPDATE (HOT) | New tuple on the same page, flagged heap-only | Pruned on the page, even by a SELECT | None |
ROLLBACK | Nothing; the xid is marked aborted in pg_xact | The tuples you wrote are dead immediately | None |
The words.
| Term | In plain words | Where you see it |
|---|---|---|
| Tuple / row version | One physical copy of a row | SELECT ctid, xmin, xmax, * FROM t |
| Dead tuple | A version no running snapshot can see | pg_stat_user_tables.n_dead_tup, pgstattuple |
| xmin horizon | The oldest xid any snapshot, session, slot or prepared transaction still needs | pg_stat_activity.backend_xmin, pg_replication_slots.xmin |
| Bloat | Space held by dead tuples and empty slots beyond what the live data needs | pgstattuple, wiki estimate query |
| HOT update | Update that stays on the same page and touches no index | n_tup_hot_upd |
| Freezing | Marking old tuples as "visible to everyone forever" so their xid can be recycled | age(relfrozenxid), age(datfrozenxid) |
| Wraparound | The 32-bit xid counter coming back round, so old rows would look like the future | WARNING: database "mydb" must be vacuumed within ... transactions |
The three things to do.
| Situation | Do this |
|---|---|
| Any application | Keep 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 table | Per-table autovacuum_vacuum_scale_factor / threshold, faster cost settings, lower fillfactor if updates miss HOT |
| Monitoring | Alert 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 tempdb | Table holds every version until VACUUM |
| Update writes a small undo record | Update writes a whole new tuple (plus index entries unless HOT) |
| Rollback must apply undo, can be slow | Rollback is instant: the xid is marked aborted |
| Old readers reconstruct rows by walking undo | Old readers read the old tuple directly |
| Cleanup: purge threads, undo retention | Cleanup: VACUUM / autovacuum |
| Long transaction grows the undo / version store | Long transaction grows tables and indexes (bloat) |
| Failure mode: undo full, ORA-01555, history list length | Failure 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
- "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). - "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.
- "VACUUM FULL is the thorough VACUUM; run it nightly." It rewrites the table under an
ACCESS EXCLUSIVElock that blocks evenSELECT, 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 column | Meaning |
|---|---|
t_xmin / xmin | xid of the inserting transaction |
t_xmax / xmax | xid of the deleting or updating transaction, or of a row locker; 0 if none; may hold a multixact id |
t_cid / cmin, cmax | Command 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_infomask2 | Flag 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 |
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.
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.
| Product | Where version metadata lives |
|---|---|
| PostgreSQL | In every heap tuple header (xmin, xmax, t_ctid) |
| MySQL InnoDB | Hidden 6-byte DB_TRX_ID and 7-byte DB_ROLL_PTR in each clustered-index record; old versions in undo |
| Oracle | Interested 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.
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).
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 entriesReal 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.
| Product | What an update costs |
|---|---|
| PostgreSQL | New full tuple + one entry per index (unless HOT) + WAL for both |
| MySQL InnoDB | In-place change of the clustered record + undo record; secondary indexes change only if their columns change (delete-mark + insert) |
| Oracle | In-place change + undo + redo |
| SQL Server | In-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).
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 lookupReal 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.
| Product | Where commit status lives |
|---|---|
| PostgreSQL | pg_xact (CLOG), 2 bits per xid, plus pg_subtrans for subtransactions and pg_multixact for multixacts |
| MySQL InnoDB | Transaction system and undo log headers; readers compare DB_TRX_ID to the read view |
| Oracle | Transaction table in the undo segment header; delayed block cleanout plays the hint-bit role |
| SQL Server | Transaction sequence numbers on versions in the version store |
Fix / how to use it:
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 nowSnapshots 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:
- its
xminis committed and finished-before-me (or is my own xid and was inserted by an earlier command, percmin); and - its
xmaxis 0, aborted, a lock-only marker, or not finished-before-me (or is my own xid from a later command, percmax).
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.
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 removableReal 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).
| Product | What a snapshot is | How long it lives |
|---|---|---|
| PostgreSQL | xmin:xmax:xip_list | Statement (RC) or transaction (RR, Serializable) |
| MySQL InnoDB | Read view: m_low_limit_id, m_up_limit_id, list of active trx ids | Statement (RC) or from first consistent read to commit (RR, default) |
| Oracle | SCN (system change number) | Statement (default) or transaction (SERIALIZABLE, READ ONLY) |
| SQL Server | Transaction sequence number | Statement (RCSI) or transaction (SNAPSHOT) |
Fix / how to use it:
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:
| Holder | Where to see it | Typical cause |
|---|---|---|
| Running and idle in transaction sessions | pg_stat_activity.backend_xmin, backend_xid, xact_start, state | Long 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 slots | pg_replication_slots.xmin, catalog_xmin | A logical decoding consumer (Debezium, CDC) that stopped; a physical slot for a dead replica |
Hot standby queries via hot_standby_feedback = on | Standby's backend_xmin reported through the walsender (pg_stat_replication.backend_xmin) | Long analytics queries on a replica |
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 removedReal 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.
| Product | What holds old versions alive | Where you see it |
|---|---|---|
| PostgreSQL | Oldest snapshot/xid, prepared xacts, replication slots, standby feedback | pg_stat_activity, pg_prepared_xacts, pg_replication_slots |
| MySQL InnoDB | Oldest read view; undo for it cannot be purged | SHOW ENGINE INNODB STATUS "History list length", information_schema.innodb_trx |
| Oracle | Undo needed by the oldest query (bounded by UNDO_RETENTION unless guaranteed) | V$UNDOSTAT, V$TRANSACTION |
| SQL Server | Oldest active snapshot transaction | sys.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.
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".
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 chainReal 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.
| Product | Equivalent |
|---|---|
| PostgreSQL | HOT + fillfactor + page pruning |
| MySQL InnoDB | Not needed: in-place update; secondary indexes untouched unless their columns change. MERGE_THRESHOLD and page fill are separate concerns |
| Oracle | PCTFREE reserves block space for row growth (avoids row migration) |
| SQL Server | FILLFACTOR on indexes (leaf page free space), not for version placement |
Fix:
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:
| Command | What it does | Lock | Gives disk back to OS | Extra disk |
|---|---|---|---|---|
VACUUM | Removes dead tuples and their index entries, updates FSM and visibility map, freezes old tuples | SHARE 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 tuple | Same | Same | None |
VACUUM FULL | Rewrites table and rebuilds all indexes | ACCESS EXCLUSIVE for the whole run (blocks SELECT) | Yes | About the table + indexes size |
CLUSTER | Rewrite in index order | ACCESS EXCLUSIVE | Yes | Same |
REPACK (current manual) | Rewrite, optionally USING INDEX to cluster | ACCESS EXCLUSIVE | Yes | Same |
REPACK (CONCURRENTLY) | Online rewrite; lock "held only while swapping the table and index files" | Short ACCESS EXCLUSIVE at the end | Yes | Same |
pg_repack extension | Builds a copy, captures concurrent changes with a trigger into a log table, swaps | Short ACCESS EXCLUSIVE at start and end; table needs a PRIMARY KEY or not-null unique index | Yes | Same |
TRUNCATE | Drops all rows at once | ACCESS EXCLUSIVE | Yes | None ("strict MVCC semantics are violated") |
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.
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 runReal 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.
| Product | Reclaim space online | Shrink file |
|---|---|---|
| PostgreSQL | VACUUM / autovacuum | VACUUM FULL, CLUSTER, REPACK [CONCURRENTLY], pg_repack |
| MySQL InnoDB | Purge (automatic) | OPTIMIZE TABLE / ALTER TABLE ... FORCE (online DDL rebuild) |
| Oracle | Automatic (undo); space reused in segment | ALTER TABLE ... SHRINK SPACE, MOVE ONLINE |
| SQL Server | Ghost cleanup task, version store cleanup | ALTER INDEX ... REBUILD (ONLINE = ON), DBCC SHRINKFILE |
| SQLite | PRAGMA auto_vacuum, freelist | VACUUM (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
dead tuples > Minimum(autovacuum_vacuum_max_threshold,
autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuples)
defaults: 100,000,000 50 + 0.2 * reltuplesor 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.
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% biggerReal 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.
| Product | Background cleanup | Main knobs |
|---|---|---|
| PostgreSQL | Autovacuum launcher + workers | autovacuum_max_workers, autovacuum_naptime, autovacuum_vacuum_scale_factor, autovacuum_vacuum_threshold, autovacuum_vacuum_cost_delay, autovacuum_vacuum_cost_limit |
| MySQL InnoDB | Purge coordinator + purge threads | innodb_purge_threads (1 if ≤16 logical CPUs, else 4), innodb_purge_batch_size (300), innodb_max_purge_lag (0 = no throttling) |
| SQL Server | Ghost cleanup, version store cleanup thread | Mostly automatic |
| Oracle | Undo is reused automatically | UNDO_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:
| Method | Cost | What you get |
|---|---|---|
pg_stat_user_tables (n_live_tup, n_dead_tup, last_autovacuum, autovacuum_count) | Free | Dead 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-visible | Approximate dead_tuple_percent, approx_free_percent |
pgstattuple('t') | Reads every page | Exact tuple_percent, dead_tuple_percent, free_percent |
pgstatindex('idx') | Reads the whole index | avg_leaf_density (about 90 on a fresh B-tree), leaf_fragmentation |
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.
| Product | Where bloat shows up | Measure |
|---|---|---|
| PostgreSQL | Heap, indexes, TOAST tables | pgstattuple, pgstatindex, wiki estimate |
| MySQL InnoDB | Undo tablespaces (history), fragmented clustered index after deletes | information_schema.INNODB_TABLESTATS, DATA_FREE in information_schema.TABLES |
| SQL Server | Version store in tempdb (or PVS with ADR), index fragmentation | sys.dm_db_index_physical_stats, sys.dm_tran_version_store_space_usage |
| Oracle | Undo tablespace growth; segment space below high water mark | DBMS_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.
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.
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/minReal 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.
| Product | Large values |
|---|---|
| PostgreSQL | TOAST table per relation, vacuumed separately |
| MySQL InnoDB | Off-page LOB pages; old LOB versions also need purge |
| SQL Server | LOB pages; only the changed fragment goes to the version store |
| Oracle | LOB segments with their own undo/retention (RETENTION, PCTVERSION) |
Fix: keep frequently changing fields out of big documents; check both sizes.
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:
| Knob | Default | Meaning |
|---|---|---|
vacuum_freeze_min_age | 50 million | Tuples older than this get frozen when VACUUM visits their page |
vacuum_freeze_table_age | 150 million | Above this age(relfrozenxid), VACUUM runs aggressively (visits every page not all-frozen); capped at 95% of autovacuum_freeze_max_age |
autovacuum_freeze_max_age | 200 million | Forces an anti-wraparound autovacuum, "even if autovacuum is disabled" |
vacuum_failsafe_age | 1.6 billion | VACUUM drops cost delay, skips index vacuuming and uses all of shared buffers to finish |
vacuum_max_eager_freeze_failure_rate | 0.03 | How much eager freezing a normal vacuum may attempt on all-visible pages |
| Warning point | 100 million xids before wraparound | WARNING: database "mydb" must be vacuumed within 99985967 transactions |
| Stop point | 3 million xids before wraparound | ERROR: 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.
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 runsReal 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.
| Product | Counter width | Wraparound handling |
|---|---|---|
| PostgreSQL | 32-bit xid in tuples (64-bit xid8 in functions) | Freezing via VACUUM; warnings at 100M left, stop at 3M left |
| MySQL InnoDB | 48-bit (6-byte DB_TRX_ID) | Not a practical concern |
| Oracle | SCN, a much wider counter | No freezing step |
| SQL Server | 64-bit transaction sequence numbers | Not a concern |
| CockroachDB, Spanner | Hybrid logical / TrueTime timestamps | Not a concern; old versions removed after gc.ttlseconds (CockroachDB) |
Fix: monitor age, keep autovacuum fast enough, and know the runbook in Wraparound emergency.
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".
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/replacedReal 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.
| Product | Multiple lockers on one row |
|---|---|
| PostgreSQL | Multixact id in xmax, members in pg_multixact |
| MySQL InnoDB | Lock structures in memory (lock system), not on the row |
| Oracle | ITL slots in the block header |
| SQL Server | Lock 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 heap | InnoDB undo | |
|---|---|---|
| Where old versions live | In the table pages, next to current ones | In undo tablespaces (rollback segments) |
| Cost of an update | New full tuple; new index entries unless HOT | In-place change plus a smaller undo record |
| Rollback | Nothing to undo; the aborted xid is just invisible | Apply undo records (long rollback after a big update) |
| Reading old data | Direct; old tuple is on the page | Rebuild from the undo chain (slow with long chains) |
| Reading current data | May have to skip dead versions until vacuumed | Always the newest record first |
| Cleanup | VACUUM / autovacuum | Purge threads (innodb_purge_threads) |
| Backlog metric | n_dead_tup, xmin horizon age | History list length (SHOW ENGINE INNODB STATUS) |
| What a long transaction grows | Tables and indexes (bloat) | Undo tablespaces; reads slow down walking versions |
| Counter wraparound | 32-bit xid, needs freezing | 48-bit trx id, no freezing |
| Secondary index | Points to heap TID; dead entries until vacuum | Points 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
| Product | Old versions live in | Cleanup | Long-transaction symptom | Key metric / knob |
|---|---|---|---|---|
| PostgreSQL | Heap pages (in-table), TOAST | VACUUM / autovacuum | Table and index bloat; xid age | n_dead_tup, backend_xmin, age(datfrozenxid) |
| MySQL InnoDB | Undo tablespaces | Purge threads | History list length, undo growth, slow reads | innodb_purge_threads, innodb_max_purge_lag |
| Oracle | Undo segments | Automatic reuse after retention | ORA-01555 snapshot too old | UNDO_RETENTION, RETENTION GUARANTEE |
| SQL Server | Version store (tempdb, or PVS in the database with ADR) | Version cleanup thread | tempdb / PVS growth, errors 3966/3967 | sys.dm_tran_version_store_space_usage |
| SQLite | No MVCC for writers; WAL mode keeps old pages in the WAL for readers | Checkpoint | WAL file grows while a reader holds an old end mark | PRAGMA wal_checkpoint, wal_autocheckpoint |
| MongoDB (WiredTiger) | Update chains in cache, history store on disk | Eviction, history store cleanup | Cache pressure; transactions aborted after transactionLifetimeLimitSeconds (60 s) | WiredTiger cache stats |
| CockroachDB | MVCC versions per key in Pebble | MVCC GC after gc.ttlseconds | Old versions kept for the TTL (and protected timestamps for backups/changefeeds) | gc.ttlseconds |
| Redis | No MVCC (single-threaded command execution) | n/a | n/a | n/a |
Mechanics
Every knob in one table
| Parameter | Default (PostgreSQL 19 docs) | Scope | What it changes |
|---|---|---|---|
autovacuum | on | server | Daemon on/off (anti-wraparound runs anyway) |
autovacuum_max_workers | 3 | server (reload) | Concurrent workers; slots reserved by autovacuum_worker_slots (typically 16) |
autovacuum_naptime | 1min | server | Delay between runs per database |
autovacuum_vacuum_threshold | 50 | server, per table | Base dead-tuple count |
autovacuum_vacuum_scale_factor | 0.2 | server, per table | Fraction of reltuples added |
autovacuum_vacuum_max_threshold | 100,000,000 | server, per table | Cap on the computed threshold |
autovacuum_vacuum_insert_threshold / _insert_scale_factor | 1000 / 0.2 | server, per table | Insert-driven vacuums (freezing, visibility map) |
autovacuum_analyze_threshold / _scale_factor | 50 / 0.1 | server, per table | When to ANALYZE |
autovacuum_vacuum_cost_delay | 2 ms | server, per table | Sleep after reaching the cost limit |
autovacuum_vacuum_cost_limit | -1 (uses vacuum_cost_limit = 200) | server, per table | Cost units before sleeping, shared among workers |
vacuum_cost_delay | 0 (manual VACUUM unthrottled) | session | Throttle for manual VACUUM |
vacuum_cost_page_hit / _miss / _dirty | 1 / 2 / 20 | server | Cost accounting |
autovacuum_work_mem / maintenance_work_mem | -1 / 64MB | server | Memory for dead tuple references (fewer index passes) |
vacuum_freeze_min_age | 50 million | session, per table (autovacuum_freeze_min_age) | Freeze cutoff |
vacuum_freeze_table_age | 150 million | session, per table | Aggressive vacuum trigger |
autovacuum_freeze_max_age | 200 million | server start, per table (lower only) | Forced anti-wraparound autovacuum |
vacuum_failsafe_age | 1.6 billion | session | Failsafe mode |
autovacuum_multixact_freeze_max_age | 400 million | server start | Multixact forced vacuum |
vacuum_truncate | on | server, per table | Truncate empty tail pages (needs brief ACCESS EXCLUSIVE) |
log_autovacuum_min_duration | 10min | server, per table | Log slow autovacuum runs (0 = log all) |
idle_in_transaction_session_timeout | 0 (off) | session, role, database | Kill sessions idle inside a transaction (SQLSTATE 25P03) |
transaction_timeout | 0 (off), PostgreSQL 17+ | session, role, database | Kill any transaction longer than this (SQLSTATE 25P04) |
statement_timeout | 0 (off) | session, role | Cancel long statements (57014) |
hot_standby_feedback | off | standby | Standby reports its xmin to the primary |
max_standby_streaming_delay | 30s | standby | How long replay waits before cancelling conflicting queries |
max_slot_wal_keep_size | -1 (unlimited) | server | Invalidate slots that retain too much WAL |
idle_replication_slot_timeout | 0 (off) | server | Invalidate slots idle longer than this at checkpoint |
fillfactor (table storage parameter) | 100 | per table | Free 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).
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 advancedViews and functions you will use
| View / function | Columns that matter |
|---|---|
pg_stat_user_tables | n_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_activity | pid, state (idle in transaction, idle in transaction (aborted)), xact_start, backend_xid, backend_xmin, backend_type (autovacuum worker) |
pg_stat_progress_vacuum | phase, heap_blks_total, heap_blks_scanned, index_vacuum_count, indexes_total, indexes_processed |
pg_replication_slots | slot_name, slot_type, active, xmin, catalog_xmin, inactive_since, wal_status |
pg_stat_replication | backend_xmin (from hot_standby_feedback), lag columns |
pg_prepared_xacts | gid, prepared, transaction |
pg_class / pg_database | relfrozenxid, relminmxid, reltuples, relpages, relallvisible, relallfrozen / datfrozenxid, datminmxid |
| Functions | age(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.
| Message | Meaning | Action |
|---|---|---|
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 left | Runbook 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 left | Runbook; read-only works, VACUUM works |
FATAL: terminating connection due to idle-in-transaction timeout (SQLSTATE 25P03) | idle_in_transaction_session_timeout fired | Fix the code path; retry from the start |
FATAL: terminating connection due to transaction timeout (SQLSTATE 25P04) | transaction_timeout fired | Same |
ERROR: canceling statement due to conflict with recovery (SQLSTATE 40001) | Standby replay needed to remove versions your query uses | hot_standby_feedback, longer max_standby_streaming_delay, or run elsewhere |
ERROR: canceling autovacuum task (log) | A lock request conflicted with a normal autovacuum | Stop frequent conflicting DDL/ANALYZE |
autovacuum: VACUUM public.t (to prevent wraparound) (pg_stat_activity.query) | Anti-wraparound run; not cancellable by lock conflicts | Let it finish; do not queue DDL behind it |
ORA-01555: snapshot too old (Oracle) | Needed undo overwritten | Raise undo retention / size, shorten query |
History list length 1234567 (MySQL SHOW ENGINE INNODB STATUS) | Purge backlog | Find the old transaction in innodb_trx |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Big table vacuumed too rarely | Per-table thresholds | ALTER TABLE ... SET (autovacuum_vacuum_scale_factor = 0.01, ...) | Precise, no restart | Must be maintained per table |
| Autovacuum too slow everywhere | Raise cost limit / lower delay | autovacuum_vacuum_cost_limit = 2000 | Fewer backlogs | More I/O during vacuum |
| Cleanup blocked | Kill the horizon holder | pg_terminate_backend, drop slot, rollback prepared | Immediate | That session's work is lost |
| Cleanup blocked again next week | Timeouts per role | idle_in_transaction_session_timeout, transaction_timeout | Self-healing | Long legit jobs need their own role |
| Table bloated after a one-off event | Online rewrite | pg_repack, REPACK CONCURRENTLY | Smaller file, online | 2× disk, extension/PK needed, load |
| Index bloat | REINDEX CONCURRENTLY | Per index | Online | Waits for old transactions; two table scans |
| Hot counter | HOT-friendly schema + batching | Side table, fillfactor, no index on counter | Far fewer dead tuples | Slight staleness |
| Delete-heavy history | Partitioning | DROP/DETACH old partitions | No dead tuples at all | Schema and query changes |
| Wraparound near | Runbook | Holders → plain VACUUM of oldest tables | Restores writes | Hours 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.
-- 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.
// 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
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.
-- 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:
// 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:
// 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()
}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:
// 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
// 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
// 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
// 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.
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.
-- 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:
// 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
// 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.
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 failureHot counters and HOT updates
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
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).
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.
-- 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 itThe 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| OLTP web app | Defaults + idle_in_transaction_session_timeout per role | transaction_timeout, alerts on backend_xmin age | Most bloat comes from one forgotten transaction |
| One huge hot table | Per-table scale factor 0.005–0.02 | Higher per-table cost limit | Default 20% waits too long |
Counters / last_seen | Side table, no index on the counter, fillfactor 70–90 | Batch increments | HOT and fewer versions |
| Job queue table | Small table, aggressive autovacuum, SKIP LOCKED | Delete or partition processed jobs | Constant churn |
| Append-only events | Partition by time | autovacuum_freeze_min_age = 0, insert-based vacuum | No dead tuples; freezing done early |
| Long analytics | Replica without feedback, or a warehouse | statement_timeout on replicas | Keep the primary's horizon free |
| CDC / logical replication | Monitor slot catalog_xmin age | max_slot_wal_keep_size, idle_replication_slot_timeout | Abandoned slots bloat silently |
| Table already bloated once | pg_repack or REPACK CONCURRENTLY once, then fix the cause | Check disk headroom | Rewrites are recovery, not maintenance |
| Bloated index | REINDEX CONCURRENTLY | pgstatindex before and after | Online |
age(datfrozenxid) above 1 billion | Find holders, plain VACUUM unthrottled | vacuumdb --min-xid-age | Restore headroom before the warning |
| MySQL InnoDB history list length growing | Find old transaction in information_schema.innodb_trx | innodb_purge_threads, innodb_max_purge_lag | Same 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), oldestbackend_xmin. - 10×: per-table autovacuum for the top ten tables,
autovacuum_vacuum_cost_limitraised,autovacuum_max_workers5–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_ageon 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.
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
# terminal A and B: docker exec -it pg psql -U postgresCREATE 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.
-- 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.
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.
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 startExperiment 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.
-- 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'; -- 0Experiment 5: idle in transaction timeout.
-- 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 timeoutExperiment 6: watch age() climb. Each pg_current_xact_id() in its own transaction consumes one xid.
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 0Common misconceptions
| Belief | Reality |
|---|---|
| "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
| Topic | Remember |
|---|---|
| UPDATE | = new tuple + xmax on the old one + t_ctid link |
| Visibility | xmin committed and before my snapshot, xmax empty/aborted/after my snapshot |
| Snapshot | xmin:xmax:xip_list; per statement in RC, per transaction in RR/Serializable |
| Horizon holders | backend_xmin/backend_xid, prepared xacts, slot xmin/catalog_xmin, standby feedback |
| HOT | No indexed column changed + room on the page; raise room with fillfactor |
| Trigger | dead > min(100M, 50 + 0.2 × reltuples); lower scale factor per big table |
| Speed | autovacuum_vacuum_cost_limit up, cost_delay down; limit is shared by workers |
| Rewrite | pg_repack / REPACK CONCURRENTLY online; VACUUM FULL only offline |
| Index bloat | pgstatindex → REINDEX INDEX CONCURRENTLY |
| Measure | n_dead_tup estimate; pgstattuple exact; wiki query loose |
| Freezing | min age 50M, table age 150M, forced at 200M, failsafe 1.6B |
| Wraparound stop | 100M left warns, 3M left blocks writes; runbook: prepared → long xacts → slots → VACUUM |
| Timeouts | idle_in_transaction_session_timeout (25P03), transaction_timeout (25P04, 17+) per role |
| InnoDB | Undo log + purge; watch history list length |
| Oracle / SQL Server | Undo + ORA-01555 snapshot too old / version store in tempdb or PVS |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| MVCC | Multiversion 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 |
xmin | xid of the transaction that inserted the tuple (t_xmin) |
xmax | xid that deleted/updated or locked the tuple, or a multixact id (t_xmax) |
cmin / cmax | Command 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_infomask | Tuple flag bits: hint bits, frozen, lock-only, HOT flags |
| Infomask hint bits | XMIN_COMMITTED, XMIN_ABORTED, XMAX_COMMITTED, XMAX_ABORTED cached commit status in t_infomask |
| xid | 32-bit transaction id, assigned at the first write |
xid8 | 64-bit non-wrapping xid used by functions like pg_current_xact_id() |
| Virtual transaction id | Id of a transaction that has not written; does not consume an xid |
CLOG / pg_xact | Commit log: 2 bits of status per xid (pg_clog before PostgreSQL 10) |
| Snapshot | xmin:xmax:xip_list deciding which xids count as finished |
xip_list | Transactions in progress when the snapshot was taken |
| Visibility rules | xmin committed-before-snapshot and xmax not committed-before-snapshot |
| Dead tuple | Version invisible to every possible snapshot; removable by VACUUM |
| Recently dead | Deleted version some snapshot may still need; "not yet removable" |
| xmin horizon | Oldest xid still needed by any snapshot, session, slot or prepared transaction |
backend_xmin / backend_xid | pg_stat_activity columns: a session's snapshot xmin and its own xid |
| Idle in transaction | Session state: transaction open, no query running |
| Long-running transactions | Transaction whose snapshot or xid is old enough to block cleanup |
| Replication slot | Server-side marker that retains WAL and, via xmin/catalog_xmin, old versions for a consumer |
hot_standby_feedback | Standby setting that reports its oldest xmin to the primary |
| Prepared transaction | Two-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 pruning | On-page removal of dead HOT chain members during normal access |
fillfactor | Table/index storage parameter: % of page filled on insert |
| VACUUM | Removes dead tuples and index entries, updates FSM/VM, freezes old tuples |
| VACUUM FULL | Rewrites table and indexes under ACCESS EXCLUSIVE |
| REPACK | Built-in rewrite command in the current manual; CONCURRENTLY locks only at the swap |
| pg_repack | Extension for online rewrites using a trigger and log table; needs a PK or unique not-null index |
| CLUSTER | Rewrite ordered by an index |
| Autovacuum launcher | Persistent process that starts workers per database every autovacuum_naptime |
| Autovacuum worker | Process that runs VACUUM/ANALYZE on one database's tables |
autovacuum_vacuum_scale_factor / autovacuum_vacuum_threshold | Fraction of rows and base count of dead tuples that trigger vacuum |
autovacuum_vacuum_cost_delay / autovacuum_vacuum_cost_limit | Sleep 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 |
| Bloat | Dead and free space far beyond the working margin |
| Table bloat / index bloat | Bloat in the heap / in index pages (B-trees do not shrink by themselves) |
| Table bloat estimation | Statistics-based query (wiki, check_postgres); loose |
| pgstattuple | Extension: exact tuple-level and index statistics (pgstattuple, pgstattuple_approx, pgstatindex) |
n_dead_tup / last_autovacuum | pg_stat_user_tables columns: estimated dead tuples; time of last autovacuum |
| REINDEX CONCURRENTLY | Online index rebuild that blocks no writes |
| TOAST and vacuum (TOAST) | Out-of-line storage for large values in a separate, separately vacuumed table |
| Freezing | Marking tuples as older than every normal xid (flag bit since 9.4) |
FrozenTransactionId | Special xid 2, older than every normal xid |
vacuum_freeze_min_age | Age above which VACUUM freezes tuples (50M) |
| Aggressive vacuum | Scan of every page not all-frozen; advances relfrozenxid |
relfrozenxid / datfrozenxid | Oldest 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_age | Age (1.6B) where VACUUM drops throttling and skips index work |
| xid wraparound | 32-bit counter cycling so unfrozen old rows would appear to be in the future |
| Multixact | Id in xmax standing for several row lockers; members in pg_multixact |
mxid_age | Age of a multixact id (relminmxid, datminmxid) |
| Undo log | InnoDB/Oracle storage of before-images used for rollback and consistent reads |
| Rollback segment | InnoDB/Oracle structure holding undo logs |
| Purge | InnoDB background removal of delete-marked rows and undo no longer needed |
| History list length | InnoDB backlog of undo pages awaiting purge |
| Read view | InnoDB's snapshot |
| Snapshot too old | Oracle ORA-01555: needed undo already overwritten |
UNDO_RETENTION | Oracle minimum undo retention in seconds |
| SQL Server version store | SQL Server row versions in tempdb, or persistent version store (PVS) with ADR |
idle_in_transaction_session_timeout | Terminates sessions idle inside a transaction (25P03) |
transaction_timeout | PostgreSQL 17+ cap on transaction duration (25P04) |
References
- PostgreSQL 19 documentation: Routine Vacuuming, Concurrency Control: Introduction, Transaction Isolation, Heap-Only Tuples, Database Page Layout, System Columns, Transactions and Identifiers, System Information Functions, System Administration Functions, Automatic Vacuuming parameters, Client Connection Defaults, Replication parameters, Hot Standby, Cumulative Statistics, Progress Reporting, VACUUM, REPACK, REINDEX, CREATE TABLE (fillfactor), TOAST, Free Space Map, pgstattuple
- PostgreSQL release notes: 6.5 (9 June 1999), 17
- Michael Stonebraker, "The Design of the POSTGRES Storage System", VLDB 1987. Berkeley technical report version: PDF
- PostgreSQL wiki: Hint Bits, Show database bloat
- pg_repack: documentation
- MySQL 8.4 Reference Manual: InnoDB Multi-Versioning, Purge Configuration
- Oracle: Managing Undo, ORA-01555
- Microsoft: Transaction locking and row versioning guide
- Go:
database/sql,pgx/v5/stdlib - Laravel 13 documentation: Database: Getting Started, Queues, Artisan Console, HTTP Client