Rebuilding PostgreSQL indexes with REINDEX CONCURRENTLY

REINDEX CONCURRENTLY rebuilds a bloated or collation-affected index while the table stays available for writes, at the cost of more time, more I/O and a cleanup step if it fails. This page covers when to use it, its caveats, and how to schedule rebuilds you can verify.

On this page

When REINDEX CONCURRENTLY is the right way to rebuild an index

Choose REINDEX CONCURRENTLY when an index on a live production table has grown bloated, or when its sort order no longer matches the data after an operating system or C library update changed collation behavior, and you cannot accept a write lock for the rebuild. A plain REINDEX takes a lock that blocks writes to the table for as long as the rebuild runs, which on a large table can mean a write outage measured in hours. REINDEX CONCURRENTLY builds a replacement index alongside the existing one while normal reads and writes continue, then swaps the new index in and drops the old one. The trade-off is that the work takes longer, uses more CPU and I/O, and can fail partway through in ways a plain rebuild does not, leaving an invalid index behind.

Confirm the exact locking behavior, the number of table scans it makes, and any restrictions on which index types, partitioned tables or concurrent operations it supports in the REINDEX documentation for your server version. Those details have changed across major releases, so do not rely on a summary from memory or an older guide. Also confirm whether your version can rebuild all indexes on a table or schema concurrently, because that choice affects how you split the work. Check the PostgreSQL high availability documentation for how the rebuild's extra write and WAL volume will reach your standbys and replication lag.

This page is for planning a scheduled rebuild, not for recovering from a failure in progress. If a rebuild has already failed and left an unusable index, or if a collation change is already causing wrong query results, you need the cleanup and verification steps in the sections that follow, and a decision about whether to fail over or restore. Before you start, decide which indexes justify the cost, record the current index sizes and definitions, confirm free disk space for the new index while the old one still exists, and agree on a window and a rollback point with the application owners. Illustrative example: a team that finds one 200 GB index with heavy bloat should rebuild that index alone before touching the rest of the table.

Which index problems justify a concurrent rebuild

A concurrent rebuild fixes index-level problems: physical bloat, sort order that no longer matches the data, and damaged index pages. Each trigger below needs evidence gathered before any REINDEX runs, because the same symptoms can come from a query, a statistics or a schema problem that a rebuild will leave untouched.

Bloat measured inside the index

Index bloat is space occupied by dead or sparse index pages that a rebuild can return to a compact state. Before rebuilding, compare the index's on-disk size with an estimate of its live content, and check the table's vacuum history so you know the bloat is not simply waiting for autovacuum. Confirm the index is still used with its usage statistics. A rebuild will not fix a bad query plan, a missing index, or a table that is bloated in its heap rather than its indexes.

Collation or locale change

After an operating system or glibc upgrade, the sort order of text may change, so B-tree indexes on text columns can return wrong results or miss rows. Check the database and column collations, the glibc version recorded on the server, and whether queries using these indexes return different rows than before the upgrade. Rebuild affected indexes, and confirm the change is not hiding a deeper data issue. A rebuild will not correct data already stored in the wrong order in other objects, such as constraints or partitions you have not checked.

Suspected index corruption

Symptoms such as queries that return different results with and without an index scan, or errors while reading index pages, suggest corruption. Run amcheck on the index first to confirm which pages are damaged and record the error text. A rebuild replaces the index contents from the table, so it can clear the damage in the index, but it will not repair damage in the heap. If the table itself reports errors, the rebuild is the wrong first step.

Writes that cannot pause

Plain REINDEX takes locks that block writes to the table for the duration of the rebuild. When the table serves an active workload, the rebuild has to use REINDEX CONCURRENTLY so that inserts, updates and deletes continue. Check the write rate, the lock queue, and whether the rebuild can run inside the window your application tolerates. Concurrent rebuilds take longer and need extra disk space, so measure both before choosing the method.

Invalid indexes left by a failed build

