Overview: automate detection + safe removal in a pipeline: (1) detect candidate redundant indexes via heuristics, (2) verify safety with usage & cost checks, (3) schedule staged removal with monitoring, (4) block CI reintroductions.Heuristics:- Exact duplicates: same key columns order + same INCLUDEs.- Overlapping prefixes: index A columns = (a,b) and B = (a,b,c) — A may be redundant if A not used and B covers all queries.- Included columns equality: same keys but different INCLUDEs where one INCLUDE set ⊇ other.- Low usage & high maintenance: indexes with near-zero reads but high write cost (measured by r/w counters).Queries to find candidates (Postgres-style):sql
-- exact duplicate keys + include comparison (example)
SELECT i1.indexrelid::regclass AS idx1, i2.indexrelid::regclass AS idx2
FROM pg_index i1
JOIN pg_index i2 ON i1.indkey = i2.indkey AND i1.indexrelid < i2.indexrelid
WHERE i1.indisvalid AND i2.indisvalid;
sql
-- overlapping prefix heuristic
SELECT a.indexrelid::regclass AS smaller, b.indexrelid::regclass AS larger
FROM my_index_columns a
JOIN my_index_columns b ON b.table = a.table
WHERE a.columns = left(b.columns, length(a.columns)) AND a.columns != b.columns;
Safe-removal checks:- Verify index usage metrics over long window (30–90 days): scans, last_used, planner_usage.- Run EXPLAIN ANALYZE of sampled production queries pre/post in a staging clone to ensure no plan regressions and latency increase threshold (e.g., <5%).- Ensure no constraint depends on the index (unique/primary).- Schedule removal in low-traffic window and keep fast rollback plan (recreate DDL).Monitoring after removal:- Short-term: track latency, error rates, query plans for top N queries; alert on threshold breaches.- Medium-term: monitor replica lag, write latency, CPU, and index rebuild times.- Auto-rollback trigger if SLA or key query p95 increases beyond set thresholds.CI gates to prevent reintroduction:- Enforce index DDL review in PRs with automated linter: detect re-adding known-removed indexes or creating duplicates/overlaps and block merge.- Add a test that runs schema-diff against canonical schema and queries the index catalog for forbidden patterns.- Add cost estimation check in CI: new index must show expected benefit on sampled query workload or have approved JIRA.Implementation notes:- Start conservative: flag -> staging test -> manual approval -> automated rollout.- Maintain an index metadata registry (reason, owner, created_at, removal date) so ownership/intent is recorded.