A PostgreSQL CREATE UNIQUE INDEX CONCURRENTLY on a 400 GB orders table failed with a duplicate-key error; what state is left behind, and how do you recover?
answer
- the catalog entry already committed
- planner ignores it, writers may not
- indisvalid versus indisready
- IF NOT EXISTS on the retry
- drop concurrently, then rebuild
basics
~20 sThe index stays in the catalog marked INVALID, and queries ignore it. If it failed after its first build pass, writes still maintain it and it still rejects duplicates. Resolve the duplicates, DROP INDEX CONCURRENTLY it, then rebuild.
solid answer
~40 sA concurrent build commits its catalog entry first, so a later failure does not remove it: the index stays in `pg_index` with `indisvalid = false`, and psql's `\d` prints it with `INVALID`. Queries never use it. What else it does depends on `indisready`. If duplicates already existed, the first pass fails and the index is not ready, so writes ignore it. If the failure came later, in the validation pass, it is ready: every write keeps maintaining it and, being unique, it keeps rejecting duplicates with 23505 although nothing can query it. To recover, find and resolve the duplicate `external_ref` values, `DROP INDEX CONCURRENTLY` the leftover, and build again; `REINDEX INDEX CONCURRENTLY` is the alternative. Do not retry with `IF NOT EXISTS`: it sees the invalid index's name and skips.
code
sql · 9 linesSELECT n.nspname AS schema_name,
c.relname AS index_name,
i.indisvalid,
i.indisready,
pg_size_pretty(pg_relation_size(i.indexrelid)) AS size
FROM pg_index AS i
JOIN pg_class AS c ON c.oid = i.indexrelid
JOIN pg_namespace AS n ON n.oid = c.relnamespace
WHERE NOT i.indisvalid;go deeper
Know that a failed CREATE INDEX CONCURRENTLY leaves an index marked INVALID, visible in psql's \d output, and that it must be dropped or rebuilt.
Explain why the leftover exists: the catalog entry committed in its own transaction. Name pg_index.indisvalid and indisready and what each flag changes for queries and writes.
Diagnose which phase failed from indisready, explain why a ready unique leftover still raises 23505, and run the safe sequence: resolve duplicates, DROP INDEX CONCURRENTLY, rebuild without IF NOT EXISTS, verify.
Treat invalid indexes as a fleet hygiene problem: monitoring on pg_index, migration tooling that refuses IF NOT EXISTS for concurrent builds, and pre-flight duplicate checks before unique builds.
## Why a failed concurrent build leaves an index behind `CREATE INDEX CONCURRENTLY` runs as a series of separate transactions. The first one only **registers** the new index in the catalog `pg_index`, marked `indisvalid = false`, and commits. Later transactions build it, make it ready for inserts and finally mark it valid. If any later step fails (a uniqueness violation, a deadlock with SQLSTATE `40P01`, an error while evaluating an index expression, a cancel, a `statement_timeout`, a full disk), only the current transaction rolls back. The committed catalog entry stays, and psql's `\d marketplace.orders` lists the index followed by the word `INVALID`. ## Reading the leftover's state Two `pg_index` flags tell you how much the leftover still does: | `indisvalid` | `indisready` | What it means | |---|---|---| | false | false | Failed during or before the first build pass. Queries and writes ignore it; it still holds a name and some disk. | | false | true | Failed after the first pass committed (validation pass or final wait). Writes **maintain** it, a unique one **enforces** uniqueness, queries never use it. | | true | true | A normal, usable index. | For a duplicate-key failure both rows are possible. If `orders` already held duplicate `external_ref` values, the first pass hits them while building and fails early, leaving a not-ready index. If the table was clean but a writer inserted a duplicate during the build, either that writer gets the `23505` error itself (a ready index already enforces uniqueness) or the validation pass meets the duplicate and fails, leaving a ready, enforcing, invalid index. The manual states it directly: if a failure occurs in the second scan, the invalid index continues to enforce its uniqueness constraint. ## What the leftover costs - **Write overhead without read benefit**, once it is ready: every `INSERT` and every non-HOT `UPDATE` adds entries to it. - **Uniqueness errors from an index nobody can query**: a ready, invalid unique index keeps rejecting duplicate keys. - **Disk and WAL** for an index the planner never touches. - **A false sense of done**: a migration retried with `CREATE INDEX CONCURRENTLY IF NOT EXISTS` finds an object with that name, issues a notice and skips, so the release reports success while the index is unusable. The manual warns that `IF NOT EXISTS` gives no guarantee the existing index resembles the one requested. - **Skipped maintenance**: `REINDEX TABLE CONCURRENTLY` skips invalid indexes with the warning `skipping reindex of invalid index`, hinting `Use DROP INDEX or REINDEX INDEX.` ## Recovering safely 1. **List every invalid index**, not only the one you expect, with the catalog query in the example, and note `indisready` for each. 2. **Fix the cause.** For a unique index, find and resolve the duplicate keys first, or the next attempt fails the same way. For a deadlock or a timeout, find what conflicted, or give that session a limit that fits a 400 GB build. 3. **Drop it without blocking**: `DROP INDEX CONCURRENTLY marketplace.orders_external_ref_uidx;`. Like the build, it cannot run inside a transaction block, and it takes one index name. 4. **Build again** with `CREATE UNIQUE INDEX CONCURRENTLY`, without `IF NOT EXISTS`, so a leftover cannot silently satisfy it. 5. **Verify** that `indisvalid` is now true. The alternative to steps 3 and 4 is `REINDEX INDEX CONCURRENTLY marketplace.orders_external_ref_uidx;`, which rebuilds the leftover under its own name. Only the `REINDEX INDEX` form can rebuild an invalid index concurrently. Either way, a unique rebuild fails again while duplicates remain. ## Making the next attempt succeed - Run the duplicate check **before** the build, not after it. - Make sure the migration does not carry a `statement_timeout` shorter than the build can take; a cancel at hour three costs as much as a failure. - Keep other DDL away from `orders` while the build runs; a lock conflict that ends in a deadlock fails the build. - Alert on `pg_index` rows with `indisvalid = false`, so a leftover never lives quietly for months.
- Why can retrying with CREATE INDEX CONCURRENTLY IF NOT EXISTS make things worse?`IF NOT EXISTS` checks only the name. The invalid leftover already owns that name, so PostgreSQL issues a notice and does nothing, and the migration tool records success. The table keeps an index the planner ignores, which may still cost write overhead and enforce uniqueness, and nobody looks again until a query plan or an alert reveals it.
- Why not just run REINDEX TABLE CONCURRENTLY on orders to repair it?Because `REINDEX TABLE CONCURRENTLY` skips invalid indexes, warning `skipping reindex of invalid index` with the hint `Use DROP INDEX or REINDEX INDEX.` Only `REINDEX INDEX CONCURRENTLY` naming the leftover rebuilds it in place. For a unique index it still fails while duplicate keys remain, so resolve those first.
- Could application writes fail with a duplicate-key error before the unique build had finished?Yes. Once the first pass commits, the index is ready for inserts and uniqueness is enforced against other transactions from the start of the second scan, so a writer inserting a duplicate `external_ref` can get 23505 while the index is still invalid, and even if the build later fails.
- A failed concurrent build rolls back completely, like any failed statement.
- An INVALID index costs nothing, because the planner never uses it.
- Retrying with IF NOT EXISTS is a safe way to rerun a failed build.
- REINDEX TABLE CONCURRENTLY repairs every invalid index on the table.
- Removing the leftover needs a plain DROP INDEX, so a write outage is unavoidable.