Tuning PostgreSQL autovacuum

Autovacuum keeps dead rows, statistics and transaction IDs under control, but default settings often lag behind write-heavy tables. This page explains which settings to change, how to measure the effect and how to find tables autovacuum never finishes.

On this page

PostgreSQL autovacuum tuning: when the defaults fall behind

If bloat, slow queries or wraparound warnings keep appearing on your busiest tables, the usual cause is that autovacuum is not keeping pace with the rate at which those tables change. Autovacuum runs in the background and is the mechanism that keeps up with dead row versions, not a setting you can ignore once the server is live. It does three jobs: it removes dead tuples so their space can be reused, it refreshes the planner statistics that query plans depend on through the analyze step, and it freezes old transaction IDs so the database never runs out of them. When any of those jobs falls behind, you see a different symptom: tables growing on disk, plans that drift from reality, or a warning that a database is approaching transaction ID wraparound.

Default thresholds are written for an average table. Autovacuum starts a run on a table once its dead tuples exceed a base threshold plus a fraction of the table's row count, so on a very large table the fraction can mean millions of dead rows accumulate before any work starts. The same logic makes a small table with a high update rate get vacuumed often but briefly, while a large, fast-changing table can run for hours and still be behind when the next burst of writes arrives. Cost-based throttling, the limit on worker count and the number of workers available to the whole cluster add further constraints. Confirm the current default values for your PostgreSQL version in the autovacuum documentation before you change anything, because a change that looks reasonable on paper can make a busy table worse if workers are already saturated.

Tuning should start with measurement, not with a list of settings to copy. Identify which tables show high dead tuple counts, long or repeated autovacuum runs, or a steadily rising age, and record when autovacuum last ran on them. Then decide per table whether the problem is a threshold that starts too late, a throttle that makes each run too slow, or a worker shortage across many tables. Per-table storage parameters are usually the right first lever for one or two large tables, because they avoid changing behavior for the whole cluster. Ask whoever runs your database to confirm which monitoring source already exposes these figures, so the baseline is captured before the first change.

Which autovacuum settings fit which symptom

This table matches each autovacuum setting to the symptom it addresses, the trade-off of changing it, and whether a reload is enough. Find the symptom you see in production first, then change only the settings that address it. Confirm exact defaults against the PostgreSQL documentation for your version before editing any value.

SettingSymptom it addressesTrade-off when raised or loweredReload or restart
autovacuum_vacuum_scale_factorLarge tables where dead tuples pile up between runs because the default fraction of rows triggers vacuum too lateLowering it vacuums more often and uses more I/O; raising it lets bloat grow between runsReload
autovacuum_vacuum_thresholdSmall, frequently updated tables that need a fixed floor of dead rows before vacuum startsLowering it increases vacuum frequency on small tables; raising it delays cleanupReload
Per-table storage parameters (autovacuum_vacuum_scale_factor, autovacuum_vacuum_threshold on the table)One hot table that needs far more aggressive settings than the rest of the clusterPrecise control, but each override must be tracked and reviewed as data growsReload
autovacuum_max_workersMany tables due for vacuum at once, so some write-heavy tables wait in the queueMore workers clear backlogs faster but share the cost limit and add I/O and CPU loadRestart
autovacuum_vacuum_cost_delay and autovacuum_vacuum_cost_limitAutovacuum runs too slowly to keep up with write volume, or it competes with user queries for I/OLower delay or higher limit makes vacuum faster and heavier on disk; the reverse protects foreground latencyReload
autovacuum_freeze_max_ageTables approaching transaction ID wraparound that need anti-wraparound vacuum earlierLower values force freezing sooner and more often; higher values postpone work but leave less marginRestart
autovacuum_vacuum_insert_thresholdAppend-heavy tables that rarely update or delete, so visibility map and freezing lag behind insertsLower values vacuum insert-only tables more often; higher values defer that maintenanceReload
log_autovacuum_min_durationSlow or repeated autovacuum runs that need evidence before any tuningLogging every run adds log volume; set a threshold so only long runs appearReload

How to tune autovacuum safely in production

