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_timeoutcan 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_timeouthandles 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