Skip to content

Manage Long-Running Queries

See which statements run on your Managed PostgreSQL service, find the session at the root of a lock chain, cancel or terminate it, and set timeouts so that runaway statements stop on their own.

A long statement or a transaction left open holds its locks, keeps old row versions that VACUUM cannot remove, and makes schema changes wait behind it.

See What Is Running

pg_stat_activity has one row per server process. Keep client sessions that are not idle, except your own, and sort by statement age:

SELECT pid,
       usename,
       datname,
       client_addr,
       state,
       wait_event_type,
       wait_event,
       now() - query_start AS running_for,
       query
FROM pg_stat_activity
WHERE backend_type = 'client backend'
  AND pid <> pg_backend_pid()
  AND state <> 'idle'
ORDER BY running_for DESC;

In psql, \x on switches to expanded output, which keeps long statements readable.

ColumnMeaning
stateactive, idle, idle in transaction (a transaction is open and nothing runs), or idle in transaction (aborted)
wait_event_type, wait_eventWhat the backend waits for. Lock means it is blocked by another session. Empty on an active backend means it is running on CPU.
query_startStart of the current or last statement
xact_startStart of the current transaction, older than query_start when a transaction spans several statements

avnadmin is a member of pg_read_all_stats and sees every column for the sessions of all database users. Other users see <insufficient privilege> in query, and NULL in state and backend_type, for sessions that are not their own, so a filter on backend_type hides those rows from them. Sessions of the platform’s postgres and _aiven roles show <insufficient privilege> even to avnadmin.

The query column is cut at track_activity_query_size bytes, 1024 by default. You can raise it up to 10240 in --pg-settings; changing it restarts the service.

Find Sessions Stuck Inside a Transaction

A session idle in transaction runs nothing but keeps every lock its transaction took. For such a session, query is the last statement it ran:

SELECT pid,
       usename,
       state,
       now() - xact_start   AS transaction_age,
       now() - state_change AS idle_for,
       client_addr,
       query                AS last_statement
FROM pg_stat_activity
WHERE backend_type = 'client backend'
  AND state IN ('idle in transaction', 'idle in transaction (aborted)')
ORDER BY xact_start;

Find What Is Blocking What

Cancelling a blocked session solves nothing: find the one at the root of the chain. pg_blocking_pids() returns the sessions a backend waits for:

SELECT blocked.pid                 AS blocked_pid,
       blocked.usename             AS blocked_user,
       now() - blocked.query_start AS blocked_for,
       left(blocked.query, 60)     AS blocked_query,
       blocking.pid                AS blocking_pid,
       blocking.usename            AS blocking_user,
       blocking.state              AS blocking_state,
       now() - blocking.xact_start AS blocking_transaction_age,
       left(blocking.query, 60)    AS blocking_query
FROM pg_stat_activity blocked
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid) ON true
JOIN pg_stat_activity blocking ON blocking.pid = b.pid
WHERE blocked.backend_type = 'client backend'
ORDER BY blocked_for DESC;

A typical chain: a session that ran SELECT count(*) FROM orders in a transaction and stayed open (blocking_state = idle in transaction) blocks an ALTER TABLE orders ..., which in turn blocks every new SELECT on orders. The result shows two rows, and the blocking_pid of the oldest row is the session to deal with. See Run schema migrations safely to avoid creating such chains.

Cancel a Statement

pg_cancel_backend() stops the running statement and keeps the session open. The client receives ERROR: canceling statement due to user request:

SELECT pg_cancel_backend(PID);

Parameters:

  • PID: the pid from pg_stat_activity.

true means the signal was sent. The statement stops at its next interruption check, usually immediately; run the pg_stat_activity query again to confirm.

Terminate a Session

pg_terminate_backend() ends the backend, rolls back its transaction and closes the connection. It is the only option for an idle in transaction session, which has no statement to cancel:

SELECT pg_terminate_backend(PID, 5000);

Parameters:

  • PID: the pid from pg_stat_activity.
  • 5000: optional. Milliseconds to wait for the backend to exit; the function returns false if it is still there after that time. Without it, the function returns as soon as the signal is sent.

Terminating the session of an application that reproduces the same statement only moves the problem. Fix the statement or add a timeout.

Act on Several Sessions

Keep the filter narrow, and always keep backend_type = 'client backend' and pid <> pg_backend_pid():

SELECT pid, usename, now() - query_start AS running_for, pg_cancel_backend(pid)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
  AND state = 'active'
  AND pid <> pg_backend_pid()
  AND usename = 'reporting'
  AND now() - query_start > interval '10 minutes';

Who Can Cancel or Terminate

avnadmin is a member of pg_signal_backend, so it can cancel and terminate the sessions of every database user. It cannot signal the platform’s superuser sessions, for example the backup and monitoring processes:

ERROR:  permission denied to terminate process
DETAIL:  Only roles with the SUPERUSER attribute may terminate processes of roles with the SUPERUSER attribute.

Another user can only signal sessions of roles it has the privileges of. Otherwise it gets:

ERROR:  permission denied to cancel query
DETAIL:  Only roles with privileges of the role whose query is being canceled or with privileges of the "pg_signal_backend" role may cancel this query.

Check whether a user can signal the sessions of a given role:

SELECT pg_has_role('reporting', 'app_owner', 'USAGE');

To allow it, connected as avnadmin, grant the role that owns the sessions, here app_owner, to the user, here reporting:

GRANT app_owner TO reporting;

This also gives reporting every privilege of app_owner. Granting pg_signal_backend instead lets the user signal every non-superuser session.

Stop Long-Running Statements Automatically

ParameterEffect
statement_timeoutCancels a statement that runs longer than the value.
lock_timeoutCancels a statement that waits longer than the value for a lock.
idle_in_transaction_session_timeoutTerminates a session idle inside an open transaction for longer than the value.
idle_session_timeoutTerminates a session idle outside a transaction for longer than the value.

All four have user context: avnadmin and every other user can set them per session, and avnadmin can set them per role and per database. A value without unit is in milliseconds; 0 disables the timeout.

For the current session:

SET statement_timeout = '30s';
SET lock_timeout = '3s';

For every new session of a role, or of a database:

ALTER ROLE reporting SET statement_timeout = '60s';
ALTER ROLE reporting SET idle_in_transaction_session_timeout = '2min';
ALTER DATABASE defaultdb SET statement_timeout = '30s';

Role and database settings apply to sessions opened afterwards, not to SET ROLE. Check what a session has in force with SHOW statement_timeout;. A statement that exceeds statement_timeout fails with ERROR: canceling statement due to statement timeout.

Do not put a statement_timeout on the role that runs migrations, index builds or bulk loads: those run long by design.

Through a connection pool in transaction mode, a plain SET stays on the server connection and can apply to other clients’ transactions. Use ALTER ROLE, ALTER DATABASE or SET LOCAL inside a transaction instead. See Manage connection pools.

Set idle_in_transaction_session_timeout for the Service

idle_in_transaction_session_timeout is also a service parameter, in milliseconds, from 0 to 604800000. A new service uses 86400000, 24 hours. To set ten minutes:

exo dbaas update SERVICE_NAME -z ZONE -f \
  --pg-settings '{"idle_in_transaction_session_timeout":600000}'

Parameters:

  • SERVICE_NAME: name of the Managed PostgreSQL service, for example my-postgresql.
  • ZONE: zone the service runs in, for example ch-gva-2.

The change applies without a restart. A session that exceeds the timeout is closed with FATAL: terminating connection due to idle-in-transaction timeout. statement_timeout and lock_timeout are not service parameters: set them per role or per database as above.

Related Pages

Last updated on