---
title: "Avoid Transaction ID Wraparound"
description: "Track transaction ID age on Managed PostgreSQL, find what blocks freezing, and tune autovacuum so that wraparound never becomes an emergency."
url: https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/avoid-transaction-id-wraparound/
product: "PostgreSQL"
section: product
last_updated: 2026-11-10
---
> For AI agents: the documentation index is at https://community.exoscale.com/llms.txt. Every page is available as markdown at `<page URL>index.md` or with `Accept: text/markdown`.

# Avoid Transaction ID Wraparound

Track how close a Managed PostgreSQL service is to transaction ID wraparound, remove what prevents rows from being frozen, and give autovacuum enough throughput to stay ahead.

## How Wraparound Happens

Every transaction that writes gets a 32-bit transaction ID (XID), and each row version records the
XID that created it. Comparisons between XIDs are circular: from the point of view of any
transaction, roughly two billion XIDs are in the past and two billion in the future. A row that
stays unchanged long enough would therefore eventually appear to be in the future and vanish.

`VACUUM` prevents that by freezing old rows: it marks them as visible to every transaction, after
which their XID no longer matters. Each table records in `pg_class.relfrozenxid` the oldest XID
that may still be unfrozen in it, and each database records the oldest of those in
`pg_database.datfrozenxid`. Wraparound is only a risk when freezing falls behind the rate at which
XIDs are consumed.