A concurrent build that fails can leave an index marked invalid. Queries will not use it, but it still adds write overhead and occupies disk space. Find invalid indexes in the system catalogs, confirm no build is still running, and drop or rebuild them before retrying. A rebuild will not help if the failure cause, such as a unique violation in the data, is still present. Fix the cause first.

REINDEX and index rebuild options compared

This table compares REINDEX CONCURRENTLY at index, table and schema scope with plain REINDEX, a CREATE INDEX CONCURRENTLY and swap, and pg_repack. Read each row against your own write load, free disk and tolerance for a failed run, and confirm the lock levels for your PostgreSQL version in the official docs before scheduling work. The main takeaway is that the concurrent options avoid blocking writes but cost more time, more disk and more cleanup when something fails.

OptionLock behavior on writesExtra disk and timeBehavior on failureBest fit
REINDEX CONCURRENTLY on one indexWrites continue; takes a stronger lock only briefly at start and end, confirm levels for your versionNeeds free space for the new index while the old one exists; slower than plain REINDEXCan leave an INVALID index with the new name that must be droppedSingle bloated or collation-affected index on a busy table
REINDEX CONCURRENTLY on a tableWrites continue; each index is rebuilt in turn, so the table's indexes are never all unavailable togetherExtra space peaks at roughly the size of the largest index being rebuilt, confirm against your indexesFailed indexes can be left INVALID; the run must be rechecked index by indexSeveral bloated indexes on one table during a planned window
REINDEX CONCURRENTLY on a schema or databaseWrites continue; work runs table by table, so a long run touches many locks over timeLongest total runtime; disk use is still per index, but total effort scales with object countA failure partway through leaves earlier rebuilds complete and later ones untouched; resume by listing invalid indexesScheduled maintenance across many tables where elapsed time is acceptable
Plain REINDEXTakes a lock that blocks writes (and reads) on the table or index for the full rebuildLess extra disk and usually faster, since no concurrent write handling is neededA failure rolls back the rebuild, leaving the original index in placeTables or indexes that can be offline, such as a dedicated maintenance window
CREATE INDEX CONCURRENTLY, then swapWrites continue during the build; the swap needs a short lock and a drop of the old indexTwo copies exist during the build and the swap; more manual steps and more timeFailed builds leave an INVALID index to drop; the original index is untouched until the swapTeams that want control over the swap, or that need the new index definition changed
pg_repack (sibling topic)Writes continue during most of the rebuild, with short lock moments at start and finishNeeds extra disk for the new copy of the table and indexes, plus its own extension setupFailed runs are cleaned up by the tool; confirm behavior for your pg_repack versionTable bloat as well as index bloat, when the extension is allowed on your servers

How a concurrent rebuild moves from candidate to verified index

The rebuild starts with identifying the index and checking disk headroom and long-running transactions, since a concurrent build needs room for the new index and can be held back by old transactions. It then runs REINDEX CONCURRENTLY, which builds a replacement alongside the old index while writes continue. On success, verify the new index and drop the old one. On failure, the new index is left behind as invalid and must be dropped before the rebuild is retried.

Phases and branch points for a concurrent index rebuild.

What happens to writes, transactions and the old index during a rebuild

REINDEX CONCURRENTLY builds a replacement index next to the existing one while normal reads and writes continue against the table. The engine scans the table, creates the new index entries, and then waits for every transaction that might still be using the old index or its snapshot to finish. Only after that wait does it swap the new index into place and drop the old one. The wait step is where most surprises come from: a single long-running or idle-in-transaction session that started before the rebuild can hold up completion for as long as it stays open, so the operation can appear stalled while it is actually waiting on that session. Before you start, identify sessions with old transaction start times and plan how to end or exempt them. Confirm the exact waiting and locking behavior for your version in the PostgreSQL documentation for REINDEX.

Because the table stays online, the concurrent build does more total work than a plain rebuild. It performs two passes over the table and must keep the new index current with changes made during the build, so it typically takes longer and generates more I/O and WAL. It also needs free disk space for the new index while the old one still exists, which means the peak disk need is roughly the size of the old index plus the new one. Check free space and WAL archive capacity before you begin, and ask your team to size these from measured index sizes in your environment rather than from a rule of thumb. Replicas and backup jobs will see the extra WAL, so confirm the impact on replication lag with your monitoring.

