Query icon
Log icon
If icon
SlackIncomingWebhook icon
OutputValues icon
Pause icon
Sleep icon
Fail icon
Schedule icon

CockroachDB Query Contention and Cancel Guard

Audit long-running and lock-contended CockroachDB statements, alert Slack, cancel the worst offender with CANCEL QUERY after approval and verify it stopped.

Categories
DataInfrastructure

A single statement can hold a CockroachDB cluster back. A runaway query with a bad plan runs for minutes. An application that opens a transaction, takes a write lock on a row, then waits on a slow network call keeps that lock the whole time. Every other transaction that needs the same row queues behind it. The cluster stays up and most keys answer normally, so a dashboard of cluster health shows nothing. One table slows to a crawl and nobody can see why.

The hard part is telling the two apart. A statement that has been running for two minutes might be a report that is simply slow. It might instead be a transaction holding a contended lock while a dozen others wait on it. The first wants to be left alone. The second wants to be cancelled, because cancelling it rolls back its transaction and frees everyone waiting.

This blueprint reads the running statements and the live lock table together. It flags a statement that is over a time threshold. It also flags a statement whose transaction holds a contended lock with waiters even when it is not yet long-running. It marks each one as the blocker, a waiter or a plain long runner. With approval, it cancels the worst offender with CANCEL QUERY, then reads the running statements again and fails the run if that query is still there.

This blueprint was created by zkasuran.

Findings

Category Meaning What to do
BLOCKER The statement's transaction holds a contended lock that other transactions are waiting on Cancelling it rolls back the transaction and frees the waiters
WAITING The statement is blocked waiting on a lock another transaction holds Cancel the blocker, not this one. Cancelling the waiter only clears the victim
LONG_RUNNING Over the time threshold with no lock conflict Usually a slow or runaway query. Judge it before cancelling
  • Running statements come from crdb_internal.cluster_queries, the table behind SHOW CLUSTER STATEMENTS. It carries the query_id that CANCEL QUERY takes and the txn_id used for the joins.
  • The live lock picture comes from crdb_internal.cluster_locks. A row with granted true and contended true is a held lock with waiters. A row with granted false is a transaction waiting. Joining it to the running statements by txn_id is what separates a blocker from its victim.
  • crdb_internal.cluster_contention_events adds recent history: how many times a transaction has been the blocker in a resolved contention event. Those events are recorded after a wait ends, so they lag the live picture. The guard reads them for context and treats them as a detection signal only when min_recent_contention_events is above 0.

Safety

  • Every read is against a crdb_internal system view. Nothing touches user data.
  • A statement is cancelled only when auto_remediate is true, when dry_run is false and when a human resumes the Pause.
  • Exactly one statement is cancelled per run, the worst offender, chosen as the blocker with the most waiters first, then the longest running.
  • The only write the flow ever issues is CANCEL QUERY '<query_id>'. It never drops anything and never cancels a session or a transaction wholesale.
  • CockroachDB internal statements (application_name starting with $ internal) are always excluded. So is anything named in excluded_applications.

How it works

  1. audit (io.kestra.plugin.jdbc.postgresql.Query, read-only) lists running statements over long_running_seconds or holding a contended lock with at least min_waiters waiters. It joins cluster_queries to cluster_locks for the live blocker and waiter picture. It also joins cluster_contention_events for recent history. It labels each row BLOCKER, WAITING or LONG_RUNNING. Rows come back worst first.
  2. summary logs every row with its elapsed time, how many transactions it blocks and how long it has held or waited on a lock.
  3. route (io.kestra.plugin.core.flow.If):
    • clean: nothing is over the threshold or contended, so it logs that.
    • findings: alert posts the statements to Slack. target pins the worst offender's query_id.
      • remediate_gate runs only when auto_remediate is true and dry_run is false.
      • approve (io.kestra.plugin.core.flow.Pause, behavior: FAIL) holds for up to an hour and records the change record you give it.
      • cancel runs CANCEL QUERY against the one chosen query_id.
      • settle waits, then reaudit reads the running statements again. verify_result fails the run if that query_id is still there.
  4. errors alerts Slack when the audit itself cannot run.

What you get

  • One list that separates a statement blocking others from a statement waiting on one, which a plain count of long-running queries cannot do.
  • A single, named cancellation per run, behind a human approval, rather than a blanket kill of every long query.
  • A re-read of the running statements as proof, so a green run means the query is gone rather than assumed gone.
  • CockroachDB internal work and any application you name left alone.

