skip to content

Activity & Wait Events

pg_stat_activity shows what every PostgreSQL backend is doing and waiting on, and pg_blocking_pids() names who blocks it. Interviewers ask how to find and stop a stuck or blocking session.

part ofPostgreSQLread it →
on this pageshow

explore

questions

5

In PostgreSQL, what does the pg_stat_activity view show, and what do its state values such as 'idle in transaction' mean?

level: juniorimportance: must knowfreq 78%

answer

  1. one row per server process
  2. client backends and background processes
  3. active, idle, idle in transaction
  4. xact_start versus query_start
  5. query shows the last statement

basics

~20 s

pg_stat_activity has one row per PostgreSQL server process, showing who is connected, what each runs or waits on, and since when. The state idle in transaction means a transaction is open but no statement is running.

solid answer

~40 s

`pg_stat_activity` returns one row per server process: client backends plus background processes such as the checkpointer and autovacuum workers, told apart by `backend_type`. For each it shows `pid`, `usename`, `datname`, `application_name`, `client_addr`, `state`, the wait columns, the timestamps `backend_start`, `xact_start`, `query_start` and `state_change`, and `query`. `state` is `active` (running a statement), `idle` (waiting for a command, no transaction), `idle in transaction` (inside an open transaction but doing nothing) or `idle in transaction (aborted)` (a statement failed and the client has not rolled back). Outside `active`, `query` is the *last* statement run. `idle in transaction` is the row to worry about: its locks stay held until the client commits or rolls back.

code

sql · 11 lines
sql
SELECT pid,
       usename,
       application_name,
       state,
       now() - xact_start   AS xact_age,
       now() - state_change AS in_state_for,
       left(query, 60)      AS last_query
FROM pg_stat_activity
WHERE backend_type = 'client backend'
  AND state <> 'idle'
ORDER BY xact_start NULLS LAST;

go deeper

for a junior

Recall that pg_stat_activity has one row per server process and name the main state values, especially the difference between idle and idle in transaction.

for a middle

Explain which timestamp measures what: xact_start for transaction age, query_start for the statement, state_change for time in the current state, and why query shows the last statement.

for a senior

Show that you know what an idle-in-transaction session costs other sessions, how privileges hide rows from monitoring users, and that the view stays frozen within one transaction.

for a principal

Discuss what you would alert on from this view, such as transaction-age thresholds per application, and why monitoring roles should get pg_monitor rather than superuser.

