Header Ad Placement

PostgreSQL CREATE INDEX CONCURRENTLY: What a Failed Build Leaves Behind

POSTGRESQL OPERATIONS

CONCURRENTLY protects ordinary writes from the standard index-build lock. It does not promise a quick migration, an atomic rollback, or a useful index after failure.

By Hossam

The migration finished with an error. What remains?

An engineer adds an index to a busy PostgreSQL table using CREATE INDEX CONCURRENTLY. The application continues writing, but the operation later fails. Is the database back where it started? Not necessarily. PostgreSQL documents failure paths that leave an invalid index behind, still adding maintenance work even though queries cannot use it.

That is the practical boundary behind the keyword. A concurrent build changes how the operation interacts with normal traffic. It does not turn index creation into a free background task, nor does it make every failed attempt disappear. Planning the change means planning its waiting phases, resulting catalog state and recovery path as well as its successful completion.

This guide follows PostgreSQL 18 documentation, not a claim about the latest release. It is documentation-based operational analysis. No database was deployed, migration timed or production incident reproduced for this article. The fictional review below illustrates decisions rather than test results.

Documentation: CREATE INDEX.

Concurrent does not mean lock-free

A normal CREATE INDEX prevents inserts, updates and deletes on the target table while it builds the index, though reads can continue. The concurrent form avoids locks that prevent those ordinary writes. That difference can matter more than finishing the index as fast as possible.

It still takes locks. The explicit-locking documentation lists CREATE INDEX CONCURRENTLY among the commands acquiring SHARE UPDATE EXCLUSIVE, a mode that conflicts with itself and several stronger modes. Calling the operation lock-free hides interactions with maintenance and schema changes.

The concurrent path also does more work: two table scans, with waits between stages. PostgreSQL warns that the extra CPU and I/O can slow other operations. A migration that permits writes can still make the application slower. Write availability and unchanged latency are different acceptance criteria.

Documentation: CREATE INDEX, Explicit Locking.

Why a build can wait after it has scanned the table

The concurrent operation first registers an invalid index in one transaction, then performs its two scans in separate transactions. Before each scan, it waits for existing transactions that have modified the table to finish. After the second scan, it waits for transactions holding snapshots that predate that scan.

The CREATE INDEX reference describes further interactions with concurrent builds on other tables when the indexes use predicates or non-simple column expressions. The point is not to memorize a single duration estimate. The operation has transaction-lifetime dependencies that are not described by the number of rows left to scan.

Even after the index is marked valid, older transactions can delay its usability for their queries in the documented worst case. A long-running migration therefore needs an observer who can distinguish scanning from waiting. Treating every pause as stalled I/O can lead to the wrong intervention.

Documentation: CREATE INDEX, Index creation progress.

Read progress as phases, not a universal percentage

PostgreSQL exposes pg_stat_progress_create_index for active CREATE INDEX and REINDEX backends. Its command and phase columns identify the operation and current stage. The progress documentation names waiting for writers before build, building the index, waiting for writers before validation and validation stages, among others.

The counters are phase-specific. blocks_total and blocks_done describe blocks processed in the current phase, while locker counters and current_locker_pid are useful during applicable waits. Dividing two block counters and labeling the result total migration completion can hide a later validation scan or snapshot wait.

Use the view to ask a narrower question: what phase is this backend in, and what evidence explains progress in that phase? Record that answer alongside workload and transaction context. The absence of a progress row after a backend finishes is not, by itself, proof that a valid index now exists.

Documentation: Index creation progress, pg_index catalog.

An invalid index is not the same as no index

If a scan encounters a problem such as a deadlock or a uniqueness violation, a concurrent build can fail while leaving its index invalid. PostgreSQL ignores that potentially incomplete index for query planning, but the reference warns that it still consumes update overhead.

The pg_index catalog makes the distinction explicit. indisvalid describes validity for queries. indisready describes readiness for inserts and updates, and indislive identifies an index that should still be treated as live rather than being dropped. These flags answer different questions; object existence alone does not establish usefulness.

Do not repair this by directly editing system-catalog flags. The supported recovery paths in CREATE INDEX are to drop the failed index and try the concurrent build again, or consider REINDEX INDEX CONCURRENTLY. The appropriate choice depends on the actual object, failure and environment. Review it with the database owner rather than running a generic cleanup command against an unverified name.

Documentation: CREATE INDEX, pg_index catalog, REINDEX.

Unique builds can affect writers before success

For a unique concurrent index, PostgreSQL starts enforcing uniqueness against other transactions when the second scan begins. Other queries can receive uniqueness errors before the index becomes available for querying, and even if the build eventually fails.

The documented second-scan failure case is particularly easy to misread: the invalid index can continue enforcing uniqueness afterward. That does not mean its contents have been validated as a complete, trustworthy uniqueness guarantee. The catalog reference explicitly warns that uniqueness is not guaranteed true for an invalid unique index.

Those statements are compatible. An unfinished object can reject some new writes while still failing to establish that the whole existing table satisfies the intended rule. Keep both effects in the incident record instead of reporting either that the failed index does nothing or that its constraint is fully established.

