WORKINGCHAPTER 09

B+ trees in the engine

What a Postgres btree index does with high keys, splits, duplicates and dead versions, how it bloats, how to measure that, and the two updates that never touch it

55 MINDATABASESUPDATED 2026-11-02
PREDICT

orders has indexes on (id) and (customer_id). You run UPDATE orders SET total_cents = total_cents + 1 WHERE id = 7. total_cents has no index. Which of the two indexes gets a new entry?

You know from the outside what an index does: a query over two million rows reads four pages instead of eighteen thousand. This chapter is the inside: what the pages hold, what happens on an insert, what happens to the entries of a row that was updated or deleted, and why an index that VACUUM has cleaned can still be twice its proper size. Everything here is nbtree, the Postgres btree access method, on version 17. Most of it transfers to InnoDB and SQLite with the names changed.

The shape, in the simulation

The simulation below is the structure every btree index has: internal pages of separator keys and child pointers, leaves holding the entries, all leaves at one depth, siblings linked. Run SORTED INSERTS and watch a leaf fill, split in half and push a key up. Then run NO SPLITS to see what the tree would become without that rule.

▶ SIMULATION
B+ TREE · FANOUT 4
keys 0 · max keys/node 3
leaf splits 0 · internal 0 · root 0
—
NODES BY LEVEL
leaves (depth 1): []
QUERY
leaf depth 1
lookup: —
leaf chain— (1 leaves)
✓ all leaves at the same depth✓ keys in order across leaves, none lost
SCHEDULE
01[LOAD]insert 16 keys, 5 … 60
02[QUERY]lookup 42: descend from the root to a leaf
03[QUERY]range scan 42..50: follow leaf next pointers
04[QUERY]report
Start of lookup + range scan scenario. 4 steps.
B+ tree (fanout F: at most F children, F-1 keys per node)
===================================================

Structure
  internal nodes: keys + child pointers only (no row data)
  leaves: keys + row data (or row ids), linked by next pointers
  every leaf sits at the same depth

Lookup(K)
  start at root; pick the child whose range holds K; repeat to a leaf
  cost: one page read per level = height

Range(lo, hi)
  lookup(lo), then follow leaf next pointers until a key > hi

Insert(K)
  1. find the leaf, insert K in sorted position
  2. leaf overfull? split into left | right,
     COPY right[0] up to the parent as the separator
  3. parent overfull? split it, MOVE its middle key up
  4. root split? make a new root: the tree grows by one level,
     at the top, so all leaves stay at the same depth

Why it stays shallow
  fanout 500, 3 levels  -> ~125 million keys, 3 page reads
  balanced binary tree  -> ~27 levels for the same keys
  unbalanced binary tree, sorted inserts -> one level per key
BREAK IT NOT YET

The same seven sorted inserts run at every fanout. At FANOUT 4 the root splits once and the tree stops at 2 levels. Change FANOUT until the root has to split a second time and the tree grows to 3 levels.

GOAL: the seven inserts grow the tree to 3 levels

FIX IT NOT YET

Implement leaf insertion. leaf is a sorted array of keys. Insert key in order. If the leaf now has more than maxKeys keys, split it into two non-empty sorted halves and return { left, right, separator }, where separator is the key copied up to the parent: every key in left is below it and every key in right is at or above it. Otherwise return the leaf array.

Hold on to two things from the sim. Splits are the only growth mechanism, and a split is expensive: it allocates a page, moves half the entries, writes three pages (left, right, parent) and logs all of it. And the tree is shallow because fanout is high: a Postgres leaf page of bigint keys holds about 400 entries (16 bytes each at fillfactor 90), an internal page about 400 downlinks, so two million entries need about 5 000 leaves, 13 internal pages and one root: three levels, four page reads for any lookup including the metapage. A billion rows is five levels.

What is on a Postgres btree page

