Preventing PostgreSQL transaction ID wraparound

Learn how to spot transaction ID age climbing, find what blocks freezing, run emergency VACUUM steps and set the autovacuum options that keep a self-hosted PostgreSQL cluster out of read-only mode.

On this page

Preventing PostgreSQL transaction ID wraparound before the database goes read-only

Transaction ID wraparound is the risk that PostgreSQL runs out of room in its transaction counter, so it must freeze old row versions before the counter cycles. Prevention means three things: monitoring transaction age, letting autovacuum freeze rows on time, and removing whatever blocks that freezing. If transaction age is rising or a wraparound warning has appeared, the goal is to act before PostgreSQL protects itself by refusing commands near the limit and forcing the server into a state where it will not accept new writes. DeployOpen plans and verifies this work in infrastructure you control, so the steps below can be checked against your own servers rather than taken on trust.

Start by measuring. Query the age of each database and the oldest unfrozen transaction in each table, then compare those figures with the autovacuum and freeze settings in your configuration, such as autovacuum_freeze_max_age and vacuum_freeze_table_age. Confirm the exact thresholds and the warning levels for your PostgreSQL version against the PostgreSQL continuous archiving docs and the server documentation for that release, instead of relying on remembered values. Decide who receives alerts on age trends, not only on the final warning, and record which tables are growing older fastest. Those tables usually point to the workload that needs attention.

Next, find what blocks freezing. Long-running transactions, idle sessions holding snapshots, stale replication slots and prepared transactions that were never completed can all stop vacuum from advancing the oldest transaction ID. Check these sources before changing any vacuum setting, because more aggressive autovacuum cannot freeze rows that an old snapshot still needs. Plan the emergency steps in writing: which manual VACUUM runs take priority, who approves any cancellation of a session, and how the team confirms that age is falling. Ask your DeployOpen contact to include this runbook and the monitoring setup in the written scope so that the recurrence controls are tested, not only documented.

What blocks freezing and stops autovacuum from catching up

Wraparound risk grows when something holds back the oldest transaction that vacuum can clean up, or when autovacuum cannot keep pace with the rate of XID consumption. The cards below cover the blockers that appear most often, how each one shows up in monitoring, and what to check first. Several can be active at once, so check them in order rather than fixing only the first one you find.

Long-running and idle-in-transaction sessions

A session that stays open in a transaction keeps its snapshot, so the xmin horizon cannot advance past it and vacuum cannot remove or freeze rows newer than that snapshot. Check pg_stat_activity for the oldest backend_xmin and for sessions in the idle in transaction state, sorted by xact_start. Find the oldest open transaction first, then decide with the application owner whether to end it or fix the code that left it open.

Continuous archiving docs

Replication slots and lagging standbys

A replication slot or a standby with hot_standby_feedback enabled can pin an old xmin on the primary, so vacuum keeps the same backlog even when no client is connected. Inspect pg_replication_slots for inactive slots and compare xmin and catalog_xmin against the current transaction age. An unused slot should be dropped only after confirming no consumer still needs it, because dropping a slot that a consumer depends on breaks that consumer.

Forgotten prepared transactions

Two-phase commit transactions that were prepared with PREPARE TRANSACTION but never committed or rolled back hold their xmin until they are resolved. They do not appear in pg_stat_activity, so they are easy to miss. Query pg_prepared_xacts and check the prepared timestamp and the owning transaction manager. Confirm the transaction manager's recovery state before resolving anything, because an open prepared transaction may belong to a distributed commit still in progress.

Autovacuum workers starved by cost limits

Autovacuum throttles itself through cost-based delays, so a busy table can take far longer to freeze than its write rate consumes XIDs. Look at the per-table age(relfrozenxid) trend and at whether autovacuum is running on the affected tables at all. Review autovacuum_vacuum_cost_limit, autovacuum_vacuum_cost_delay and autovacuum_max_workers together, and confirm them in the official configuration reference for your major version before changing them.

