In this lesson, you will learn how the Visibility Map acts as a "shortcut" for the VACUUM process, allowing PostgreSQL to skip scanning pages that don't need cleaning.
The Problem: Scanning Every Page
When VACUUM runs, its primary job is to find dead tuples (rows marked for deletion) and reclaim their space. In a large database, scanning every single page in a table is incredibly expensive. Most pages in a stable table consist of rows that are already "old" and visible to all active transactions. Checking every row against the transaction state is unnecessary if we already know the status of the data on that page.
The Solution: The Visibility Map
The Visibility Map is a small, separate data structure—a bitmap—associated with each heap file. Each bit in the map represents a page in the table. If a bit is set to 1 (or "all-visible"), it guarantees two things:
- Every row on that page is visible to all current and future transactions (no dead tuples to clean).
- The page does not contain any rows that need to be "frozen."
Vacuum Freeze and Optimization
"Freezing" is the process of marking a row as permanently visible to prevent Transaction ID (XID) wraparound. Because the Visibility Map tells VACUUM that a page contains no dead tuples and needs no freezing, VACUUM can simply skip that page entirely. This drastically reduces I/O.
Furthermore, this map enables Index-Only Scans. If a query needs data that exists in an index, PostgreSQL checks the Visibility Map. If the page is marked "all-visible," the database knows the row data is valid without needing to visit the heap (the table storage) to verify it against the COMMIT LOG.
Visualizing the Logic
Imagine a table with 1,000 pages. 990 of them are marked as "all-visible" in the map. The vacuum process looks at the map, sees the 1s, and essentially does this:
-- Conceptual logic inside VACUUM
FOR page IN 1..total_pages LOOP
IF visibility_map_check(page) == 'all-visible' THEN
CONTINUE; -- Skip this page entirely!
ELSE
scan_page_for_dead_tuples_and_freeze(page);
END IF;
END LOOP;
Key Takeaway: The Visibility Map prevents unnecessary I/O by allowing VACUUM to skip "all-visible" pages and enabling index-only scans to retrieve data without visiting the heap.