A Postgres btree index file is 8 KB pages like the heap. Block 0 is the metapage: it records the root’s block number and level, the fast root, and whether the index can use deduplication (allequalimage). bt_metap('orders_customer_idx') from pageinspect shows it. The rest are tree pages. Each uses the page’s special space for btpo_prev and btpo_next (the sibling links), btpo_level (0 for leaves) and flags (leaf, root, half-dead, deleted).

Leaf entries are (key, heap TID) and they are kept in order of key and then TID, so an index is unique at the physical level even when its keys are not. Internal entries are (separator key, child block); since version 12 the separator is suffix-truncated to the shortest prefix that still separates its children, so an index on (customer_id, created_at) has internal pages that mostly hold customer_id alone and fan out wider.

The first item on every page that is not the rightmost on its level is the high key: an upper bound on what the page may contain. It is the detail that makes concurrent splits safe. Postgres uses Lehman and Yao’s algorithm: a reader descends holding a lock on one page at a time. If a split happens underneath it, it can arrive at a page whose high key is below the key it wants. It then follows btpo_next to the right sibling instead of restarting. Splitting a leaf therefore needs no lock on the parent at the moment of the split; the downlink is inserted in a second step, and until then the right-link stands in. bt_page_items shows the high key at itemoffset 1 with a TID that is not a heap location.

Inserts, splits and fill factor

An insert descends to the leaf, moving right as needed, and inserts in key order. If the leaf is full it splits. Where it splits depends on what the insert looks like: a plain split is 50/50; an insert into the rightmost leaf (the usual case for an increasing key like a bigserial or a timestamp) splits so that the left page keeps fillfactor worth of entries and the new entry goes right, which is why an index on an increasing key is dense; and Postgres 12 added a split-point heuristic that keeps entries with the same key prefix together so that later inserts land where there is room.

The btree fillfactor (default 90; set with CREATE INDEX ... WITH (fillfactor = 70)) is how full CREATE INDEX and rightmost splits leave a leaf. At 90 a bulk-built index on a non-changing table is as dense as it will ever be; at 70 there is room for inserts into the middle without an immediate split. Internal pages use 70 regardless.

Random keys are the opposite case. A UUIDv4 primary key spreads two thousand inserts a second across every leaf, so each insert touches a random page (cold cache, random I/O) and splits arrive everywhere at once, leaving every leaf half full. The Decide at the end is that choice.

Duplicates: deduplication

Non-unique indexes have duplicates, and a plain (key, TID) entry per duplicate repeats the key. Since Postgres 13 a leaf that is about to split first tries deduplication: entries with equal keys are merged into one posting list tuple that stores the key once followed by a sorted array of heap TIDs, 6 bytes each. bt_page_items shows these as a non-null tids array. For the shop’s orders(customer_id) index, where a customer has four orders on average and the busiest have hundreds, the index is about a third the size it would be without it. For orders(status), with four distinct values across two million rows, it is a fraction.

Deduplication is on by default (WITH (deduplicate_items = off) disables it) and cannot be used when “equal” does not mean “same bytes”: numeric (1.0 and 1.00), float4/float8 (-0 and 0), jsonb, text under a nondeterministic collation, arrays, ranges and composites, and any index with INCLUDE columns. bt_metap reports allequalimage true when it is possible. Unique indexes do use it, but only to buy time for the version-churn case described next.

Dead versions: bloat

Here is the part that makes indexes expensive. The heap chapter showed that an UPDATE inserts a new row version and leaves the old one until VACUUM. Each index entry points at one version. So a non-HOT update leaves, in every index, an entry pointing at the old version that will be dead the moment the transaction commits and nobody needs it. A DELETE does the same for every entry of the row. Those entries are index bloat: live pages holding dead pointers.

Three mechanisms remove them, in order of cost.

Simple deletion happens for free during scans. An index scan that follows an entry to the heap and finds the version dead sets the entry’s LP_DEAD bit (“known dead”). The next insert into that page that would otherwise have to split first removes every LP_DEAD entry.

