How to Create Indexes Without Blocking Writes
Add indexes to a busy table without blocking writes: concurrent index creation, its cost, failure handling and safe rollback.
On this page
Introduction
A plain CREATE INDEX takes a lock that blocks writes to the table for the whole build, which on a large table means minutes or hours of downtime. Production databases offer a concurrent variant that builds the index without blocking writes, at the cost of doing more work and taking longer. Using it well means knowing what it blocks, how it fails, how to clean up after a failure, and how to roll out an index change on a busy table without an outage.
Why a Normal Index Blocks
A normal CREATE INDEX takes a SHARE lock that conflicts with writes: existing writes finish, but new writes queue until the index is built. On a table with millions of rows the build can take minutes, and during that time every write stalls. For a service, that is an outage scheduled by the migration.
The concurrent variant allows writes to continue while the index builds. It is slower overall and uses more CPU and I/O, but it does not hold the blocking lock, so the table stays writable. For a large or busy table, the extra cost is worth the availability.
-- BLOCKS writes for the whole build:
CREATE INDEX idx_orders_customer ON orders (customer_id);
-- Does NOT block writes (allows concurrent writes during the build):
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);
-- slower and more resource-intensive, but the table stays writable
How CONCURRENTLY Works and What It Does
The concurrent build happens in phases: it takes a brief lock, builds the index by scanning the table while writes proceed, then takes a second brief lock to wait for transactions that started before the build and to mark the index valid. Writes are never blocked for the long scan; they are only briefly blocked at the start and end.
Because writes continue during the build, the index must also record changes for rows modified during the scan, which is where the extra cost comes from. The final brief lock waits for any transaction that could have a stale view, which is why it can take a moment to complete on a busy table.
# CREATE INDEX CONCURRENTLY phases
1. brief lock; start building (writes continue)
2. scan the table into the new index; record changes to modified rows
3. brief lock; wait for in-flight transactions; mark the index VALID
# writes blocked only briefly at phases 1 and 3, never during the scan
What It Cannot Run Inside
CREATE INDEX CONCURRENTLY cannot run inside a transaction block, because the phases require commits between them. A migration wrapped in a single transaction will fail with a clear error. Run it as its own statement outside any transaction, which also means it cannot roll back as part of a larger migration’s atomicity.
Because it is not transactional as a unit, a failure partway leaves an invalid index behind. The index exists but is not usable, and it must be dropped before retrying. Making the migration idempotent (drop if exists, then create concurrently) is what lets a retry recover from a partial failure.
-- WRONG: cannot run this inside a transaction
BEGIN;
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id); -- error
COMMIT;
-- RIGHT: its own statement, outside a transaction; idempotent for retries
DROP INDEX CONCURRENTLY IF EXISTS idx_orders_customer;
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);
Handling Failure and Invalid Indexes
If the concurrent build fails (a deadlock, a unique-constraint violation, an out-of-space error, a cancellation), it may leave an INVALID index: the catalog entry exists but the index has no data and is not used by the planner. Drop it before retrying, or the next attempt fails with a name conflict.
Detect invalid indexes with a query over the system catalogs, because they are invisible in normal operation: the planner simply does not use them, so the only symptom is a missing index. A migration that checks for and drops invalid indexes before creating is self-healing.
-- Find leftover invalid indexes (they cost space but are unused).
SELECT c.relname AS index_name, i.indisvalid, t.relname AS table_name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_class t ON t.oid = i.indrelid
WHERE NOT i.indisvalid; -- invalid indexes are not used by the planner
-- clean up before retrying:
DROP INDEX CONCURRENTLY IF EXISTS idx_orders_customer;
Resource Cost and Timing
The concurrent build scans the table twice in effect (once to build, once to catch up) and takes longer than a normal build. Plan the resource cost: enough space for the index, enough I/O and CPU headroom that the build does not degrade the service it is meant to keep available, and a time when the extra load is tolerable.
Use statement timeouts carefully: a timeout that cancels the build leaves an invalid index. Set a long enough timeout for the build or run it in a session where the timeout is raised, and prefer to let it complete than to cancel it partway.
# planning a concurrent index build
[ ] space for the index (it can be large)
[ ] I/O + CPU headroom so the build does not degrade the service
[ ] schedule for a low-load window if it competes for resources
[ ] long enough statement_timeout (a cancel leaves an INVALID index)
# prefer letting it finish over cancelling partway
Rolling Out an Index Change
Deploying an index change should be additive and reversible: create the new index concurrently, verify the planner uses it (EXPLAIN), keep the old index until the new one is proven, then drop the old one concurrently. This sequence never leaves the table without a needed index and allows a rollback at each step.
Dropping the old index concurrently also avoids the blocking lock. Verify the new index is actually being used before dropping the old one, because dropping it prematurely removes the plan you rely on. This is the expand-contract discipline for indexes.
-- expand: add the new index without blocking
CREATE INDEX CONCURRENTLY idx_orders_customer_new ON orders (customer_id, created_at);
-- verify the planner uses it:
EXPLAIN SELECT * FROM orders WHERE customer_id = $1 ORDER BY created_at;
-- contract: once proven, drop the old one without blocking
DROP INDEX CONCURRENTLY IF EXISTS idx_orders_customer;
Common Pitfalls and Conclusion
Do not run CREATE INDEX CONCURRENTLY inside a transaction; it cannot. Do not leave an invalid index after a failure; drop it before retrying. Do not set a short statement timeout that cancels the build. Do not drop the old index before the new one is proven in the plan. And do not forget the extra resource cost the concurrent build needs.
Zero-downtime index creation is CREATE INDEX CONCURRENTLY run outside a transaction, with idempotent drop-before-create, invalid-index cleanup on failure, adequate resource planning and a statement timeout long enough to finish. Roll it out additively, verify the new index is used, then drop the old one concurrently. Then an index change on a busy table costs resources, not availability.
Sources: PostgreSQL: CREATE INDEX, PostgreSQL: Explicit locking, PostgreSQL: Monitoring indexes (pg_index).
FAQ
- Why can CREATE INDEX CONCURRENTLY not run in a transaction?
- Because it works in phases that require commits between them, so it cannot be part of a single transaction block. Run it as its own statement outside any transaction, and make it idempotent because it cannot roll back as a unit.
- What is an invalid index?
- The leftover of a failed concurrent build: the catalog entry exists but the index has no data and the planner does not use it. It costs space and is invisible except for the missing index, so a migration should detect and drop invalid indexes before creating.
Report a problem with this articleOpens a pre-filled issue on GitHub.