Tables too large for the vacuum cycle

A very large table can take longer to scan than the interval between autovacuum runs, so the oldest unfrozen rows keep moving closer to the limit. Watch for a table whose relfrozenxid age stays high across several runs, and check whether a manual VACUUM on that table has been running for many hours. Plan these tables separately with a scheduled vacuum window, and confirm the storage and I/O headroom before increasing vacuum work on a live system.

Which autovacuum and freeze settings fit which situation

This table compares the main autovacuum and freeze settings by the situation they suit, what each one trades off, and what to confirm for the client's PostgreSQL version. Read it to pick settings for a given workload, then verify defaults and behavior in the docs for the exact major version in use.

SettingWhen it fitsTrade-offConfirm for the client's version
autovacuum_freeze_max_ageClusters where the oldest unfrozen XID in a database approaches the limit faster than normal autovacuum keeps up, so anti-wraparound vacuums must start earlier.Lowering it forces more frequent freezing and more I/O, which can land during business hours. Raising it gives more headroom but leaves less room before emergency freezing.The default value, the allowed range, and whether changes need a restart or a reload in the target version.
vacuum_freeze_min_ageTables with heavy churn where freezing older rows earlier prevents large, expensive freeze passes later.Freezing rows sooner means more work per vacuum run. Freezing later defers work but can leave a larger amount of work for an aggressive vacuum.The default and whether the parameter applies per session or only to autovacuum in the version in use.
vacuum_freeze_table_ageLarge tables where a periodic whole-table freeze scan is preferable to waiting until the anti-wraparound threshold forces one.Triggering table-wide freeze scans more often increases read I/O and can slow other work. Setting it too high delays freezing until it becomes urgent.The default, the relationship to autovacuum_freeze_max_age, and how the scan interacts with visibility map use.
autovacuum_vacuum_cost_limitSystems with spare I/O capacity outside business hours, or where vacuum is falling behind on a busy cluster and needs more throughput.A higher limit lets vacuum do more work per cycle and finish sooner, but competes with application queries for disk. A lower limit protects latency but risks falling behind.The default and whether it is set globally, per table, or both. Confirm how it interacts with autovacuum_vacuum_cost_delay.
autovacuum_max_workersClusters with many large or busy tables where a single worker cannot keep up with dead tuples and freezing across databases.More workers share the same I/O budget and memory, so each worker gets less throughput. Too many can increase contention with application work.The default, whether a restart is required, and how the cost limit is divided among workers in the version in use.
Per-table storage parameters (autovacuum_freeze_min_age, autovacuum_freeze_table_age, autovacuum_vacuum_cost_limit, and similar)A small number of very large or very hot tables that need different freezing or vacuum behavior from the rest of the database.Per-table settings add targeted control but create configuration drift that is easy to miss during reviews and upgrades. They also need monitoring per table.Which storage parameters the version supports and how to list current overrides from the catalog before changing anything.

Setting up wraparound monitoring and prevention