Bottom-up deletion (Postgres 14) is for the case the Why describes: an update that did not change an indexed column, so this index gained an entry that is a pure duplicate of the previous version’s. When such an index is about to split a leaf because of version churn, it first visits the heap for the entries on that page that look like duplicates, confirms which are dead, and deletes them. It is what keeps a frequently updated table’s unchanged indexes from growing, and it makes the Why’s incident far less common on 14 and later. It does not run on inserts or deletes.

VACUUM is the complete pass: it collects dead heap TIDs, then scans every index and removes every entry that points at one. It is also the only one of the three that can give pages back: a leaf left wholly empty is unlinked from its siblings and parent (the half-dead protocol in the nbtree README) and, after a later VACUUM has confirmed no scan can still be on it, put in the free space map for reuse.

What none of them do is merge two half-empty pages. Delete half the rows of a table and VACUUM returns the heap space to the free space map and the index entries vanish, but the index has the same number of leaf pages at half density, forever, until it is rebuilt. Random inserts fill them slowly; an increasing key never touches them again.

Measuring bloat

pgstattuple has pgstatindex, which walks the index and reports:

CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT tree_level, index_size, leaf_pages, empty_pages, deleted_pages,
       avg_leaf_density, leaf_fragmentation
FROM pgstatindex('orders_customer_idx');

avg_leaf_density is the number: a healthy bulk-built index sits near its fillfactor, 90; a churned one drifts towards 50 and below. leaf_fragmentation is the percentage of leaf pages whose right sibling is not the next physical block, which hurts range scans on spinning disks and matters little on SSDs. deleted_pages are reclaimable; empty_pages are waiting to be. The function reads every page of the index, so on a 20 GB index it takes a while; on a production system run it against the indexes pg_stat_user_indexes shows are written most, not everything.

A faster estimate is the comparison pg_relation_size(index) against what a fresh build would need. pgstattuple('orders') gives the same breakdown for the heap: dead_tuple_percent and free_percent.

HOT: the update that skips the index

A heap-only tuple update is one where the new row version goes on the same heap page as the old one and no index needs to know. Two conditions, both checked at update time: no column that any index references changes (compared bit for bit, and columns in partial-index predicates and expression indexes count; BRIN is the exception because it summarises page ranges rather than pointing at rows), and the page has room. When both hold, the new version is written on the same page, flagged HEAP_ONLY_TUPLE, and the old version is flagged HEAP_HOT_UPDATED with its t_ctid pointing forward. Indexes keep pointing at the first version’s line pointer. A reader follows the chain within the page.

The chain is cleaned up without VACUUM. Pruning runs opportunistically when a page is read and is nearly full or has a recent failed update: dead intermediate versions are removed and their line pointers freed, and the root line pointer becomes a redirect to the oldest version that may still be visible. The index entry stays valid because it points at the redirect.

Two numbers tell you how much of this you are getting:

SELECT n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd,
       round(100.0 * n_tup_hot_upd / nullif(n_tup_upd, 0), 1) AS hot_pct
FROM pg_stat_user_tables WHERE relname = 'orders';

n_tup_newpage_upd (Postgres 16) is the diagnosis: updates whose new version had to leave the page. If it is most of n_tup_upd on a table whose updated columns are unindexed, the fix is heap fillfactor (70 to 80 for heavily updated tables; it costs that much heap space) and letting pruning do its job. If the updated column is indexed, no fill factor helps; the only fixes are to drop that index or stop updating that column on the hot path.

Index-only scans and the visibility map

An index holds keys and TIDs but no xmin/xmax, so it cannot by itself say whether an entry’s row is visible to your snapshot. An index-only scan avoids the heap by checking the visibility map: if the page an entry points to is marked all-visible, every tuple on it is visible to every current transaction and the index entry can be trusted. If not, the executor fetches the heap tuple. EXPLAIN (ANALYZE) reports these as Heap Fetches: n. A freshly updated table has few all-visible pages and an index-only scan degenerates into an index scan with extra bookkeeping; VACUUM sets the bits (any insert, update or delete clears the page’s bit). pg_visibility_map_summary('orders') counts all-visible and all-frozen pages. The planner uses pg_class.relallvisible to decide whether an index-only scan is worth it, so a table that has not been vacuumed since it was loaded may never get one.

