Heap and Index: Two Separate Structures
Two structures, usually two files
1. Indexes (B-trees)
Store index tuples: key → row pointer. Small, sorted, many-per-table. Purpose: fast lookup.
e.g. email="john@ex.com" → record #1
2. Heap (table pages)
Store full rows — all columns — plus per-row metadata such as MVCC stamps. Large, unordered, one per table. Purpose: hold the complete records.
e.g. #1 = {user_id:1, email:john@ex.com, age:25}
Disk layout, and what a pointer actually is
Take a three-row users table (user_id, email, age). The database file is a flat sequence of fixed-size pages — 8 KB in Postgres, 16 KB in InnoDB. Each page has a header identifying its type: heap row page, B-tree node, free-space map, and so on.
The pointer stored in an index leaf is a TID (Tuple ID) — (page_number, slot_number). An exact physical location, not a vague range.
How the index changes size
- Growth: when an index page fills, the B-tree splits it — a new page is allocated from the Free Space Map, and the parent gains a pointer. The index expands one page at a time, wherever free pages exist.
DROP INDEX: pages are marked free in the FSM and reused by future inserts or other indexes. They are not returned to the OS immediately;VACUUMcan truncate trailing empty pages to shrink the file.CREATE INDEX: scan the heap, sort the entries, write out fresh B-tree pages.- Fragmentation: splits and deletes leave gaps over time.
REINDEXrebuilds cleanly from scratch;VACUUMreclaims dead heap rows.
How CREATE INDEX CONCURRENTLY guarantees nothing is missed
It runs in phases, tiling two time windows together using PostgreSQL's own snapshot/visibility machinery:
- Register, invisible. The index enters the catalog with
indisready = false,indisvalid = false. Nothing uses it or maintains it yet. Wait for every transaction that might not see the new catalog row. - First heap scan. Take a snapshot, scan the whole heap, build entries for every row visible at that snapshot. No table lock held.
- Mark write-ready.
indisready = true. Queries still ignore it, but every INSERT/UPDATE/DELETE from this point maintains index entries. Wait for transactions that started before the flag flipped, so nobody is still writing without maintaining it. - Second heap scan. Take a newer snapshot and re-scan for rows the index is missing — anything inserted between snapshot 1 and the write-ready flag, the gap where writes were happening but nobody was maintaining the index.
- Wait, then mark valid. Wait until every transaction that started before the second scan has finished, so no query is running against a view of the table predating the index. Then
indisvalid = true. The index is live.
Nothing is missed because the first scan covers everything before the build started, the write-ready flag captures every write after it, and the second scan plugs the gap between those two moments.
How the sort avoids overwhelming RAM — external merge sort
PostgreSQL never tries to sort the whole table in memory.
Step 1. Build sorted runs. Read the heap in chunks that fit in maintenance_work_mem (default 64 MB for index builds), sort each chunk in memory, spill it to a temp file as a sorted run. Repeat until the heap is consumed.
Step 2. k-way merge. Open all run files at once. Keep a min-heap in memory with one slot per run; pull the smallest key across all runs, write it to output, advance that run's pointer.
RAM during the merge is one page per run file — tiny regardless of table size.
Step 3. Write B-tree pages. The sorted stream of (key, TID) pairs is written directly as leaf pages; internal nodes are then built bottom-up from the leaf level.
A 500 GB table with 64 MB of maintenance_work_mem produces ~8,000 sorted runs; the merge phase still needs only ~8,000 read-buffer slots — a few hundred MB, not 500 GB. Raising maintenance_work_mem means fewer, larger runs and fewer merge passes.
A query, end to end
SELECT age FROM users WHERE email = 'john@example.com'
Step 1 — navigate the email index
B-tree leaf: 'john@example.com' → TID = (page=23, slot=5)
Step 2 — jump to the exact page and slot
load heap page 23 into the buffer pool (1 disk read)
slot 5 → byte offset 1,240 within that page
read row: {user_id:1, email:john@example.com, age:25}
extract age = 25
Total: ~4 page reads (3 for the B-tree descent + 1 heap page)How a page number becomes a byte on disk
byte_offset = page_number × 8192 → pread(fd, buffer, 8192, byte_offset)
one arithmetic operation, one syscall, O(1). The OS seeks to that offset and reads exactly 8 KB.
Inside a single page
slot_numberindexes into the slot array — each entry fixed-size (offset + length).slot[n].offsetis the byte offset within this page where the tuple starts.- Total: two pointer chases from TID → tuple bytes, both in RAM.
File segmentation: which file holds page N?
A table's pages form one continuous logical address space, but PostgreSQL never lets a single OS file exceed 1 GB. Each segment holds exactly 1 GB ÷ 8 KB = 131,072 pages.
Why 1 GB, and why split at all:
- Portability across file-size limits. Some filesystems and platforms Postgres historically supported capped a single file at 2–4 GB (32-bit
off_t, old FAT variants). Capping at 1 GB — well under any known limit — sidesteps this everywhere without per-OS special-casing. - Tooling friendliness.
cp,tar,rsyncand backup scripts behave better on bounded-size files than on one multi-hundred-GB monolith.
base/<db_oid>/<relfilenode> ← pages 0 – 131,071
base/<db_oid>/<relfilenode>.1 ← pages 131,072 – 262,143
base/<db_oid>/<relfilenode>.2 ← pages 262,144 – 393,215
segment_number = page_number / 131072
offset_within_segment = (page_number % 131072) × 8192This is still pure arithmetic — no lookup table. And it is not a claim about physical disk layout: it's a logical split of one relation's byte-address space into bounded OS files, orthogonal to the extent-map question from the SSTables and sparse indexes part. Whether the bytes inside one segment are physically contiguous is the filesystem's business, same as any other file.
Where the relfilenode lives: the table-name → physical-file mapping is in the system catalog pg_class (SELECT relname, relfilenode, reltablespace FROM pg_class WHERE relname='users'). That catalog row is itself in a system heap file and is cached in shared memory after the first lookup, so normal queries never re-read it from disk.
full path from TID to bytes
TID = (page=170000, slot=5)
│
├─ segment = 170000 / 131072 = 1 → open file "<relfilenode>.1"
├─ offset = (170000 % 131072) × 8192
│ = 38928 × 8192 = 318,898,176 bytes into that file
│
pread(fd, buf, 8192, 318898176) → 1 disk read, 8 KB page in RAM
│
└─ slot[5].offset = 1240 → tuple starts at byte 1240 in the pageOne page, many records — why slots exist
A typical 8 KB heap page holds 50–200 rows. Records are variable-size, so without a slot array you would have to scan record 1 → 2 → 3 to find where record 3 starts. The slot array sits at a known position (top of page) with fixed-size entries, so:
slot_array_start + (3 × slot_size) → read offset value (490) → jump to byte 490
two arithmetic operations. Constant time regardless of how many records are on the page.
This is also why external indexes store (page, slot) rather than a raw byte offset: if a record moves within its page during compaction, only the slot's offset value changes — every index pointing at it stays valid.
Why this design
| Benefit | Because |
|---|---|
| Fast lookup | Indexes are small sorted B-trees — navigate to the record ID, then jump straight to it. |
| Multiple indexes | Email, user_id and age indexes live independently without duplicating the data. |
| Efficient storage | Data is stored once, in the heap. Indexes only point at it. |
| Each optimized for its job | Heap pages hold whole rows plus MVCC metadata; B-tree pages hold many small sorted tuples. Heap stays good for writes (write the full row once); index stays small (key + pointer only); range queries work because index keys are sorted. |
✓ The cost you pay
With index:
read index pages → find record ID
read data page → get the actual row
Total: 2 disk accesses (min)✗ The alternative, and why it's worse
Store key + entire row inside the index:
read 1 index page → get everything
...but now every index duplicates
every column of every row.Three ways to lay out the data itself
| Method | Layout | Advantage | Disadvantage |
|---|---|---|---|
| Heap storage (most common — PostgreSQL) | Records in arbitrary order; indexes point in | Fast inserts — just find room and append | Every lookup needs an index |
| Clustered index (SQL Server, MySQL InnoDB) | Records stored sorted by primary key | PK lookups are one step — no second jump to a heap | Inserts are slower; order must be maintained |
| Column store (analytics — see Analytics and table formats) | All values of one column stored together | Fast analytical scans over a few columns | Slow full-row lookups |
What if one column value is bigger than a page?
PostgreSQL pages are 8 KB, and a single column value can be far larger. It is not stored inline. PostgreSQL uses TOAST (The Oversized-Attribute Storage Technique):
- The heap row keeps a normal tuple header plus its small inline fields.
- If a field is too large, PostgreSQL first tries to compress it.
- If it's still too large, the value is stored out of line — broken into chunks in a separate per-table TOAST table — and the heap row keeps only a small TOAST pointer.
Heap row on page 891:
id = 123
title = "big document"
body = TOAST_POINTER( toast_table_oid, chunk_ids... )
TOAST table:
chunk 0 -> first piece of body
chunk 1 -> next piece
...The practical rule: rows never span heap pages; large column values move out of line; the base row stays small enough to fit a normal page.
The Invariants
- Guarantees: A TID resolves to exact bytes in O(1) arithmetic plus two in-RAM pointer chases, and stays valid while the row moves within its page.
- Does not guarantee: That a TID still points at the row you meant — a row that moves to a different page gets a new TID, and the old index entry lingers until VACUUM (see VACUUM and free space). Nor does the index know anything about visibility; that is resolved entirely at the heap (see MVCC and visibility).