This sequence moves from confirming that autovacuum is falling behind to changing settings one table and one host at a time, so each change can be measured against a baseline. It ends with before and after evidence that the tuning held under real write load.

  1. Confirm the problem with dead tuple counts

    Start by querying the statistics views for dead tuples and last autovacuum and autoanalyze times, using pg_stat_user_tables with columns such as n_dead_tup, n_live_tup, last_autovacuum and last_autoanalyze. The DBA or platform engineer running the check should record the results with the table size and the time of day. The step is done when you can name the tables where dead tuples keep growing or where the last autovacuum run is far older than the last burst of writes. If the numbers look normal, stop here, because tuning will not fix a problem that is not present.

  2. Enable slow autovacuum logging

    Set log_autovacuum_min_duration in postgresql.conf to a threshold your team chooses, then reload the configuration. Each autovacuum run that exceeds the threshold is written to the server log with its duration, pages removed and dead tuples found. Confirm the setting with SHOW log_autovacuum_min_duration; and check the log after a busy period. The step is done when the log shows entries for the tables you flagged, which gives you a timing baseline before any change. Choose the threshold with the team that reads the logs, since a very low value produces a lot of output.

  3. Identify the top write-heavy tables

    Rank tables by insert, update and delete activity using the cumulative counters in pg_stat_user_tables, such as n_tup_ins, n_tup_upd and n_tup_del, sampled over a window that includes normal business load. Compare the ranking with table size and with the dead tuple numbers from the first step. The output is a short list of candidate tables, usually a handful of large, frequently updated ones. Ask the application owners whether any of these tables have batch jobs at known times, because that timing affects when autovacuum should be allowed to run.

  4. Set per-table scale factors and thresholds

    For each candidate table, set storage parameters such as autovacuum_vacuum_scale_factor, autovacuum_vacuum_threshold, autovacuum_analyze_scale_factor and autovacuum_analyze_threshold with ALTER TABLE ... SET (...). Lower scale factors make autovacuum start sooner on large tables, where the default fraction of rows would otherwise allow a lot of bloat to build before a run. Record each change in version control with the reason. The step is done when pg_class.reloptions shows the new values for each table and the next autovacuum runs on those tables appear in the log. Confirm the exact parameter names and defaults against the current PostgreSQL documentation for your major version before you apply them.

  5. Check I/O headroom before changing cost limits

    Before raising autovacuum_vacuum_cost_limit, lowering autovacuum_vacuum_cost_delay or increasing autovacuum_max_workers, have the infrastructure team measure disk utilization, latency and queue depth during peak writes. Autovacuum competes with application queries for the same storage, so more aggressive settings on a saturated disk can slow the whole system. The output is a written statement of available I/O capacity at peak. Change one global setting at a time, reload, and repeat the measurement. Ask your storage or cloud provider for the IOPS and throughput limits that apply to your volumes, because these set the ceiling for any worker count you choose.

  6. Review freeze settings and transaction age

    Check how close each database and table is to the point where anti-wraparound vacuum becomes mandatory by querying age(relfrozenxid) for tables and datfrozenxid for databases. Review autovacuum_freeze_max_age and related freeze parameters against the largest tables, and confirm that aggressive freeze runs will finish within your maintenance and I/O limits. The step is done when you have a current list of tables with the oldest frozen transaction IDs and a documented decision on each freeze setting. Treat any table approaching the limit as a priority, and follow the PostgreSQL operations guidance on wraparound if the numbers are already high.

  7. Verify with before and after metrics

    Repeat the dead tuple query, the autovacuum log review and the I/O measurements over a comparable period after the changes are in place. Compare last autovacuum times, dead tuple counts, run durations in the log and disk latency against the baseline captured in the first steps. The step is done when a written comparison shows the target tables stayed close to their live row counts and the host stayed within its I/O headroom. If a table still falls behind or a run never finishes, return to the logs and keep the change under review rather than assuming it worked.

Freeze settings and transaction ID age

PostgreSQL uses 32-bit transaction IDs, and autovacuum prevents the counter from wrapping around by freezing old row versions so they remain visible regardless of the counter's position. The freeze settings are a risk decision, not a speed setting. Lowering autovacuum_freeze_max_age makes anti-wraparound vacuums start earlier and run more often, which spends I/O on tables that might not need it yet. Raising it defers that work and leaves a larger safety margin to consume. Before changing either value, query age(datfrozenxid) per database and age(relfrozenxid) per table to see how close each object is to the threshold, and record the current values of autovacuum_freeze_max_age, vacuum_freeze_min_age and vacuum_freeze_table_age so the change is reviewable.

