Sub topic 9
Reclaiming space: pruning, HOT updates, and VACUUM
This chapter assumes you know that an UPDATE writes a new row version and leaves the old one behind, and that you can read xmin, xmax, and ctid. It also assumes you can read heap_page_items output from pageinspect. Those topics come from the earlier chapters on tuple headers and row versions.
Why dead tuples pile up
PostgreSQL never overwrites a row in place. An UPDATE writes a new tuple and sets xmax on the old one. A DELETE only sets xmax. The old version stays in the page because some running transaction may still need to see it.
A dead tuple is a version that no current or future snapshot can see. Three mechanisms remove dead tuples, and they differ in who runs them and what they can clean:
| Mechanism | Who runs it | Scope | Touches indexes? |
|---|---|---|---|
| Page pruning | Any query that reads a page | One heap page | No |
| HOT update | The UPDATE itself | One heap page | Avoids new index entries |
| VACUUM | You or autovacuum | Whole table and its indexes | Yes |
What decides whether a tuple is dead
The server keeps a horizon: the oldest transaction ID that any running transaction or snapshot might still need. A tuple whose xmax committed before that horizon is dead to everyone and can be removed.
A long-running transaction, an idle-in-transaction session, a stale replication slot, or a forgotten prepared transaction holds the horizon back. While it does, no tuple deleted after that point can be reclaimed, and both pruning and VACUUM remove nothing from those pages.
Line pointer states
A line pointer (lp_flags) is in one of four states.
| `lp_flags` | Name | Meaning |
|---|---|---|
| 0 | `LP_UNUSED` | Free slot, can be reused by a new tuple |
| 1 | `LP_NORMAL` | Points to a tuple (`lp_off`, `lp_len`) |
| 2 | `LP_REDIRECT` | No tuple of its own. `lp_off` holds the offset number of another line pointer |
| 3 | `LP_DEAD` | Tuple is dead. Storage may or may not be reclaimed yet |
Line pointers cannot simply vanish. An index entry holds a ctid, and that ctid contains the line pointer number. While any index entry might still point at a slot, the slot must stay allocated. This is why cleanup happens in stages.
Page pruning
Pruning is opportunistic cleanup of a single heap page. When a query fetches a page, PostgreSQL checks whether pruning is likely to help. The page header records the oldest xmax that could become removable (pd_prune_xid). Pruning runs when that hint says something is removable and the page is nearly full. "Nearly full" means free space is below the larger of 10% of the page and the room reserved by fillfactor.
Pruning does the following:
- Removes the tuple data of dead versions and compacts the remaining tuples toward the end of the page, which creates one contiguous block of free space.
- Sets the line pointers of dead heap-only tuples (see the HOT section) to
LP_UNUSED, because no index entry can point at them. - Turns the line pointer at the start of a HOT chain into an
LP_REDIRECTthat points to the first live version. - Marks other dead tuples' line pointers
LP_DEAD. These have no storage left, but the slot stays because an index may reference it.
Pruning does not scan indexes, does not update the free space map, and does not shrink the file. A SELECT can write to a page this way, which is why read-only workloads sometimes generate WAL and dirty pages.
HOT updates
A normal UPDATE must insert a new entry into every index on the table, even indexes on columns it did not change. That is expensive, and it leaves more dead index entries behind. A HOT (heap-only tuple) update avoids this.
An update is HOT when both conditions hold:
- No indexed column changed value. In PostgreSQL 16 and later, changes to columns used only by summarizing indexes such as BRIN also qualify.
- The new version fits on the same page as the old one.
In a HOT update, the old tuple gets the HEAP_HOT_UPDATED flag. The new tuple gets HEAP_ONLY_TUPLE, and no index entry is created for it. The index keeps pointing at the first line pointer. A scan follows t_ctid from one version to the next inside the page until it finds the visible version. Later, pruning replaces the root with a redirect, and the chain's dead members disappear without any index work.
Watching a HOT update
This example uses a small table with fillfactor = 70, which leaves 30% of each page free for new versions. The bit masks 16384 (0x4000) and 32768 (0x8000) test HEAP_HOT_UPDATED and HEAP_ONLY_TUPLE in t_infomask2. Run each statement on its own so each commits separately.
CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE TABLE hot_demo (
id int PRIMARY KEY,
note text,
balance int
) WITH (fillfactor = 70);
INSERT INTO hot_demo VALUES (1, 'first', 100);
-- balance is not indexed, so this update can be HOT
UPDATE hot_demo SET balance = balance + 1 WHERE id = 1;
SELECT lp, lp_flags, lp_off, t_xmin, t_xmax, t_ctid,
(t_infomask2 & 16384) <> 0 AS hot_updated,
(t_infomask2 & 32768) <> 0 AS heap_only
FROM heap_page_items(get_raw_page('hot_demo', 0));You should see two rows. Line pointer 1 is the old version, with hot_updated true and t_ctid of (0,2). Line pointer 2 is the new version, with heap_only true. The primary key index has only one entry, which points at line pointer 1.
Now run VACUUM and look again:
VACUUM hot_demo;
SELECT lp, lp_flags, lp_off, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('hot_demo', 0));Line pointer 1 now has lp_flags = 2. Its lp_off is 2, the offset number it redirects to, and its tuple fields are null. Line pointer 2 holds the live row.
Next, change an indexed column, which forces a normal update:
UPDATE hot_demo SET id = 2 WHERE id = 1;
SELECT lp, lp_flags, t_xmin, t_xmax, t_ctid,
(t_infomask2 & 16384) <> 0 AS hot_updated,
(t_infomask2 & 32768) <> 0 AS heap_only
FROM heap_page_items(get_raw_page('hot_demo', 0));The new version has heap_only false because it needed its own index entry for the key value 2.
Tuning for HOT
Check how often updates are HOT with the statistics view:
SELECT relname, n_tup_upd, n_tup_hot_upd, n_dead_tup
FROM pg_stat_user_tables
WHERE relname = 'hot_demo';These counters are reported asynchronously, so they can lag a moment behind your statements. If n_tup_hot_upd is far below n_tup_upd on a heavily updated table, check two things:
- Indexes on frequently updated columns. Each one makes updates to that column non-HOT. Drop indexes you do not use.
- Free space on the page. Lower the fillfactor so a page keeps room for new versions:
ALTER TABLE hot_demo SET (fillfactor = 80);. The setting applies to pages filled afterward, so existing pages are unchanged until the table is rewritten. The trade-off is a larger table, since pages start out partly empty.
VACUUM
Pruning cannot free line pointers that indexes may reference. VACUUM does that job, in three steps:
- Scan the heap. VACUUM reads pages, prunes them, and records the TIDs of
LP_DEADline pointers in memory. The memory available for this list is set bymaintenance_work_mem(orautovacuum_work_mem). - Clean the indexes. VACUUM scans each index and deletes entries that point at the recorded TIDs.
- Clean the heap. The recorded line pointers change from
LP_DEADtoLP_UNUSED, so new tuples can reuse them.
If the TID list fills memory before the scan finishes, steps 2 and 3 run mid-scan and then step 1 resumes. Each extra round scans every index again, so a table with many indexes and too little vacuum memory vacuums slowly.
When it finishes, VACUUM also records free space in the free space map and marks pages in the visibility map. It also freezes old tuples to protect against transaction ID wraparound. If the last pages of the file are completely empty and VACUUM can take a brief exclusive lock, it truncates them and returns that space to the operating system.
Otherwise, plain VACUUM does not shrink the file. The freed space stays inside the table for reuse. Check the effect with pg_relation_size before and after:
VACUUM (VERBOSE) hot_demo;
SELECT pg_relation_size('hot_demo') AS bytes;VACUUM FULL
VACUUM FULL rewrites the whole table into a new file with no dead space, then rebuilds its indexes. It returns space to the operating system, but it holds an ACCESS EXCLUSIVE lock for the whole run, which blocks reads and writes. It also needs enough free disk for a second copy of the table. Use it for one-off recovery after a large purge, not as routine maintenance.
Autovacuum
The autovacuum daemon starts a VACUUM on a table when dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuples. The defaults are 50 and 0.2, so a table with 1,000,000 rows is vacuumed after about 200,050 dead tuples. For large, busy tables, set a lower scale factor on that table:
ALTER TABLE hot_demo SET (autovacuum_vacuum_scale_factor = 0.02);Common errors
- Expecting DELETE to shrink the table. The file keeps its size. Freed space is reused by later inserts and updates.
- Expecting pruning to fix index bloat. Pruning never touches indexes. Only VACUUM removes dead index entries.
- Setting a low fillfactor and seeing no change. It applies only to newly written pages.
- Running VACUUM FULL during business hours. It blocks all access to the table.
- Blaming autovacuum when a long transaction holds the horizon. Fix the old transaction first.
Exercise
A table has a primary key on id and a secondary index on email. A job runs UPDATE users SET last_login = now() WHERE id = $1 thousands of times per minute, and n_tup_hot_upd is close to zero. Name two possible causes and one fix for each.
Show answer
Cause 1: an index exists on last_login (or an expression using it), so every update changes an indexed column and cannot be HOT. Fix: drop the index if it is not needed, or move that lookup elsewhere. Cause 2: pages are full, so the new version does not fit on the same page. Fix: lower fillfactor (for example to 80) and rewrite the table, so pages keep free space for new versions.
Exercise
After pruning a page, a dead tuple's line pointer is LP_DEAD and not LP_UNUSED. Why can pruning not free it, and what step frees it?
Show answer
An index entry may still hold a ctid that names that line pointer. If the slot were reused, the index entry would lead to the wrong row. VACUUM first deletes the index entries that point at the dead TIDs (index cleanup), then marks the line pointers LP_UNUSED in its heap cleanup pass.