skip to content

In PostgreSQL, how do you confirm a B-tree index on the orders table is bloated, and how does REINDEX CONCURRENTLY rebuild it without blocking writes?

level: seniorimportance: should knowfreq 44%

answer

  1. a contrib function for B-tree pages
  2. leaf density against the fillfactor
  3. a transient copy beside the old one
  4. swap names, then drop
  5. _ccnew and _ccold leftovers

basics

~20 s

Run pgstattuple's pgstatindex(): a freshly built B-tree shows avg_leaf_density around its 90 fillfactor, so a much lower figure on a large index means bloat. REINDEX INDEX CONCURRENTLY builds a _ccnew copy alongside, swaps it in, then drops the old one.

solid answer

~50 s

With the `pgstattuple` extension installed, `SELECT * FROM pgstatindex('marketplace.orders_seller_created_idx')` reads every page of a B-tree. A fresh build packs leaf pages to the default fillfactor of 90, so `avg_leaf_density` near 90 is healthy; a figure far below it, with high `leaf_fragmentation` and a size well above a fresh build, means bloat. To fix it, `REINDEX INDEX CONCURRENTLY` takes only `SHARE UPDATE EXCLUSIVE` locks: it creates a transient index with a `_ccnew` suffix, builds it in two passes like `CREATE INDEX CONCURRENTLY`, repoints constraints and swaps the names, marks the old index dead and drops it. It needs disk for a second copy, cannot run in a transaction block, and on failure leaves an `INVALID` `_ccnew` index to drop. Plain `REINDEX` instead blocks writes and, through `ACCESS EXCLUSIVE` on the index, almost every query on the table.

code

sql · 10 lines
sql
CREATE EXTENSION IF NOT EXISTS pgstattuple;

SELECT index_size,
       leaf_pages,
       avg_leaf_density,
       leaf_fragmentation
FROM pgstatindex('marketplace.orders_seller_created_idx');

-- Sent on its own, outside any transaction block
REINDEX INDEX CONCURRENTLY marketplace.orders_seller_created_idx;

go deeper

for a junior

Know that indexes can grow larger than their data needs and that REINDEX rebuilds them; CONCURRENTLY is the form that keeps writes running.

for a middle

Use pgstatindex and read avg_leaf_density against the default fillfactor of 90, and know that REINDEX CONCURRENTLY cannot run inside a transaction block.

for a senior

Choose between plain REINDEX, REINDEX CONCURRENTLY and drop-and-create by their locks, disk need and constraint handling; clean up _ccnew and _ccold leftovers; know the exclusion-constraint and catalog limits.

for a principal

Decide when bloat is worth a rebuild at all, budget disk headroom for second copies across the fleet, and fix the write pattern that causes the bloat rather than scheduling rebuilds.

