Schedule icon
Query icon
Get icon
Return icon
Switch icon
Log icon
SlackIncomingWebhook icon
Set icon

PostgreSQL Hot Standby Conflict and Query Cancellation Sentinel

Audit PostgreSQL read replica recovery conflicts with Kestra, detect query cancellations from WAL replay, and alert Slack on replication delay.

Categories
DataInfrastructure

PostgreSQL read replicas running streaming replication frequently encounter hot standby recovery conflicts when WAL replay from the primary (such as vacuum cleanup or table locks) clashes with long-running analytical queries executing on the standby. When the replication delay threshold (max_standby_streaming_delay) is exceeded, PostgreSQL abruptly terminates client queries with recovery conflict errors, causing sudden analytical pipeline failures and dashboard outages. This blueprint connects directly to PostgreSQL read replicas on a recurring schedule, queries pg_stat_database_conflicts alongside active query runtimes, tracks conflict delta baselines in Kestra KV storage, detects query cancellation storms, and alerts Slack with actionable diagnostics.

How it works

  1. probe_standby_metrics (io.kestra.plugin.jdbc.postgresql.Query) connects to the standby database instance and executes an analytical query against pg_stat_database_conflicts, pg_stat_activity, and PostgreSQL WAL functions. It captures recovery state (pg_is_in_recovery()), calculates byte replication lag (pg_wal_lsn_diff), extracts granular conflict metrics (confl_snapshot, confl_lock, confl_deadlock, confl_bufferpin), and counts active queries exceeding long_query_threshold_seconds. allowFailure: true ensures network connection failures are caught gracefully.
  2. get_previous_baseline (io.kestra.plugin.core.kv.Get) retrieves the total conflicts counter recorded during the prior run from Kestra namespace KV storage.
  3. classify_conflict_status (io.kestra.plugin.core.debug.Return) evaluates operational state using declarative Pebble expressions:
    • UNREACHABLE: The standby endpoint could not be contacted over JDBC.
    • NOT_A_STANDBY: The target host is a primary read/write node rather than a standby replica.
    • CANCELLATION_STORM: New recovery conflicts occurred since the prior run (delta > 0), indicating active client queries were cancelled.
    • REPLICATION_STALL_RISK: No cancellations yet, but replication lag exceeds max_lag_bytes_threshold or long-running queries are actively pinning recovery.
    • HEALTHY: Standby replication is synchronized with zero new cancellations.
  4. route_by_conflict_status (io.kestra.plugin.core.flow.Switch) branches on the evaluated status:
    • HEALTHY: Emits an informational log confirming nominal replication position.
    • CANCELLATION_STORM: Dispatches an incident alert to Slack containing exact conflict category breakdowns, replication delay, and tuning advice.
    • REPLICATION_STALL_RISK: Alerts database operators to impending cancellation risks from active analytical queries.
    • NOT_A_STANDBY: Advises operators of target configuration mismatch.
    • UNREACHABLE: Dispatches an urgent endpoint offline alert to on-call teams.
  5. update_conflict_baseline (io.kestra.plugin.core.kv.Set) saves the current conflict count to namespace KV storage to establish the baseline for the next interval.
  6. log_audit_summary (io.kestra.plugin.core.log.Log) writes an immutable summary log entry across all executions for auditability.
  7. The top-level errors handler dispatches a Slack webhook alert if any unexpected task error occurs, preventing silent monitoring blackouts.
  8. standby_conflict_schedule triggers the sentinel recurringly every 15 minutes (configured with disabled: true for safe onboarding).

What you get

  • Proactive visibility into PostgreSQL read replica query cancellations before users report broken dashboards.
  • Differential tracking using Kestra KV store to alert on fresh cancellation spikes rather than cumulative lifetime totals.
  • Granular conflict root-cause attribution distinguishing vacuum snapshot conflicts from DDL table lock conflicts.
  • Early warning alerting when long-running queries pin WAL replay and cause replica replication lag to spike.
  • Continuous audit trail in Kestra execution history for database reliability trend analysis.

Who it's for

  • Database Reliability Engineers (DBREs) and Platform Engineers maintaining PostgreSQL replication topologies.
  • Analytics Engineers and Data Engineers running heavy BI queries and data extraction jobs on read replicas.
  • Site Reliability Engineers (SREs) monitoring database high-availability and query failure rates.

Why orchestrate this with Kestra

Ad-hoc monitoring scripts and metric scrapers lack stateful differential tracking across runs and require maintaining separate cron daemons and unencrypted credentials. Kestra orchestrates the monitoring lifecycle declaratively with encrypted secret management, built-in key-value persistence for delta calculations, visual execution timelines, and seamless integration into automated escalation workflows.

Prerequisites

  • A running PostgreSQL standby replica (accessible locally via Docker postgres:16 or over the network).
  • A database user account with SELECT privileges on pg_stat_database_conflicts and pg_stat_activity.
  • A Slack Incoming Webhook URL for receiving incident notifications.

Secrets

  • POSTGRES_PASSWORD: Database user password for connecting to the PostgreSQL standby replica (required).
  • SLACK_WEBHOOK_URL: Slack Incoming Webhook URL used for dispatching alert messages (required).

Quick start

  1. Configure the POSTGRES_PASSWORD and SLACK_WEBHOOK_URL secrets in your Kestra namespace.
  2. Import this blueprint into your Kestra instance and adjust standby_host and standby_port to point to your PostgreSQL read replica.
  3. Click Execute to run a manual verification pass.
  4. Verify execution logs and check that status outputs HEALTHY.
  5. Enable the standby_conflict_schedule trigger to begin automated recurring standby health monitoring.

How to extend

  • Add automated query cancellation: In the REPLICATION_STALL_RISK branch, integrate a task invoking pg_cancel_backend(pid) to gracefully terminate offending analytical queries before replication lag breaches SLA limits.
  • Add multi-channel escalation: Route CANCELLATION_STORM alerts to PagerDuty or Opsgenie using Kestra notification plugins for immediate off-hours paging.
  • Export metrics: Append a DuckDB or Prometheus push task to graph recovery conflict frequency and replication lag trends over time.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.