skip to content

VACUUM

removing dead versions, cleaning indexes, and why the file doesn't shrink. VACUUM FULL and the bloat it fixes.

address
everything.mvcc.vacuum
part
part 14, MVCC and vacuum
chapter
chapter 7 of 12
reading time
10 min

VACUUM finds row versions no snapshot can see anymore, removes the index entries that point at them, and marks their slots free for reuse. it also sets the visibility map and records free space. what it doesn't do is give space back: the file stays the size it was, except for empty pages at the very end. VACUUM FULL writes a brand new, compact file, and holds an ACCESS EXCLUSIVE lock on the table the whole time.

the picture

you know how nothing in postgres is ever overwritten? every UPDATE and DELETE leaves a dead version behind. something has to come round and collect them, or every table only ever grows, and every scan wades through more and more dead rows. that's VACUUM.

think of a car park. VACUUM is the attendant walking the levels, towing abandoned cars and painting their bays as free (the free space map), and putting a "nothing to do here" sticker on each clean level (the visibility map). the car park is still the same size afterwards. new cars fill the free bays. VACUUM FULL is building a new, smaller car park next door, driving every car across, and demolishing the old one, with the gates shut while it happens.

here's a six-page table on a real postgres 18.6 server: two rows in every three deleted, then VACUUM, then VACUUM FULL.

the table as loaded
file 6 pages (48 KB)live 47,328 Bdead 0 Bfree 864 B

204 rows, 34 to a page, six pages, vacuumed once: every page is all-visible.

live tuplesdead tuplesfree spacepage header, VM bits (● all-visible, ■ all-frozen)
step 1/4
real output, a postgres 18.6 server · vacuum-sweep
step through. after the DELETE every page is still full, two thirds dead. VACUUM turns the dead tuples into free space and sets every page's all-visible bit (●): still six pages. VACUUM FULL writes the 68 live rows into two new pages, and leaves the visibility map empty.

what VACUUM does, in order

hover a stage.

one plain VACUUM of one table. hover a stage. the indexes are cleaned before the heap slots are freed, so no index entry ever points at a slot that's been reused.

look at page 0, before and after the VACUUM. after the DELETE it held 34 tuples, every one still there. after the VACUUM:

the page =
byte 0 header line pointerstuples, byte 8,192
lower 160free 144 B, unlitupper 304
lpctidxminxmaxt_ctidid
(0,1)758760(0,1)1
(0,2)758760(0,2)2
(0,3)7580(0,3)3
(0,4)758760(0,4)4
(0,5)758760(0,5)5
(0,6)7580(0,6)6
(0,7)758760(0,7)7
(0,8)758760(0,8)8
(0,9)7580(0,9)9
(0,10)758760(0,10)10
(0,11)758760(0,11)11
(0,12)7580(0,12)12
(0,13)758760(0,13)13
(0,14)758760(0,14)14
(0,15)7580(0,15)15
(0,16)758760(0,16)16
(0,17)758760(0,17)17
(0,18)7580(0,18)18
(0,19)758760(0,19)19
(0,20)758760(0,20)20
(0,21)7580(0,21)21
(0,22)758760(0,22)22
(0,23)758760(0,23)23
(0,24)7580(0,24)24
(0,25)758760(0,25)25
(0,26)758760(0,26)26
(0,27)7580(0,27)27
(0,28)758760(0,28)28
(0,29)758760(0,29)29
(0,30)7580(0,30)30
(0,31)758760(0,31)31
(0,32)758760(0,32)32
(0,33)7580(0,33)33
(0,34)758760(0,34)34
tuple (0,1) · off 7960 · len 232 B
t_xmin758 committed
t_xmax760 committed
t_ctid(0,1) itself: the newest version
infomaskHASVARWIDTHXMIN_COMMITTEDKEYS_UPDATED
t_hoff24 B
dataid 1pad xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx…
headerline pointer → tuplefree space, unlitdeadin progress
real postgres 18.6 output · a native server · traces/vacuum-sweep

