Measuring B-Tree Page Density Before Autovacuum Falls Behind
Heap autovacuum keeps table bloat mostly predictable, yet secondary B-tree indexes on monotonically advancing timestamps or random UUIDs quietly erode shared_buffers hit ratios long before disk capacity alerts fire.
A common operational surprise in busy PostgreSQL clusters happens when query latency degrades slowly over weeks while n_dead_tup stays below 5% on the parent heap. The culprit is often a sparse B-tree index: random key inserts force frequent 50/50 leaf page splits, and range deletes leave behind mostly empty leaf pages that are never reclaimed until all tuples on a page become dead simultaneously.
Why heuristic catalog estimates mislead
Catalog-only bloat estimators guess average tuple width from pg_stats and assume uniform fillfactor. For composite indexes with skewed NULL distributions or heavy HOT-bypassing updates, catalog guesses easily drift by 20–30 percentage points.
When an index sits below ~10 GB or during off-peak diagnostics, pgstatindex() from the built-in pgstattuple extension gives exact structural visibility into leaf fill efficiency.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT
indexrelid::regclass AS index_name,
pg_size_pretty(pg_relation_size(indexrelid)) AS total_size,
s.tree_level,
round(s.avg_leaf_density::numeric, 2) AS avg_leaf_density_pct,
round(s.leaf_fragmentation::numeric, 2) AS leaf_fragmentation_pct,
s.empty_pages,
s.deleted_pages
FROM pg_stat_user_indexes i
CROSS JOIN LATERAL pgstatindex(i.indexrelid) s
WHERE i.relname = 'events_log'
ORDER BY pg_relation_size(indexrelid) DESC;
Interpreting density vs. fragmentation
Freshly built PostgreSQL B-trees default to a fillfactor of 90%, placing healthy avg_leaf_density around 82–90%. Random UUIDv4 indexes naturally settle near 65–70% due to 50/50 splits. Anything below 45% signals substantial wasted cache footprint: every index range scan touches twice as many 8 KiB buffers as necessary.
Meanwhile, leaf_fragmentation measures out-of-order physical leaf linkages on disk. Even on NVMe, high leaf fragmentation hurts OS readahead during wide index-only scans.
Online remediation without table locks
Since PostgreSQL 12, REINDEX INDEX CONCURRENTLY rebuilds dense index pages without blocking concurrent readers or writers, and PostgreSQL 14+ bottom-up index deletion dramatically reduces unnecessary splits caused by non-indexed column updates.
SET maintenance_work_mem = '512MB';
REINDEX INDEX CONCURRENTLY idx_events_log_tenant_created_at;
Scheduling monthly pgstatindex audits on only the top ten largest indexes keeps scan overhead tiny while stopping silent shared-buffer churn weeks before an outage.