Who it's for

  • Teams running CockroachDB who have watched one table slow down while the cluster looked healthy.
  • Platform engineers who need to cancel a runaway or a lock holder safely, with an approval and a record, not an ad hoc CANCEL QUERY typed at 2am.
  • Anyone evaluating the PostgreSQL plugin against CockroachDB who wants an example that reads the lock tables and drives CANCEL QUERY.

Why orchestrate this with Kestra

Contention is a moving target. A statement that is fine on one run is a blocker on the next. Kestra runs the same audit every few minutes, keeps each run with its numbers and sends the statements to Slack. The cancel is disruptive, so it sits behind auto_remediate, dry_run and a Pause that records the change record. The run reports success only after a second read shows the statement stopped.

Tested end to end

On Kestra 2.0.5 OSS against CockroachDB v24.1 (cockroachdb/cockroach:latest-v24.1, single node, insecure), with a local HTTP sink standing in for Slack. The worst offender was confirmed with cockroach sql running SHOW CLUSTER STATEMENTS and SELECT ... FROM crdb_internal.cluster_locks, not only from the Kestra log.

Run Cluster state Result
1 No long statement Clean. 0 rows. Clean branch logged
2 A SELECT pg_sleep(600) running 1 row, LONG_RUNNING, elapsed over the threshold. Alert sent, no change
3 One transaction holding a write lock while a second blocks on the same row 2 rows, the holder BLOCKER with 1 waiter, the blocked UPDATE WAITING. Worst offender was the blocker
4 Same as run 3, auto_remediate: true, dry_run: true Same report. Both statements still running when checked with cockroach sql
5 Same as run 3, auto_remediate: true, dry_run: false, approval declined Pause resumed with approved: false. Nothing cancelled, both still running
6 Same as run 3, approved CANCEL QUERY on the blocker. The re-read showed still_running: 0, the waiter acquired the lock and committed, cluster_locks for the row went empty
7 Unreachable host errors alert sent

Prerequisites

  • A CockroachDB cluster reachable over the Postgres wire protocol, which is what the PostgreSQL plugin speaks to it.
  • The SQL role needs VIEWACTIVITY to see other sessions and CANCELQUERY to cancel them. A role cannot cancel a statement run by an admin.
  • Local testing: a single insecure node is enough. SELECT pg_sleep(600) gives a long runner. Two BEGIN sessions updating the same row give a lock conflict.

Secrets

  • COCKROACH_PASSWORD: the SQL password, read by the password input's default. An insecure local node ignores it.
  • 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:26257/defaultdb?sslmode=require Any node of the cluster
db_user root The role the queries connect as
password {{ secret('COCKROACH_PASSWORD') }} SQL password, ignored by an insecure node
long_running_seconds 300 Elapsed time at which a statement is flagged
min_waiters 1 Waiters on a held contended lock that flag a statement early
min_recent_contention_events 0 Recent blocker events that flag a statement. 0 turns this off
excluded_applications [] Application names never cancelled
settle_duration PT5S Wait after the cancel before the re-read
auto_remediate false Allow CANCEL QUERY
dry_run true Must be false before anything is cancelled

Quick start

  1. Add the COCKROACH_PASSWORD and SLACK_WEBHOOK_URL secrets.
  2. Import the flow and set jdbc_url to one of your nodes and db_user to a role with VIEWACTIVITY and CANCELQUERY.
  3. Run it once and read the categories. A WAITING row wants you to cancel the matching BLOCKER, not the waiter.
  4. To cancel the worst offender, run with auto_remediate: true and dry_run: false, then resume the Pause with approved: true and your change record.
  5. Enable the every_5_minutes trigger, which always runs in safe mode.

How to extend

  • Cancel every blocker over a waiter threshold in a loop, rather than only the single worst offender.
  • Add a CANCEL SESSION branch for a transaction that holds a lock while sitting idle, where there is no running statement to cancel.
  • Store the first-seen time of a blocker in a KV key, so a transaction that blocks others for longer than a budget is paged rather than cancelled on sight.
  • Record each cancelled query_id, user and query text to a table for an audit trail.
  • Loop over several clusters by passing a list of JDBC URLs.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.