Cookbook recipe

Kill a runaway query or connection safely

Applies to PostgreSQL 13–17 Last reviewed May 2026 Grounded in source
Estimated investigation4 min

Scenario

A query is pegging CPU or holding a lock. You need to cancel it — gently first, forcefully if needed. Diagnose it Find the offending backend: SELECT pid, now()-query_start AS runtime, state, left(query,80) FROM pg_stat_activity WHERE…

Investigation Path

A query is pegging CPU or holding a lock. You need to cancel it — gently first, forcefully if needed.

Diagnose it

Find the offending backend:

SELECT pid, now()-query_start AS runtime, state, left(query,80)
FROM pg_stat_activity
WHERE state <> 'idle' ORDER BY runtime DESC;

Why it happens

pg_cancel_backend cancels the current query but keeps the session. pg_terminate_backend kills the whole connection (rolls back its transaction). Prefer cancel first.

This is a Pro lesson

Get every Learning Pathway and cookbook recipe — grounded in PostgreSQL source code, with diagnostics, fixes, and prevention for each topic.

Continue this lesson to learn:

  • How to fix it
  • Prevent it next time
  • Related & next steps
  • All 36 Learning Pathway lessons
  • 170+ cookbook recipes
  • Source-grounded diagnostics & fixes

Secure checkout Cancel anytime Source-grounded

Career Impact

This scenario builds production judgment and operational confidence under pressure.

Open Career Dashboard →

Keep going

Related & next steps

Was this helpful?

← All cookbook recipes