Rebuilding

REINDEX INDEX orders_customer_idx rebuilds at fillfactor density and takes an ACCESS EXCLUSIVE lock on the index, blocking reads that would use it and writes to the table for the duration: minutes on a large index. REINDEX INDEX CONCURRENTLY (Postgres 12) builds a new index alongside under a SHARE UPDATE EXCLUSIVE lock, catches up with changes made during the build, swaps names and drops the old one, each step in its own transaction. Reads and writes continue. It cannot run in a transaction block, must wait for every transaction that could modify the index, and if it fails it leaves an INVALID index named orders_customer_idx_ccnew that costs writes until you DROP INDEX it. Schedule it after a mass delete or update, not on a timer; avg_leaf_density under 60 on an index that is scanned a lot is a reasonable trigger.

LAB Build it, bloat it, measure it, fix it ~40 MIN
YOU NEEDthe labs/databases stack from docs/LABS.md running and loaded at scale 1psql: `docker compose exec db psql -U atlas shop`a second terminal for the break

This lab rewrites orders and scrambles a quarter of its customer_id values, and step 7 reloads the shop to undo that. Check \d orders first: the HOT result in step 3 assumes no index on orders contains total_cents, so drop any such index from your D1 set for the duration (step 7 tells you how to put it back).

1. Build an index and read its pages.

CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE EXTENSION IF NOT EXISTS pg_visibility;
CREATE INDEX orders_customer_idx ON orders (customer_id);
SELECT * FROM bt_metap('orders_customer_idx');
SELECT type, live_items, avg_item_size, free_size, btpo_prev, btpo_next, btpo_level
FROM bt_page_stats('orders_customer_idx', 1);
SELECT itemoffset, ctid, itemlen, data, htid, tids[1:3] AS first_tids
FROM bt_page_items('orders_customer_idx', 1) ORDER BY itemoffset LIMIT 4;
SELECT tree_level, pg_size_pretty(index_size) AS size, leaf_pages, avg_leaf_density, leaf_fragmentation
FROM pgstatindex('orders_customer_idx');
The metapage shows level 2 (three levels: root, one internal level, leaves) and allequalimage t. Block 1 is the leftmost leaf: type l, btpo_level 0, btpo_prev 0 (no left sibling), free_size around 800 bytes (fillfactor 90). Item 1 is the high key: its data is a customer_id and its ctid is not a heap address. Items 2 onwards are entries; where a customer has more than one order the row has tids filled in and itemlen larger than 16: posting lists from deduplication. pgstatindex shows avg_leaf_density near 90 and leaf_fragmentation 0: a bulk build writes leaves in order.

2. Update an unindexed column on a full table.

SELECT pg_size_pretty(pg_relation_size('orders')) AS heap, pg_size_pretty(pg_relation_size('orders_customer_idx')) AS idx;
SELECT n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd FROM pg_stat_user_tables WHERE relname = 'orders';
UPDATE orders SET total_cents = total_cents + 1 WHERE id BETWEEN 1 AND 100000;
SELECT pg_sleep(1.5);
SELECT n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd FROM pg_stat_user_tables WHERE relname = 'orders';
SELECT pg_size_pretty(pg_relation_size('orders')) AS heap, pg_size_pretty(pg_relation_size('orders_customer_idx')) AS idx;
n_tup_upd rises by 100 000 and almost all of it lands in n_tup_newpage_upd; n_tup_hot_upd barely moves. The heap grows by about 7 MB, from 144 MB to 151 MB (about 920 new pages). The index gets 100 000 new entries even though customer_id did not change, each pointing at a new page, yet its size barely moves (24 MB before and after in a reference run): bottom-up deletion removes the now-dead old entries as leaves fill, and deduplication packs the rest. The pg_sleep gives the statistics collector time to flush; without it the counters can lag by a second.

3. Make room, then do the same update.

VACUUM FULL rewrites the table and its indexes under an exclusive lock and takes 10 to 30 seconds here. Never on a production table; the migrations chapter in module four covers the alternatives.

ALTER TABLE orders SET (fillfactor = 70);
VACUUM FULL orders;
SELECT pg_size_pretty(pg_relation_size('orders')) AS heap, pg_size_pretty(pg_relation_size('orders_customer_idx')) AS idx;
UPDATE orders SET total_cents = total_cents + 1 WHERE id BETWEEN 1 AND 100000;
SELECT pg_sleep(1.5);
SELECT n_tup_upd, n_tup_hot_upd, n_tup_newpage_upd FROM pg_stat_user_tables WHERE relname = 'orders';
SELECT pg_size_pretty(pg_relation_size('orders')) AS heap, pg_size_pretty(pg_relation_size('orders_customer_idx')) AS idx;
The heap is about 40% larger after the rewrite, 206 MB against 144 MB (30% of every page is empty). This time n_tup_hot_upd rises by about 43 000 of the 100 000, and the index does not change size: those new versions went on their own page, chained to the old one, and no index was touched. The other 57 000 still went to new pages and the heap grows by about 6 MB, because this statement updates every row on each page it touches, and 30% free space holds new versions for only about four rows in ten. Same statement, same rows; the only difference is free space, and how much of each page one statement rewrites.

4. Bloat the index on purpose, then measure.

Updating the indexed column cannot be HOT. Three rounds of half a million random reassignments:

UPDATE orders SET customer_id = 1 + floor(random() * 500000)::bigint WHERE id % 4 = 0;
UPDATE orders SET customer_id = 1 + floor(random() * 500000)::bigint WHERE id % 4 = 0;
UPDATE orders SET customer_id = 1 + floor(random() * 500000)::bigint WHERE id % 4 = 0;
SELECT tree_level, pg_size_pretty(index_size) AS size, leaf_pages, deleted_pages, avg_leaf_density, leaf_fragmentation
FROM pgstatindex('orders_customer_idx');
SELECT dead_tuple_percent, free_percent FROM pgstattuple('orders');
Each round takes a few seconds. The index has doubled, from 24 MB to about 48 MB, avg_leaf_density has dropped (about 84) and leaf_fragmentation is near 50: random keys split leaves everywhere, and the new pages are allocated wherever the file ends. pgstattuple('orders') shows a dead_tuple_percent around 17: about 1.5 million dead versions waiting for VACUUM.

5. VACUUM, then REINDEX CONCURRENTLY, measuring each.

VACUUM (VERBOSE) orders;
SELECT pg_size_pretty(index_size) AS size, leaf_pages, deleted_pages, avg_leaf_density FROM pgstatindex('orders_customer_idx');
SELECT * FROM pg_visibility_map_summary('orders');
REINDEX INDEX CONCURRENTLY orders_customer_idx;
SELECT pg_size_pretty(index_size) AS size, leaf_pages, deleted_pages, avg_leaf_density FROM pgstatindex('orders_customer_idx');
VERBOSE reports the index pass: “index scan needed”, about 1.55 million dead item identifiers removed, and few or no index pages newly deleted (no leaf was emptied completely). Afterwards index_size is unchanged and avg_leaf_density has fallen further, to about 53: the entries are gone, the pages stay. pg_visibility_map_summary shows most pages all-visible now. After REINDEX INDEX CONCURRENTLY, the index is back to roughly its step-1 size with density near 90. VACUUM removes; only a rebuild compacts.

6. Index-only scan and heap fetches.

UPDATE orders SET total_cents = total_cents WHERE id BETWEEN 1 AND 50000;
SET enable_seqscan = off; SET enable_bitmapscan = off;
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM orders WHERE customer_id BETWEEN 1000 AND 1200;
VACUUM orders;
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM orders WHERE customer_id BETWEEN 1000 AND 1200;
RESET enable_seqscan; RESET enable_bitmapscan;
Both plans are Index Only Scan using orders_customer_idx. The first shows Heap Fetches: in the tens (24 of 809 rows in a reference run) and a correspondingly larger Buffers: shared hit count (29 against 8): the update cleared all-visible bits on several hundred pages and every entry pointing into them needed a heap check. After VACUUM the second shows Heap Fetches: at or near 0 and fewer buffers. The index did not change between the two runs; the visibility map did.