This sequence confirms the PostgreSQL version and support status, measures transaction age, alerts well before the limit, clears the blockers that stop freezing, tunes autovacuum for the largest tables, and proves with a test that freezing progresses. The output is a monitored, tested setup that a team can hand to operations.

  1. Confirm version and support status

    Record the exact server version with SELECT version(); and compare the major version against the supported list in the PostgreSQL versioning policy. Supported majors today are 14 through 18, and versions 13 and earlier are unsupported, so an unsupported cluster needs an upgrade plan alongside the wraparound work. Minor releases are the routine fix path, so also check whether the server is on the latest minor release for its major. Done when the version, support end date and minor level are written in the runbook and an owner is named for any upgrade.

  2. Query database and table transaction age

    Run SELECT datname, age(datfrozenxid) FROM pg_database ORDER BY 2 DESC; to see which databases are oldest, then query pg_class joined to pg_namespace for age(relfrozenxid) on the largest tables, filtered to relkind r and m. Compare results against the autovacuum_freeze_max_age setting, which controls when anti-wraparound autovacuum starts. Also note tables where age is close to that setting, since those are the ones autovacuum will force to freeze first. Done when you have a ranked list of the oldest databases and tables saved as a baseline.

  3. Alert well before the wraparound limit

    Create an alert on the database and table age queries with thresholds set below the point where anti-wraparound autovacuum must run, so operators have time to act. Choose thresholds with your DBA based on your write rate and the autovacuum settings on your cluster, and confirm the limit with the transaction ID documentation for your version. Route the alert to a channel someone watches around the clock, and test that it fires by temporarily lowering the threshold in a non-production cluster. Done when a test alert reaches the on-call channel and the threshold values are recorded with their rationale.

  4. Review long transactions and replication slots

    Find sessions holding back the freeze horizon with SELECT pid, state, xact_start, backend_xmin FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY age(backend_xmin) DESC; and check pg_replication_slots for slots whose xmin or catalog_xmin is old. Long idle-in-transaction sessions, abandoned slots and lagging standbys with hot_standby_feedback can all stop vacuum from advancing. Identify the owner of each blocker before terminating anything. Done when every session or slot older than your alert threshold has an owner and a fix, or a documented reason it stays.

  5. Tune autovacuum for the largest tables

    Review autovacuum_vacuum_scale_factor, autovacuum_freeze_max_age and per-table storage parameters for the tables with the highest age and write volume. Large tables usually need lower scale factors or table-level overrides so vacuum runs before age builds up, and the cost limits need to match your I/O capacity. Make changes in a test environment first and confirm each setting with the PostgreSQL routine vacuuming documentation for your version. Done when the changed settings are recorded in version control and the ages of the largest tables are trending down or holding steady.

  6. Verify freezing progresses with a test

    Run a controlled vacuum on a representative table with VACUUM (VERBOSE, FREEZE) schema.table; in a staging copy, then compare age(relfrozenxid) before and after. Confirm that relfrozenxid advances and that pg_stat_progress_vacuum shows the job running as expected. Repeat the check on production during a quiet period with a DBA present, starting with the table nearest its limit. Done when the age measurably drops after vacuum and the same measurement is scheduled to repeat on a fixed review cadence.

Emergency VACUUM steps when age is already high

When a table's transaction age is already close to the limit, the first job is to remove whatever stops vacuum from advancing, then freeze the oldest tables in order of age. Start by checking for long-running transactions, idle-in-transaction sessions and abandoned replication slots, because a session holding an old snapshot prevents freezing no matter how hard vacuum runs. Terminate or ask the owners to end blockers that are safe to stop, and confirm with the application team before cancelling anything that writes. Next, rank tables by age, typically using the relation age and the database-level age views, and run manual VACUUM (FREEZE, VERBOSE) on the oldest tables first. Running several freezes at once multiplies I/O, so watch disk latency and replication lag and throttle with vacuum_cost_limit or by working through tables sequentially.

Avoid VACUUM FULL during this window. It rewrites the table, takes an ACCESS EXCLUSIVE lock for the duration and needs free disk space roughly equal to the table size, so it can stall the application and fill the volume at the same time it is trying to prevent an outage. Plain freezing keeps the table readable and writable while it runs. Single-user mode is a last resort that PostgreSQL documents for cases where the server will not accept normal connections to perform the freeze. Its exact procedure, the risks and the cleanup steps belong in the official documentation, and you should confirm them against your server's version before you attempt anything, not improvise from a forum post. Involve a database specialist early if the server has already stopped accepting writes, if blockers cannot be identified, or if freezing progresses too slowly to beat the limit.

Security and operational considerations for vacuum changes

Emergency and preventive vacuuming touch privileges, configuration, alerting and recovery tooling at once. The four areas below are the ones where a wraparound fix can quietly create a second incident if they are not controlled before work starts.

Privileges for vacuum and monitoring

Running VACUUM on a table requires ownership of the table or membership in a role with the MAINTAIN privilege on it, and a role that reads cluster-wide activity needs access to the statistics views. Decide up front which accounts run manual freezing, which run the age monitoring query, and whether those accounts are superuser-free. Confirm that monitoring credentials can read pg_stat_activity and the vacuum views without the ability to change data, and rotate them through your normal secrets process.

Authentication methods docs

Autovacuum changes under change control

Lowering autovacuum_freeze_max_age, raising autovacuum_vacuum_cost_limit or changing per-table storage parameters alters I/O load across the whole cluster, so each change needs a record, an owner and a rollback value. Treat every setting change as a production change with a ticket, a test on a restored copy, and a documented reason. Reviewers should check whether the change affects the replicas and backup jobs that share the same storage.

Alerting and log access for on-call

The on-call team needs the age alert, the log lines from autovacuum, and the path to the database within minutes, including at night and on weekends. Confirm who receives the page, that log_autovacuum_min_duration is set so long runs are recorded, and that responders can read the server logs without shell access to the primary. Test the alert by simulating a threshold breach in a non-production environment.

Backups and standbys during long vacuums

A long anti-wraparound vacuum generates write-ahead log and I/O that can delay archiving, slow base backups and push standbys behind the primary. Before starting, confirm that WAL archiving keeps pace, that the backup window does not overlap the freeze work, and that synchronous standbys will not stall commits under the extra load. Check replica lag during a test run so the team knows what to expect in production.

Continuous archiving docs

Questions teams ask before preventing transaction ID wraparound

What drives the cost or effort of a wraparound review?

The main drivers are how many databases and tables are in scope, how large the biggest tables are, how many clusters run PostgreSQL, and how much of the vacuum history your team can already show. A review of one cluster with a few hundred tables is a very different job from a review across a fleet with mixed PostgreSQL versions. Effort also rises when autovacuum has been disabled or tuned by hand over years, because each override needs to be explained before it is changed. Ask any provider for a quote built from a written scope that lists the clusters, the access granted, the monitoring data available and the deliverables, including whether the findings report comes with a fix plan and a retest. Costs are one-time for the review and tuning, while monitoring and periodic re-checks recur.

How long does a wraparound tuning project take?

The duration depends mostly on table size, write volume and the I/O capacity of the storage, because a freeze pass has to read and rewrite table pages and that work competes with normal traffic. A large table with heavy churn can take far longer to freeze than a small reference table, and the safe pace depends on how much load the system can absorb during business hours. This page does not give a duration because none was supplied for this topic. Ask for a plan that sorts tables by transaction age and estimated freeze work, states which steps run in a maintenance window, and names the metrics you will watch while the work runs.

What does the work need from our team?

The work needs a named database owner who can approve changes to autovacuum and maintenance windows, an application owner who can identify long transactions and idle sessions, and someone who can grant read access to the statistics views and server logs. Your team should also supply the current postgresql.conf settings, any per-table storage parameters, the replication and backup setup, and the PostgreSQL major version in use. Expect to provide time for change review, because lowering freeze thresholds or raising worker counts changes load on the whole server. Confirm that you have a rollback path for each setting before the work begins.

Can our team handle wraparound prevention alone?

A capable DBA team can handle wraparound prevention alone if it has time, access to the systems and experience with vacuum internals. Most teams struggle less with the commands than with the judgment calls: which long-running transaction to end, whether a replication slot is holding back cleanup, and how aggressive freezing can be before it hurts latency. Teams that do this only after an incident often lack a baseline to compare against. A useful middle path is to have an outside reviewer check the monitoring, thresholds and runbook once, then keep the routine work in-house. Be honest about the staffing you can commit to over the coming months.

How should monitoring for transaction age be set up?

