Sub topic 5
VACUUM and the all-visible bit
This chapter assumes you can read basic EXPLAIN output and know that PostgreSQL tables are stored as a heap of row versions (tuples) with MVCC. It also assumes you know what an index-only scan is and why it needs the visibility map. Here we look at the other half of the mechanism: how pages get their all-visible bit, what clears it, and how to keep it set.
The bit that makes index-only scans cheap
Every heap table has a companion file called the visibility map, stored in the _vm fork of the relation. It holds two bits per heap page:
- all-visible: every tuple on the page is visible to every current and future transaction.
- all-frozen: every tuple on the page is also frozen, so even an anti-wraparound vacuum can skip the page.
An index-only scan reads the index entry, then checks the all-visible bit for the heap page the entry points to. If the bit is set, the scan returns the value from the index and never touches the heap. If the bit is clear, the scan must fetch the heap tuple to check whether the row version is visible to its snapshot. EXPLAIN (ANALYZE) counts each of these visits under Heap Fetches.
Index entries carry no transaction information, so the index cannot tell you whether a row is visible. The visibility map stands in for that information at page granularity. Anything that keeps the bit set makes index-only scans fast. Anything that clears it brings the heap visits back.
Who sets the bit: VACUUM
Only VACUUM sets all-visible bits. Neither ANALYZE nor a CREATE INDEX sets them, and neither does reading the table. A freshly loaded table has no bits set, so your first index-only scan after a bulk load still visits the heap. That is why the examples in this tutorial run VACUUM (ANALYZE) orders after loading.
While VACUUM scans a heap page, it does the following:
- It removes dead tuples, meaning row versions that no running transaction can still see. Their index entries are removed too.
- It checks whether every remaining tuple on the page is visible to all transactions. This holds when each tuple's inserting transaction committed and is older than the oldest transaction horizon (the oldest snapshot any running transaction might still use), and when no tuple is deleted-but-still-visible.
- If the page qualifies, it sets the all-visible bit. If all tuples are also frozen, it sets the all-frozen bit.
VACUUM can skip pages whose all-visible bit is already set, because they contain nothing to clean. That makes repeat vacuums on mostly static tables cheap. It also means the map is self-maintaining. Pages that change lose their bit and get re-examined, and pages that don't change keep it.
Who clears the bit: writes
Any INSERT, UPDATE or DELETE that touches a heap page clears its all-visible bit, and the clearing is WAL-logged. The page stays unflagged until a later VACUUM revisits it. An UPDATE clears the bit on the page holding the old version and on the page receiving the new one, if they differ.
The important consequence is that index-only scan speed depends on the write pattern. A table where recent rows change often, such as orders in progress, will always have many pages without the bit. A table that is mostly append-only or historical keeps the bit on most pages.
Seeing the bits
You can count the set bits with the pg_class statistics and with the pg_visibility extension:
SELECT relname, relpages, relallvisible
FROM pg_class
WHERE relname = 'orders';
CREATE EXTENSION IF NOT EXISTS pg_visibility;
SELECT * FROM pg_visibility_map_summary('orders');relallvisible is a statistic that VACUUM refreshes, so it can lag behind reality. pg_visibility_map_summary reads the map itself and returns the current counts of all-visible and all-frozen pages. The ratio relallvisible / relpages also matters for planning: the planner uses it to estimate how many heap fetches an index-only scan will need. If the ratio is low, the planner prices the index-only scan as expensive and may choose another plan.
Watching the bit get cleared and restored
The next script updates a few rows and re-runs the covered query, then vacuums and runs it again. It assumes the orders_customer_total_idx index from earlier in this tutorial exists and the table was vacuumed once.
UPDATE orders SET total = total + 1 WHERE customer_id = 42;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;
VACUUM orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total FROM orders WHERE customer_id = 42;In the first plan, Heap Fetches is greater than zero. The update touched pages holding customer 42's rows and cleared their bits. After VACUUM, the second plan should report fewer fetches, usually none. The table has about 100 rows for that customer spread over roughly as many pages, so the effect is small in absolute terms. Run the same experiment with an update that touches a large share of the table and the difference becomes obvious.
What decides whether a page qualifies
A VACUUM run can finish without setting a bit on a page that looks clean. Three conditions matter.
The oldest snapshot. VACUUM computes a horizon from the oldest running transaction or snapshot. A tuple inserted or deleted by a transaction newer than that horizon is not yet visible to everyone, so its page cannot be marked all-visible. A long-running transaction, an idle-in-transaction session, a stale replication slot with hot_standby_feedback, or a forgotten prepared transaction can hold the horizon back for hours. Under those conditions VACUUM runs normally and reports success, yet recently written pages never get their bit.
Page locks. VACUUM skips a page it cannot immediately lock for cleanup, if another backend has it pinned. It tries again on a later run. This is rare on quiet tables and more common on very hot ones.
Truncated or skipped scans. VACUUM may skip ranges of pages that are already all-visible. That is fine. Pages that are not marked are always scanned, except under options such as DISABLE_PAGE_SKIPPING being off and a page being briefly unavailable, as described above.
Autovacuum and index-only scans
You normally rely on autovacuum rather than manual vacuums. The default triggers are:
| Setting | Default | Fires when |
|---|---|---|
| `autovacuum_vacuum_threshold` + `autovacuum_vacuum_scale_factor` | 50 + 0.2 | dead tuples exceed 50 + 20% of the table |
| `autovacuum_vacuum_insert_threshold` + `autovacuum_vacuum_insert_scale_factor` | 1000 + 0.2 | inserted tuples since the last vacuum exceed 1000 + 20% of the table (PostgreSQL 13 and later) |
The insert-based trigger was added in PostgreSQL 13 specifically so append-only tables get vacuumed and have their pages marked all-visible. On older versions an insert-only table received no regular vacuum, so index-only scans on it kept visiting the heap.
For a large table, 20% is a lot. On a table of 50 million rows, autovacuum waits for 10 million changes. You can lower the factors for individual tables:
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_vacuum_insert_scale_factor = 0.05
);To check whether autovacuum is keeping up, look at the statistics view:
SELECT relname,
n_live_tup,
n_dead_tup,
n_ins_since_vacuum,
last_vacuum,
last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'orders';n_ins_since_vacuum (PostgreSQL 13 and later) shows how much has been inserted since the last vacuum. A large number with an old last_autovacuum means many pages lack the bit.
Common mistakes
- Expecting the bit to appear after loading data. Run
VACUUMonce after a bulk load. - Vacuuming while an old transaction is open. Check
pg_stat_activityfor oldxact_startandbackend_xminvalues. Long sessions defeat the vacuum even when it runs. - Reading
relallvisibleas exact. It is a statistic. Usepg_visibility_map_summarywhen you need the true count. - Tuning autovacuum globally for one table. Prefer per-table storage parameters, as shown above, so other tables keep sensible defaults.
Summary
VACUUM is the only process that turns pages into all-visible pages, and writes are what turn them back. An index-only scan is therefore only as good as the fraction of heap pages currently flagged. Keep autovacuum frequent on tables where you depend on index-only scans, keep transactions short so the horizon advances, and verify the result with Heap Fetches and pg_visibility_map_summary.
Exercise
A table is loaded with 5 million rows and indexed with a covering index. You run ANALYZE and then an index-only query, and EXPLAIN (ANALYZE) shows Heap Fetches close to the number of rows returned. Give the cause and the fix. Then name a second reason the same symptom could persist after the fix.
Show answer
ANALYZE does not set visibility map bits, and the freshly loaded pages have none, so every index entry needs a heap visit to check visibility. Run VACUUM (or VACUUM (ANALYZE)) on the table. If Heap Fetches stays high afterwards, a long-running or idle-in-transaction session may be holding back the oldest-snapshot horizon, so VACUUM cannot mark recently written pages all-visible. Check pg_stat_activity for old xact_start or backend_xmin.
Exercise
Why does the planner sometimes avoid an index-only scan on a table even though the covering index exists, and which statistic does it use to decide?
Show answer
The planner estimates heap fetches from relallvisible / relpages in pg_class. If few pages are marked all-visible, the index-only scan is priced close to a plain index scan and another plan may win. Running VACUUM refreshes the statistic and the bits.