Skip to content

PostgreSQL transaction ID wraparound: the emergency runbook

Your log says the database must be vacuumed within N transactions and the number keeps falling. Find what is pinning the XID horizon, clear it, freeze the offending tables, and stop it from recurring.

Your PostgreSQL log has started repeating WARNING: database "appdb" must be vacuumed within 10985967 transactions, and the number shrinks every few minutes. That countdown is real: when it runs out, the server refuses every command that would assign a new transaction ID, and the way back in is a shutdown plus single-user mode. You are in the right place. The first query to run, from any database on the instance, is this one:

SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;

The database at the top of that list is the one the warning is about. Everything below is about finding what is stopping its age from falling and removing it — and in practice it is almost always one session, one replication slot, or one prepared transaction, not a vacuum that is merely slow.

What you’ll accomplish

  • Read the countdown correctly and know how much room is actually left before the server stops.
  • Measure XID age at both levels that matter: age(datfrozenxid) per database and age(relfrozenxid) per table.
  • Identify which of the four possible holders is pinning the horizon, and clear it safely.
  • Run an aggressive freeze on the tables that are genuinely behind and watch the age fall.
  • Retune autovacuum so the same countdown does not start again next quarter.

End state: age(datfrozenxid) back well under autovacuum_freeze_max_age, no warning in the log, and autovacuum keeping up on its own.

Prerequisites

  • A superuser, or a role with enough privilege for each step: pg_monitor to read query text in pg_stat_activity, pg_signal_backend to terminate other sessions, ownership of the tables you vacuum (or MAINTAIN on PostgreSQL 17+), and REPLICATION or superuser to drop a replication slot.
  • Shell access on the database host as the operating-system user that owns the data directory, in case you end up in single-user mode. On a managed service you will not have this — see the boundaries section.
  • PostgreSQL 9.6 through 18. The mechanism is the same across all of them, but the numbers differ slightly by major version: vacuum_failsafe_age only exists from 14 onward, the VACUUM VERBOSE output was reworked in 14 and again in 16, and the exact wording of the refusal message changed in 14. Read the thresholds in this guide as the shape of the problem, and confirm the exact defaults on your build with SHOW autovacuum_freeze_max_age;.

How it works

PostgreSQL stamps every row version with the transaction ID that created it and, on delete or update, the one that removed it. Transaction IDs are 32-bit, so at any moment a backend can only distinguish two billion transactions into the past and two billion into the future — the counter is a circle, not a line. A row whose creating XID drifts more than 2^31 into the past would suddenly appear to be in the future, and the row would vanish from every query.

Freezing is what prevents that. VACUUM marks sufficiently old, still-live rows as frozen, meaning “visible to everyone, no XID comparison needed”. Once a page is fully frozen it stops aging. Each table records the oldest XID it might still have unfrozen in pg_class.relfrozenxid; each database records the minimum of its tables in pg_database.datfrozenxid; the cluster’s real horizon is the minimum across all databases, template0 and template1 included. The age() function converts any of those into “how many transactions ago”, which is the number the warning counts down.

Scale of PostgreSQL transaction ID age showing the four thresholds: 200 million triggers anti-wraparound autovacuum, 1.6 billion triggers the vacuum failsafe, about 2.13 billion starts the log warning, and about 2.14 billion stops the server accepting new writes

The critical point for an emergency: VACUUM cannot advance relfrozenxid past the oldest XID that any part of the system might still need to see. That value — the removable cutoff, or xmin horizon — is held back by open transactions, by replication slots reserving a snapshot for a consumer, and by prepared transactions sitting in the two-phase commit table. If any one of those is stuck at an XID from two months ago, then vacuum can run on every table, every night, forever, and the age will not move by a single transaction. That is why the first real action is never “run VACUUM harder”.

Multixact wraparound is the same failure