## Measuring index bloat with pgstatindex An index is **bloated** when it holds many empty or nearly empty pages, so it is much larger, and slower to scan, than a fresh build of the same data. In PostgreSQL B-tree pages that become completely empty are recycled, but a page where most, not all, keys were deleted stays allocated, so a pattern that deletes most of each key range leaves sparse pages behind. The `pgstattuple` contrib module measures this directly. Its function `pgstatindex(regclass)` reads every page of a B-tree index and returns: | Column | What to look at | |---|---| | `index_size` | bytes on disk, including the metapage | | `tree_level` | height of the tree | | `leaf_pages`, `internal_pages` | page counts by kind | | `empty_pages`, `deleted_pages` | pages with nothing useful in them | | `avg_leaf_density` | average fullness of leaf pages, in percent | | `leaf_fragmentation` | how far the leaf order on disk departs from logical order | - A fresh B-tree build fills leaf pages to the **fillfactor**, 90 by default, so `avg_leaf_density` close to 90 is healthy and a figure like 40 means the leaves are less than half used. - The scan reads the whole index, so on a large index it costs real I/O; run it off-peak. - Execute rights go to superusers and members of `pg_stat_scan_tables` by default. - `pgstatginindex` and `pgstathashindex` cover GIN and hash; for other types, track physical size over time. ## Rebuild options and their locks | Method | What it blocks | Extra cost | |---|---|---| | `REINDEX INDEX` | writes to the table, plus `ACCESS EXCLUSIVE` on the index, which blocks almost every query that plans against the table | fastest single pass | | `REINDEX INDEX CONCURRENTLY` | schema changes, `VACUUM`, `ANALYZE` and a second concurrent build (`SHARE UPDATE EXCLUSIVE`); reads and writes continue | two passes, waits, a second copy on disk | | `DROP INDEX CONCURRENTLY` then `CREATE INDEX CONCURRENTLY` | the same as above | queries lose the index during the build; cannot drop an index backing a constraint | Plain `REINDEX` blocks reads because the planner takes `ACCESS SHARE` on every index of a table it plans for, whichever index the query will use. ## What REINDEX CONCURRENTLY does, step by step Each step is its own transaction: 1. Add a transient index definition to `pg_index`, named with a `_ccnew` suffix, and take session-level `SHARE UPDATE EXCLUSIVE` locks on the index and table. 2. Build the new index in a first pass, then mark it ready for inserts. 3. Run a second pass to add rows written during the first. 4. Repoint every constraint at the new index, swap the names, mark the new index valid and the old one invalid. 5. After waiting for queries that might still use it, mark the old index not ready, so writes stop maintaining it. 6. Drop the old index and release the session locks. The new index briefly coexists with the old one, so you need **free disk for a full second copy**, plus the WAL the build generates. ## Limits and failure handling - It cannot run inside a transaction block, and only one concurrent build runs per table at a time. - `REINDEX SYSTEM` does not accept `CONCURRENTLY`; system catalogs cannot be reindexed concurrently. - Indexes behind **exclusion constraints** cannot be reindexed concurrently: named directly they raise an error, and a table-level run skips them. - If it fails, an `INVALID` index ending in `_ccnew` is the half-built copy: drop it and run again. One ending in `_ccold` is the original that could not be dropped after a successful swap: just drop it. - Progress appears in `pg_stat_progress_create_index`, with `command` set to `REINDEX CONCURRENTLY`. Prevention, such as B-tree deduplication and fillfactor choices, belongs to the B-tree and storage topics; rewriting a whole bloated table with `VACUUM FULL` or `pg_repack` belongs to table-bloat work.

  • When is DROP INDEX CONCURRENTLY plus CREATE INDEX CONCURRENTLY worse than REINDEX CONCURRENTLY?
    When the index backs a primary key or unique constraint: `DROP INDEX CONCURRENTLY` does not support `CASCADE`, so it cannot remove such an index, while `REINDEX CONCURRENTLY` repoints the constraint to the new copy. Even for a plain index, drop-and-create leaves queries without the index for the whole build, pushing them onto slower plans; reindex keeps the old one serving until the swap.
  • How do you clean up after a failed REINDEX CONCURRENTLY?
    Look for `INVALID` indexes in psql's `\d` output. A name ending in `_ccnew` (or `_ccnew1` and so on) is the transient copy: drop it, fix the cause and run `REINDEX CONCURRENTLY` again. A name ending in `_ccold` is the original left after a successful swap: dropping it is all that remains.

Replacing a worn bridge by building the new one right beside it: traffic keeps using the old bridge during construction, the roads are switched over in a moment, and only then is the old bridge torn down. For a while you need room for two bridges.

  • Plain REINDEX only blocks writes, so queries keep running normally meanwhile.
  • REINDEX CONCURRENTLY rebuilds the index in place and needs no extra disk.
  • Plain VACUUM compacts half-empty B-tree pages and shrinks the index file.
  • System catalog indexes can be rebuilt with REINDEX SYSTEM CONCURRENTLY.
  • An avg_leaf_density of 90 means the index is 90 percent bloat.