Practical technical guides / Core IT: databases

A Failed CREATE INDEX CONCURRENTLY Can Leave an Invalid Index That Still Takes Writes

Measured on PostgreSQL 18.4: an index left invalid before it was marked ready costs nothing, after that it grows on every write. Find leftovers and clean up.

By Sandeep Belgavi · Published 2026-11-26

Measured on PostgreSQL 18.4: an index left invalid before it was marked ready costs nothing, after that it grows on every write. Find leftovers and clean up.

The failed build is not gone

CREATE INDEX CONCURRENTLY is how teams add indexes to busy PostgreSQL tables without blocking writes. It is also one of the few DDL commands that can fail and leave something behind. A migration that adds a unique index on the case reference column of the help-desk table at Belgavi's Book Store fails with a uniqueness violation, the deploy tool reports an error, and the engineer fixes the data and reruns the migration. The rerun fails differently: the index name already exists. The catalog holds an index marked INVALID from the first attempt.

The PostgreSQL 18 documentation describes this. If a problem arises while scanning the table, such as a deadlock or a uniqueness violation in a unique index, CREATE INDEX fails but leaves behind an invalid index, which is ignored for querying purposes because it might be incomplete, but still consumes update overhead. That last clause is the one that matters in production, and on PostgreSQL 18.4 it turned out to depend on where the build failed. This guide measures three failure cases on a disposable cluster, shows how to find leftovers, and gives a cleanup procedure.

Three phases, three catalog states

A concurrent build runs in several transactions. It first enters the index into the catalog as invalid. It then waits for transactions that have modified the table, scans the table to build the index, and marks the index ready, meaning it receives new rows from inserts and updates. It waits again, scans a second time to catch rows written during the first scan, waits for transactions whose snapshots predate that scan, and finally marks the index valid.

Two pg_index columns record the result. indisready says whether the index is maintained on writes. indisvalid says whether the planner may use it. A failed build leaves indisvalid false, and indisready is whatever the build had reached.

Measure it on PostgreSQL 18.4

The companion probe creates a table of 200,000 synthetic case rows in which every case reference appears four times, then produces three failures and reads the catalog after each one.

case                                              indisvalid  indisready  size     grows on insert  planner uses it
unique build meets existing duplicates            false       false       0 B      no               no
REINDEX CONCURRENTLY of that invalid index        false       false       0 B      no               no   (adds cic_ref_key_ccnew)
build cancelled in "waiting for old snapshots"    false       true        4.52 MB  yes              no

The unique build found the duplicates while building in the first scan, before the index was marked ready. It left a zero-byte invalid index that did not grow when 50,000 more rows were inserted. For that failure, on this version, the leftover costs a catalog entry and a name, not write overhead.

The third case was produced deliberately. An open REPEATABLE READ transaction held a snapshot taken before the build, so the build reached its final wait, reported by pg_stat_progress_create_index as the phase waiting for old snapshots, and stopped there. At that point the index had been built and marked ready. Cancelling the build with pg_cancel_backend left an index of 4,521,984 bytes with indisready true. Inserting 50,000 rows grew it to 6,094,848 bytes, while EXPLAIN for an equality lookup on the indexed column still chose a sequential scan. That is the documented situation exactly: every write pays to maintain an index that no query can use.

A separate probe run, on a larger copy of the table, cancelled a non-unique build with a 300 millisecond statement timeout before it was marked ready, and the leftover again had indisready false and zero bytes. The pattern is consistent across the three measurements: a failure before the index is marked ready leaves an empty shell, and a failure after it leaves a maintained, unusable index.

The uniqueness trap

The documentation adds a sharper caveat for unique indexes. Uniqueness is enforced against other transactions from the moment the second table scan begins, and if a failure occurs in the second scan, the invalid index continues to enforce its uniqueness constraint afterwards. A ready but invalid unique index therefore cannot speed up a single query and can still reject inserts. The probe did not reproduce a second-scan failure of a unique build, so this is stated from the documentation, but it changes how urgently such a leftover must be removed.

Find every leftover

