Sub topic 10
The Free Space Map and Visibility Map
This chapter assumes you know what an 8 KB heap page is and how line pointers and tuples sit inside it. It also assumes you know that UPDATE and DELETE leave dead row versions behind until VACUUM removes them. You should be able to run SQL in psql with a role that can create extensions.
A table's main fork holds the pages with your rows. PostgreSQL keeps two small companion forks next to it. The free space map (FSM) answers "which page has room for a new row?" The visibility map (VM) answers "which pages contain only rows that every transaction can see?" Both are small, and both save a lot of work.
Where the two forks live
Each fork is its own file in the table's file set. The file names add a suffix to the table's file node number:
| Fork | File name | Information per heap page | Main users |
|---|---|---|---|
| main | `16384` | the page itself | everything |
| FSM | `16384_fsm` | 1 byte of free space | INSERT, VACUUM |
| VM | `16384_vm` | 2 bits (all-visible, all-frozen) | VACUUM, index-only scans |
You can list the sizes of every fork of a table:
SELECT pg_relation_size('accounts', 'main') AS main_bytes,
pg_relation_size('accounts', 'fsm') AS fsm_bytes,
pg_relation_size('accounts', 'vm') AS vm_bytes;A fork that does not exist yet reports 0 bytes. The VM is created by VACUUM. Since PostgreSQL 11, tables smaller than 4 pages get no FSM file at all. For such a table the inserting backend just tries each page in turn.
The free space map
What it stores
The FSM keeps one byte per heap page. The byte holds the page's free space divided by 256 of the block size. With 8 KB pages the granularity is 32 bytes, so a page with 1,000 free bytes is recorded as 31 (992 bytes). The recorded value always rounds down, so the FSM never promises more space than a page has.
The bytes are organized as a binary tree inside each FSM page. A parent node holds the maximum of its children. To find a page with at least N bytes free, PostgreSQL starts at the root. If the root value is too small, no page qualifies. Otherwise it walks down toward a qualifying leaf, which takes a handful of steps even for a huge table. Larger tables use a three-level tree of FSM pages.
How INSERT uses it
When a backend inserts a tuple, it picks a target page in this order:
- The page it used last time for this table, if the tuple still fits.
- A page returned by the FSM that has enough space.
- A brand-new page appended to the end of the file, if the FSM has no candidate.
Step 3 is how a table grows. If the FSM is out of date and does not know about reusable space, the table grows even though it contains dead space.
Who updates it
The FSM is not maintained on every change. Updating it for each row write would add contention and WAL traffic. Instead, VACUUM records each page's free space as it cleans the page, and then propagates the values up the tree. Inserters also update the FSM when they find a suggested page too full. The FSM is a hint: an entry can be stale, and an inserter that visits a stale page just asks again. For the same reason, FSM changes are not individually WAL-logged, and after a crash the map may be slightly wrong until the next vacuum.
Looking at it
The pg_freespacemap extension exposes the map:
CREATE EXTENSION IF NOT EXISTS pg_freespacemap;
SELECT * FROM pg_freespace('accounts');
SELECT pg_freespace('accounts', 0) AS free_bytes_in_block_0;pg_freespace(rel) returns one row per page, with blkno and avail in bytes, rounded to the 32-byte granularity.
The visibility map
What it stores
The VM keeps two bits per heap page:
- all-visible: every live tuple on the page is visible to every current and future transaction. No dead tuples and no tuples from in-progress transactions are present.
- all-frozen: every tuple on the page is frozen, so its transaction IDs never need to be examined again (added in PostgreSQL 9.6).
One 8 KB VM page covers about 32,000 heap pages, which is roughly 250 MB of table. The VM for a 100 GB table is only a few hundred kilobytes.
Two jobs
Letting VACUUM skip pages. A normal VACUUM skips pages marked all-visible, because they hold nothing to clean. An aggressive vacuum, which happens when the table's oldest unfrozen transaction ID is old enough, skips only all-frozen pages. On a large table where most data never changes, this turns a full scan into a scan of the recently changed part.
Enabling index-only scans. An index entry has no visibility information, so a normal index scan must visit the heap to check whether the row is visible. An index-only scan first checks the VM. If the heap page is all-visible, the index entry alone is enough and the heap visit is skipped. If the bit is not set, the scan fetches the heap page anyway. EXPLAIN ANALYZE counts these as Heap Fetches.
When bits change
- Set by VACUUM, after it confirms the page is clean. Autovacuum also triggers on insert counts (PostgreSQL 13 and later), so insert-only tables eventually get their bits set.
- Cleared by any INSERT, UPDATE, or DELETE that touches the page. The clearing is WAL-logged, because a wrongly set bit would make index-only scans return wrong results.
The bit is also mirrored by the PD_ALL_VISIBLE flag in the page header, which lets writers clear it quickly.
Watching both maps work
This walkthrough needs the pg_visibility and pg_freespacemap extensions from the contrib package. Run it in a scratch database.
CREATE EXTENSION IF NOT EXISTS pg_visibility;
CREATE EXTENSION IF NOT EXISTS pg_freespacemap;
CREATE TABLE fsm_demo (id int PRIMARY KEY, payload text);
INSERT INTO fsm_demo
SELECT g, repeat('x', 200) FROM generate_series(1, 10000) g;
-- Before VACUUM: nothing is marked all-visible.
SELECT * FROM pg_visibility_map_summary('fsm_demo');
VACUUM fsm_demo;
-- After VACUUM: most or all pages are all-visible.
SELECT * FROM pg_visibility_map_summary('fsm_demo');
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM fsm_demo WHERE id < 100;The plan should show an Index Only Scan with Heap Fetches: 0. If the planner chooses a different plan on your system, run SET enable_seqscan = off; first and repeat the EXPLAIN.
Now change half of the rows:
DELETE FROM fsm_demo WHERE id % 2 = 0;
SELECT * FROM pg_visibility_map_summary('fsm_demo');
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id FROM fsm_demo WHERE id < 100;The DELETE touched every page, so all_visible drops to 0 and the index-only scan reports many heap fetches. Free space exists only as dead tuples at this point, and the FSM does not know about it. Check the table size, then vacuum:
SELECT pg_relation_size('fsm_demo') AS bytes_before;
VACUUM fsm_demo;
SELECT count(*) AS pages, sum(avail) AS free_bytes
FROM pg_freespace('fsm_demo');
INSERT INTO fsm_demo
SELECT g, repeat('y', 200) FROM generate_series(10001, 15000) g;
SELECT pg_relation_size('fsm_demo') AS bytes_after;After VACUUM, pg_freespace reports about half of each page as free. The 5,000 new rows are about as many as the deleted ones, so bytes_after should stay close to bytes_before. The inserts reused the space that the FSM pointed to. Without that VACUUM, the same inserts would have appended new pages at the end of the file.
Common errors and gotchas
- Index-only scans that still fetch the heap. The scan is only as good as the VM. A table with frequent updates, or one that autovacuum has not reached, shows high
Heap Fetches. Run VACUUM, or lowerautovacuum_vacuum_scale_factorfor that table. - Long transactions block the bit. VACUUM cannot mark a page all-visible if some old snapshot could still need a dead tuple on it. A forgotten open transaction keeps VM bits unset across the whole database.
- Table growth despite deletes. If deleted space does not get reused, check that VACUUM or autovacuum is running. The FSM only learns about free space when VACUUM records it.
- Statistics lag.
pg_class.relallvisibleis refreshed by VACUUM and ANALYZE. The planner uses it to estimate the cost of index-only scans, so a stale value leads to poor plan choices. - Rebuilding. The FSM and VM are derived data. If they are damaged, a VACUUM rebuilds the information.
pg_visibilityalso providespg_check_visibleandpg_check_frozen, which list pages whose bits claim more than the page contents support.
Summary
The FSM is a compact, approximate per-page record of free bytes. It lets INSERT reuse space instead of extending the file, and VACUUM feeds it. The VM is a two-bit-per-page record of which pages are fully visible or frozen. It lets VACUUM skip stable pages and lets index-only scans skip heap visits. Writers clear VM bits immediately, while VACUUM sets them later, so both forks reflect the last cleanup more than the current moment.
Exercise
A table has had many rows deleted, but its file keeps growing when new rows are inserted. autovacuum is disabled. Which fork is stale, and what does this cause?
Show answer
The free space map is stale. Dead tuples leave space in the pages, but only VACUUM records that space in the FSM. With no FSM entries, inserters find no candidate page and append new pages at the end of the file, so the table grows. Running VACUUM records the free space, and later inserts reuse it.
Exercise
An index-only scan on a frequently updated table shows a large "Heap Fetches" count in EXPLAIN ANALYZE. Give two likely causes and one fix.
Show answer
Likely causes: recent INSERT, UPDATE, or DELETE operations cleared the all-visible bits on many pages and VACUUM has not run since, or a long-running transaction prevents VACUUM from marking pages all-visible. The scan has to check the heap page for every index entry that points to a page without the bit. A fix is to run VACUUM on the table, or tune autovacuum for that table so it runs more often. For the long-transaction cause, end the old transaction.
Exercise
Why does one 8 KB visibility map page cover far more table data than one 8 KB free space map page?
Show answer
The VM needs only 2 bits per heap page, so one VM page covers about 32,000 heap pages. The FSM needs 1 byte per heap page, plus the interior nodes of its search tree, so one FSM page covers only about 4,000 heap pages.