7. Put the shop back. Do this after the break below if you try it.

DROP INDEX orders_customer_idx;
ALTER TABLE orders RESET (fillfactor);
docker compose exec -T db psql -U atlas -d shop -f /shop/load.sql
The reload truncates and regenerates all six tables in about 25 seconds, so customer_id and the page layout are as loaded again, at the default fillfactor. Indexes survive a TRUNCATE, so your D1 index set is still there; if you dropped one for step 3, recreate it with docker compose exec -T db psql -U atlas -d shop -f /shop/queries/d1-indexes.sql.
Hold a transaction open and try to rebuild. In a second terminal: docker compose exec db psql -U atlas shop, then BEGIN; SELECT count(*) FROM orders WHERE customer_id = 42; and leave it. In the first terminal run REINDEX INDEX CONCURRENTLY orders_customer_idx;. It builds the new index and then hangs. SELECT pid, state, wait_event_type, wait_event, left(query, 30) FROM pg_stat_activity WHERE wait_event IS NOT NULL; from a third session shows it waiting on a virtual transaction id: it cannot mark the old index unusable until every transaction that might have a snapshot of it finishes, and an idle-in-transaction session never will. Press Ctrl-C in the first terminal and run \d orders: an index orders_customer_idx_ccnew marked INVALID is left behind, taking writes and serving no reads. DROP INDEX orders_customer_idx_ccnew; cleans up, and idle_in_transaction_session_timeout is the setting that would have ended the blocker.
DECIDE

You are designing a new orders table that will take 2 000 inserts per second from six services. Ids must be generated by the service before the row is inserted, because the id goes into a payment request that is sent in the same step. Order lookups are by id, and most reads are of the last few hours' orders. Which primary key type do you pick?

READING
  1. PAPER
    The Ubiquitous B-Tree Douglas Comer, 1979

    The survey that fixed the vocabulary. Sections 1 to 3 are the structure, the insert and delete algorithms and the cost analysis in a dozen pages; the B+ tree variant Postgres uses is in section 4. Skip section 5 (1979 implementations). Read: sections 1 to 4.

  2. PAPER
    Efficient Locking for Concurrent Operations on B-Trees Philip L. Lehman and S. Bing Yao, 1981

    The high key and the right-link. Read section 3 for the B-link structure and section 4 for why a reader never needs to hold more than one lock; the proofs can be skipped. nbtree is this paper with page-level read locks added. Read: sections 1, 3 and 4.

  3. DOC
    B-Tree Indexes: Implementation

    The official description of structure, bottom-up deletion and deduplication, including the exact list of types that cannot be deduplicated and the deduplicate_items parameter.

  4. CODE
    nbtree README

    The design document in the source tree: Lehman and Yao adapted to shared buffers, the half-dead page deletion protocol, suffix truncation, posting lists and bottom-up deletion, with the reasoning. Long; read the first third and the deduplication section.

  5. CODE
    Heap-Only Tuples (HOT) README

    Exactly when an update can be HOT, what pruning does to line pointers, and why indexes point at the chain root. The document behind the lab's steps 2 and 3.

  6. DOC
    Heap-Only Tuples

    The short user-facing version of the README: the two conditions, the fillfactor advice and the pg_stat_all_tables counters to watch.

  7. DOC
    pgstattuple

    The columns of pgstatindex and pgstattuple and the approximate variant for large tables. Keep it beside you when you read avg_leaf_density.

  8. POST
    Use The Index, Luke Markus Winand

    The free online book on indexing for developers. Its 'Anatomy of an Index' and 'Modifying Data' chapters are the external view of this chapter: what a leaf node and a balanced tree cost, and why every index is a tax on writes.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Write-ahead logging, checkpoints and crash recovery →