Sub topic 12
Index bloat and REINDEX CONCURRENTLY
This chapter assumes you know what dead tuples are, how VACUUM and autovacuum work, and what a B-tree index is. It also assumes you can read pg_stat_user_tables output. Here the focus moves from the table to its indexes. Indexes bloat too, and VACUUM treats them differently.
Why indexes bloat
Every index entry points to a row version by its physical location. When an UPDATE creates a new row version, each index on the table needs a new entry for it, unless the update is a HOT update. The old entry stays until VACUUM removes it. A DELETE leaves its index entries in place for the same reason.
VACUUM does clean index entries that point to dead tuples. What it cannot do is shrink the index file or repack the pages. The main cases are:
- Sparse pages. If most entries on a B-tree leaf page are removed, the page stays allocated and holds the few survivors. Pages are merged or deleted only when they become completely empty.
- Empty pages. A page that has become empty is marked deleted and placed in a free list. The index can reuse it later, but the file does not get smaller.
- Skewed access patterns. Keys that are inserted in one range and deleted in another, such as timestamps with old rows purged, leave many half-empty pages behind.
- Page splits. Random keys such as UUIDs split pages as the index grows. Pages end up partly filled, and that space stays unused.
Recent PostgreSQL versions reduce this. Version 13 added B-tree deduplication, and version 14 added bottom-up deletion, which removes dead entries before a page has to split. These changes slow bloat down but do not eliminate it.
What bloated indexes cost
- Disk space and cache. An index twice as large as it needs to be takes twice the shared buffers and OS cache for the same information.
- Slower scans. Range scans read more pages for the same number of useful entries. Index-only scans read more of the index.
- Slower maintenance. VACUUM has to scan every index in full on each run, so large indexes make every VACUUM pass slower.
Measuring index bloat
Start with size. A large index on a small or mostly static table is the first suspect.
SELECT s.indexrelname,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size,
s.idx_scan
FROM pg_stat_user_indexes AS s
WHERE s.relname = 'orders'
ORDER BY pg_relation_size(s.indexrelid) DESC;The idx_scan column also matters. An index that is never scanned does not need rebuilding. It needs dropping, after you confirm that no constraint or replica depends on it.
For exact figures on a B-tree index, use pgstatindex from the pgstattuple extension you installed earlier.
SELECT index_size,
leaf_pages,
empty_pages,
deleted_pages,
avg_leaf_density,
leaf_fragmentation
FROM pgstatindex('public.orders_customer_id_idx');avg_leaf_density is the percentage of leaf page space holding data. A freshly built B-tree has a density near 90%, which is the default index fillfactor of 90. A density below roughly 50% on a large index is a reasonable sign that a rebuild will pay off. Compare against the index's own history, because a healthy index on random keys settles around 65–75%. leaf_fragmentation shows how far the physical page order has drifted from the logical key order.
Like pgstattuple on tables, pgstatindex reads the whole index, so run it off-peak on large indexes.
Why VACUUM FULL is not the answer for indexes
VACUUM FULL rebuilds all indexes on the table as part of the table rewrite, and it holds an ACCESS EXCLUSIVE lock the whole time. If only one index is bloated, that is far too heavy. Rebuilding just that index is cheaper and can be done without blocking writes.
REINDEX CONCURRENTLY
REINDEX builds a fresh copy of an index from the table data and replaces the old one. The plain form blocks writes to the table while it runs. The CONCURRENTLY option, available from PostgreSQL 12, avoids that.
REINDEX INDEX CONCURRENTLY public.orders_customer_id_idx;You can also rebuild every index on a table, or every index in a database:
REINDEX TABLE CONCURRENTLY public.orders;How it works
The command takes a SHARE UPDATE EXCLUSIVE lock on the table. That lock allows reads and writes, but it conflicts with itself. A second REINDEX, a VACUUM, or most ALTER TABLE forms on the same table will wait or fail.
Because the command waits for transactions that could still see the table in an older state, a long-running transaction can stall it. This is the same class of blocker you met earlier for VACUUM. If a REINDEX CONCURRENTLY seems stuck, query pg_stat_activity for old backend_xmin values and old transactions before cancelling anything.
Costs and limits
- Disk space. The old and new indexes exist at the same time, so you need free space for a full second copy of the index.
- Time and I/O. Two table scans and two waiting phases make it slower than a plain REINDEX.
- No transaction blocks.
REINDEX CONCURRENTLYcannot run insideBEGIN ... COMMIT. - No exclusion constraints. Indexes that back an exclusion constraint cannot be rebuilt concurrently.
- Unique indexes can fail. If the table has a conflicting duplicate by the time the build finishes, the command errors out.
- Replication. The rebuild is written to WAL and replays on standbys. A large index produces a large burst of WAL, so watch replica lag.
Cleaning up a failed run
If the command is cancelled or fails, it can leave an extra invalid index behind. Its name usually ends in _ccnew, or _ccold if the failure came late. An invalid index is still maintained on every write but never used for queries, so it costs you with no benefit.
SELECT c.oid::regclass AS index_name,
i.indrelid::regclass AS table_name
FROM pg_index AS i
JOIN pg_class AS c ON c.oid = i.indexrelid
WHERE NOT i.indisvalid;Drop what you find with DROP INDEX CONCURRENTLY, then retry the rebuild. psql's \d tablename also marks these indexes as INVALID.
DROP INDEX CONCURRENTLY public.orders_customer_id_idx_ccnew;Before PostgreSQL 12
On older versions you can get the same effect by hand. Build a replacement, drop the old index, and rename the new one.
CREATE INDEX CONCURRENTLY orders_customer_id_idx_new
ON public.orders (customer_id);
DROP INDEX CONCURRENTLY public.orders_customer_id_idx;
ALTER INDEX public.orders_customer_id_idx_new
RENAME TO orders_customer_id_idx;This does not work for indexes that back a primary key or unique constraint. Those need ALTER TABLE ... ADD CONSTRAINT ... USING INDEX and a short lock.
Choosing a method
| Situation | Approach |
|---|---|
| One bloated index, table must stay writable | `REINDEX INDEX CONCURRENTLY` |
| Table and its indexes are all bloated | pg_repack, or `REPACK` where available |
| Maintenance window, table can be locked | Plain `REINDEX` or `VACUUM FULL` |
| Index never scanned | Drop it, after checking constraints and replicas |
| Index backs an exclusion constraint | Plain `REINDEX` in a window, or recreate the constraint |
Keeping indexes from bloating again
- Drop unused indexes. Every index adds an entry for each non-HOT update. Fewer indexes means more HOT updates and less index churn.
- Avoid indexing frequently updated columns unless queries need them. Updating an indexed column rules out HOT for that row.
- Keep autovacuum current. Dead index entries remain until VACUUM runs, so lagging autovacuum means growing indexes as well as tables.
- Use a lower index fillfactor only when you have evidence. B-tree indexes use 90 by default. A lower value leaves room for inserts in the middle of the key range but makes the index larger from the start.
- Rebuild on a schedule only if measurements justify it. Many indexes reach a stable size and gain nothing from repeated rebuilds.
Exercise
pgstatindex reports avg_leaf_density of 38 for a 12 GB index, and the table has a long-running transaction that has been open for hours. You run REINDEX INDEX CONCURRENTLY and it appears to hang. What is the likely cause, what do you check first, and what free disk space do you need?
Show answer
The command waits for transactions that began before its build phases, so the old transaction is probably holding it up. Check pg_stat_activity for old xact_start and backend_xmin values, and end or commit that transaction if it is safe to do so. You need roughly 12 GB of free space for a second copy of the index, because the old and new indexes exist side by side until the swap finishes.
Exercise
A REINDEX TABLE CONCURRENTLY was cancelled halfway. How do you find leftovers, and why should you remove them?
Show answer
Query pg_index for rows where indisvalid is false, and look for names ending in _ccnew or _ccold. Drop them with DROP INDEX CONCURRENTLY. An invalid index is still updated on every write but is never used by queries, so it adds write cost and disk usage with no benefit.