delete two rows in every three. every page still holds all its tuples, two thirds of them dead, and loses its all-visible bit. the index still has 204 entries.

switch moments and step through the slots. the deleted tuples' slots are unused afterwards, and the live tuples were slid together toward the end of the page, so the free space is one gap again.

11 live tuples and 22 unused slots, and free space went from 144 to 5484 bytes. the page has 33 line pointers now, not 34: slot 34 was the last one and unused, so it was cut off the array. unused slots in the middle can't be removed (that would change other tuples' ctids), so they wait for the next insert on this page.

the index lost its dead entries in the same VACUUM:

T1DELETE FROM t WHERE id % 3 <> 0
123… 198 more202203204root,a leaf

after the DELETE: 204 entries, still one per tuple, dead or not.

step 1/2
real output, a postgres 18.6 server · vacuum-sweep
t_pkey, one leaf page, before and after. two thirds of the keys go: the ones whose heap tuple was dead.

VACUUM (VERBOSE) says all of it in its own words. this is the server log from that step:

  1. INFO: vacuuming "postgres.public.t"
  2. INFO: finished vacuuming "postgres.public.t": index scans: 1
  3. pages: 0 removed, 6 remain, 6 scanned (100.00% of total), 0 eagerly scanned
  4. tuples: 136 removed, 68 remain, 0 are dead but not yet removable
  5. removable cutoff: 761, which was 0 XIDs old when operation ended
  6. frozen: 0 pages from table (0.00% of total) had 0 tuples frozen
  7. visibility map: 6 pages set all-visible, 0 pages set all-frozen (0 were all-visible)
  8. index scan needed: 6 pages from table (100.00% of total) had 136 dead item identifiers removed
  9. index "t_pkey": pages: 2 in total, 0 newly deleted, 0 currently deleted, 0 reusable
  10. avg read rate: 0.000 MB/s, avg write rate: 0.000 MB/s
  11. buffer usage: 48 hits, 0 reads, 0 dirtied
  12. WAL usage: 21 records, 0 full page images, 2360 bytes, 0 buffers full
real output, a postgres 18.6 server · vacuum-sweep
VACUUM VERBOSE on the capture's table. the lines worth reading are hot: what it removed, what it set in the visibility map, and the index pass.

"0 are dead but not yet removable": nothing was holding these versions back. when something is, that number isn't 0, and that's the xmin horizon.

the same thing in the browser

the same table, built in a block. nothing reads it before the VACUUM, so the browser engine's eager pruning never gets a chance:

sqldb=lab · session vac
CREATE TABLE t (id int PRIMARY KEY, pad text NOT NULL);
INSERT INTO t SELECT g, repeat('x', 200) FROM generate_series(1, 204) AS g ORDER BY g;
DELETE FROM t WHERE id % 3 <> 0;
SELECT pg_relation_size('t') AS heap_bytes, pg_relation_filenode('t') AS filenode,
       (SELECT sum(live_items) FROM bt_page_stats('t_pkey', 1)) AS index_entries,
       (SELECT count(*) FILTER (WHERE all_visible) FROM pg_visibility_map('t')) AS all_visible_pages;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 204
#3 · DELETE 136
#4 · SELECT 1
heap_bytesint8filenodeoidindex_entriesint8all_visible_pagesint8
49152245762040
(1 row)
sqldb=lab · session vac
continues session vac (1 earlier block run first)
VACUUM t;
SELECT pg_relation_size('t') AS heap_bytes, pg_relation_filenode('t') AS filenode,
       (SELECT sum(live_items) FROM bt_page_stats('t_pkey', 1)) AS index_entries,
       (SELECT count(*) FILTER (WHERE all_visible) FROM pg_visibility_map('t')) AS all_visible_pages,
       (SELECT sum(avail) FROM pg_freespace('t')) AS free_bytes;