If it falls far enough behind, PostgreSQL first emits warnings and then stops assigning new XIDs,
which means the database no longer accepts writes. See
[The Warnings and the Hard Stop](#the-warnings-and-the-hard-stop).

## Read the Freeze Thresholds of Your Service

```sql
SHOW autovacuum_freeze_max_age;
SHOW autovacuum_multixact_freeze_max_age;
SHOW vacuum_freeze_min_age;
SHOW vacuum_freeze_table_age;
```

`autovacuum_freeze_max_age` is the table age at which autovacuum starts an anti-wraparound vacuum
on a table, even when autovacuum is disabled for that table. Managed PostgreSQL sets its own value
instead of the upstream default of 200 million, and the value is not the same on every service, so
read it on yours. Any alert threshold you configure in a monitoring tool should be derived from
this value rather than copied from the tool's defaults.

## Monitor the Age of Each Database

The following query reports, per database, the current age, how many transactions remain before
anti-wraparound autovacuum is forced, and how much of the roughly two billion usable XIDs has been
consumed:

```sql
SELECT datname,
       age(datfrozenxid) AS xid_age,
       current_setting('autovacuum_freeze_max_age')::bigint
         - age(datfrozenxid) AS xids_until_forced_vacuum,
       round(100.0 * age(datfrozenxid) / 2000000000, 2) AS pct_of_xid_space
FROM pg_database
ORDER BY age(datfrozenxid) DESC;
```

How to read it:

- A negative `xids_until_forced_vacuum` means anti-wraparound autovacuum is due or already
  running. That is not an emergency, but it shows that routine autovacuum is not freezing fast
  enough on its own.
- A `pct_of_xid_space` that keeps rising over days is the signal to investigate. Set your alert
  well below 100: PostgreSQL starts warning when about 40 million XIDs remain.

The list includes `_aiven`, `template0` and `template1`. They are kept frozen by the platform's
autovacuum and normally stay at a low age.

## Find the Tables Holding the Age Back

A database is only as young as its oldest table. List the oldest relations, including TOAST tables:

```sql
SELECT c.oid::regclass                               AS relation,
       c.relkind,
       age(c.relfrozenxid)                           AS xid_age,
       mxid_age(c.relminmxid)                        AS mxid_age,
       pg_size_pretty(pg_total_relation_size(c.oid)) AS size,
       s.last_autovacuum
FROM pg_class c
LEFT JOIN pg_stat_all_tables s ON s.relid = c.oid
WHERE c.relkind IN ('r', 'm', 't')
ORDER BY age(c.relfrozenxid) DESC
LIMIT 20;
```

`mxid_age()` tracks the separate multixact counter, which is consumed when several transactions
lock the same row at once, for example with `SELECT ... FOR SHARE` or foreign key checks under
concurrency. It has its own threshold, `autovacuum_multixact_freeze_max_age`, which is not part of
the service settings. A workload that locks rows heavily can approach that limit before the XID
limit.

TOAST tables appear as `pg_toast.pg_toast_<oid>`. Map them back to their parent table with:

```sql
SELECT c.oid::regclass     AS parent_table,
       t.relname           AS toast_table,
       age(t.relfrozenxid) AS toast_xid_age
FROM pg_class c
JOIN pg_class t ON t.oid = c.reltoastrelid
ORDER BY age(t.relfrozenxid) DESC
LIMIT 10;
```

> [!NOTE]
> Keep the join on `reltoastrelid`. `avnadmin` has no `USAGE` privilege on the `pg_toast` schema,
> so casting a name such as `'pg_toast.pg_toast_16500'::regclass` fails with
> `permission denied for schema pg_toast`.

## Find What Is Blocking the Freeze

`VACUUM` can only freeze row versions that no running transaction may still need. Anything that
holds back that horizon prevents freezing in every table, however often autovacuum runs. Check the
four usual causes.

Old transactions and sessions, including `idle in transaction`:

```sql
SELECT pid,
       usename,
       state,
       age(backend_xmin)  AS xmin_age,
       now() - xact_start AS xact_age,
       left(query, 80)    AS query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC
LIMIT 10;
```

Replication slots, active or not:

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

The `pghoard_local` slot belongs to the platform's backup and WAL archiver. It is always present
and does not hold an `xmin`. A logical slot whose subscriber has gone away holds a `catalog_xmin`
and also pins WAL on disk: see
[Prevent a full disk](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/prevent-full-disk/index.md#find-wal-held-back-by-a-replication-slot).

Prepared transactions:

```sql
SELECT gid, prepared, owner, database, age(transaction) AS xid_age
FROM pg_prepared_xacts
ORDER BY prepared;
```

`max_prepared_transactions` is `0` by default, so this view stays empty unless you raised that
setting.

Queries on a read replica with `hot_standby_feedback`: a long query on a
[read replica](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-read-replicas/index.md) can hold back
the primary's horizon. Check from the primary:

```sql
SELECT application_name, state, backend_xmin, age(backend_xmin) AS xmin_age
FROM pg_stat_replication;
```

The row with `application_name = pghoard` is the backup and WAL archiver, not a replica, and is
present on every service.

## Stop Sessions from Holding the Horizon Back

A session left `idle in transaction` keeps its snapshot, and therefore the freeze horizon, for as
long as it stays open. On a new service, `idle_in_transaction_session_timeout` is `86400000` ms,
that is 24 hours. Lower it for the whole service:

```bash
exo dbaas update SERVICE_NAME -z ZONE -f \
  --pg-settings '{"idle_in_transaction_session_timeout":300000}'
```

Parameters:

- `SERVICE_NAME`: name of the Managed PostgreSQL service, for example `my-postgresql`.
- `ZONE`: zone the service runs in, for example `ch-gva-2`.
- `idle_in_transaction_session_timeout`: milliseconds, from `0` (disabled) to `604800000`. The
  example is 5 minutes. The change applies without a restart.

When the timeout fires, PostgreSQL closes the connection with
`FATAL:  terminating connection due to idle-in-transaction timeout` and rolls the transaction back.
Make sure the application reconnects before you lower it on a production service. The parameter
can also be set per role or per database, see
[Manage long-running queries](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-long-running-queries/index.md#stop-long-running-statements-automatically).

To end an offending session now, `avnadmin` can terminate the backends of other database users,
because it is a member of `pg_signal_backend`:

```sql
SELECT pid, usename, pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction'
  AND now() - xact_start > interval '1 hour';
```

Terminating a backend rolls its transaction back. Backends of the platform's superuser roles
cannot be terminated and return `permission denied to terminate process`.

## Give Autovacuum More Throughput

Once nothing blocks the horizon, check whether autovacuum does enough work per round. Its
parameters are nested in the `autovacuum` object of `--pg-settings`:

```bash
exo dbaas update SERVICE_NAME -z ZONE -f \
  --pg-settings '{"autovacuum":{"autovacuum_vacuum_cost_limit":2000,"autovacuum_naptime":30}}'
```

Parameters:

- `autovacuum_vacuum_cost_limit`: amount of work autovacuum may do before it pauses for
  `autovacuum_vacuum_cost_delay`. Default `-1`, which falls back to `vacuum_cost_limit` (`200`).
  Range `-1` to `10000`. Raising it is the most direct way to make autovacuum faster.
- `autovacuum_naptime`: seconds between autovacuum runs on a given database. Default `60`, range
  `1` to `86400`.
- `autovacuum_vacuum_cost_delay` (not in the example): milliseconds autovacuum sleeps once it has
  spent its cost limit. Default `2`, range `-1` to `100`.

These three apply without a restart. Sending them at the top level of `--pg-settings` instead of
inside `autovacuum` is rejected with
`Additional property autovacuum_vacuum_cost_limit is not allowed`. Updates are merged into the
stored configuration, so send only what you change. See
[Configure PostgreSQL settings](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/configure-settings/index.md).

Two autovacuum parameters restart the service when changed, so apply them in a window you control:

```bash
exo dbaas update SERVICE_NAME -z ZONE -f \
  --pg-settings '{"autovacuum":{"autovacuum_max_workers":4,"autovacuum_freeze_max_age":300000000}}'
```

Parameters:

- `autovacuum_max_workers`: number of tables autovacuum can process at the same time. Default `3`,
  range `1` to `20`. Each worker can use up to `maintenance_work_mem`, so do not raise it far on a
  small plan.
- `autovacuum_freeze_max_age`: range `200000000` to `1500000000`. A lower value starts
  anti-wraparound vacuums earlier and more often. A higher value only postpones them and does not
  help an autovacuum that cannot keep up.

## Freeze a Table on Demand

When one table holds the age of a database back, freeze it directly instead of waiting for
autovacuum:

```sql
VACUUM (FREEZE, VERBOSE) public.orders;
```

`VERBOSE` reports `new relfrozenxid` for the table and for its TOAST table. Add `PARALLEL N` to
process several indexes in parallel during the index phase, up to
`max_parallel_maintenance_workers`.

Watch a long vacuum from a second session:

```sql
SELECT p.pid,
       p.relid::regclass                          AS table_name,
       p.phase,
       pg_size_pretty(p.heap_blks_total * 8192)   AS total,
       pg_size_pretty(p.heap_blks_scanned * 8192) AS scanned,
       now() - a.xact_start                       AS running_for,
       left(a.query, 80)                          AS query
FROM pg_stat_progress_vacuum p
JOIN pg_stat_activity a ON a.pid = p.pid;
```

An autovacuum worker that is protecting a table from wraparound shows
`autovacuum: VACUUM schema.table (to prevent wraparound)` in the `query` column. Let it finish:
`relfrozenxid` only advances when a run completes, and a cancelled worker is started again later.

### What avnadmin Can Vacuum

- Tables in a database that `avnadmin` owns, which includes `defaultdb` and the databases
  `avnadmin` creates, whatever role owns the table.
- Tables it owns, or on which it holds the `MAINTAIN` privilege (PostgreSQL 17 and later), in other
  databases.
- Not the shared system catalogs such as `pg_authid` or `pg_database`. A database-wide
  `VACUUM (FREEZE);` skips them with `permission denied to vacuum "pg_authid", skipping it`, and
  because `datfrozenxid` accounts for those catalogs, a manual database-wide vacuum does not
  necessarily lower the age of the database. Autovacuum handles the shared catalogs.

## The Warnings and the Hard Stop

When a database comes within about 40 million transactions of the limit, PostgreSQL adds a warning
to every transaction that assigns an XID:

```text
WARNING:  database "mydb" must be vacuumed within 39985967 transactions
```

When fewer than about three million remain, it refuses to assign new XIDs. Reads keep working,
writes fail with:

```text
ERROR:  database is not accepting commands that assign new transaction IDs to avoid wraparound data loss in database "mydb"
```

This is the wording of PostgreSQL 16 and later; PostgreSQL 15 uses a shorter error message. Treat
the first warning as an incident. The upstream recovery procedure works over a normal
connection and does not require single-user mode: resolve old prepared transactions, end old
sessions, drop obsolete replication slots, then run `VACUUM` in the affected database. Run it as
`avnadmin` with the queries on this page, and contact Exoscale support if the age does not go down,
for example because the oldest relation is a system catalog that `avnadmin` cannot vacuum.

## Related Pages

- [Prevent a full disk on Managed PostgreSQL](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/prevent-full-disk/index.md)
- [Manage long-running queries](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-long-running-queries/index.md)
- [Prepare Managed PostgreSQL for high load](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/prepare-for-high-load/index.md)
- [Configure PostgreSQL settings](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/configure-settings/index.md)
- [Use read replicas](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-read-replicas/index.md)
- [Routine vacuuming in the PostgreSQL documentation](https://www.postgresql.org/docs/18/routine-vacuuming.html) ↗

