Query icon
Log icon
If icon
SlackIncomingWebhook icon
Loop icon
Sequential icon
Fail icon
Schedule icon

PostgreSQL Invalid Index Rebuild Guard

Detect invalid PostgreSQL indexes after failed concurrent builds, check duplicates, REINDEX CONCURRENTLY, drop _ccnew leftovers and re-audit.

Categories
DataInfrastructure

CREATE INDEX CONCURRENTLY and REINDEX CONCURRENTLY do not roll back when they fail. A statement timeout, a cancelled migration or a duplicate key leaves the index in the catalog, marked INVALID. From then on, PostgreSQL updates it on every insert and update but never uses it for a query. The table is slower to write, and the index the migration was meant to add is missing. Nothing reports it: the migration tool logged one error, and the next deploy moved on.

This blueprint lists every invalid index. It alerts Slack, and can rebuild each one without blocking writes. A unique index is rebuilt only after a check that no duplicate key is left, since otherwise the rebuild would fail and leave yet another invalid index. A second audit verifies the result.

This blueprint was created by zkasuran.

Findings

Kind What it is Fix
INVALID An index left by a failed CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY REINDEX INDEX CONCURRENTLY
INVALID on a unique index with duplicates The build failed on duplicate keys, which are still there Skipped, with the number of duplicate keys to fix first
LEFTOVER_CCNEW The <name>_ccnew copy left by a cancelled REINDEX CONCURRENTLY DROP INDEX CONCURRENTLY

How it works

  1. audit (io.kestra.plugin.jdbc.postgresql.Query, read-only) returns every index with indisvalid = false, outside system schemas. For each one it returns:
    • its definition and kind;
    • the fix statement, built with regclass so names are quoted by PostgreSQL;
    • for a unique index, a duplicate-key count query over its columns and partial-index predicate.
  2. summary logs every finding.
  3. route (io.kestra.plugin.core.flow.If):
    • clean: logs it.
    • findings: alert posts to Slack.
      • remediate_gate runs only when auto_remediate is true and dry_run is false.
      • remediate (io.kestra.plugin.core.flow.Loop) handles one index at a time. For a unique index, duplicates counts duplicate keys, and fix runs only when there are none.
      • reaudit runs the audit again. verify_result fails if an index reported as fixed is still invalid, a new invalid index appeared, or an iteration did not report a result.
      • skipped_notice posts the indexes that were skipped or failed.
  4. errors alerts Slack when the audit cannot run.

What you get

  • A daily list of the indexes that cost write time and serve no query.
  • Rebuilds that do not block writes, and never start on a unique index that would fail again.
  • Cleanup of the _ccnew copies that cancelled rebuilds leave behind.

Who it's for

  • Teams that run schema migrations with concurrent index builds on large tables.
  • DBAs and platform teams responsible for many PostgreSQL databases.
  • Teams evaluating the PostgreSQL plugin who want an example of a catalog query driving maintenance statements one by one.

Why orchestrate this with Kestra

Finding invalid indexes is one query, but fixing them safely is a sequence: check duplicates first, rebuild one index at a time so a failure stays isolated, then check again. Kestra runs that sequence on a schedule, behind two gates. It reports skipped indexes to the owners, and keeps an execution history of what was rebuilt where.

Tested end to end

On Kestra 2.0.5 OSS against PostgreSQL 16, with a local HTTP sink standing in for Slack:

  • orders (200,000 rows) has a unique index on ref that failed on 10 duplicate keys;
  • events (600,000 rows) has an index whose concurrent build was cancelled by a statement timeout.
Run Inputs Result
1 defaults 2 invalid indexes reported, alert sent
2 auto_remediate: true, dry_run: false events_payload_idx rebuilt and valid. orders_ref_uq skipped: 10 duplicate keys, Slack notice sent. Verified
3 duplicates deleted, and a REINDEX CONCURRENTLY cancelled by a timeout Reports orders_ref_uq and the leftover events_payload_idx_ccnew
4 same, dry run Nothing changed: 2 invalid indexes still in pg_index
5 same, remediate _ccnew dropped, orders_ref_uq rebuilt. psql shows both valid, 0 invalid left
6 defaults Clean
7 unreachable database errors alert sent

Prerequisites

  • For the audit, any role can read the catalog. For remediation, the table owner or a superuser. PostgreSQL 12 or later for REINDEX CONCURRENTLY.
  • Local testing:
    • docker run -d --name pg -p 5432:5432 -e POSTGRES_PASSWORD=pg postgres:16;
    • create a table with duplicate values, then run CREATE UNIQUE INDEX CONCURRENTLY on it.

Secrets

  • POSTGRES_USERNAME / POSTGRES_PASSWORD: credentials used by every query.
  • SLACK_WEBHOOK_URL: used by alert, skipped_notice and the errors block.
  • In Kestra OSS, provide each one as a base64-encoded environment variable prefixed SECRET_.

Inputs

Input Default Purpose
jdbc_url jdbc:postgresql://localhost:5432/app Database
auto_remediate false Allow rebuilds and drops
dry_run true Must be false for a statement to run

Quick start

  1. Add the POSTGRES_USERNAME, POSTGRES_PASSWORD and SLACK_WEBHOOK_URL secrets.
  2. Import the flow and set jdbc_url.
  3. Run it once and read the invalid indexes.
  4. Run it with auto_remediate: true and dry_run: false, outside peak hours: a concurrent rebuild reads the whole table.
  5. Enable the daily trigger, which always runs in safe mode.

How to extend

  • Trigger the flow at the end of your migration pipeline, so a failed concurrent build is caught right away.
  • Loop over a list of JDBC URLs to check every database of a cluster.
  • List the duplicate keys of a skipped unique index in the Slack notice, so the owner can fix them.
  • Add a Pause for approval before rebuilding indexes on very large tables.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.