Per-table storage parameters let you set freeze behavior for a specific hot table without changing the cluster default. autovacuum_freeze_max_age can be overridden per table, which is useful when one large append-only table reaches the threshold on its own schedule. Autovacuum also raises its own priority once a table crosses the anti-wraparound limit, and it will run even when autovacuum is disabled for that table, so turning autovacuum off to save I/O is not a freeze strategy. The sensible decision is which tables will reach the threshold first, how long an anti-wraparound vacuum on each one is likely to take on your hardware, and whether that run can overlap with peak write traffic. Measure this in a staging copy with realistic table sizes rather than estimating it.

Confirm your exact version's documented defaults and behavior in the PostgreSQL routine vacuuming documentation before setting thresholds. If the cluster is approaching the wraparound limit, the recovery steps belong to the operations and troubleshooting pages for PostgreSQL, so this section only covers how to keep that from happening. Treat freeze settings as part of your monitoring plan: alert on the age of the oldest transaction ID per database and per large table, and record who approves any change to freeze thresholds, because a value that looks conservative for speed can leave a table with too little margin during an unexpected outage.

Spotting tables autovacuum never finishes

Autovacuum can run every day and still fall behind. The cards below cover the signals that show a table is not being cleaned, where to look for each one in pg_stat_activity and pg_stat_all_tables, and the fix that usually follows. Check them in order, because a blocked vacuum and an under-throttled vacuum look similar from the outside.

Vacuum runs that never complete

A vacuum on a large, busy table can run for hours. Open pg_stat_activity and filter for rows whose query begins with autovacuum and whose query_start is old. Then compare pg_stat_progress_vacuum for the same process to see whether the heap scan is advancing. If the phase has not moved for a long time, the worker is either throttled or waiting. Raising cost limits or splitting the table's maintenance window are the usual fixes.

Continuous archiving docs

Repeated anti-wraparound runs

A table that keeps triggering anti-wraparound vacuum is a warning sign. Check relfrozenxid age in pg_class and last_autovacuum in pg_stat_all_tables. If the same table is vacuumed for freezing again and again without the age dropping, the freeze pass is not completing. Lower autovacuum_freeze_max_age per table on very large tables, and plan freeze work before the age approaches the limit.

Long transactions blocking cleanup

Vacuum cannot remove dead tuples that a running transaction can still see. Look in pg_stat_activity for sessions with an old xact_start, especially those in state idle in transaction. Also check pg_replication_slots and standby feedback, since a lagging consumer holds back the xmin horizon. Ending or fixing the long session is usually the fix, and no tuning setting will help until it is resolved.

Cost limits too low for table size

Autovacuum sleeps after doing a set amount of work, controlled by autovacuum_vacuum_cost_limit and autovacuum_vacuum_cost_delay. On a large table, a conservative budget can keep one worker busy for a very long time while dead tuples accumulate. Compare the pace of pages_scanned in pg_stat_progress_vacuum with the table's size. If progress is slow and no lock or transaction blocks it, raise the limit for that table or lower the delay.

Dead tuples rising despite frequent runs

When n_dead_tup in pg_stat_all_tables keeps climbing even though last_autovacuum is recent, vacuum is finishing but not keeping up. The table may be receiving writes faster than one worker can clean them. Check whether the table has a low autovacuum_vacuum_scale_factor and whether the worker count (autovacuum_max_workers) is shared across too many busy tables. Give the hot table its own thresholds before raising global settings.

Index bloat left behind

Vacuum removes dead index entries, but indexes that were heavily updated can stay large. Compare index size over time with pg_relation_size and check idx_scan in pg_stat_all_indexes for indexes that are rarely read. Heavy bloat that vacuum cannot return to the operating system usually needs a planned REINDEX CONCURRENTLY or a rebuild during a quiet window, along with a review of which indexes the workload still needs.

How the tuning loop fits together

The loop starts with pg_stat_user_tables and autovacuum log output, which show dead tuples, last vacuum times and how long runs take. Tables that stay over threshold are then matched to a fix: per-table storage parameters for the few write-heavy tables, or global cost limits and worker counts when many tables lag. After a reload, the slow-run logs show whether the change worked. If a table still lags, or a long transaction keeps cleanup from removing dead rows, the loop returns to measurement.

The measure, adjust, reload and observe cycle for autovacuum tuning.

How tuning differs by workload and hosting