The statement cannot run inside a transaction block, so it must be issued on its own rather than wrapped in BEGIN and COMMIT. Some related restrictions, such as which index types and partitioned objects are supported, and how the command behaves on indexes used for constraints, vary by version. Treat each of these as an item to confirm against the REINDEX documentation for your PostgreSQL version before you write the runbook, and test the full sequence on a copy of production with comparable data volume and concurrent load.

How to run a concurrent rebuild with checks at each stage

This sequence rebuilds one named index without blocking writes, and each step ends with a check that tells the operator whether it is safe to continue. The result is a valid replacement index that the planner uses for real queries.

  1. Confirm the index, its size and its bloat

    The DBA identifies the target index and its owning table, then reads its size and its estimated bloat from the catalogs, for example with pg_relation_size() on the index and pg_stat_user_indexes for scan counts. Check whether the index is still used at all by reviewing idx_scan before spending maintenance time on it. The step is complete when the team has the index name, its size, and a written reason for the rebuild, such as bloat or a collation change. If the index shows no scans over a meaningful period, the better outcome may be dropping it, which the team should confirm with the application owners first.

  2. Check free disk space and WAL capacity

    Before the rebuild starts, the operator checks free space on the data volume, since the new index is written beside the old one until the swap, and checks the free space on the volume holding pg_wal. Confirm that archiving is working and that no stale replication slot is holding WAL, using pg_replication_slots. The concurrent build generates WAL and needs room for the new index plus the old one. The step is complete when free space on both volumes is confirmed against the index size from the previous step, with a margin the team has agreed in advance. Your exact margin should come from your own storage and backup policy.

  3. End long-running and idle-in-transaction sessions

    Concurrent index builds wait for transactions that were open before they started, so a single idle-in-transaction session can stall the rebuild for a long time. Query pg_stat_activity for sessions where the state is idle in transaction or where the transaction start time is old, and identify the application or user behind each one. Ask the owners to close them or end them if the impact is accepted. The step is complete when a query over pg_stat_activity returns no sessions that the team considers blocking, and the operator has recorded what was ended and why.

  4. Run REINDEX CONCURRENTLY on the named index

    Run REINDEX INDEX CONCURRENTLY on the specific index name, not on the whole table, so the scope matches the plan. Run it in a monitored session with a log of the start time, and watch for lock waits in pg_locks and for the build progress view pg_stat_progress_create_index. The command takes more time than a plain REINDEX and cannot run inside a transaction block. If it fails or is cancelled, the operation leaves an invalid index behind, which the next step addresses. The step is complete when the command returns without error and the operator confirms the rebuild finished in the log.

  5. Find and drop invalid indexes left by failures

    After any failed or cancelled concurrent build, query pg_index for rows where indisvalid is false, and check for leftover indexes with names ending in _ccnew or _ccold. An invalid index still consumes write overhead and disk space, and the planner does not use it. Drop each invalid leftover with DROP INDEX CONCURRENTLY so the cleanup does not block writes, then rerun the rebuild if the original index is still bloated. The step is complete when the query returns no invalid indexes for the table, which the team should record with the output.

  6. Verify the new index is valid

    Confirm that the rebuilt index is valid by querying pg_index for its indisvalid and indisready flags, and compare its size against the old figure from the first step. Check that no other index on the table was left invalid. Confirm that any constraint or foreign key depending on the index still refers to a valid index. The step is complete when the rebuilt index reports valid and ready, and the size change matches the bloat the team expected to remove.

  7. Confirm the planner uses the index with EXPLAIN

    Choose a representative query that the index was built to serve, and run EXPLAIN (ANALYZE, BUFFERS) against a production-like copy or a read replica where that is safe. Confirm the plan references the rebuilt index by name and that the row estimates are reasonable. Compare the buffer counts with the figures captured before the rebuild if you have them. The step is complete when the plan uses the index for the query and the team has saved the plan output with the change record. If the planner ignores the index, check statistics with ANALYZE before changing anything else.