The catalog query is short, and it should run after every migration that builds or rebuilds an index concurrently.

-- Author: Sandeep Belgavi. Invalid indexes, whether they are maintained on writes, and their size.
SELECT indexrelid::regclass AS index_name,
       indrelid::regclass   AS table_name,
       indisready           AS maintained_on_writes,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_index
WHERE NOT indisvalid
ORDER BY pg_relation_size(indexrelid) DESC;

In psql the same indexes show INVALID in the output of \d for the table. REINDEX CONCURRENTLY failures leave names with suffixes. The REINDEX documentation explains them: an invalid index suffixed _ccnew is the transient copy created during the rebuild and should be dropped before trying again, while one suffixed _ccold is the original index that could not be dropped after a successful rebuild and can simply be dropped. A number may follow the suffix, as in _ccnew1. In the probe, rebuilding the invalid unique index with REINDEX INDEX CONCURRENTLY failed on the same duplicates and left cic_ref_key_ccnew beside the original.

Clean up without blocking writes

The documented recovery is to drop the invalid index and run CREATE INDEX CONCURRENTLY again, or to rebuild it with REINDEX INDEX CONCURRENTLY, which is the only form of REINDEX that can build an invalid index concurrently. Use DROP INDEX CONCURRENTLY for the drop so that it does not take a lock that blocks writes on a busy table.

-- Author: Sandeep Belgavi. Remove the leftovers, fix the cause, then build again.
DROP INDEX CONCURRENTLY IF EXISTS cic_ref_key_ccnew;
DROP INDEX CONCURRENTLY IF EXISTS cic_ref_key;
-- resolve duplicate case_ref values first, or the next unique build fails the same way
CREATE UNIQUE INDEX CONCURRENTLY cic_ref_key ON cic_orders (case_ref);

Fix the cause before retrying. For a uniqueness violation, find duplicates with a GROUP BY on the key and decide which rows are wrong. For a cancellation, find what held the old snapshot: long transactions, idle-in-transaction sessions and logical replication slots are the usual suspects, and pg_stat_activity shows the first two.

Make migrations idempotent about this

A migration tool that runs CREATE INDEX CONCURRENTLY should not assume the name is free. Before building, check pg_index for an existing index with that name. If it exists and is valid, skip. If it exists and is invalid, drop it concurrently and rebuild. If the tool wraps statements in a transaction, remember that CREATE INDEX CONCURRENTLY cannot run inside a transaction block, so the step must run on its own.

A lock_timeout on the build session does end a build that is stuck behind a long transaction, but measure what it leaves. In the companion run a 2 second lock_timeout ended the build in the phase waiting for old snapshots with LockNotAvailable, and the leftover had indisready true: the costly kind. So pair any timeout with the leftover query as the last step of every migration, and drop what it finds, so that an interrupted deploy is detected on the same day rather than months later from slow inserts.

Partitioned tables need a different plan

The documentation notes that concurrent builds for indexes on partitioned tables are not supported. The supported route is to build the index concurrently on each partition, then create the partitioned index on the parent non-concurrently, which is then a metadata-only operation that attaches the existing partition indexes. Each per-partition build can fail in the same ways measured above, so run the leftover query across all partitions before creating the parent index, or the parent build will find an invalid index where it expected a usable one.

When none of this applies

On a table that can tolerate a short write lock, such as a small reference table or a table in a maintenance window, a plain CREATE INDEX is simpler: it either succeeds or rolls back completely and leaves nothing behind. The concurrent form exists for large, busy tables, and its partial failure states are the price of not blocking them.

Verification checklist

Run the leftover query in CI against a database restored from production schema after every migration test. Alert in production when any invalid index exists for longer than a deploy window, and treat an invalid index with indisready true as urgent because it costs every write. Re-run the companion probe on your PostgreSQL version before relying on the phase behaviour measured here on 18.4, because the build's internal phases can change between major versions.

Primary references and authorship

Sources checked 2026-11-26. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/sql/postgres_invalid_concurrent_index. Views are my own and do not represent any employer, past or present.