Event, log and audit tables mostly receive inserts and rarely see updates or deletes. Because dead tuples are scarce, the main risk is not bloat but vacuum falling behind on freezing and visibility map maintenance, which grows as the table grows. Tuning focuses on making sure vacuum runs at a steady pace instead of in rare, large bursts that compete with ingestion.

  • Per-table thresholds: Lower the scale factor for the largest tables so vacuum runs on a predictable schedule rather than after a very large number of rows change.
  • Freeze settings: Review autovacuum_freeze_max_age and vacuum_freeze_min_age on the biggest tables so anti-wraparound vacuums do not arrive as unplanned, long runs.
  • Insert-triggered vacuum: Check how insert-driven autovacuum behaves on your PostgreSQL version, since it exists to keep the visibility map current on tables that never update.
  • Cost limits: Raise autovacuum_vacuum_cost_limit only as far as I/O headroom allows during ingestion peaks.
  • Slow run logging: Set log_autovacuum_min_duration so long freeze runs on the largest tables appear in logs.

Check how long autovacuum runs on the largest tables, whether anti-wraparound runs occur during business hours, and whether ingestion latency rises while vacuum is active.

Operational risks when changing autovacuum

Autovacuum settings change how hard the database works in the background, and that work competes with your application for disk, CPU and attention. The six risks below connect because each one is easy to miss after a tuning change looks successful on paper.

I/O saturation from aggressive cost limits

Raising the autovacuum cost limit or lowering cost delay lets workers read and write pages faster. On a busy disk, that speed can push out foreground queries and checkpoint writes. Before raising limits, check disk utilization, write latency and I/O wait during the heaviest hour of the day. Raise limits in small steps on one table group, then compare query latency and I/O wait against the baseline.

Continuous archiving docs

Extra load during business hours

Per-table thresholds can make vacuum run more often on a table that is busy at noon. A table that qualifies for vacuum at 2 p.m. may trigger heavy I/O while customers are active. Review the time windows when vacuum runs on your largest tables, and consider whether scheduled manual runs during quieter periods fit your operating model. Confirm with your own workload data rather than assuming off-peak timing is automatic.

Configuration drift across replicas

Settings in postgresql.conf and per-table storage parameters are not always applied identically on every node. A standby promoted after failover may run with older autovacuum values than the primary, and vacuum behavior then changes at the worst moment. Compare effective settings on each node after every change, and record which values were applied and when, so a failover does not silently change maintenance behavior.

Monitoring and alerting on autovacuum activity

Autovacuum runs silently unless you measure it. Without alerts on dead tuple counts, time since the last vacuum, and runs that exceed an expected duration, a table can fall behind for weeks before anyone notices. Track the statistics views that record last autovacuum times and dead tuples per table, and alert when a high-write table has not been vacuumed within the window you chose. Logging slow runs gives you the duration history needed to judge changes.

Change control for persistent settings

Storage parameters set with ALTER TABLE persist in the catalog until someone changes them again, and they outlive the reason they were set. Keep a written record for each change, including the table, the value, the expected effect and the rollback value. Review these settings during upgrades, since major version changes are a natural point to confirm that each override still fits the workload.

Access controls on storage parameter changes

Any role that owns a table can usually change its autovacuum storage parameters, so a broad grant on ownership or ALTER rights can change maintenance behavior for critical data. Limit ownership of production tables to a small set of accounts, restrict who can change server-wide settings, and log DDL changes. Confirm your own role model with your database administrators, because the exact privileges depend on how your team manages ownership.

Authentication methods docs

Questions teams ask before tuning autovacuum

How much effort does an autovacuum tuning engagement take?

The effort depends mostly on how many tables are affected, how write-heavy they are, and how much history the team has about their workload. A review of a single cluster with a few hot tables is much smaller than a review of a fleet with many databases, mixed workloads and unclear ownership of each table. Effort also rises when the team has no monitoring of dead tuples, vacuum runs or bloat, because the engineer must first establish a baseline before changing any setting. Ask for the scope in writing, including which clusters, which databases and how many tables are in the review, and whether the work includes testing in a non-production environment. Every change should be verified against the same measurements used to find the problem.

Can our own team tune autovacuum without a partner?

Yes, if the team has someone who can read pg_stat_user_tables, interpret pg_stat_progress_vacuum and make changes through a controlled release process. The settings themselves are documented in the PostgreSQL manual, and many teams adjust per-table storage parameters successfully. The harder part is judging side effects: a more aggressive setting can add I/O during peak hours, and a too-gentle one lets bloat grow until queries slow down or a freeze deadline approaches. A partner is most useful when the team lacks time to measure, when several teams share the cluster, or when the database is subject to audit and changes need a documented rationale. Confirm internally who owns each table and who approves production changes before deciding.