Cleaning up invalid indexes after a failed rebuild

A failed or interrupted REINDEX CONCURRENTLY can leave the index in an invalid state. PostgreSQL builds the replacement alongside the original, and if the build is cancelled, errors out, or the session ends, the new index is left behind marked invalid. The planner will not use it for queries, but it is still maintained on every insert, update and delete. That means an invalid index costs write overhead and disk space while providing no read benefit, and it must never be treated as a usable index. Check the state before assuming a rebuild succeeded. In the catalog, pg_index.indisvalid is false for an invalid index, and joining pg_index to pg_class and pg_namespace gives the index names and schemas. Review the list with the owning team, since a leftover index may carry the original name plus a _ccnew or _ccold suffix depending on the stage that failed.

Before dropping any invalid index, answer three questions. First, is a retry planned? If the rebuild will run again soon, confirm the retry will not collide with the leftover object, and note that dropping it with DROP INDEX CONCURRENTLY avoids blocking writes on the table. Second, does the index back a constraint? An index that enforces a primary key, unique or exclusion constraint cannot simply be dropped without changing the constraint, so the constraint and its index must be handled together. Third, does anything depend on it? Foreign keys, application hints, and monitoring or query scripts that reference the name can break. Confirm the exact object name and schema before running any drop, and record the decision so the retry starts from a known catalog state.

Confirm the remaining details in your own environment rather than assuming them. Check your PostgreSQL version's documentation for the exact behavior of invalid index cleanup, the naming of intermediate indexes, and whether a given constraint type applies. Run the catalog query on a replica or staging copy first if you can, and keep a note of the table's size and current write load, because the retry will repeat the same cost. If many invalid indexes appear, treat it as a process problem to investigate before rebuilding more indexes, not as a cleanup chore.

Operational risks to plan for before a rebuild

A concurrent index rebuild avoids blocking writes, but it still consumes privileges, disk, WAL, backup windows and query plan stability. The cards below cover the checks that connect those risks, and who should own each one before the first REINDEX runs.

Privileges and index ownership

REINDEX needs ownership of the index or table, or membership in a role that has it. Confirm which role runs the rebuild in each database and that the account can create the replacement index on the table's schema. Ask the database owner or platform DBA to grant this in advance, and record the grant in change control so the run does not stall on a permission error in production.

Continuous archiving docs

Replication lag and WAL volume

Each index rebuild writes WAL that standbys must receive and replay. Measure replay lag on every standby before starting, and set a stop threshold for the rebuild. Confirm that archiving and replication slots have headroom, since a lagging standby can hold WAL on the primary. The DBA who owns replication should own this check.

Backup and restore timing

A large rebuild can overlap a scheduled base backup or a point-in-time recovery window, and a restore taken mid-rebuild may contain an invalid index. Ask the backup owner to confirm the backup schedule and retention for the rebuild window, and to verify that a recent base backup and WAL archive are complete before the run starts.

Query plan changes after activation

When the rebuilt index replaces the old one, the planner may choose different plans, including for queries that were fine before. Capture the top queries and their EXPLAIN output before the change, and compare afterward. The application or performance owner should review the list and agree on which plans matter most.

Monitoring for invalid indexes

A failed REINDEX CONCURRENTLY can leave an invalid index behind, which still costs writes and storage while doing nothing for queries. Add a check that lists invalid indexes in pg_index for each database after every run, and alert on any result. The on-call database team should own the alert, and the cleanup steps should be written before the rebuild window opens.

Change control and rollback plan

Agree the scope, the order of tables, the time window and the stop conditions in writing before the run. The rollback plan should state that the old index stays in place until the new one is verified and that a failed rebuild needs cleanup rather than a restore. The change owner signs off, and the application owner confirms the window is acceptable.

How to schedule rebuilds of large indexes

