Autovacuum Tuning and Maintenance
Intermediate12 min
Configure and monitor PostgreSQL autovacuum to reclaim dead tuples, prevent table bloat, and avoid transaction ID wraparound.
Prerequisites
- -PostgreSQL database with write activity
- -Superuser access for configuration changes
Steps
1
Check current autovacuum settings
View the running autovacuum configuration parameters.
$ psql -U postgres -c "SELECT name, setting, short_desc FROM pg_settings WHERE name LIKE 'autovacuum%' ORDER BY name;"
2
Find tables needing vacuum
Identify tables with the most dead tuples that are waiting for vacuum.
$ psql -U postgres -d mydb -c "SELECT relname, n_live_tup, n_dead_tup, round(n_dead_tup::numeric / GREATEST(n_live_tup, 1) * 100, 2) AS dead_pct, last_autovacuum FROM pg_stat_user_tables WHERE n_dead_tup > 1000 ORDER BY n_dead_tup DESC LIMIT 10;"
3
Run manual vacuum with verbose output
Manually vacuum a specific table and see detailed statistics.
$ psql -U postgres -d mydb -c "VACUUM (VERBOSE, ANALYZE) orders;"
ANALYZE updates table statistics for the query planner. Always combine VACUUM with ANALYZE.
4
Check table bloat
Estimate wasted space from dead rows in frequently updated tables.
$ psql -U postgres -d mydb -c "SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) AS total_size, n_dead_tup, last_autovacuum, last_autoanalyze FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT 10;"
5
Tune autovacuum for a heavy-write table
Override autovacuum settings at the table level for high-throughput tables.
$ psql -U postgres -d mydb -c "ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.05, autovacuum_analyze_scale_factor = 0.02, autovacuum_vacuum_cost_delay = 10);"
Lower scale factors trigger vacuum sooner. Default is 0.2 (20% dead tuples). Set 0.05 for active tables.
Full Script
FAQ
Discussion
Loading comments...