sre

Build a Postgres Autovacuum Agent: Forecast Transaction ID Wraparound, Name What Is Blocking Vacuum (Long Transactions, Stale Replication Slots, Prepared Transactions), and Ship Per-Table Tuning as Migration PRs

Build a Postgres autovacuum agent: forecast transaction ID wraparound, name what blocks vacuum, and ship per-table autovacuum tuning as safe migration PRs.

December 3, 2026·12 min read·
#ai#sre#devops#postgresql#automation#reliability#performance#incident-response

What This Agent Does

A Postgres autovacuum agent answers three questions every night, for every database in the fleet. How many days until the oldest table forces an anti-wraparound vacuum, and how many until the server stops accepting writes? Which tables is autovacuum failing to keep up with? And for each of those, is the cause a setting or a blocker: a transaction open since Tuesday, a replication slot nobody consumes, a prepared transaction orphaned by a crashed coordinator? It then does one of two things. For a setting problem, it opens a pull request with a per-table ALTER TABLE ... SET (autovacuum_...) migration. For a blocker, it posts a finding that names the session, slot, or transaction and its owner, and stops there. It holds no credential that can terminate a backend, drop a slot, or run VACUUM.

That split is the reason this is more than a dashboard panel on n_dead_tup. Dead tuple counts tell you vacuum is behind. They do not tell you that tuning will not help, and the most common response to a bloated table, making autovacuum more aggressive, does nothing at all when something is pinning the xmin horizon. Vacuum runs, removes zero rows, and runs again.

Why Wraparound Deserves a Forecast, Not an Alert

Transaction IDs are 32-bit, so a row can be at most about 2.1 billion transactions older than the current one before its visibility becomes ambiguous. Vacuum prevents that by freezing old rows. When a table's relfrozenxid age passes autovacuum_freeze_max_age (200 million by default), Postgres launches an aggressive anti-wraparound vacuum on it even if autovacuum is disabled. If freezing still does not happen, current versions start logging warnings with 40 million IDs left and refuse to assign new transaction IDs with 3 million left. At that point the database is read-only until someone vacuums it, which on a multi-terabyte table can take most of a day.

The forced vacuum has its own failure mode well before the cliff. An ordinary autovacuum worker cancels itself when another session wants a conflicting lock. An anti-wraparound worker does not. So the migration that adds a column on Thursday waits behind a vacuum that started Wednesday, and every query on the table queues behind the migration. That outage is the usual way teams learn the number 200 million. A static alert at "age above 180 million" fires on a table that has been sitting at that age harmlessly for months and stays quiet about the one burning 30 million IDs a day. The agent forecasts instead.

Step 1: Collect Ages and the Burn Rate

The collector runs as a role with pg_monitor and no table privileges, the same role the Postgres MCP server uses.

-- vacagent/ages.sql
SELECT c.oid::regclass          AS rel,
       c.relkind, c.relpersistence,
       age(c.relfrozenxid)      AS xid_age,
       mxid_age(c.relminmxid)   AS mxid_age,
       pg_table_size(c.oid)     AS bytes,
       c.reltuples::bigint      AS est_rows,
       c.reloptions,
       s.n_dead_tup, s.n_ins_since_vacuum,
       s.last_autovacuum, s.autovacuum_count
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 200;

-- current position, without consuming a transaction ID
SELECT pg_snapshot_xmax(pg_current_snapshot())::text AS xid8_now,
       current_setting('autovacuum_freeze_max_age')::bigint AS freeze_max_age;

Three details in that query matter. relkind = 't' includes TOAST tables, which carry their own relfrozenxid and are frequently the oldest relation in the database while their parent looks healthy. relpersistence = 't' marks temporary tables: autovacuum cannot process another session's temp table, so a connection pooler session that created one in March holds the whole database's frozen horizon back. And mxid_age tracks the second counter, multixact IDs, which wrap the same way and get consumed fast by workloads with many SELECT ... FOR SHARE locks or foreign key checks on hot parent rows.

