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

PostgreSQL Duplicate Index Guard

Find duplicate and prefix-redundant PostgreSQL indexes, alert Slack with the space wasted, drop them concurrently and verify the kept index remains.

Categories
DataInfrastructure

Duplicate indexes pile up quietly. A migration adds an index the ORM already created. Someone adds a plain index next to a unique constraint on the same column. An index on (customer_id) sits next to one on (customer_id, created) that serves the same lookups. Each extra index is written on every INSERT and UPDATE, vacuumed, backed up and replicated, while the planner uses the other one.

This blueprint finds exact duplicates and prefix-redundant indexes, with their size and scan count. It alerts Slack, and can drop them with DROP INDEX CONCURRENTLY, one at a time. It then checks that each index it kept is still there and valid, and that the dropped ones are gone.

This blueprint was created by zkasuran.

What counts as redundant

Two btree indexes on the same table are compared on columns, sort order, expressions, predicate, operator classes and collations:

Kind Rule Dropped by default
DUPLICATE Same columns, sort order, expressions, predicate, operator classes and collations Yes
PREFIX_REDUNDANT Its columns are the leading columns of another index with the same predicate Only with drop_prefix_redundant: true

Which index is kept:

  • A primary key, an index backing a constraint and a unique index are kept over a plain index. A primary key, a constraint index and the replica identity index are never dropped.
  • A unique index is only dropped when another unique index has the same columns and never for a non-unique one.
  • Partial and expression indexes are only compared with indexes having the same predicate and expressions.

How it works

  1. audit (io.kestra.plugin.jdbc.postgresql.Query, read-only) compares every pair of valid btree indexes on each table with the rules above. It returns each redundant index with the index that covers it, both definitions, the size, idx_scan since the last stats reset, and a DROP INDEX CONCURRENTLY IF EXISTS statement built with regclass.
  2. summary logs every finding and the total space.
  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 (concurrencyLimit: 1) drops one index at a time. Two duplicates of each other are never dropped together.
      • reaudit runs the audit again, and kept_check confirms that every kept index still exists and is valid.
      • verify_result fails if a kept index is missing or a dropped one is still reported.
  4. errors alerts Slack when the audit cannot run.

What you get

  • Every index that costs writes and space without serving a query the other index does not.
  • Drops that never touch primary keys, constraint indexes or the replica identity index and never remove both sides of a pair.
  • A check that the index left in place is still valid after the run.

Who it's for

  • Teams with schemas built over years of migrations and ORM-generated indexes.
  • DBAs reducing write amplification, WAL volume and backup size.
  • Teams evaluating the PostgreSQL plugin who want an example of a catalog analysis driving DROP INDEX CONCURRENTLY.

Why orchestrate this with Kestra

Duplicates come back with every migration. Kestra runs the comparison every week, sends the redundant indexes and the space they take to Slack, and drops them behind auto_remediate and dry_run, one at a time. It verifies that the covering index survived, and keeps a history of every index removed.

Tested end to end

On Kestra 2.0.5 OSS against PostgreSQL 16, with a local HTTP sink standing in for Slack. Indexes added on top of the existing ones:

  • on orders: orders_customer_idx2 (same as orders_customer_idx), orders_ref_plain (same column as the unique orders_ref_uq), and orders_customer_created_idx (customer_id, created);
  • on events: (kind) and (lower(kind));
  • on shipments: (carrier) and (carrier) WHERE carrier = 'ups'.
Run Inputs Result
1 defaults 3 findings, 7 MB. orders_customer_idx2 duplicates orders_customer_idx, orders_ref_plain duplicates the unique orders_ref_uq, orders_customer_idx is a prefix of orders_customer_created_idx (report only). The expression and partial indexes are not flagged. Alert sent
2 auto_remediate: true, dry_run: true Same report, 6 indexes still on orders
3 auto_remediate: true, dry_run: false The 2 duplicates dropped. orders_customer_idx and orders_ref_uq checked as still valid. A query on customer_id still uses an index
4 drop_prefix_redundant: true orders_customer_idx dropped. EXPLAIN for customer_id = 42 now uses orders_customer_created_idx
5 defaults Clean
6 unreachable database errors alert sent

Prerequisites

  • For the audit, any role can read the catalog and statistics. For remediation, the owner of the tables.
  • idx_scan counts since the last statistics reset. Read it with that in mind on a freshly restarted server.
  • Local testing:
    • docker run -d --name pg -p 5432:5432 -e POSTGRES_PASSWORD=pg postgres:16;
    • create the same index twice under two names.

Secrets

  • POSTGRES_USERNAME / POSTGRES_PASSWORD: credentials used by every query.
  • SLACK_WEBHOOK_URL: used by alert 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
drop_prefix_redundant false Also drop prefix-redundant indexes
auto_remediate false Allow DROP INDEX
dry_run true Must be false for an index to be dropped

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 review each redundant index and the one that covers it.
  4. Run it with auto_remediate: true and dry_run: false to drop the exact duplicates.
  5. Enable the weekly trigger, which always runs in safe mode.

How to extend

  • Save each dropped index definition so it can be recreated in one statement.
  • Loop over a list of JDBC URLs to check every database of a cluster.
  • Ask for approval with a Pause before dropping indexes larger than a threshold.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.