When the index is small and the table sees little write traffic, the main risk is not blocking but doing the work at the wrong time. A concurrent rebuild still takes longer than a plain rebuild, still reads the table twice and still adds load, so a quiet window is the right place for it. Run one index at a time, even when several are bloated, and start with the index that matters most to your slowest queries.

  • Pick a window with known low load: Use the period your monitoring shows as quiet, and avoid the nightly batch or month-end jobs that also generate I/O.
  • Batch one index at a time: Issue one REINDEX INDEX CONCURRENTLY per session and wait for it to finish before starting the next.
  • Keep the job cancellable: Set a statement_timeout for the session so a rebuild cannot run unbounded into business hours.
  • Check for invalid leftovers after each run: Confirm the index is valid before moving on, since a failed run can leave an invalid index behind.
  • Check replica lag at the end of each step: Even on a quiet system, confirm standbys have caught up before the next index starts.

Before scheduling anything on production, rebuild the same index on a copy of the database with similar data volume and measure the elapsed time and I/O impact yourself.

Limits to confirm in your environment before you plan the work

REINDEX CONCURRENTLY has restrictions that depend on the index type, the table layout, the extensions in use, the server role and your PostgreSQL major version. Confirm each item below against your own catalogs and the documentation for your version before you estimate effort or pick a maintenance window.

Index types and constraints

Confirm which indexes your rebuild covers. Concurrent rebuilds handle ordinary B-tree, GiST, GIN and similar indexes, but expression and partial indexes, indexes that back constraints, and exclusion constraints need separate handling. Run \d tablename or query pg_index and pg_constraint to list every index, its constraint links and its predicates. Then read the REINDEX page for your version to confirm which forms it accepts.

Replication docs

Partitioned tables and their indexes

Partitioned tables cannot be rebuilt concurrently as a parent object. Rebuild each partition's index instead, and check whether any index on the partitioned parent is itself invalid. Query pg_inherits and pg_partitioned_table to map the hierarchy, then confirm in the REINDEX documentation for your version how partitioned indexes are processed before writing the runbook.

Extensions and custom access methods

Indexes built by extensions, such as custom operator classes or non-core access methods, may behave differently under a concurrent build. Run a query on pg_am and pg_opclass joined to pg_index to find every index that uses a non-core method. Test the rebuild on a copy and confirm the extension's own documentation covers concurrent builds before you include those indexes in the plan.

Collation versions and mismatch checks

Collation-affected indexes are the usual reason to rebuild, but you must confirm which ones are affected before you schedule work. Compare pg_database.datcollversion and pg_collation.collversion against the current library version reported by your operating system, and use ALTER DATABASE ... REFRESH COLLATION VERSION only after the rebuilds are planned. Record the results so the affected index list is traceable.

Standbys and logical replication targets

A standby cannot run REINDEX itself, because it is a read-only server. Rebuilds run on the primary and their effect reaches standbys through WAL replay, so confirm replay lag and disk headroom on each standby. Logical replication subscribers keep their own indexes, so you must rebuild those separately. Check pg_stat_replication and each subscriber's index definitions before you schedule the work.

Failover docs

Version-specific behavior

Concurrent rebuild behavior changes between major versions, and the versions in support today differ in what they accept and report. Confirm the exact behavior for your server with the REINDEX page for that version, and check your version's support end date. Plan any upgrade before the rebuild so you do not repeat the work on a newer release, since upgrade steps are covered in the upgrade documentation.

Upgrade docs

Questions buyers ask before they rebuild indexes or hire help

What drives the effort of rebuilding a PostgreSQL index?

The effort depends mainly on the size of the index, how many writes the table takes while the rebuild runs, how much free disk space the server has, and how many other indexes, constraints and replicas depend on the table. A large index on a busy table takes longer and needs more temporary space than a small index on a quiet one. Each standby server also has to replay the changes, so replica count and lag matter. Ask your team to pull index sizes, write rates and free disk from your own monitoring before planning the window.

Can our own team rebuild indexes without outside help?

Yes, many teams do this in-house. REINDEX CONCURRENTLY is a standard command, and the main work is planning: identifying bloated or collation-affected indexes, checking disk headroom, scheduling the rebuilds and checking the result. Teams without much PostgreSQL experience usually benefit from a rehearsal on a copy of production data, a written rollback path for failed builds, and someone who knows how to read the catalog for invalid indexes. Outside help makes most sense when the rebuild list is long, the database is business critical, or the team lacks time to run a controlled change.

What does a consultant's scope usually include, and how is it quoted?

A typical scope covers an inventory of indexes to rebuild, a check of disk, replication and locking risks, a runbook with ordering and timing, execution in agreed windows, verification of index validity and query plans, and a clean-up of any invalid indexes left behind. DeployOpen works on fixed scope agreed in writing before work starts. DeployOpen does not publish a price list. A quote follows from the written scope, so the request should list the databases, the number of indexes, the environments and the change windows involved.

How long will a rebuild take, and can you give a figure?

No reliable figure exists without measuring your data. Build time depends on index size, table activity, hardware, parallel settings and replica lag, and a figure from another environment does not transfer. The practical approach is to time a rebuild of a representative index on a copy of production data, then extrapolate across the list with a safety margin. Ask any provider to base its timeline on that measurement and on your own change calendar rather than on a generic number.

What does the work need from our team?

Expect to provide read access to the system catalogs and index statistics, a staging copy for rehearsal, and access to monitoring for disk, replication lag and lock waits. You also need named owners for approving the change list, the maintenance windows and the rollback decision, plus the application team who can confirm that slower queries during the build are acceptable. Without those approvals, a rebuild tends to stall at the point where a rebuild must be stopped or retried.

What should we do about an invalid index after a failed rebuild?

When REINDEX CONCURRENTLY fails or is cancelled, PostgreSQL can leave an index marked invalid. Invalid indexes are not used for queries but still cost write overhead, so they should be removed or rebuilt. Identify them in the catalog first, confirm the index is not needed for a constraint, then drop it concurrently or retry the rebuild. Check the PostgreSQL REINDEX documentation for the exact behavior of your version before running commands, and record the action in the change log.

Should we rebuild all bloated indexes in one pass?

Usually not. Rebuilding everything at once multiplies disk use, replica lag and the number of possible failure points. A safer plan ranks indexes by measured bloat and query impact, rebuilds the most important ones first in small batches, and checks each batch before starting the next. Large indexes on write-heavy tables are better handled in their own windows. This sequencing is part of the scope a consultant would normally plan.

How DeployOpen scopes and delivers PostgreSQL index rebuilds

DeployOpen treats an index rebuild as a planned change to a production database, not a one-line command. We scope the indexes, the windows and the rollback path in writing, build and test the rebuild on a copy of your environment, and hand over the runbook and monitoring your team needs to repeat it.

How we scope

  • Inventory the indexes to rebuild, with the reason for each: measured bloat, collation change or a failed build.
  • Confirm the PostgreSQL version, replicas, write load and maintenance windows that set the order of work.
  • Agree the written scope, deliverables and timeline before work starts, as engagements are fixed-scope.

How we build

  • Test the REINDEX CONCURRENTLY run on a restored copy of production, checking duration, disk use and lock behavior.
  • Write the rebuild sequence, including checks for leftover invalid indexes and a rollback plan for each index.
  • Plan large rebuilds in batches with disk headroom checks and monitoring of WAL volume and replication lag.

How we hand over

  • Deliver a runbook covering each command, its expected lock behavior, and the cleanup steps after a failure.
  • Provide a query for finding invalid indexes and a schedule your team can run without DeployOpen present.
  • Document the verification results and the settings and alerts that keep bloat and collation drift visible.

How we support

  • Offer ongoing support, upgrades and continuous testing as a retainer for recurring index maintenance.
  • Retest rebuilt indexes and the affected query plans after each planned maintenance cycle.
  • Review the runbook when PostgreSQL minor or major versions change, so the procedure stays current.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.