pg_snapshot_xmax returns a 64-bit value that never wraps, so the difference between two nightly collections is the number of transaction IDs consumed that day. The forecast is arithmetic:

# vacagent/forecast.py
HARD_STOP = 2**31 - 3_000_000

def forecast(xid_age: int, burn_7d: list[int], freeze_max_age: int) -> dict:
    burn = max(sorted(burn_7d)[len(burn_7d) // 2], 1)   # median daily burn
    peak = max(burn_7d)
    return {
        "days_to_forced_vacuum": max(freeze_max_age - xid_age, 0) / burn,
        "days_to_write_stop":    (HARD_STOP - xid_age) / peak,   # pessimistic
        "burn_per_day": burn,
    }

The forced-vacuum estimate uses the median because it is a planning number. The write-stop estimate uses the worst day of the week because it is a safety number. On RDS and Aurora, the CloudWatch metric MaximumUsedTransactionIDs gives the same age without a connection and makes a good cross-check: if the agent's number and CloudWatch disagree, the agent is looking at the wrong database in the instance.

Step 2: Find What Pins the xmin Horizon

Vacuum can only remove row versions that no snapshot can still see. Four things hold old snapshots, and each lives in a different view.

-- vacagent/blockers.sql
SELECT 'backend' AS kind, pid::text AS id, usename, application_name,
       state, age(backend_xmin) AS xmin_age,
       extract(epoch FROM now() - xact_start)::int AS xact_seconds
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL AND pid <> pg_backend_pid()

UNION ALL
SELECT 'slot', slot_name, NULL, plugin,
       CASE WHEN active THEN 'active' ELSE 'inactive' END,
       greatest(age(xmin), age(catalog_xmin)), NULL
FROM pg_replication_slots

UNION ALL
SELECT 'prepared', gid, owner, database, 'prepared',
       age(transaction), extract(epoch FROM now() - prepared)::int
FROM pg_prepared_xacts

UNION ALL
SELECT 'standby_feedback', application_name, usename, client_addr::text,
       state, age(backend_xmin), NULL
FROM pg_stat_replication
WHERE backend_xmin IS NOT NULL

ORDER BY xmin_age DESC NULLS LAST;

The collector deliberately leaves out pg_stat_activity.query. Statement text can contain literals, and the blocker's identity is fully described by user, application name, state, and age. The top row of this result is the horizon. Everything written to any table after that row's snapshot is unremovable, regardless of autovacuum settings.

The wrapper attaches the horizon to each lagging table with one test: a table is blocked when its last three autovacuum runs completed (the autovacuum_count rose between snapshots) while n_dead_tup did not fall, and the oldest xmin holder is older than the table's last_autovacuum. It is starved when the count did not rise at all and the trigger point was passed. It is mistuned when vacuums run and succeed but the trigger point is absurd for the table's size.

Step 3: Compute the Trigger Point Per Table

Autovacuum vacuums a table when dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × reltuples. The defaults are 50 and 0.2, which is sensible at ten thousand rows and indefensible at a billion.

# vacagent/trigger.py
def trigger_point(est_rows: int, reloptions: list[str] | None, g: dict) -> int:
    opts = dict(o.split("=", 1) for o in (reloptions or []))
    threshold = int(opts.get("autovacuum_vacuum_threshold", g["threshold"]))
    scale = float(opts.get("autovacuum_vacuum_scale_factor", g["scale_factor"]))
    return int(threshold + scale * est_rows)

def proposal(est_rows: int) -> dict | None:
    if est_rows < 10_000_000:
        return None                        # defaults are fine at this size
    return {
        "autovacuum_vacuum_scale_factor": 0,
        "autovacuum_vacuum_threshold": max(100_000, est_rows // 200),
    }

An events table with 800 million rows has a default trigger point of 160 million dead tuples. Each vacuum then has to clean 160 million index entries per index in one pass, takes hours, and is likely to be interrupted by a deploy before it finishes. The proposal replaces the proportional rule with a fixed one: vacuum every 4 million dead rows, often and briefly. The wrapper computes these numbers; the model never does arithmetic.

starved tables point somewhere else. Count the rows in pg_stat_progress_vacuum: if that equals autovacuum_max_workers on most collections, the workers are saturated. The instinct is to raise the worker count, and on its own that makes things worse, because autovacuum_vacuum_cost_limit is a budget shared between all running workers. Five workers on the budget of three each run slower. The finding the agent emits for this case is a parameter group change that raises the cost limit alongside the workers, and it goes to the platform team as an issue, not to a service team as a migration.

Step 4: The Model Classifies One Table and Writes the Finding

The model sees one relation at a time: its ages and forecast, its last seven snapshots, the computed trigger point and proposal, the wrapper's blocked/starved/mistuned flag, and the top five rows of the blocker query.

VERDICT_SCHEMA = {
    "type": "object",
    "properties": {
        "verdict": {"type": "string", "enum": [
            "tune_table", "blocked_by_backend", "blocked_by_slot",
            "blocked_by_prepared_xact", "blocked_by_standby_feedback",
            "workers_saturated", "temp_table_holdback", "healthy",
            "needs_human"]},
        "blocker_id": {"type": "string"},
        "evidence": {"type": "string"},
        "why_tuning_will_not_help": {"type": "string"},
        "urgency": {"type": "string", "enum": ["page", "ticket", "info"]},
    },
    "required": ["verdict", "evidence", "urgency"],
}

SYSTEM = (
    "You review vacuum health for one PostgreSQL relation. Facts and all "
    "numbers are computed for you; cite them, never recompute them.\n"
    "If the wrapper flag is 'blocked', the verdict must be one of the "
    "blocked_by_* values and must name the oldest xmin holder. Never return "
    "tune_table for a blocked relation: more frequent vacuums remove nothing "
    "while the horizon is pinned.\n"
    "blocked_by_slot: say whether the slot is inactive and what consumes it "
    "if the plugin or name makes that clear. Never recommend dropping it; "
    "state that an owner must confirm the consumer is gone.\n"
    "tune_table: only for 'mistuned', and only with the provided proposal.\n"
    "urgency 'page' only when days_to_write_stop is under 7 or xid_age is "
    "above 1.5 billion. Use 'ticket' when days_to_forced_vacuum is under 14.\n"
    "needs_human: the relation is a TOAST or temp table with no clear parent "
    "owner, or the snapshots contradict each other."
)

The useful work the model does here is the paragraph a human reads at the top of the finding. "Table orders has 61 million dead tuples and vacuumed four times this week removing nothing. The horizon is held by logical slot debezium_orders_v1, inactive, xmin age 212 million. A slot named debezium_orders_v2 is active. This looks like a connector migration that left the old slot behind" is something a query result does not say and an on-call engineer needs. The wrapper overrides the model in one direction only: a tune_table verdict on a relation flagged blocked is discarded and logged as a model error.

Step 5: The Tuning PR

For tune_table, the agent renders a migration in the owning repository's dialect, the same detection the Postgres index agent uses.

# migrations/versions/20261203_tune_autovacuum_events.py
from alembic import op

def upgrade():
    op.execute("SET lock_timeout = '3s'")
    op.execute("""
        ALTER TABLE events SET (
            autovacuum_vacuum_scale_factor = 0,
            autovacuum_vacuum_threshold    = 4000000,
            autovacuum_vacuum_insert_scale_factor = 0,
            autovacuum_vacuum_insert_threshold    = 20000000
        )""")

def downgrade():
    op.execute("SET lock_timeout = '3s'")
    op.execute("""
        ALTER TABLE events RESET (
            autovacuum_vacuum_scale_factor, autovacuum_vacuum_threshold,
            autovacuum_vacuum_insert_scale_factor,
            autovacuum_vacuum_insert_threshold
        )""")

Changing storage parameters takes a SHARE UPDATE EXCLUSIVE lock. It does not block reads or writes, and reads and writes do not queue behind it while it waits, which makes this one of the few ALTER TABLE forms that is safe at noon. It does conflict with a vacuum already running on the table, and an anti-wraparound vacuum will not step aside, so the lock_timeout stays. The schema migration review agent will pass this migration for the same reasons.

The insert thresholds (PostgreSQL 13 and later) are there for append-mostly tables. A table that only receives inserts never accumulates dead tuples, so before version 13 its first vacuum was the anti-wraparound one, freezing 200 million transactions of rows in a single pass. Insert-triggered vacuums freeze pages gradually and make the forced vacuum a non-event.

The PR body states the old and new trigger points, the vacuum durations from the last month of server logs where log_autovacuum_min_duration is set, and what the agent will watch afterwards.

Guardrails That Live in Code

  • Read-only role, no exceptions. pg_monitor cannot call pg_terminate_backend on other users' sessions, drop slots, or roll back prepared transactions. The agent describes those actions in a finding with the exact statement, and a human runs it. Killing a session is quick to do and impossible to undo for whoever was eleven hours into a backfill.
  • Blockers go to the owner, not a channel. The usename and application_name map to a service through the catalog. An idle-in-transaction session from billing-worker goes to the billing team with a suggestion to set idle_in_transaction_session_timeout on that role.
  • Paging follows the approval-gate pattern in reverse. The agent may page on its own only from the deterministic thresholds in the prompt, re-checked in code. The model cannot escalate a ticket to a page by wording.
  • One tuning PR per table, two open per database. After merge the agent watches for a week: vacuum frequency should rise, duration per run should fall, and n_dead_tup at trigger time should match the new threshold. If vacuums on that table now occupy a worker more than half the time, it posts the revert.
  • Failed collection fails closed. A database the agent cannot reach gets a finding saying so. Silence must never mean healthy.

Run the first weeks in shadow mode, posting the forecast table and verdicts without opening PRs. The check is simple: for every blocked_by_* verdict, did a human looking at the same views name the same blocker?

Honest Limits

The forecast assumes next week burns transaction IDs like this week. A batch job that wraps each row in its own transaction can consume a month of IDs in an afternoon, and the agent will only see it at the next collection. Collect hourly on databases whose days_to_write_stop is under 60, and keep the plain CloudWatch alarm as the backstop.

The xmin horizon is cluster-wide for most purposes, but the agent reads one database per connection. A long transaction in a neighbouring database on the same instance shows up in pg_stat_activity and is caught; a temp table there is not, unless the collector visits every database, including the ones nobody remembers creating.

Fixed thresholds go stale. A proposal sized for 800 million rows is too aggressive after a retention job cuts the table to 50 million and too lax after it grows to five billion. The agent re-evaluates tables it has already tuned and proposes a new value when the row estimate moves by more than a factor of three, which means some tables will get a PR every year.

Finally, the agent prevents the emergency and does not handle it. Past 1.6 billion, version 14 and later switch a running vacuum into failsafe mode on their own, skipping index cleanup and throttling. If you are there, the job is a manual VACUUM (FREEZE, INDEX_CLEANUP OFF) on the oldest tables by a person who has first cleared every blocker in Step 2, and the query and vacuum tuning basics are reading for the week after.

#ai#sre#devops#postgresql#automation#reliability#performance#incident-response
D
DevToCashAuthor

Senior DevOps/SRE Engineer · 10+ years · Professional Trader (IDX, Crypto, US Equities)

I write about real infrastructure patterns and trading strategies I use in production and in live markets. No courses, no affiliate hype — just documentation of what actually works.

More about me →