Multixact IDs, used when several transactions lock the same row concurrently, are a separate 32-bit counter with the same wraparound problem, the same freezing mechanism, and its own thresholds (autovacuum_multixact_freeze_max_age, default 400 million). The diagnosis is identical with different function and column names:

SELECT datname, mxid_age(datminmxid) AS mxid_age
FROM pg_database
ORDER BY mxid_age DESC;

If that number is the one climbing, work through this guide substituting mxid_age(relminmxid) for age(relfrozenxid). The holders and the fix are the same.

Step-by-step

1. Measure the age per database. Run the opening query again and write down the number, so you can prove later that it moved:

SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;
  datname  |  xid_age
-----------+------------
 appdb     | 2136501244
 postgres  |  173229118
 template1 |  173229118
 template0 |  173229118

Anything above 200 million means an anti-wraparound autovacuum is already being forced. Above about 2.13 billion is the warning band. Above about 2.14 billion the server stops.

2. Find the tables that are actually behind. Connect to the database at the top of that list — relfrozenxid is per-database, so this query only sees the tables of the database you are connected to:

SELECT c.oid::regclass AS relation,
       age(c.relfrozenxid) AS xid_age,
       pg_size_pretty(pg_total_relation_size(c.oid)) AS size
FROM pg_class c
WHERE c.relkind IN ('r', 'm', 't')
ORDER BY xid_age DESC
LIMIT 20;
         relation         |  xid_age   |  size
--------------------------+------------+---------
 public.events            | 2136501244 | 412 GB
 pg_toast.pg_toast_16419  | 2136501244 | 88 GB
 public.audit_log         | 1904772310 | 61 GB
 public.orders            |  187330021 | 4200 MB

Keep 't' in the relkind filter. TOAST tables age independently and are a common blocker that a table-only query hides.

3. Find the session holding the horizon. This is the query that usually ends the investigation:

SELECT pid, datname, usename, state,
       age(backend_xmin) AS xmin_age,
       now() - xact_start AS xact_duration,
       left(query, 50) AS query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY xmin_age DESC
LIMIT 10;
  pid  | datname |  usename  |        state        |  xmin_age  | xact_duration |               query
-------+---------+-----------+---------------------+------------+---------------+------------------------------------
 24817 | appdb   | analytics | idle in transaction | 2136498771 | 61 days 04:12 | SELECT * FROM events WHERE created
 31902 | appdb   | app       | active              |       1183 | 00:00:00.412  | UPDATE orders SET status = $1 WHER

An xmin_age in the billions next to an xact_duration measured in days is your answer. Ask whoever owns that connection to commit or roll back first; if nobody claims it, terminate it:

SELECT pg_terminate_backend(24817);
 pg_terminate_backend
----------------------
 t

Note that pg_cancel_backend() does nothing to an idle-in-transaction session — there is no statement running to cancel. Termination is the only lever.

Decision aid listing the four holders of the PostgreSQL XID horizon — long-running transaction, idle-in-transaction session, abandoned replication slot, prepared transaction — with the catalog view to check and the action to clear each

4. Check for an abandoned replication slot. A slot pins a snapshot on behalf of a consumer that may not exist anymore:

SELECT slot_name, slot_type, database, active, active_pid,
       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;
   slot_name   | slot_type | database | active | active_pid |  xmin_age  | catalog_xmin_age | wal_status
---------------+-----------+----------+--------+------------+------------+------------------+------------
 replica_dc2   | physical  |          | f      |            | 2136499002 |                  | lost
 cdc_warehouse | logical   | appdb    | t      |      12044 |            |            41277 | reserved

active = f with an old xmin is a slot whose replica or CDC consumer is gone. Confirm it is genuinely dead — dropping a slot a live replica still needs will break that replica permanently — then remove it:

SELECT pg_drop_replication_slot('replica_dc2');
 pg_drop_replication_slot
--------------------------

5. Check for a prepared transaction. These are invisible in pg_stat_activity and survive restarts, which is what makes them so easy to miss:

SELECT gid, database, owner, prepared,
       transaction AS xid,
       age(transaction) AS xid_age
FROM pg_prepared_xacts
ORDER BY xid_age DESC;
         gid          | database | owner |           prepared            |   xid    |  xid_age
----------------------+----------+-------+-------------------------------+----------+------------
 _jta_txn_00417a29b1  | appdb    | app   | 2026-05-14 09:21:44.118+00    | 10993511 | 2136497219

A gid prepared two months ago belongs to a transaction coordinator that crashed and never came back. Confirm with whoever owns that coordinator, then resolve it:

ROLLBACK PREPARED '_jta_txn_00417a29b1';
ROLLBACK PREPARED

If max_prepared_transactions is non-zero but nothing in your stack uses two-phase commit, set it to 0 at the next restart so this cannot happen again.

6. Freeze the tables that are behind. Only now, with the horizon released, is vacuum able to do anything. Raise the memory it can use and remove its throttle for this session:

SET maintenance_work_mem = '2GB';
SET vacuum_cost_delay = 0;
VACUUM (FREEZE, VERBOSE) public.events;
INFO:  aggressively vacuuming "appdb.public.events"
INFO:  finished vacuuming "appdb.public.events": index scans: 1
pages: 0 removed, 54001233 remain, 54001233 scanned (100.00% of total)
tuples: 8811243 removed, 1902773311 remain, 0 are dead but not yet removable
frozen: 41883901 pages from table (77.56% of total) had 1502773119 tuples frozen
removable cutoff: 2144931882, which was 118 XIDs old when operation ended
new relfrozenxid: 2144931882, which is 2136501126 XIDs ahead of previous value

Two lines in that output tell you whether it worked. removable cutoff ... which was 118 XIDs old means nothing is holding the horizon back anymore. new relfrozenxid ... ahead of previous value is the age actually falling. For the rest of the database, vacuumdb parallelises and skips tables that do not need it:

vacuumdb --freeze --analyze --jobs=4 --min-xid-age=500000000 --echo --dbname=appdb
SELECT pg_catalog.set_config('search_path', '', false);
VACUUM (FREEZE, ANALYZE) public.audit_log;
VACUUM (FREEZE, ANALYZE) public.events;

7. Retune autovacuum so it does not recur. The reloadable settings first — these make autovacuum fast enough to keep up:

ALTER SYSTEM SET autovacuum_vacuum_cost_delay = '2ms';
ALTER SYSTEM SET autovacuum_vacuum_cost_limit = '3000';
ALTER SYSTEM SET maintenance_work_mem = '1GB';
ALTER SYSTEM SET idle_in_transaction_session_timeout = '15min';
ALTER SYSTEM SET log_autovacuum_min_duration = '0';
SELECT pg_reload_conf();
 pg_reload_conf
----------------
 t

autovacuum_freeze_max_age and autovacuum_max_workers are postmaster-level and need a restart, so change them in a planned window. Resist the urge to raise autovacuum_freeze_max_age as the fix — it buys time now and makes the eventual freeze larger and later. For one enormous table it is usually better to lower its threshold so it freezes in smaller, more frequent passes:

ALTER TABLE public.events SET (autovacuum_freeze_max_age = 150000000,
                               autovacuum_vacuum_cost_delay = 0);
ALTER TABLE

Validate it works

Re-run the per-database measurement and compare against the number you wrote down in step 1:

SELECT datname, age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;
  datname  | xid_age
-----------+-----------
 template0 | 173241902
 postgres  | 173241902
 template1 | 173241902
 appdb     |     14877

appdb has dropped from 2.13 billion to five figures. Confirm no table is still lagging:

SELECT max(age(relfrozenxid)) AS worst_table_age
FROM pg_class
WHERE relkind IN ('r', 'm', 't');
 worst_table_age
-----------------
           14877

While long freezes are still running, watch them rather than guessing:

SELECT pid, relid::regclass AS relation, phase,
       heap_blks_scanned, heap_blks_total,
       round(100.0 * heap_blks_scanned / nullif(heap_blks_total, 0), 1) AS pct
FROM pg_stat_progress_vacuum;
  pid  |    relation     |       phase       | heap_blks_scanned | heap_blks_total | pct
-------+-----------------+-------------------+-------------------+-----------------+------
 41207 | public.audit_log| scanning heap     |           4118220 |         7994113 | 51.5

Finally, confirm the warning has stopped appearing in the server log. It is emitted on transaction assignment, so on a busy instance its absence for a few minutes is proof enough.

Troubleshooting

Autovacuum keeps getting cancelled by DDL locks. Below the anti-wraparound threshold, an autovacuum worker yields as soon as any session requests a conflicting lock, so a migration job that runs ALTER TABLE every ten minutes can starve a large table indefinitely. Look for ERROR: canceling autovacuum task in the log after setting log_autovacuum_min_duration = 0. Pause the migration job until the freeze finishes. Above the anti-wraparound threshold the reverse is true — the worker no longer yields, and your DDL queues behind it instead.

A replication slot for a replica that no longer exists. wal_status of lost and active = f are the giveaway. If a high-availability manager such as Patroni owns the cluster, remove the standby from its configuration before dropping the slot, or the manager will simply recreate it on the next reconciliation loop and the horizon will re-pin.

VACUUM runs but the age does not move. Read the removable cutoff line in the VERBOSE output. If the cutoff is millions of XIDs old, something still holds the horizon and the vacuum was wasted work. Re-check pg_prepared_xacts, which no amount of vacuuming will clear, and also check whether a standby with hot_standby_feedback = on is running a long report — its snapshot propagates back to the primary and pins the horizon exactly like a local transaction.

The database has already refused connections. The message reads database is not accepting commands that assign new XIDs to avoid wraparound data loss. There is a reserve of roughly one million XIDs held back specifically so you can recover. Stop the server and start a stand-alone backend as the data-directory owner:

sudo systemctl stop postgresql@16-main
sudo -u postgres /usr/lib/postgresql/16/bin/postgres --single \
  -D /var/lib/postgresql/16/main \
  -c config_file=/etc/postgresql/16/main/postgresql.conf appdb
PostgreSQL stand-alone backend 16.3
backend> VACUUM (FREEZE, VERBOSE);

Single-user mode gives you one session, no autovacuum, no replication and no concurrency, so a large database can take hours. Resolve any prepared transactions here too — ROLLBACK PREPARED works at this prompt. Exit with Ctrl-D and start the server normally.

Vacuum is too slow because of the cost delay. A throttled autovacuum on a 400 GB table can be slower than the rate at which the XID counter advances, which means you never catch up. On PostgreSQL 14 and later the failsafe at vacuum_failsafe_age disables the delay automatically at 1.6 billion, but do not wait for it: set autovacuum_vacuum_cost_delay = 0 on the affected table for the duration of the emergency and restore it afterward.

When this is the wrong approach

If age(datfrozenxid) is under 200 million and merely rising, nothing is broken — that is the counter doing its job, and the fix is ordinary autovacuum tuning, not an emergency procedure. If your actual complaint is table bloat or disk usage rather than a wraparound countdown, freezing will not help you; that is a different problem with different tools for large tables.

VACUUM FULL and pg_repack do reset relfrozenxid, but the first takes an ACCESS EXCLUSIVE lock for the whole rewrite and both need free disk roughly equal to the table. Neither is an emergency tool when the table is hundreds of gigabytes and the countdown is in hours.

On a managed database service you usually have neither shell access nor the ability to run single-user mode, so the recovery path in this guide stops at step 6. Open a ticket with the provider well before the stop threshold rather than after — once the instance refuses commands, only they can bring it back. The upstream reference for all of this is the PostgreSQL routine vacuuming documentation, and the defaults for every setting named above are in the autovacuum configuration reference.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.