Documentation: CREATE INDEX, pg_index catalog.

A name collision is not a successful retry

CREATE INDEX IF NOT EXISTS only avoids an error when a relation with the same name already exists. PostgreSQL explicitly says it does not guarantee that the existing index resembles the one that would have been created.

That means an automated migration cannot use a notice about an existing name as its acceptance test. Check the intended table, definition and validity. A left-behind invalid index, an older definition or a different object with the same name can invalidate the conclusion that the intended change is complete.

Preserve the original error and inspect state before retrying. Repeating a creation command under a new name can leave redundant artifacts or add more work without resolving the first failure. A retry policy needs an object-state check, not only an exception handler.

Documentation: CREATE INDEX, pg_index catalog.

The migration runner and table shape matter

CREATE INDEX CONCURRENTLY cannot run inside a transaction block. A migration runner that automatically wraps the whole file in a transaction must support an appropriate non-transactional path for this operation. Removing the wrapper changes rollback expectations, so the recovery plan must be explicit.

Only one concurrent index build can run on a given table at a time, and schema modification is not allowed while the index is being built. Launching several concurrent builds on the same table is therefore not a general way to make the migration finish sooner.

PostgreSQL 18 does not support a concurrent build directly on a partitioned parent index. Its reference describes building indexes concurrently on individual partitions and then creating the parent partitioned index non-concurrently, with matching indexes already present. That final parent operation is metadata-only in the documented case. Do not apply a single-table recipe to a partition hierarchy without checking the complete attachment and validity state.

Documentation: CREATE INDEX.

Rebuilding has its own failure artifacts

REINDEX INDEX CONCURRENTLY is a documented option for an invalid index, but it is not merely another spelling of CREATE INDEX CONCURRENTLY. Concurrent rebuilding creates a replacement and moves through its own sequence of readiness, validity and name changes.

The REINDEX reference distinguishes leftover invalid replacement indexes with a _ccnew suffix from original indexes left with a _ccold suffix, including possible numbered variants. Those states have different recovery meanings. A blanket rule to drop every index whose name contains either suffix would skip the investigation that makes cleanup safe.

Keep the exact failing command, object identity and state together. This article describes the documented distinction, not permission to delete an index. Recovery changes can affect performance, dependencies and locking, and need an environment-specific review.

Documentation: REINDEX.

A fictional review with three different failures

Imagine Cedar adds an index to its orders table. In the first run, progress reaches a wait for older snapshots. The team sees that the scan counter is no longer moving and assumes the storage system is broken. The better first question is whether the reported phase is a wait and which transaction context explains it. This scenario does not imply that every quiet counter is harmless.

In the second run, a unique concurrent build reports a duplicate-related error. The application still receives uniqueness errors afterward, yet queries cannot use the invalid index. The team records the failed build and remaining object rather than assuming transaction rollback erased the attempted change.

In the third run, the migration uses IF NOT EXISTS and reports that the name already exists. Inspection finds the earlier invalid object, not the desired successful index. All three scenarios are invented. Their shared lesson is that command output, current catalog state and application behavior must be reconciled before declaring success.

Documentation: CREATE INDEX, Index creation progress, pg_index catalog.

Validity is necessary, usefulness is a separate test

After a successful build, confirm the exact definition and valid state, then assess the workload that justified the index. PostgreSQL notes that inappropriate indexes can make performance worse. More indexes mean more structures for the database to maintain, not an automatic improvement to every query.

Use representative query plans and realistic conditions rather than demanding that every query choose the new index. The planner may reasonably prefer another access path. For expression indexes, the CREATE INDEX reference calls for ANALYZE, or waiting for autovacuum to analyze the table, to generate relevant statistics.

EXPLAIN ANALYZE is not a harmless preview: it actually runs the query, including side effects for modifying statements. Use an appropriate testing environment and review execution risk before using it. A useful acceptance record separates the migration completing, the object being valid, and the target workload behaving better under the observed conditions.

Documentation: CREATE INDEX, Using EXPLAIN.

Related reading

Migration acceptance and recovery acceptance are different reviews. See why PostgreSQL backup verification is not a restore test.

Sources and scope

This article uses the version-specific PostgreSQL 18 documentation below. It makes no measured runtime, zero-downtime or hands-on testing claim. Consult the matching documentation for your installed version before acting.


 

Comments

Docker Build Contexts: What .dockerignore Excludes and COPY Does Not

CONTAINER BUILD INPUTS The context decides which files a build can access. A copy instruction decides what one step puts into a stage. Review those boundaries separately. By Hossam Start with the input boundary, not the final image A Dockerfile that copies only application files can still have a wider build context than its author intended. The context is the set of files available to the build, while COPY describes one operation using a source. A selective copy is useful, but it is not the same control as excluding an input from the context. Docker documents .dockerignore as a way to remove matching files and directories from the context before it is sent to the builder. That makes context selection and ignore rules worth reviewing even when the final runtime image appears small. A final-image inspection answers a different question from a build-input review. This guide analyzes Docker documentation. Its example repository layout and review steps are illustrative, not captured b...

Editorial Governance & Pages