## What the view is `pg_stat_activity` is a system view with **one row per server process** of a PostgreSQL instance. PostgreSQL runs a separate operating-system process for each client connection (a **client backend**) and further processes for background work, and the view lists all of them. The column `backend_type` tells them apart: `client backend` for application connections, and values such as `autovacuum worker`, `checkpointer`, `background writer`, `walwriter`, `walsender` and `parallel worker` for the rest. Most investigations start by filtering to `backend_type = 'client backend'`. The view is live: it reflects what each process reports about itself right now, which makes it the first thing to query when an application says the database is slow or stuck. ## The columns you read first | Column | What it tells you | |---|---| | `pid` | The backend's process ID, used by every function that acts on a session | | `usename`, `datname` | The role and database of the session | | `application_name`, `client_addr` | Which application and host opened the connection | | `state` | What the backend is doing at a high level | | `wait_event_type`, `wait_event` | What it is waiting on right now, or NULL if it is not waiting | | `backend_start`, `xact_start`, `query_start`, `state_change` | When the connection, transaction, latest statement and current state began | | `query` | The current statement, or the last one if the backend is not active | | `query_id` | An identifier of that statement, filled only when query identifiers are computed | ## The state values | `state` | Meaning | |---|---| | `active` | Executing a statement (it may still be waiting inside it) | | `idle` | Waiting for the client's next command, with no transaction open | | `idle in transaction` | Inside an open transaction, but not running anything | | `idle in transaction (aborted)` | A statement in the transaction failed; waiting for the client to roll back | | `fastpath function call` | Executing a fast-path function call | | `starting` | Still in startup, including client authentication | | `disabled` | `track_activities` is off for that backend | Two details trip people up: - **`state` and the wait columns are independent.** An `active` backend may be running on CPU or waiting on a lock or a disk read; the wait columns say which. - **`query` is not always current.** In every state except `active` it is the **last** statement the session ran. An `idle` row showing an `UPDATE` means that update has finished. ## Timestamps: which age to measure The timestamps answer different questions, and choosing the wrong one hides the problem: 1. `now() - xact_start` is the **age of the open transaction**, NULL when none is open. This is the column for finding long transactions. 2. `now() - query_start` is how long the current (or last) statement has run. A transaction that ran many short statements has a young `query_start` and an old `xact_start`. 3. `now() - state_change` is how long the backend has been in its current state, so for an `idle in transaction` row it is how long the application has left the transaction untouched. 4. `backend_start` is when the connection was opened, useful for spotting connection churn or very old pooled connections. ## Why idle in transaction matters An `idle` session is cheap. An **`idle in transaction`** session is not: it keeps every lock its transaction has taken, so sessions that need a conflicting lock queue behind it, and when it holds a snapshot or a transaction ID (`backend_xmin`, `backend_xid`) it also holds back what VACUUM may remove (that side belongs to the autovacuum topic). The usual causes are application bugs: a code path that returns without committing, or a transaction held open while the application calls a slow external service. Sorting client backends by `xact_start` puts these sessions at the top. The timeout that ends them automatically, `idle_in_transaction_session_timeout`, is covered with connection tuning. An `idle in transaction (aborted)` session is different: the failed statement aborted the transaction, which released its locks, and the session refuses further commands until the client sends `ROLLBACK`. ## Visibility and limits - **Privileges.** Every role can see that a session exists, with its user and database. Query text, state, wait columns and timestamps are shown only for sessions of roles the viewer has privileges of; other rows show `<insufficient privilege>` in `query`. Superusers and members of `pg_read_all_stats` (which `pg_monitor` includes) see everything. - **Truncation.** `query` is cut at `track_activity_query_size` bytes, 1024 by default; changing it needs a server restart. - **One picture per transaction.** The activity data is collected the first time it is read in a transaction and stays the same until that transaction ends, so repeat a query in separate transactions, or call `pg_stat_clear_snapshot()`, to see change. - **No history.** The view shows the present only. Past statements and their timings live in `pg_stat_statements` and the server log, which belong to the query-statistics topic.

  • Why might a monitoring user see '<insufficient privilege>' in pg_stat_activity's query column, and how do you fix it?
    Every role sees that sessions exist, but query text, state, wait columns and timestamps are shown only for sessions of roles it has privileges of. Superusers and members of `pg_read_all_stats` see all of it. The usual fix is `GRANT pg_monitor TO monitoring_user;`, since `pg_monitor` includes `pg_read_all_stats` without granting superuser.
  • Why can the query column of an 'idle in transaction' row mislead you about which statement took a lock?
    Because `query` holds only the most recent statement. A checkout transaction that ran `UPDATE stock ...` and then a harmless `SELECT` shows the `SELECT`, though the lock came from the `UPDATE`. To see what the session actually holds you read its locks (the locking topic's `pg_locks`) or the application's own logs.

  • pg_stat_activity lists only client connections, never background processes.
  • An idle in transaction session is harmless because it is not running anything.
  • The query column always shows a statement that is executing right now.
  • query_start tells you how long the current transaction has been open.
open as a page

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%

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.

open as a page

During a PostgreSQL checkout outage, dozens of sessions wait with wait_event_type 'Lock'; how do you use pg_blocking_pids() to find and clear the root blocker?

level: seniorimportance: should knowfreq 60%

basics

~10 s

Call pg_blocking_pids(pid) for each waiting session, then find the PIDs that block others but are not blocked themselves. In a checkout pile-up that root is often an idle-in-transaction session, ended with pg_terminate_backend().

open as a page

In PostgreSQL's pg_stat_activity, how do you triage a slowdown from wait_event_type and wait_event, and what does an active row with no wait event mean?

level: seniorimportance: should knowfreq 44%

basics

~20 s

Sample pg_stat_activity repeatedly and count active sessions per wait_event_type and wait_event. Lock means lock queues, LWLock shared-memory contention, IO storage waits, Client the application; an active row with NULL waits is usually running on CPU.

open as a page

In PostgreSQL, how do you follow a long COPY FROM load with pg_stat_progress_copy, and what do the pg_stat_progress views not tell you?

level: middleimportance: nice to knowfreq 24%

basics

~10 s

While a COPY runs, pg_stat_progress_copy has one row for its backend with bytes_processed, bytes_total and tuples_processed; join it to pg_stat_activity on pid. Progress views show live counters only: no time estimate and no history.

open as a page