If icon
Fail icon
Query icon
Get icon
Return icon
Log icon
SlackIncomingWebhook icon
Set icon
Schedule icon

Track PostgreSQL Table Row Count Anomalies and Alert Slack

Detect PostgreSQL table row count drops and spikes on a schedule using Kestra KV store baselines and dispatch actionable Slack alerts.

Categories
Data

Automated data pipelines, replication jobs, and application migrations can inadvertently truncate tables, skip ETL batches, or produce runaway row duplication. Detecting unexpected data volume swings before downstream analytics, machine learning features, or customer reports consume corrupted data is critical for database reliability.

This workflow queries configured PostgreSQL tables on a schedule, calculates exact row counts in a single round trip, compares current volumes against the previous run stored in Kestra KV store, and posts an incident alert to Slack when any table breaches percentage drop or spike thresholds.

How it works

  1. hourly_anomaly_check (io.kestra.plugin.core.trigger.Schedule) initiates the workflow on a recurring hourly schedule (shipped disabled).
  2. validate_tables (io.kestra.plugin.core.flow.If) inspects the input table list with a regular expression filter (^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)?$). If an invalid identifier is provided, reject_invalid_table_names (io.kestra.plugin.core.execution.Fail) halts execution before any database connection is opened.
  3. count_tables (io.kestra.plugin.jdbc.postgresql.Query) runs a single read-only UNION ALL query against PostgreSQL with double-quoted identifiers to fetch exact count(*)::bigint for every watched table in one database round trip.
  4. get_previous_counts (io.kestra.plugin.core.kv.Get) retrieves the previous run row count map and timestamp from Kestra KV store under key postgres_table_row_count_baseline. On the initial run, this returns null.
  5. detect_anomalies (io.kestra.plugin.core.debug.Return) evaluates each table count against its baseline. When a table has no previous entry, it is treated as a baseline seed and ignored for alerts. For tables with a previous count, percent change is calculated. A DROP is flagged when count falls by at least drop_threshold_pct, and a SPIKE is flagged when count grows by at least spike_threshold_pct, provided the maximum of previous and current count meets min_rows_for_alert. A previous count of zero is treated safely as a 100% spike if current rows exceed min_rows_for_alert, avoiding division by zero.
  6. log_baseline_seeding (io.kestra.plugin.core.log.Log) logs a message when the baseline key was missing, recording that initial counts were seeded.
  7. check_anomalies_gate (io.kestra.plugin.core.flow.If) evaluates the anomaly list. If one or more tables are flagged, alert_slack (io.kestra.plugin.slack.notifications.SlackIncomingWebhook) delivers an incident card with previous counts, current counts, percentage deltas, and execution metadata.
  8. update_baseline_kv (io.kestra.plugin.core.kv.Set) updates the KV baseline map with the latest row counts and timestamp. Because this task runs sequentially after the Slack notification, any failure in Slack alert dispatch leaves the old baseline intact for a retry on the next execution.

What you get

  • Single-roundtrip row count audit across multiple PostgreSQL tables without executing multiple distinct connections.
  • SQL injection protection by enforcing strict identifier regex validation and double-quoting schema and table names.
  • Stateful anomaly detection powered by Kestra KV store without requiring external state databases or heavy Python agents.
  • Noise immunity using min_rows_for_alert to prevent alerts on small or empty tables.
  • Atomic notification delivery: one structured Slack message summarizing all anomalous tables for the run.
  • Safe state transitions: KV baseline update occurs only after Slack alert delivery succeeds.

Who it's for

  • Data Engineers and Analytics Engineers monitoring warehouse landing tables and ELT replication pipelines.
  • Database Administrators (DBAs) guarding transactional PostgreSQL databases against accidental truncation or mass deletion.
  • Site Reliability Engineers (SREs) tracking data ingestion health across production microservices.

Why orchestrate this with Kestra

  • Declarative YAML orchestration combining database drivers, state persistence, and notification webhooks without writing custom microservices.
  • Native KV store enables stateful metric comparisons between scheduled runs with zero external infrastructure.
  • Flow-level concurrency queuing (limit: 1, behavior: QUEUE) prevents race conditions between overlapping scheduled runs.
  • Secret masking ensures database credentials and Slack webhook tokens remain encrypted and redacted from execution logs.

Prerequisites

  • Reachable PostgreSQL database (version 12 or higher recommended).
  • Database user with SELECT permissions on watched tables. A read-only user is strongly recommended.
  • Incoming Webhook URL configured in Slack for your alerts channel.

Secrets

  • POSTGRES_URL: PostgreSQL JDBC connection URL, for example jdbc:postgresql://<host>:5432/<database>.
  • POSTGRES_USER: Database username with read permissions.
  • POSTGRES_PASSWORD: Database user password.
  • SLACK_WEBHOOK_URL: Slack Incoming Webhook URL for alert routing.

Quick start

  1. Configure POSTGRES_URL, POSTGRES_USER, POSTGRES_PASSWORD, and SLACK_WEBHOOK_URL in your Kestra namespace secrets.
  2. Import this blueprint into your Kestra instance.
  3. Adjust inputs.tables to point to the tables you wish to monitor (for example ["public.orders", "public.customers"]).
  4. Run the flow once manually. The initial run seeds the baseline in the KV store without sending alerts.
  5. Test anomaly detection on a throwaway table: delete half the rows in a test table, re-execute the flow, and verify the DROP alert card arrives in Slack.
  6. To reset baselines at any time, delete the postgres_table_row_count_baseline KV key in the Kestra UI; the subsequent execution will re-seed silently.
  7. Once verified, enable the hourly_anomaly_check schedule trigger.

How to extend

  • Estimate-based counting for massive tables: For multi-million or billion-row tables where SELECT count(*) causes prolonged sequential table scans, replace exact counting with an estimate query querying pg_stat_user_tables:
    SELECT schemaname || '.' || relname AS table_name, n_live_tup AS current_count
    FROM pg_stat_user_tables
    WHERE schemaname || '.' || relname IN (...)
    
  • Multi-channel routing: Extend check_anomalies_gate to page on-call teams via PagerDuty or create Jira incident tickets for drops exceeding 50%.
  • Dynamic table discovery: Add an information schema query task upstream to automatically discover all tables in a given schema rather than configuring a static list.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.