Autovacuum Tuning in PostgreSQL
Autovacuum is PostgreSQL's automatic background process that:
- Removes dead tuples created by UPDATE/DELETE.
- Updates optimizer statistics (ANALYZE).
- Prevents transaction ID wraparound, which is critical for database survival.
A DBA's first priority is often:
Ensure autovacuum is running effectively before changing application code.
How Autovacuum Decides to Run
For VACUUM:
Default values:
Example:
Table:
Trigger:
After about 2050 updates/deletes:
Problem with Large Tables
Consider:
Default trigger:
Autovacuum waits until:
which is often far too late.
This causes:
Typical Production Setting
Instead of:
Many DBAs use:
or
Example:
Trigger:
Much more aggressive.
Important Parameters
1. autovacuum_vacuum_scale_factor
Most important tuning parameter.
Check:
Typical values:
| Table Type | Value |
|---|---|
| Small tables | 0.05 - 0.2 |
| OLTP tables | 0.01 |
| Heavy update tables | 0.005 |
| Very busy tables | 0.001 |
2. autovacuum_vacuum_threshold
Default:
Formula:
Example:
Useful when small tables receive frequent updates.
3. autovacuum_analyze_scale_factor
Controls statistics refresh.
Default:
For OLTP systems:
or
helps query planning.
4. autovacuum_max_workers
Default:
Number of autovacuum workers.
Large systems:
or
Common on servers with:
5. autovacuum_naptime
Default:
Worker wake-up interval.
Usually:
is fine.
Rarely changed.
6. autovacuum_vacuum_cost_limit
Controls speed.
Default:
Many production systems:
or
Allows faster cleanup.
7. autovacuum_vacuum_cost_delay
Default:
Lower value:
or
means faster vacuum.
Tradeoff:
Per-Table Tuning
Usually better than global tuning.
Example:
Very common for:
Monitoring Autovacuum
Check Dead Tuples
Look for:
Last Vacuum
Running Vacuums
Shows:
Detect Table Bloat
Common symptom:
even though row count stays stable.
For example:
Usually means:
Anti-Patterns
1. Disabling Autovacuum
Dangerous.
Can lead to:
Never disable without a specific reason.
2. Increasing Scale Factor
Bad idea:
Large tables may never get cleaned in time.
3. Ignoring Long Transactions
Check:
A transaction running for hours can prevent dead tuple removal even if autovacuum runs.
Transaction ID Wraparound (Most Important)
Autovacuum does more than reclaim space.
PostgreSQL transaction IDs are finite (~2 billion usable before danger).
Autovacuum freezes old tuples:
Without this:
PostgreSQL will eventually force emergency vacuuming to avoid corruption.
So:
Oracle DBAs typically worry about UNDO_RETENTION, while PostgreSQL DBAs worry about whether Autovacuum can keep up with dead tuples and transaction ID freezing.
Practical OLTP Starting Point
For a busy application database:
Then monitor:
and tune high-update tables individually rather than applying extremely aggressive settings to the entire cluster.
No comments:
Post a Comment