brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pg_cancel_backend stops a PostgreSQL query, pg_terminate_backend ends the session

Postgresql
~/tips/tip-postgresql-cancel-vs-terminate-backend

SELECT pid, now() - query_start AS running, left(query, 60)

Picks the gentle or the hard way to stop a runaway query from another session.

A report query has run for twenty minutes and you want it gone. There are two functions for that, and I’d try the gentle one first.

SELECT pid, now() - query_start AS running, left(query, 60)
FROM pg_stat_activity WHERE state = 'active' ORDER BY running DESC;

SELECT pg_cancel_backend(12345);
SELECT pg_terminate_backend(12345);

pg_cancel_backend cancels the current query of that session. The client gets canceling statement due to user request, its transaction is aborted, but the connection stays open, so the app does not have to reconnect. That is the same as pressing Ctrl+C in psql.

pg_terminate_backend closes the whole connection. Use it when the cancel does not work, or when the session is idle in transaction and holding locks, because there is no running query to cancel then. Either way, its open transaction is rolled back.

Both return true when the signal was sent, not when the session is gone. Since PostgreSQL 14, pg_terminate_backend(pid, 5000) waits up to 5000 ms and returns false if the process is still there. You need to be a superuser, the same role as the target, or have pg_signal_backend, and only a superuser can touch superuser sessions. Double-check the pid before you send it. One wrong digit ends somebody else’s work.

Further reading: Server signaling functions

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link