Monitor the age of each database's oldest frozen transaction ID and of each table's relfrozenxid, and alert well before the age reaches the point where PostgreSQL forces autovacuum or refuses writes. Track the state of autovacuum workers, how long vacuum runs take, and whether the freeze horizon is moving forward. Pair those metrics with alerts on long-running transactions, idle-in-transaction sessions and inactive replication slots, since each of them can hold back the cleanup that advances the horizon. Set thresholds in two tiers, one that prompts review and one that requires action within a defined response time. Confirm the exact view and function names for your PostgreSQL version in the official documentation before you build dashboards.

What does a DeployOpen engagement scope include?

A DeployOpen engagement is fixed-scope, so the written scope, deliverables and timeline are agreed before work starts. For this topic, a typical scope can cover reviewing transaction age across the agreed clusters, identifying what blocks freezing, planning and documenting emergency vacuum steps, adjusting autovacuum and related settings with your change approval, and setting up monitoring and runbooks your team can operate. DeployOpen plans, implements, documents and supports self-hosted platforms inside your own infrastructure, so the work happens in your cloud accounts, data centers or air-gapped networks. DeployOpen does not publish a price list. Ask for a quote that lists each system in scope, the access you will provide, and what is handed over at the end.

Does a wraparound review produce compliance evidence?

A review can produce records that compliance teams use, such as documented settings, monitoring definitions and runbooks, but it does not produce an audit report or certification. Independent auditors and certification bodies issue those results after they assess your controls. Ask for the findings and the configuration evidence in a form your assessor can read, and confirm with the assessor which artifacts they expect for change management and availability controls. Keep the evidence current, because settings drift over time and an old snapshot will not show the state of the system on the day of assessment.

How age monitoring, blockers and autovacuum fit together

The diagram starts with transaction age metrics from pg_database and pg_class, which feed alerts before any threshold is near. When an alert fires, the first hand-off is a triage step that checks for three blockers: long-running sessions, stale replication slots and forgotten prepared transactions. Once blockers are cleared, autovacuum freezes eligible tables, and a manual VACUUM FREEZE covers the tables that remain behind. Check that the age drops after each run, then keep monitoring.

Triage path from transaction age alerts through blockers to freezing and back to monitoring.

How DeployOpen works on this

DeployOpen plans, implements, hardens, documents and supports self-hosted open-source platforms inside your own infrastructure, including PostgreSQL clusters. For transaction ID wraparound, the work starts with measuring transaction age on your real databases and ends with monitoring, settings and runbooks your own team can operate after handover.

How we scope

  • Engagements are fixed-scope, with the databases, versions and hosting in scope agreed in writing before work starts.
  • We review current transaction age per database and table, and which tables are the largest contributors to freezing work.
  • The written scope names which autovacuum and freeze settings may change, and which changes need your change approval first.
  • Quotes follow from the written scope, so ask for the list of systems, access and maintenance windows the price assumes.

How we build

  • We configure age-based alerts and dashboards in the monitoring stack you already run or agree to deploy.
  • We test autovacuum and freeze settings on a copy of production data before changing the live cluster.
  • We document the emergency VACUUM procedure, including who runs it, which tables go first and what to check after each step.
  • We check what blocks freezing, such as long transactions, idle sessions and replication slots, and document fixes for each cause.

How we hand over

  • You receive the configuration changes, alert definitions and dashboards, with notes on why each setting was chosen.
  • The runbook covers wraparound thresholds, escalation steps and the commands used during an incident, written for your operators.
  • We walk your team through a test of the alert path and the emergency procedure on a non-production system.
  • You receive a list of open risks, such as tables that still need manual attention, with owners and suggested priorities.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers, covering periodic age reviews after your workload changes.
  • We can review alert thresholds and autovacuum settings when table sizes, batch jobs or PostgreSQL major versions change.
  • Retainer scope, response expectations and review frequency are written down before the retainer starts, so ask for them in the quote.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.