PostgreSQL concurrent index builds: invalid objects and safe retry checks
An orders table needs a unique index. A regular index build would block writes, but switching to CREATE INDEX CONCURRENTLY fails because of existing duplicate values. Running the command again produces an “object already exists” error, which does not mean the index is usable. Database changes on a dedicated server require a complete chain of checks: command results, system catalog state, and application read/write behavior. Without these checks, an invalid index can remain in place, consuming disk space and adding write overhead.
1. Set up an isolated test and define the change boundaries
The following test assumes PostgreSQL is already installed on Debian 12 or Ubuntu 24.04, with psql, createdb, and a database role that has permission to create databases. Start by creating a dedicated test database from your terminal. If a database with the same name already exists, stop and check what it is used for; do not reuse an unfamiliar environment.
createdb index_build_lab
psql -X -v ON_ERROR_STOP=1 -d index_build_lab
Once connected, confirm the connection details, create 200,000 test rows, and add one record with a duplicate business key:
\conninfo
CREATE TABLE public.index_probe (
id bigint PRIMARY KEY,
external_id bigint NOT NULL,
payload text NOT NULL
);
INSERT INTO public.index_probe
SELECT g, g, repeat('x', 64)
FROM generate_series(1, 200000) AS g;
INSERT INTO public.index_probe
VALUES (200001, 1, 'duplicate');
ANALYZE public.index_probe;
This row count is simply a reproducible test fixture, not a performance benchmark. All test operations are confined to index_build_lab; do not copy the deletion statements into production. Epon dedicated servers come with two directly attached 1TB NVMe drives and no hardware RAID. Temporary files and new objects created during index builds must still be included in the space budget for each mount point.
Concurrent builds reduce blocking of normal writes, but they do not eliminate locks, waits, or resource consumption. Using concurrent mode is no substitute for database backups and verified recovery procedures.
2. Reproduce the failure and inspect the actual state
Run the following command in the current psql session without wrapping it in BEGIN. Because the test data contains duplicate values, a uniqueness error is expected:
CREATE UNIQUE INDEX CONCURRENTLY index_probe_external_uidx
ON public.index_probe (external_id);
Interactive psql lets you continue entering commands after the error. In an automated script, run this expected-to-fail command separately and verify its nonzero exit status. Do not disable all error checking and allow subsequent steps to pass silently.
Next, inspect the object's state:
SELECT c.relname,
i.indisunique,
i.indisready,
i.indisvalid,
pg_size_pretty(pg_relation_size(c.oid)) AS size
FROM pg_index AS i
JOIN pg_class AS c ON c.oid = i.indexrelid
WHERE i.indexrelid =
to_regclass('public.index_probe_external_uidx');
indisvalid=false means the planner cannot use this index as a normal query access path. indisready indicates whether the index is ready to be maintained by writes to the table. The combination of these flags can vary depending on the stage at which the build failed; do not hard-code a single combination as the only sign of failure.
Only a query that returns no rows indicates that the name does not resolve to an index record. The object's existence, a nonzero size, and an apparently correct definition are no substitute for checking validity. Do not use IF NOT EXISTS to hide a leftover object with the same name, either: it will not automatically repair an invalid index.
3. Remove the leftover index and address the source of duplicates
First, identify the conflicting keys and their counts:
SELECT external_id, count(*)
FROM public.index_probe
GROUP BY external_id
HAVING count(*) > 1;
In this test, the only result should be key 1 appearing twice. Drop the failed index, delete only the deliberately inserted fixture record, and then rebuild:
DROP INDEX CONCURRENTLY public.index_probe_external_uidx;
DELETE FROM public.index_probe
WHERE id = 200001
AND external_id = 1
AND payload = 'duplicate';
CREATE UNIQUE INDEX CONCURRENTLY index_probe_external_uidx
ON public.index_probe (external_id);
Commit these three statements separately; do not wrap them in a transaction. In a real application, duplicate records must be resolved according to business identity, related records, and retention rules. Simply keeping the lowest primary key and bulk-deleting the rest is not an acceptable general approach.
You must also fix the write path that produces duplicates. Finding no duplicates in a preliminary scan does not guarantee that new conflicts cannot occur during the build. A unique index may start enforcing uniqueness against other transactions late in the build. Even if the build subsequently fails, it may continue rejecting some duplicate writes. Check application error logs alongside the database state; an invalid index is not a reliable constraint mechanism.
4. Verify validity, query access paths, and duplicate-write rejection
Run the state query again. The new index should have both indisvalid=true and indisready=true. Then refresh the statistics and inspect an equality lookup:
ANALYZE public.index_probe;
EXPLAIN (ANALYZE, BUFFERS)
SELECT payload
FROM public.index_probe
WHERE external_id = 123456;
The plan should be able to use the new index, either through an index scan or a bitmap access path. Focus on the actual index name, the number of rows returned, and buffer accesses. Do not permanently disable sequential scans to create the illusion that the index is working; a sequential scan can also be a reasonable choice for a small dataset.
Next, verify that duplicate writes are rejected:
INSERT INTO public.index_probe
VALUES (200002, 1, 'must-fail');
SELECT count(*)
FROM public.index_probe
WHERE id = 200002;
The first statement should report a uniqueness violation, and the second should return zero. This test is still restricted to the test database and must use autocommit. If you place it inside an explicit transaction, you must roll back after the error before running further queries.
Keep at least the index definition, state query results, execution plan, and duplicate-write test results as verification evidence. Saving only a “CREATE INDEX” success message does not establish that the object was not subsequently replaced or show which access path the query actually used.
5. Plan for waits, resource use, and exit criteria in production
Before running the change in production, verify the database version, target table, index definition, long-running transactions, and free space on the file systems holding the table and temporary files. A concurrent build requires multiple scans and waits for relevant transactions. Do not estimate its completion time as if it were a single ordinary table scan.
During the build, monitor progress from another session:
SELECT pid, relid::regclass AS table_name, phase,
lockers_total, lockers_done,
blocks_total, blocks_done
FROM pg_stat_progress_create_index
WHERE datname = current_database();
The counters have different meanings across phases. The block ratio within one phase is not an overall progress indicator for the entire operation. To identify what a process is waiting for, also inspect its pg_stat_activity entry and pg_blocking_pids(pid). Do not terminate application transactions without first confirming the situation.
Migration tools must disable transaction wrapping for this operation. Do not launch multiple concurrent index builds on the same table at the same time. Before setting timeouts, be clear that a timeout can interrupt the build and leave an invalid object behind. Size build memory according to the current concurrent workload rather than assigning a large value simply because the server has plenty of RAM.
Cancel the operation and recheck the catalog state if free space approaches the predefined safety threshold, application latency deviates significantly from the pre-change baseline, or the transactions being waited on cannot be addressed within the current change window. Cancellation does not mean cleanup is complete. The final exit criteria are: the object is valid, query results are correct, duplicate writes are rejected as required, and no invalid index from this failed build remains. Once the test is finished, confirm that the connection still points to the dedicated test database, then drop the test table.
Frequently asked questions
Does a failed CREATE INDEX CONCURRENTLY remove the index automatically?
Not necessarily. An invalid index can remain under the same name. Inspect indisvalid and indisready in pg_index rather than treating object existence as success.
Can a migration tool wrap concurrent index creation in a transaction?
No. CREATE INDEX CONCURRENTLY and concurrent index removal must run outside a transaction block. Disable the migration tool’s transaction wrapper for these operations.
AMD EPYC 7543P Dedicated Server
From $459/month, with no setup fee or contract.