← Back to SQL, page 24

sql-0472 · Easy fresher

A runaway query has been running for an hour and is slowing everything. How do you stop it safely and prevent a repeat?

Find its process id in pg_stat_activity and call pg_cancel_backend(pid), which cancels the current query and keeps the session; use pg_terminate_backend(pid) only if cancel does not work. The query's transaction rolls back. Prevent repeats with statement_timeout for application and reporting roles, and fix the query or its index.

Full answer
text
SELECT pid, usename, now() - query_start AS runtime, left(query, 80)
FROM pg_stat_activity WHERE state = 'active' ORDER BY runtime DESC;
SELECT pg_cancel_backend(12345);

Notes:

  • Cancelling a long UPDATE or DELETE rolls it back, which can itself take time and generate WAL; that is expected.
  • Terminating ends the connection; the application must reconnect.
  • statement_timeout can be set per role (ALTER ROLE reporting SET statement_timeout = '5min') or per transaction (SET LOCAL), so ad-hoc reports cannot run forever while migrations can opt out.
  • idle_in_transaction_session_timeout handles sessions that hold transactions open without running anything.

Afterwards, EXPLAIN the query to find why it was slow. In SQLite, a long query is interrupted from the application with sqlite3_interrupt (in Python, connection.interrupt()). Described here, not run.

Key points

  • Cancel first, terminate if needed
  • The transaction rolls back
  • Set statement_timeout per role
  • Handle idle-in-transaction sessions
  • Fix the root cause afterwards

Common mistakes

  • Killing the server process from the OS
  • No timeouts on reporting roles

Follow-ups

  • Why can a cancelled DELETE take long to stop?
  • What timeout suits an API role?

Tips

  • Mention per-role timeouts