Sub topic 9
VACUUM FULL: reclaiming space with a table rewrite
This chapter assumes you have read the earlier chapters in this tutorial. You should know how MVCC leaves dead tuples behind, what table bloat is, and what plain VACUUM does. You should also be comfortable running SQL in psql and reading pg_stat_activity.
Plain VACUUM marks dead tuple space as reusable inside the table, but it rarely makes the file smaller. VACUUM FULL is the built-in way to shrink the file. It pays for that with a long, exclusive lock.
What VACUUM FULL does
VACUUM FULL builds a new copy of the table and discards the old one. The steps are:
- Take an
ACCESS EXCLUSIVElock on the table. - Read every live row version from the old file.
- Write those rows, packed tightly, into a new data file.
- Rebuild every index on the table from scratch.
- Swap the new files in for the old ones and delete the old files.
Dead tuples are never copied, so the new file has no bloat. Because the file is replaced, the space goes back to the operating system. Plain VACUUM can do this only when the free pages are at the very end of the file.
VACUUM FULL public.orders;The command rebuilds the indexes too, so it also removes index bloat on that table. It does not reorder rows by any index. That is what CLUSTER does.
Plain VACUUM compared with VACUUM FULL
| Aspect | VACUUM | VACUUM FULL |
|---|---|---|
| Lock taken | `SHARE UPDATE EXCLUSIVE` | `ACCESS EXCLUSIVE` |
| Reads and writes during the run | Allowed | Blocked |
| Disk file shrinks | Only by truncating empty pages at the end | Yes, rebuilt to the minimum size |
| Extra disk space needed | Almost none | About the size of the live data plus new indexes |
| Indexes | Cleaned of dead entries | Rebuilt from scratch |
| Can run inside a transaction block | No | No |
| Typical use | Routine, usually via autovacuum | Rare, one-time recovery |
A demonstration
This script creates a table, deletes 90% of its rows, and compares sizes after each kind of vacuum. Run it in a scratch database.
CREATE TABLE bloat_demo (
id integer PRIMARY KEY,
payload text NOT NULL
);
INSERT INTO bloat_demo
SELECT g, repeat('x', 100)
FROM generate_series(1, 200000) AS g;
SELECT pg_size_pretty(pg_total_relation_size('bloat_demo')) AS size_loaded;
DELETE FROM bloat_demo WHERE id % 10 <> 0;
VACUUM bloat_demo;
SELECT pg_size_pretty(pg_total_relation_size('bloat_demo')) AS size_after_vacuum;
VACUUM FULL bloat_demo;
SELECT pg_size_pretty(pg_total_relation_size('bloat_demo')) AS size_after_full;Expect size_after_vacuum to be about the same as size_loaded. Every page still holds some surviving rows, so VACUUM cannot truncate the file. After VACUUM FULL, the table and its index should be roughly ten times smaller. Exact numbers depend on your version and settings.
pg_total_relation_size counts the table, its indexes, and its TOAST data. That is the right measure here, because VACUUM FULL rewrites all three.
Costs and risks
The lock blocks everything
ACCESS EXCLUSIVE conflicts with every other lock mode, including the ACCESS SHARE lock that a plain SELECT takes. While the rewrite runs, no query can read or write the table. For a large table this can mean minutes or hours of an outage for anything that touches it.
The lock also hurts before the rewrite starts. If a long transaction holds any lock on the table, VACUUM FULL waits in line for it. Every query that arrives after it queues behind the waiting request, even though the long transaction would have let those queries through. A single VACUUM FULL can stall an application before it has done any work.
Set a short lock_timeout so the command gives up instead of building a queue:
SET lock_timeout = '5s';
VACUUM FULL public.orders;If the lock is not granted within five seconds, the command fails with an error and nothing has changed. Retry at a quieter moment.
It needs free disk space
The old file stays in place until the new one is complete. During the rewrite, you need room for the new table and the rebuilt indexes in addition to the existing files. If the disk fills up, the command fails and rolls back, which is safe but wasteful. Check free space before you start, especially when the table is a large share of the volume.
It generates WAL
The new table and indexes are written to the write-ahead log, so the rewrite produces WAL roughly in proportion to the size of the live data. This has three effects:
- Archive storage and replication bandwidth see a burst of traffic.
- Replicas replay the rewrite and may fall behind.
- The
ACCESS EXCLUSIVElock is replayed on standbys too. Queries on a standby that touch the table can be blocked or cancelled by replay conflicts.
It does not fix the cause
If the bloat came from an autovacuum that was too slow, or from a transaction that held back cleanup, the table will bloat again after the rewrite. Fix the cause first. The earlier chapters on autovacuum tuning and cleanup blockers cover the usual ones.
Planner statistics
VACUUM FULL updates the page and row counts in pg_class. It does not by default refresh the column statistics that the planner uses. Add ANALYZE if you want that done in the same command:
VACUUM (FULL, ANALYZE) public.orders;Watching a running rewrite
VACUUM FULL reports progress through the same view as CLUSTER. From another session, run:
SELECT pid,
relid::regclass AS table_name,
command,
phase,
heap_blks_total,
heap_blks_scanned,
heap_blks_written
FROM pg_stat_progress_cluster;The command column shows VACUUM FULL. The phase column moves through stages such as seq scanning heap, writing new heap, swapping relation files, and rebuilding index. If you cancel the command before the swap, the old table is intact and the partial new file is removed.
When to use it
VACUUM FULL is the right tool only when all of these hold:
- A large share of the table is empty space, and plain VACUUM will not give it back.
- The table can be taken offline for the duration, for example in a maintenance window, or it is small enough that the rewrite is quick.
- You have confirmed the cause of the bloat is fixed.
- There is enough free disk space for a second copy.
Reasonable cases include a one-time bulk delete, such as purging years of old data, or a table left bloated by an incident that has since been resolved.
It is the wrong tool for routine maintenance, for tables that serve live traffic, or for any situation where the bloat keeps returning. Do not schedule it on a timer.
If the table cannot go offline, the next chapter covers pg_repack and the REPACK command. These do a similar rewrite while holding the exclusive lock for only a short time.
Common errors
- "VACUUM cannot run inside a transaction block." Remove the
BEGIN, or turn off autocommit wrappers in your client. - "No space left on device." The new copy did not fit. The command rolls back and the old table is untouched. Free space or move the table to a larger tablespace before retrying.
- Lock timeout error. Another session held a conflicting lock. Look for it with
pg_stat_activityandpg_locks, then retry. - Size did not shrink as much as expected. Check that you measured the same thing before and after, ideally
pg_total_relation_size. Also check that live data is not already most of the table.
Exercise
A 200 GB table is 60% dead space after a one-time purge. The disk has 150 GB free. The table serves traffic, and the maintenance window is short. You run VACUUM FULL with lock_timeout set to 5 seconds. Name two ways this can still go wrong, and say what you would check first.
Show answer
First, the rewrite needs space for a new copy of the live data (about 80 GB) plus rebuilt indexes, so check that the free space covers both. Second, once the lock is granted, every read and write on the table is blocked for the entire rewrite, which for 80 GB of live data may exceed the maintenance window. The lock timeout only protects the wait for the lock, not the duration of the rewrite. Replicas also replay the rewrite and its lock, so check replication lag and standby queries. Because the table cannot be offline for long, an online method such as pg_repack is the better choice.
Exercise
After DELETE FROM t WHERE id % 10 <> 0 on a large table, plain VACUUM leaves the file size nearly unchanged, but VACUUM FULL shrinks it. Why?
Show answer
Plain VACUUM marks the dead tuple space as reusable within the table. It can truncate the file only when the empty pages are at the end, and here every page still contains surviving rows, so nothing can be cut off. VACUUM FULL copies only the live rows into a new, compact file and deletes the old one, so the space goes back to the operating system.