skip to content

In PostgreSQL, how do pg_cancel_backend() and pg_terminate_backend() differ, and which one ends a session stuck idle in transaction?

level: middleimportance: must knowfreq 72%

answer

  1. statement versus whole session
  2. 57014 versus 57P01
  3. an idle backend ignores cancel
  4. rollback releases the locks
  5. pg_signal_backend for non-superusers

basics

~20 s

pg_cancel_backend(pid) aborts only the statement a session is running; pg_terminate_backend(pid) closes the whole session, rolling back its open transaction. An idle-in-transaction session runs no statement, so a cancel does nothing and terminating it is what releases its locks.

solid answer

~40 s

`pg_cancel_backend(pid)` asks the backend to abort its running statement: the client gets SQLSTATE `57014` (*canceling statement due to user request*) and the connection stays open. `pg_terminate_backend(pid [, timeout])` ends the backend process with `57P01` (*terminating connection due to administrator command*), rolling back its transaction and releasing every lock it held. A backend in `idle in transaction` is waiting for client input, and PostgreSQL ignores a cancel that arrives then, so the call returns `true` and nothing changes: you need terminate. Both return `true` once the signal is sent, not once it worked; a positive `timeout` in milliseconds makes `pg_terminate_backend` wait and return `false` on expiry. Non-superusers may signal sessions of roles they are members of, or any non-superuser session through `pg_signal_backend`.

code

sql · 4 lines
sql
-- 48213 is idle in transaction and holds a stock row lock
SELECT pg_cancel_backend(48213);          -- true, but an idle backend ignores it
SELECT pg_terminate_backend(48213, 5000); -- waits up to 5 s for the exit
SELECT count(*) FROM pg_stat_activity WHERE pid = 48213;  -- 0 once it is gone

go deeper

for a junior

Recall that cancel stops the current statement while terminate ends the whole connection, and that both take the pid from pg_stat_activity.

for a middle

Explain why an idle-in-transaction backend ignores a cancel, what error each function produces in the client, and what a true return value does and does not prove.

for a senior

Show the operational habit: cancel active work first, terminate idle-in-transaction holders, never kill -9 a backend, and grant pg_signal_backend to on-call roles instead of superuser.

for a principal

Weigh manual termination against automatic guards such as session timeouts, and decide who may end other teams' sessions and how those actions are recorded.

## Two functions, two scopes PostgreSQL gives administrators two SQL functions for stopping someone else's work. Both take the backend's process ID from `pg_stat_activity.pid`: | | `pg_cancel_backend(pid)` | `pg_terminate_backend(pid, timeout)` | |---|---|---| | What it stops | The statement currently running | The whole session (backend process) | | What the client sees | `ERROR`, SQLSTATE `57014`, *canceling statement due to user request* | `FATAL`, SQLSTATE `57P01`, *terminating connection due to administrator command* | | Open transaction | Aborted by the error; inside a transaction block the session then waits for `ROLLBACK` | Rolled back as the process exits | | Connection | Stays open | Closed; the client must reconnect | | Effect on an idle backend | None | The session ends | Under the hood the first sends the backend a query-cancel signal and the second a termination signal (how operating-system signals work is a Linux topic); what matters here is how a PostgreSQL backend reacts to each. ## Why cancel does nothing to idle in transaction A backend in state `idle in transaction` is not executing anything: it sits in its main loop reading the socket for the client's next command. PostgreSQL deliberately **ignores a cancel request that arrives while the backend is reading a command from the client**, because there is no statement to abort. So `pg_cancel_backend()` returns `true` (the signal was delivered) and nothing changes: the transaction stays open, its locks stay held, and every session queued behind it keeps waiting. `pg_terminate_backend()` is the tool for that case. The backend exits, its transaction is rolled back, and all locks it held are released at once. ## When cancel is the right first step Cancel is the gentler tool and fits a session that is **actively running** something unwanted: - a runaway report query saturating the server; - a statement waiting on a lock that you would rather fail than keep queuing; - a long `UPDATE` started by mistake. The connection survives, so a connection pool keeps it, and the application receives an ordinary error it can handle. If the statement ran inside an explicit transaction block, the session moves to `idle in transaction (aborted)`: the transaction is already aborted and its locks released, and every further command fails with *current transaction is aborted, commands ignored until end of transaction block* until the client rolls back. ## Reading the return value Both functions return `true` when the signal was **sent**, not when it took effect. To know the outcome: 1. Pass a `timeout` in milliseconds to `pg_terminate_backend(pid, timeout)`. It then waits for the process to exit, returning `true` if it did, or emitting a warning and returning `false` if the time ran out. The default `0` returns at once. 2. Or query `pg_stat_activity` for that `pid` a moment later. ## Who may call them - **Superusers** may signal any backend. - A role may signal backends of roles it is a **member of**. - Members of the predefined role **`pg_signal_backend`** may signal any non-superuser backend. - Only superusers may signal **superuser** backends. Autovacuum workers count as superuser backends, but PostgreSQL 18 added **`pg_signal_autovacuum_worker`**, whose members may cancel or terminate them. Granting an on-call role `pg_signal_backend` lets it clear stuck application sessions without handing out superuser. ## What not to do instead - **Do not `kill -9` a backend.** The postmaster cannot trust shared memory after a backend dies that way, so it treats the exit as a crash: it terminates every other server process and reinitializes, running crash recovery, under the default `restart_after_crash = on`. One stuck session becomes an outage for every connection. - **Do not restart the server** to clear one session; terminate the session. - **Do not stop at the kill.** A terminated idle-in-transaction session is a symptom of an application path that left a transaction open. Find it through `application_name`, `client_addr` and the last `query`, and let a timeout (covered with connection tuning) end the next one automatically.

  • After a PostgreSQL statement is cancelled inside an explicit transaction block, what state does the session show and what must the client do?
    It shows `idle in transaction (aborted)`. The error aborted the transaction, which already released its locks, and every further statement fails with *current transaction is aborted, commands ignored until end of transaction block* until the client sends `ROLLBACK`. Application code that swallows the cancel error and carries on using the connection gets nothing but that error until it rolls back.
  • Why should you not kill -9 a PostgreSQL backend process instead of calling pg_terminate_backend()?
    The postmaster cannot know whether a backend killed that way left shared memory consistent, so it treats the exit as a crash: it terminates all other server processes and reinitializes with crash recovery (with the default `restart_after_crash = on`). One stuck session becomes a full outage. `pg_terminate_backend()` lets the backend roll back and exit cleanly.
  • In PostgreSQL 18, who may terminate an autovacuum worker?
    Autovacuum workers count as superuser backends, so superusers may, and since 18 so may members of the predefined role `pg_signal_autovacuum_worker`. Membership in `pg_signal_backend` is not enough, because that role covers only non-superuser backends.

  • pg_cancel_backend closes the connection, so the client has to reconnect.
  • Cancelling an idle in transaction session rolls it back and frees its locks.
  • A true return value means the target session has already gone.
  • kill -9 on the backend's pid is just a faster pg_terminate_backend.

Assumes PostgreSQL 18; the pg_signal_autovacuum_worker role that lets non-superusers signal autovacuum workers is new in 18.