output, from postgres 18.6
#1 · VACUUM
#2 · SELECT 1
heap_bytesint8filenodeoidindex_entriesint8all_visible_pagesint8free_bytesint8
491522457668632320
(1 row)

the same 49,152 bytes, the same file. a third of the index entries, every page all-visible, and the free space map now knows about the room on every page. new rows go into those bays, so the table won't grow until they're used up.

predict the output
after that VACUUM, you insert 100 new rows into t. how big is the file?
sql
INSERT INTO t SELECT g, repeat('y', 200) FROM generate_series(1001, 1100) AS g;
SELECT pg_relation_size('t');
sqldb=lab · session vac
continues session vac (2 earlier blocks run first)
INSERT INTO t SELECT g, repeat('y', 200) FROM generate_series(1001, 1100) AS g;
SELECT pg_relation_size('t') AS heap_bytes;
output, from postgres 18.6
#1 · INSERT 0 100
#2 · SELECT 1
heap_bytesint8
49152
(1 row)

VACUUM FULL

to actually shrink the file you have to move the rows, and moving rows changes their ctids, which every index points at. so VACUUM FULL doesn't move anything: it copies every live row into a new file, builds every index again from scratch, and switches the table over to the new files when it commits. the old files are deleted.

sqldb=lab · session vac
continues session vac (3 earlier blocks run first)
VACUUM FULL t;
SELECT pg_relation_size('t') AS heap_bytes, pg_relation_filenode('t') AS filenode,
       (SELECT count(*) FILTER (WHERE all_visible) FROM pg_visibility_map('t')) AS all_visible_pages;
output, from postgres 18.6
#1 · VACUUM
#2 · SELECT 1
heap_bytesint8filenodeoidall_visible_pagesint8
40960245850
(1 row)

a new file number (the relfilenode, see files and forks), and a smaller file. the price is the lock. while it copies, nobody else may read or write the table, so it takes ACCESS EXCLUSIVE, the strongest table lock. a plain VACUUM takes SHARE UPDATE EXCLUSIVE, which only conflicts with other vacuums and schema changes. captured on a real server:

T1
·
T2
snapshot 760:760:
T3
·
1
BEGIN; SELECT count(*) FROM t→ 68
lock manager
  • T2AccessShareLockt
  • T2AccessShareLockt_pkey
  • T2ExclusiveLock5/4

T2 opens a transaction and reads t. it holds an ACCESS SHARE lock on the table until it ends.

step 1/7
real output, a postgres 18.6 server · vacuum-full-lock
step through. plain VACUUM runs straight past T2's open read. VACUUM FULL waits for it, and T3's plain SELECT queues behind VACUUM FULL. the locks panel shows who holds what, granted or waiting.

the file went from 49152 bytes under file number 16466 to 16384 bytes under 16475. on a big table the copy takes minutes or hours, and for all of it the table is closed, and so is everyone who queues behind the lock: the lock queue chapter is about exactly that.

bloat

bloat is space a table or index takes beyond what its live rows need: dead tuples not yet vacuumed, plus free space vacuum created that new rows haven't filled. some is normal (a table with fillfactor 90 is "bloated" by design). a lot means vacuum is falling behind, or something is stopping it. indexes bloat too, and VACUUM doesn't shrink them either: emptied index pages are recycled within the index, and REINDEX CONCURRENTLY rebuilds one without blocking writes.

in the browser, VACUUM only runs when you type it. on a real server autovacuum does it in the background, triggered by how many rows changed. and VACUUM has one more job, the one that can't be skipped: freezing old tuples before the transaction counter wraps around.

keylines

  • VACUUM: prune, clean the indexes, free the slots, update the free space and visibility maps.
  • the file doesn't shrink, except for empty pages at the end. the free space gets reused.
  • VACUUM runs next to reads and writes. VACUUM FULL locks everyone out.
  • VACUUM FULL copies live rows into a new file with a new relfilenode and rebuilds the indexes.
  • bloat is dead or unused space. the fix is usually vacuuming more, not VACUUM FULL.