What does the work need from our staff and monitoring?

You need database access with enough privilege to read statistics and change table storage parameters, a person who knows the application's write patterns, and a change window for production. Monitoring should cover dead tuple counts, last autovacuum and autoanalyze times, table and index size growth, and I/O load on the storage. Without these, tuning becomes guesswork. Staff should also be able to log autovacuum runs that exceed a threshold, which requires setting log_autovacuum_min_duration and reviewing the output regularly. Ask what the engagement needs from your side before work starts, including who will review the logs after the changes, because the settings only hold if someone watches the effect over several weeks.

How long before autovacuum changes show results?

The first visible change is usually in the autovacuum logs and table statistics, because new runs start on the new thresholds, but whether query performance or bloat improves depends on how far behind the tables were. A table that has accumulated large amounts of dead rows needs one or more full cycles to catch up, and cost limit changes take effect only when the next worker starts. Settings for freezing and wraparound are judged over longer periods, since the goal is to avoid forced vacuums rather than to see an immediate gain. A realistic plan agrees on the measurements that will be checked and when, rather than promising a single date. Ask the team to define those checkpoints in the written scope.

What should a quote for autovacuum tuning include?

A quote should list the systems and databases covered, the tables in scope, the baseline measurements to be collected, the changes proposed per table and globally, and the testing approach before production. It should state what is delivered, such as a settings report, a change script, logging configuration and a review at an agreed point. It should also separate one-time work from anything recurring, for example monitoring review or follow-up tuning as the workload grows. Ask whether the quote covers staff time for knowledge transfer and whether retesting after a PostgreSQL upgrade is included. DeployOpen plans most engagements as fixed scope, with the scope and deliverables agreed in writing before work starts.

Do autovacuum settings differ between PostgreSQL versions?

The core parameters and the per-table storage options are broadly the same across supported major versions, but defaults, logging behavior and some statistics views change over time, so the reference must match the version actually running. Supported versions today are 18, 17, 16, 15 and 14, and the PostgreSQL versioning policy sets the end-of-support dates for each. Check the release notes for the version you are moving to before copying settings from an older cluster, and retest after a major upgrade because planner and I/O behavior can shift. If you plan a major upgrade, tune after the upgrade, not before, so the measurements reflect the new engine.

When should a tuning review be paired with pg_stat_statements or bloat analysis?

Pair them when the symptoms are slow queries or growing table sizes, because autovacuum is only one cause of both. Autovacuum settings can keep a table tidy, yet a slow query may come from a poor plan or a missing index, and bloat may come from long-running transactions that stop vacuum from removing dead rows at all. Running pg_stat_statements first shows which queries cost the most, and a bloat analysis shows which tables and indexes hold the excess space. Together they show whether a vacuum change will help, or whether the fix lies elsewhere. Ask the reviewer to check long transactions and replication slots as part of the same review, because these often block vacuum.

How DeployOpen scopes autovacuum tuning

DeployOpen plans autovacuum tuning as a fixed-scope piece of work on PostgreSQL you run in your own infrastructure. We start from the tables your team has measured, agree the changes and tests in writing, and leave your team with settings, dashboards and a runbook they can maintain.

How we scope

  • Agree the list of write-heavy tables and the symptoms that prompted the review before any setting changes
  • Define which tables get per-table storage parameters and which stay on the cluster defaults
  • Write the scope, deliverables and timeline down before work starts, with a quote that follows from it

How we build

  • Measure dead tuples, vacuum runs and freeze age on your production-like environment before changing thresholds
  • Apply per-table scale factors, cost limits and worker counts in a staged change with rollback steps
  • Test freeze settings and slow-run logging against a representative workload and record the observed effect

How we hand over

  • Document every changed parameter, its previous value, the reason for the change and the test that supported it
  • Set up logging of slow autovacuum runs and a view of tables that autovacuum never finishes
  • Walk your database and operations team through the monitoring queries and the runbook for future tuning

How we support

  • Review autovacuum behavior after major application releases, schema changes or large data loads when you request it
  • Offer ongoing support, upgrades and continuous checks as a retainer if your tables keep changing
  • Confirm with your PostgreSQL version's support schedule before planning changes that depend on version-specific behavior

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.