id: postgres-unused-index-storage-reclaim-guard
namespace: company.data
description: |
Audit PostgreSQL unused indexes and storage bloat using pg_stat_user_indexes.
Validates statistics maturity, detects un-scanned non-constraint indexes,
exports a downloadable CSV diagnostic report, records telemetry in KV store,
and dispatches automated Slack storage alerts to DBAs.
concurrency:
limit: 1
behavior: QUEUE
inputs:
- id: min_index_size_mb
type: FLOAT
displayName: Minimum Index Size Threshold (MB)
description: Minimum physical index size in megabytes to qualify for reclamation
audit. Ignores negligible small indexes.
defaults: 50.0
min: 1.0
max: 100000.0
- id: min_stats_age_days
type: INT
displayName: Minimum Statistics Maturity (Days)
description: Minimum number of days since pg_stat_database stats_reset. Prevents
premature index flagging on newly restarted clusters.
defaults: 14
min: 1
max: 365
- id: max_indexes_reported
type: INT
displayName: Maximum Candidate Indexes to Report
description: Maximum number of bloated unused index candidates to extract into
the diagnostic report.
defaults: 25
min: 1
max: 100
- id: database_name
type: STRING
displayName: PostgreSQL Database Name
description: Target database name to scope the unused index storage audit.
defaults: postgres
validator: ^[A-Za-z_][A-Za-z0-9_]{0,63}$
tasks:
- id: verify_stats_maturity
type: io.kestra.plugin.jdbc.postgresql.Query
description: Confirm database statistics have accumulated long enough to avoid
false positives.
url: "{{ secret('POSTGRES_JDBC_URL') }}"
username: "{{ secret('POSTGRES_USERNAME') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
timeZoneId: UTC
fetchType: FETCH_ONE
sql: |
SELECT
datname,
stats_reset,
ROUND(EXTRACT(EPOCH FROM (NOW() - COALESCE(stats_reset, NOW() - INTERVAL '30 days'))) / 86400.0, 1) AS stats_age_days,
CASE
WHEN (NOW() - COALESCE(stats_reset, NOW() - INTERVAL '30 days')) >= INTERVAL '{{ inputs.min_stats_age_days }} days' THEN true
ELSE false
END AS is_stats_mature
FROM pg_stat_database
WHERE datname = '{{ inputs.database_name }}';
- id: evaluate_unused_indexes
type: io.kestra.plugin.jdbc.postgresql.Query
description: Aggregate total unused index count and cumulative wasted storage in
megabytes.
url: "{{ secret('POSTGRES_JDBC_URL') }}"
username: "{{ secret('POSTGRES_USERNAME') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
timeZoneId: UTC
fetchType: FETCH_ONE
sql: |
WITH candidates AS (
SELECT
s.schemaname,
s.relname AS table_name,
s.indexrelname AS index_name,
pg_relation_size(s.indexrelid) AS index_bytes
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
JOIN pg_class c ON c.oid = s.indexrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE s.idx_scan = 0
AND NOT i.indisunique
AND NOT i.indisprimary
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND pg_relation_size(s.indexrelid) >= ({{ inputs.min_index_size_mb }} * 1024 * 1024)
)
SELECT
COUNT(*) AS unused_index_count,
COALESCE(ROUND((SUM(index_bytes)::numeric / (1024 * 1024)::numeric), 2), 0.0) AS total_wasted_mb,
COALESCE(ROUND((SUM(index_bytes)::numeric / (1024 * 1024 * 1024)::numeric), 3), 0.0) AS total_wasted_gb,
CASE WHEN COUNT(*) > 0 THEN true ELSE false END AS has_unused_indexes
FROM candidates;
- id: fetch_unused_indexes_telemetry
type: io.kestra.plugin.jdbc.postgresql.Query
description: Stream detailed unused index definitions and candidate drop
statements to internal storage.
url: "{{ secret('POSTGRES_JDBC_URL') }}"
username: "{{ secret('POSTGRES_USERNAME') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
timeZoneId: UTC
fetchType: STORE
sql: |
SELECT
s.schemaname,
s.relname AS table_name,
s.indexrelname AS index_name,
ROUND((pg_relation_size(s.indexrelid)::numeric / (1024 * 1024)::numeric), 2) AS index_size_mb,
ROUND((pg_table_size(s.relid)::numeric / (1024 * 1024)::numeric), 2) AS table_size_mb,
s.idx_scan AS total_scans,
pg_get_indexdef(s.indexrelid) AS index_definition,
format('DROP INDEX CONCURRENTLY IF EXISTS %I.%I;', s.schemaname, s.indexrelname) AS safe_remediation_sql
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
JOIN pg_class c ON c.oid = s.indexrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE s.idx_scan = 0
AND NOT i.indisunique
AND NOT i.indisprimary
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND pg_relation_size(s.indexrelid) >= ({{ inputs.min_index_size_mb }} * 1024 * 1024)
ORDER BY pg_relation_size(s.indexrelid) DESC
LIMIT {{ inputs.max_indexes_reported }};
- id: export_diagnostic_csv
type: io.kestra.plugin.serdes.csv.IonToCsv
description: Serialize unused index diagnostic telemetry into a downloadable CSV
artifact.
from: "{{ outputs.fetch_unused_indexes_telemetry.uri }}"
- id: check_health_and_alert
type: io.kestra.plugin.core.flow.If
description: Evaluate unused index findings and dispatch notification when
wasted storage is detected.
condition: "{{ outputs.evaluate_unused_indexes.row.has_unused_indexes &&
outputs.verify_stats_maturity.row.is_stats_mature }}"
then:
- id: log_reclamation_opportunity
type: io.kestra.plugin.core.log.Log
message: >-
PostgreSQL Storage Opportunity on database '{{ inputs.database_name
}}': Found {{ outputs.evaluate_unused_indexes.row.unused_index_count
}} unused indexes consuming {{
outputs.evaluate_unused_indexes.row.total_wasted_mb }} MB ({{
outputs.evaluate_unused_indexes.row.total_wasted_gb }} GB) of
un-scanned storage. Stats maturity: {{
outputs.verify_stats_maturity.row.stats_age_days }} days. Diagnostic
CSV Report URI: {{ outputs.export_diagnostic_csv.uri }}
- id: notify_slack_alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Send storage reclamation advisory to Slack with diagnostic report
artifact.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: >-
[STORAGE ADVISORY] *PostgreSQL Unused Index Reclamation Opportunity*
*Database:* `{{ inputs.database_name }}` *Unused Indexes Detected:*
`{{ outputs.evaluate_unused_indexes.row.unused_index_count }}` *Wasted
Storage:* `{{ outputs.evaluate_unused_indexes.row.total_wasted_mb }}
MB` (`{{ outputs.evaluate_unused_indexes.row.total_wasted_gb }} GB`)
*Statistics Maturity:* `{{
outputs.verify_stats_maturity.row.stats_age_days }} days` (Threshold:
>= `{{ inputs.min_stats_age_days }} days`) *Diagnostic CSV Report:*
`{{ outputs.export_diagnostic_csv.uri }}` *Execution ID:* `{{
execution.id }}`
else:
- id: log_healthy_state
type: io.kestra.plugin.core.log.Log
message: >-
PostgreSQL database '{{ inputs.database_name }}' is healthy. No
bloated unused indexes found exceeding {{ inputs.min_index_size_mb
}}MB with stats age {{
outputs.verify_stats_maturity.row.stats_age_days }} days.
- id: update_audit_watermark
type: io.kestra.plugin.core.kv.Set
description: Record telemetry snapshot in Kestra KV store for historical
capacity tracking.
key: "postgres_unused_index_audit_{{ inputs.database_name }}"
value:
last_audit_timestamp: "{{ now() }}"
unused_index_count: "{{ outputs.evaluate_unused_indexes.row.unused_index_count }}"
total_wasted_mb: "{{ outputs.evaluate_unused_indexes.row.total_wasted_mb }}"
stats_age_days: "{{ outputs.verify_stats_maturity.row.stats_age_days }}"
diagnostic_csv_uri: "{{ outputs.export_diagnostic_csv.uri }}"
errors:
- id: alert_audit_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Notify on task failure if database connectivity or query execution fails.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: >-
[ERROR] PostgreSQL Unused Index Audit failed in execution `{{ execution.id
}}` on database `{{ inputs.database_name }}`. Failed task: `{{
(errorLogs() | length) > 0 ? errorLogs()[0].taskId : 'unknown' }}`. Error
message: `{{ (errorLogs() | length) > 0 ? errorLogs()[0].message :
'inspect execution logs' }}`.
triggers:
- id: weekly_audit_schedule
type: io.kestra.plugin.core.trigger.Schedule
cron: "0 3 * * 1"