Video in progress

How do you detect index bloat, and when do you run `REINDEX CONCURRENTLY`?

B-tree indexes get swollen with empty space after UPDATEs/DELETEs, and VACUUM doesn't return that space to the OS. If an index is much bigger than expected, or pgstattuple shows low density, on PG12+ I rebuild it with REINDEX INDEX CONCURRENTLY without stopping writes.

📖 Answer

The signs: an index has grown bigger than the table, the same data in a fresh database gives an index three times smaller, or index scans are slowly getting slower.

Checking:

CREATE EXTENSION IF NOT EXISTS pgstattuple;

SELECT avg_leaf_density, leaf_fragmentation
FROM pgstatindex('orders_customer_id_idx');

In a freshly built B-tree, avg_leaf_density is about 90% (the default fillfactor). If it has dropped to 40-50%, half the index is empty.

Rebuilding:

REINDEX INDEX CONCURRENTLY orders_customer_id_idx;

It builds a new index next to the old one, then swaps them. A plain REINDEX blocks writes to the table the whole time.

Things to watch:

  • if CONCURRENTLY fails, an invalid index with a _ccnew suffix stays behind, and you have to DROP it by hand;
  • the process needs extra disk space equal to one more index;
  • it doesn't run inside a transaction.

One note: B-tree deduplication was added in PG13 and bottom-up deletion in PG14, so on modern versions index bloat is much rarer. That's why I don't reindex on a schedule per table, only when a measurement shows the need.