The Production Dilemma: Standard Indexing vs. Concurrent Builds
Running a standard index build on a busy production table is an easy way to trigger an outage. A standard index statement grabs a restrictive lock that freezes write operations immediately:
-- Danger: Takes a SHARE lock and blocks INSERT, UPDATE, DELETE
CREATE INDEX idx_orders_user_id ON orders(user_id);
The lock matrix explains why this hurts. Standard index creation requests a SHARE lock. While SELECT queries run normally, any incoming INSERT, UPDATE, or DELETE gets queued behind the build. If indexing a 50-million-row table takes 12 minutes, writes stall for that entire 12-minute window. Connection pools like PgBouncer hit their limits within seconds, queue up queries, and quickly cause 504 gateway timeouts across downstream services.
PostgreSQL solves this bottleneck with a non-blocking alternative: CREATE INDEX CONCURRENTLY.
Approach Comparison: Standard vs. Concurrent Index Creation
Both methods yield the exact same result: a fully functional B-tree index ready to speed up your queries. Under the hood, however, their execution mechanics couldn’t be more different.
| Feature | Standard (CREATE INDEX) | Concurrent (CREATE INDEX CONCURRENTLY) |
|---|---|---|
| Table Lock Level | SHARE |
SHARE UPDATE EXCLUSIVE |
| Blocks Concurrent Writes | Yes (queued until complete) | No (writes continue uninterrupted) |
| Table Scans Required | 1 sequential scan | 2 table scans + transaction wait phases |
| Transaction Block Allowed | Yes (runs inside BEGIN...COMMIT) |
No (must run in standalone mode) |
| Failure Behavior | Rolls back cleanly on error | Leaves an orphaned INVALID index |
| Resource Consumption | Lower CPU/IO, shorter duration | Higher cumulative CPU/IO, 2x–3x duration |
Why Concurrent Indexing Takes Longer
Concurrent builds avoid locking writes by splitting the work into three distinct phases:
- Catalog Registration: PostgreSQL registers the index in the system catalogs with
indisready = falseandindisvalid = false. The planner ignores the index, and writes do not touch it yet. - First Scan: Postgres waits for existing write transactions to finish. Once they clear, it performs a full sequential scan to build the baseline index structure.
- Second Scan: The engine sets
indisready = trueso incoming writes start updating the index. Then it scans the table a second time, catches up on any rows modified since step one, and waits for prior snapshot transactions to clear before marking the indexindisvalid = true.
Pros and Cons
Standard Indexing
- Pros: Finished faster (typically 50% to 70% quicker than concurrent runs); consumes less cumulative disk I/O; rolls back cleanly if your migration script aborts.
- Cons: Queues all write traffic; exhausts connection pools; risks downtime on large tables.
Concurrent Indexing
- Pros: Zero write interruptions; applications process payments and orders without lag; safe for round-the-clock traffic.
- Cons: Slower build times; higher cumulative I/O; leaves a broken
INVALIDindex on disk if a timeout, deadlock, or unique constraint violation halts execution.
Recommended Setup for Production Migrations
When you run concurrent builds on tables with tens of millions of rows, configure your session parameters first. Sensible defaults prevent out-of-memory errors and avoid lock-acquisition pileups.
1. Session Memory and Timeout Adjustments
Boost your maintenance memory to keep sorting in RAM, and tighten your lock acquisition timeout:
-- Give the worker enough RAM to avoid spilling temporary files to disk
SET maintenance_work_mem = '1GB';
-- Prevent long-running builds on large tables from getting killed mid-flight
SET statement_timeout = 0;
-- Fail fast if acquiring the initial lock takes longer than 5 seconds
SET lock_timeout = '5s';
2. Data Staging Preparation
Before touching production, reproduce the migration on a staging database with realistic data volumes. For instance, testing an index on a 10 GB table requires accurate test fixtures. If you need to quickly convert CSV seed data into JSON payloads for your migration harness, browser-based utilities like toolcraft.app/en/tools/data/csv-to-json let you reformat data locally without uploading sensitive company records to third-party servers.
Step-by-Step Implementation Guide
Step 1: Check for Long-Running Transactions
Concurrent index builds cannot finish until all transactions that were open when the command started have closed. An uncommitted transaction or an abandoned reporting query will cause your build to stall indefinitely:
SELECT pid, now() - xact_start AS duration, query, state
FROM pg_stat_activity
WHERE state != 'idle'
AND xact_start IS NOT NULL
ORDER BY duration DESC;
Look for queries with a duration exceeding a few minutes. Terminate any abandoned backend processes before starting your build:
SELECT pg_terminate_backend(12345); -- Replace 12345 with the offending PID
Step 2: Execute the Concurrent Index Creation
Make sure your migration framework runs this outside an active transaction block. In tools like Flyway, Rails, or Prisma, turn off transaction-wrapping for this file:
CREATE INDEX CONCURRENTLY idx_orders_customer_created
ON orders (customer_id, created_at DESC);
Track execution live with PostgreSQL’s built-in progress view:
SELECT phase, blocks_total, blocks_done, tuples_total, tuples_done
FROM pg_stat_progress_create_index;
Step 3: Identify and Root-Cause Invalid Indexes
If someone cancels your build, or if a unique constraint collides with duplicate rows, PostgreSQL will not roll back the file on disk. Instead, it leaves an index marked as INVALID.
Invalid indexes hurt performance. The query planner ignores them for SELECT queries, yet PostgreSQL still updates them on every INSERT, UPDATE, and DELETE. You pay write overhead for zero read benefit.
Locate every broken index across your database with this query:
SELECT
c.relname AS index_name,
t.relname AS table_name,
i.indisvalid,
pg_size_pretty(pg_relation_size(c.oid)) AS index_size
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_class t ON t.oid = i.indrelid
WHERE i.indisvalid = false;
Step 4: Clean Up and Rebuild Safely
Never ignore an invalid index. On PostgreSQL 12 and newer, repair it concurrently in one command:
-- PostgreSQL 12+: Rebuilds concurrently and atomically replaces the invalid index
REINDEX INDEX CONCURRENTLY idx_orders_customer_created;
If you run PostgreSQL 11 or older, drop the broken index concurrently and rebuild it from scratch:
-- Drop the broken index without blocking writes
DROP INDEX CONCURRENTLY IF EXISTS idx_orders_customer_created;
-- Recreate it concurrently
CREATE INDEX CONCURRENTLY idx_orders_customer_created
ON orders (customer_id, created_at DESC);
A safe migration comes down to three habits: kill stale transactions before you start, increase maintenance_work_mem for the session, and audit pg_index for invalid entries after any failed deploy. Done right, you can index tables with hundreds of millions of rows during peak business hours without causing a single user-facing error.
