PostgreSQL autovacuum

PostgreSQL Autovacuum Tuning for SaaS Databases

Tune PostgreSQL autovacuum by lowering cleanup thresholds on busy tables, giving workers enough resources, and removing transactions that prevent cleanup. For SaaS databases, per-table tuning matters because tenant activity rarely spreads evenly.

One customer’s bulk import can generate more maintenance work than thousands of quieter accounts. Meanwhile, large shared tables can accumulate substantial dead data before default thresholds trigger maintenance.

Start by separating three problems: when vacuum starts, how quickly it finishes, and whether PostgreSQL can remove obsolete rows.

Key Takeaways

  • Tune busy tables individually before making aggressive server-wide changes.
  • Monitor dead-tuple trends, vacuum progress, and application latency together.
  • Resolve retained snapshots and replication-slot retention before increasing vacuum resources.

How PostgreSQL Autovacuum Works

PostgreSQL uses multiversion concurrency control, or MVCC. Updates create new row versions, while older versions remain until no transaction needs them. Deletes also leave versions requiring cleanup.

Cleanup, statistics, and freezing

Autovacuum runs VACUUM to make dead-row space reusable and freeze old transaction IDs against wraparound. Its automatic ANALYZE work refreshes planner statistics, which helps PostgreSQL choose query plans.

Ordinary vacuum generally keeps reclaimed space inside the table. Therefore, an unchanged file size after vacuum doesn’t mean cleanup failed.

PostgreSQL’s routine vacuuming documentation explains these maintenance responsibilities.

When a table becomes eligible

In PostgreSQL 18, the update/delete trigger uses:

min(max_threshold, threshold + scale_factor * estimated_rows)

These abbreviations refer to the autovacuum_vacuum_* settings. Defaults are 100 million for the maximum, 50 for the threshold, and 0.2 for the scale factor.

For one million estimated rows, that means approximately 200,050 obsolete tuples before eligibility. Eligibility doesn’t guarantee an immediate worker.

Insert-triggered vacuum has separate threshold and scale-factor settings. Its calculation considers the proportion of unfrozen pages, so append-only tables still need vacuum. Freezing and visibility-map maintenance matter even without updates.

Match Settings to Your SaaS Workload

A shared table’s maintenance triggers operate at table level, not per tenant. Heavy activity from one tenant can therefore create cleanup pressure affecting everyone.

Global settings control worker capacity

autovacuum_max_workers limits concurrent workers across the server. PostgreSQL 18 also limits capacity through autovacuum_worker_slots; raising workers above available slots adds no capacity.

autovacuum_naptime controls the minimum interval between autovacuum runs on a database. It doesn’t guarantee every eligible table receives immediate attention.

autovacuum_work_mem limits memory per worker. Its default, -1, inherits maintenance_work_mem. Budget for concurrent workers alongside query memory and connections.

These settings have no per-table overrides.

Table overrides control maintenance behavior

Set table-specific options with ALTER TABLE ... SET (...). Useful overrides include:

  • autovacuum_vacuum_threshold, autovacuum_vacuum_scale_factor, and PostgreSQL 18’s autovacuum_vacuum_max_threshold control update/delete eligibility.
  • autovacuum_vacuum_insert_threshold and autovacuum_vacuum_insert_scale_factor control insert-triggered eligibility.
  • autovacuum_analyze_threshold and autovacuum_analyze_scale_factor control statistics refreshes.

Vacuum cost delay and cost limit also support table overrides. Lower delay or higher limit permits faster maintenance at the expense of competing I/O.

The autovacuum configuration reference documents server settings and table overrides.

For partitioned tables, tune individual partitions. Also schedule parent-table ANALYZE when needed, because autovacuum doesn’t automatically analyze partitioned parents.

Inspect Vacuum Activity and Bloat Signals

Run diagnostics in the affected database using an authorized monitoring role.

Start with table-level trends

SELECT relid::regclass AS table_name,
       n_live_tup,
       n_dead_tup,
       last_autovacuum,
       last_autoanalyze,
       autovacuum_count,
       pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 15;

PostgreSQL’s cumulative statistics reference describes these fields. Compare snapshots over time rather than judging one reading.

n_dead_tup is an estimate, not a bloat measurement. Persistent growth across completed vacuum cycles deserves investigation. Meanwhile, an old last_autovacuum timestamp may simply describe a quiet table.

For closer inspection, the pgstattuple extension reports tuple-level storage information. Its pgstattuple_approx function offers approximate live-tuple and free-space measurements with exact dead-tuple statistics. These scans still consume resources and require appropriate permissions.

Inspect work already running

SELECT pid,
       relid::regclass AS table_name,
       phase,
       heap_blks_total,
       heap_blks_scanned
FROM pg_stat_progress_vacuum;

Repeat the query to see progress. Heap scanning is only one phase, so its completion doesn’t mean the entire vacuum has finished.

Correlate progress with storage latency, CPU, replica lag, and application p95 latency. Also track age(datfrozenxid) in pg_database; transaction-ID age can create urgent maintenance needs even when dead-tuple counts look modest.

Remove Transactions and Slots That Prevent Cleanup

More workers can’t remove row versions that PostgreSQL must retain. Long-running snapshots can keep obsolete data alive while vacuum continues doing other useful work.

Inspect transaction ownership and age:

SELECT pid,
       application_name,
       state,
       now() - xact_start AS transaction_age,
       backend_xmin,
       pg_blocking_pids(pid) AS blockers
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
  AND pid <> pg_backend_pid()
ORDER BY xact_start
LIMIT 15;

Transaction age is a starting point; snapshot retention determines cleanup eligibility. An idle-in-transaction connection deserves attention, especially when application code leaves transactions open around external HTTP calls.

If a session is waiting on a lock, follow pg_blocking_pids() before intervening. An empty blocker array doesn’t rule out snapshot retention, because retaining row versions isn’t itself a lock wait.

Also inspect replication slots:

SELECT slot_name, active, xmin, catalog_xmin, restart_lsn
FROM pg_replication_slots;

The replication-slot view documentation distinguishes these retention markers. xmin can prevent user-table tuple cleanup; catalog_xmin retains catalog tuples. Meanwhile, restart_lsn concerns WAL retention.

Don’t drop a slot solely because it’s inactive. Resolve its consumer’s lifecycle deliberately, since removing required replication state can force resynchronization.

Example Configuration: Earlier Cleanup for Busy Tables

This illustrative PostgreSQL 18 configuration favors earlier maintenance and more worker capacity. It isn’t a universal sizing recommendation.

Server-wide configuration

Apply these through postgresql.conf or the managed service’s server-configuration mechanism:

autovacuum = on
autovacuum_max_workers = 5
autovacuum_naptime = '30s'
autovacuum_work_mem = '128MB'
autovacuum_vacuum_cost_limit = 1000
autovacuum_vacuum_cost_delay = '2ms'
log_autovacuum_min_duration = '1s'

Five workers require at least five available autovacuum_worker_slots. Changing that slot allocation requires a restart; the other settings above can reload in PostgreSQL 18.

Workers can collectively use up to 640 MB of configured vacuum memory, plus other overhead. The higher cost limit permits more maintenance work between sleeps. However, autovacuum normally balances the shared cost budget across workers, so five workers don’t each receive the full limit independently.

Logging completed autovacuum operations lasting at least one second helps reveal duration and cleanup patterns.

Per-table configuration

For an application table named public.invoices:

ALTER TABLE public.invoices SET (
  autovacuum_vacuum_threshold = 1000,
  autovacuum_vacuum_scale_factor = 0.02,
  autovacuum_analyze_threshold = 1000,
  autovacuum_analyze_scale_factor = 0.01
);

At one million estimated rows, the vacuum trigger becomes approximately 21,000 obsolete tuples. The analyze trigger becomes approximately 11,000 changed rows.

Earlier runs reduce backlog, but increase maintenance frequency. Keep server-wide trigger defaults unchanged initially so quiet tables don’t inherit unnecessary work.

Tune PostgreSQL Autovacuum in Controlled Steps

  1. Establish a baseline. Record table sizes, dead-tuple estimates, vacuum counts, transaction-ID ages, storage latency, and application p95 latency. Include peak tenant activity and scheduled jobs rather than measuring only quiet periods.
  2. Classify the workload. Separate update-heavy shared tables, append-only event tables, and quiet reference tables. For shared tables, measure the busiest tenants’ write rates because table-wide averages can hide concentrated churn.
  3. Remove cleanup blockers. Investigate old snapshots and replication slots before changing resources. Keep API transactions short, and use role-appropriate idle_in_transaction_session_timeout settings. This timeout terminates sessions idle inside transactions; it doesn’t stop actively running statements.
  4. Adjust eligibility before capacity. Lower thresholds on one busy table, then observe completed maintenance cycles. If eligible tables queue behind occupied workers, consider additional workers. If individual runs progress too slowly, evaluate cost settings, memory, and available I/O separately.
  5. Test through sustained traffic. Compare maintenance completion with incoming write volume and customer-facing latency. During migrations, process backfills in bounded transactions using an indexed cursor. Commit between batches, preserve tenant filters and RLS context, and pause backfills when resource contention exceeds your operating limits.

Change one setting group at a time so regressions have an identifiable cause. Keep the previous values available for rollback.

For uneven tenant activity, partitioning may provide separate maintenance boundaries when it also fits query and retention requirements. Don’t introduce thousands of partitions solely to obtain different autovacuum settings; each partition adds planning and operational considerations.

Frequently Asked Questions

Should we disable autovacuum during a bulk update?

Keep it enabled. Bulk updates create obsolete row versions, and disabling cleanup lets maintenance debt accumulate. Smaller committed batches give vacuum opportunities to work between batches. Anti-wraparound protection can still trigger vacuum even when ordinary autovacuum is disabled.

Will VACUUM shrink a bloated table?

Ordinary vacuum generally makes space reusable within the table. VACUUM FULL rewrites it and requires an ACCESS EXCLUSIVE lock, which blocks normal access. Treat shrinking as separately planned maintenance, not a routine response to elevated dead-tuple estimates.

Keep Cleanup Ahead of Write Traffic

Reliable autovacuum tuning combines earlier table-level triggers, sufficient worker capacity, and transactions that release obsolete row versions promptly. Lower thresholds alone won’t solve blocked cleanup or saturated storage.

Start with one busy table and compare complete maintenance cycles under representative traffic. Keep the settings that control backlog without pushing customer-facing latency beyond your limits.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *