Video in progress
What is the difference between `pg_cancel_backend` and `pg_terminate_backend`, and how do you safely stop a hung query on prod?
pg_cancel_backend(pid) cancels only the current query, and the session and connection stay alive. pg_terminate_backend(pid) drops the whole session, and an open transaction is rolled back. I cancel first, and terminate if that doesn't help.
📖 Answer
First I identify exactly whom to stop:
SELECT pid, usename, application_name, state,
now() - xact_start AS tx_age,
now() - query_start AS query_age,
left(query, 80) AS query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY xact_start NULLS LAST
LIMIT 20;
Then:
SELECT pg_cancel_backend(12345); -- stops the query
SELECT pg_terminate_backend(12345); -- drops the session
When cancel isn't enough:
- the session is
idle in transaction: there's no query to cancel, but the locks are held. Only terminate helps; - the query is stuck somewhere that doesn't check for signals (for example, on the network or in some extension functions).
Things to be careful about:
- the big transaction of a terminated session is rolled back: that's fast, but the data it wrote is lost; if it was a batch job, I warn its owner;
- if the Hikari connection is dropped, the application gets an error on the next query and the pool opens a new connection: one query fails, that's all;
- killing an
autovacuumprocess is pointless: it comes back after a while, or immediately if it's an anti-wraparound one; - I never
kill -9at the OS level: the postmaster puts the whole cluster into crash recovery.
To keep it from happening again, I set statement_timeout and idle_in_transaction_session_timeout.
Sign up to mark studied questions and save your progress.