Monitor Running Queries in PostgreSQL using pg_stat_activity
Monitor Running Queries in PostgreSQL with pg_stat_activity
Where pg_stat_statements aggregates queries that already finished and pgBadger reads logs after the fact, pg_stat_activity is the real-time snapshot: one row per server process, showing what each one is doing at the moment the query runs. It is the right starting point when the question is "what is the database doing right now", whether that means working sessions, sessions waiting on a lock, parallel workers, or connections doing nothing.
Purpose and Overview
A single row in pg_stat_activity combines identity (pid, usename, application_name, client_addr), timing (backend_start, xact_start, query_start, state_change), and what the backend is doing (state, wait_event_type, wait_event, query). The view has one row per server process, so it includes background processes such as the checkpointer and autovacuum workers as well as client connections. The backend_type column tells them apart.
Reading it well comes down to three habits. First, look at every state, not only active. A session in idle in transaction holds its locks and its snapshot while running nothing, and it is often the real cause behind a pile of waiting queries. Second, read the timestamps for what they mean: query_start is when the current query began if the state is active, or when the last query began if it is not, while state_change is when the backend entered its current state. Third, remember that the view is a snapshot with no history. A query that finished a second ago is gone, so anything meant to catch slow work has to poll.
Two related posts cover narrower slices of this view: slow active queries over a threshold and finding idle connections. The queries below take the wide view: everything running now, parallel query groups, and blocking chains.
Sample Code
All sessions, with how long each has been in its current state:
1SELECT
2 pid,
3 usename,
4 application_name,
5 state,
6 wait_event_type,
7 wait_event,
8 clock_timestamp() - xact_start AS xact_age,
9 clock_timestamp() - state_change AS in_state_for,
10 left(query, 120) AS query
11FROM pg_stat_activity
12WHERE backend_type = 'client backend'
13 AND pid <> pg_backend_pid()
14ORDER BY state, xact_start NULLS LAST;
Parallel query groups, with each worker listed under its leader (PostgreSQL 13 and later):
1SELECT
2 coalesce(leader_pid, pid) AS leader,
3 pid,
4 backend_type,
5 state,
6 wait_event_type,
7 wait_event,
8 left(query, 80) AS query
9FROM pg_stat_activity
10WHERE backend_type IN ('client backend', 'parallel worker')
11 AND (leader_pid IS NOT NULL
12 OR pid IN (SELECT leader_pid
13 FROM pg_stat_activity
14 WHERE leader_pid IS NOT NULL))
15ORDER BY leader, leader_pid NULLS FIRST;
Blocked sessions next to the sessions blocking them (PostgreSQL 9.6 and later):
1SELECT
2 w.pid AS waiting_pid,
3 w.usename AS waiting_user,
4 w.wait_event_type,
5 w.wait_event,
6 clock_timestamp() - w.query_start AS waiting_for,
7 left(w.query, 80) AS waiting_query,
8 b.pid AS blocking_pid,
9 b.state AS blocking_state,
10 clock_timestamp() - b.xact_start AS blocker_xact_age,
11 left(b.query, 80) AS blocking_last_query
12FROM pg_stat_activity w
13CROSS JOIN LATERAL unnest(pg_blocking_pids(w.pid)) AS x(blocker)
14LEFT JOIN pg_stat_activity b ON b.pid = x.blocker
15ORDER BY waiting_for DESC;
Once a blocked pid is known, the lock it is waiting for is in pg_locks:
1SELECT locktype, relation::regclass AS relation, mode, granted
2FROM pg_locks
3WHERE pid = 12345 -- replace with a waiting_pid
4 AND NOT granted;
Notes: pg_stat_activity and its state column exist since PostgreSQL 9.2. Superusers and roles with privileges of pg_read_all_stats (which pg_monitor includes) see all information about all sessions. Other roles see all information only about their own sessions, and many columns are null in rows about other sessions. The monitoring query excludes its own row with pid <> pg_backend_pid(), which is more reliable than matching on query text.
Code Breakdown
The three queries answer different questions, so each filters differently.
Client backends only
backend_type = 'client backend' removes the checkpointer, WAL writer, autovacuum launcher, and similar processes, which are not what a slow-application investigation is after. The column has existed since PostgreSQL 10.
Age columns
clock_timestamp() - xact_start is how long the current transaction has been open, and it is null when no transaction is open. clock_timestamp() - state_change is how long the backend has been in its current state. For an active row that is roughly how long the query has been running. For an idle in transaction row it is how long the session has been sitting still. clock_timestamp() is used instead of now() because now() returns the start time of the current transaction and would drift if the query ran inside a longer transaction block.
Parallel workers and leader_pid
When a query runs with parallel workers, each worker appears as its own row with backend_type = 'parallel worker', and leader_pid holds the PID of the leader. A leader has a null leader_pid. The group query uses that: workers are rows with a non-null leader_pid, and leaders are rows whose pid appears as someone's leader_pid. Grouping with coalesce(leader_pid, pid) keeps each worker under its leader so a plan that launched eight workers reads as one unit and not nine unrelated sessions. A logical replication parallel apply worker also fills leader_pid, which is why the group query filters on backend_type.
pg_blocking_pids()
pg_blocking_pids(pid) returns an array of the PIDs blocking the given backend from acquiring a lock, or an empty array if there are none. A process counts as a blocker if it holds a conflicting lock (a hard block) or if it is waiting for a conflicting lock and sits ahead in the wait queue (a soft block). unnest() turns the array into one row per blocker, and the LEFT JOIN keeps the row even when the blocker has no matching session. That happens with a prepared transaction, which is represented by a zero process ID. Under parallel query the function reports client-visible PIDs and the array may contain duplicates, so add DISTINCT if the output is aggregated.
The function needs exclusive access to the lock manager's shared state for a short time, and frequent calls can affect performance. Run it ad hoc during an incident, or on a coarse polling interval, and not in a tight loop on a busy server.
Key Session States
The state column describes what the backend is doing, and each value points to a different next step.
active
The backend is executing a query. A non-null wait_event on an active row means the query is running but stuck on something: the two columns are independent. wait_event_type = 'Lock' means a heavyweight lock, IO means a read or write is outstanding, and Client means the backend is waiting on the application socket.
idle in transaction
The backend is inside a transaction but is not running a query. It can still hold locks, and an open transaction prevents vacuum from removing recently dead rows that only that transaction may still see. The query column shows the last statement the session ran, not a statement in progress. This is the state that most often shows up as the blocker in the third query.
idle in transaction (aborted)
Similar to idle in transaction, except one of the statements in the transaction caused an error. The session is waiting for the client to issue ROLLBACK.
idle, fastpath function call, and disabled
idle means the backend is waiting for a new client command. fastpath function call means the backend is executing a fast-path function. disabled is reported when track_activities is disabled for that backend. PostgreSQL 18 also reports starting for a backend still in initial startup and client authentication.
Practical Applications
The right query depends on what the incident looks like from the application side.
Latency spike with no deploy
Run the first query and sort the output by state. A cluster of active rows with wait_event_type = 'Lock' points to a blocking problem, which the third query traces to a specific blocking_pid. A cluster of active rows with IO waits points to reads or writes the storage is not keeping up with, and pg_stat_statements shows which statements are doing them.
Finding the head of a lock queue
When many sessions wait, they usually trace back to one blocker, and that blocker is frequently in the idle in transaction state with an old blocker_xact_age. The third query lists that session next to the sessions it holds up. The query shown for it is the last statement it ran, which is the clue for finding the code path that opened the transaction and never closed it. Cancelling or terminating the blocker is covered in the session termination procedure.
Checking whether parallel query is happening
After a configuration or index change that alters plans, the second query shows whether big reports now run with parallel workers and how many each leader has at that moment.
Capacity and pool sizing
Counting rows per state over time, for example once a minute into a log table, shows whether the pool is mostly idle, mostly active, or full of idle in transaction sessions. Each pattern calls for a different fix: a smaller pool, more capacity, or application changes to close transactions.
Version Compatibility
The state column arrived in PostgreSQL 9.2. PostgreSQL 9.6 added the wait_event_type and wait_event columns, replacing the earlier boolean waiting, and added pg_blocking_pids(). PostgreSQL 10 added backend_type and the predefined monitoring roles pg_monitor, pg_read_all_settings, pg_read_all_stats, and pg_stat_scan_tables.
PostgreSQL 13 added leader_pid, which the parallel-group query depends on. PostgreSQL 14 added query_id, shown when compute_query_id is enabled or a third-party module computes identifiers. It matches a running statement to its row in pg_stat_statements. PostgreSQL 18 adds the starting state, so code that checks for a fixed list of states should tolerate a value it does not know.
Query text in the view is truncated at 1,024 bytes by default; the limit is set by the track_activity_query_size parameter.
Best Practices
- Grant
pg_monitorto monitoring accounts — it exposes sessions and statistics without superuser rights, and without it the query text of other users' sessions is hidden. - Look at all states before filtering — excluding
idleis sensible for a "working now" view, but the idle-in-transaction rows are often the culprits. - Poll, do not sample once — the view has no history, so a slow query that ended between two manual checks leaves nothing behind.
- Limit
pg_blocking_pids()frequency — it briefly takes exclusive access to lock manager state, so run it on demand or every minute or so, not in a busy loop. - Cap the work of the monitor itself — set a short
statement_timeoutin the monitoring session so a diagnostic query never becomes the long-running statement. - Check the query text before acting — confirm
usenameandquerymatch the intended target before cancelling or terminating apid.
References
- PostgreSQL: The Cumulative Statistics System — Columns of
pg_stat_activity, session states, wait event types, and the privilege rules for seeing other sessions. - PostgreSQL: System Information Functions —
pg_blocking_pids()andpg_backend_pid(), including the note on hard and soft blocks and the lock manager cost. - PostgreSQL: pg_locks — Lock types, modes, and the
grantedcolumn used to see what a blocked session is waiting for. - PostgreSQL: Client Connection Defaults —
idle_in_transaction_session_timeout, including why an open idle transaction holds locks and prevents vacuuming away recently dead tuples. - PostgreSQL: Predefined Roles —
pg_monitor,pg_read_all_stats, andpg_signal_backend. - depesz: Understanding pg_stat_activity — A walk through the timestamp columns and states, including the difference between
query_startandstate_change. - Crunchy Data: One PID to Lock Them All — Tracing a lock wait from
pg_stat_activitythroughpg_locksto the blocking process.
Posts in this series
- How Many Connections Can Your PostgreSQL Database Handle?
- PostgreSQL Backend Connections via pg_stat_database
- pg_blocking_pids — Find Blocking Queries in PostgreSQL
- List PostgreSQL Databases by Size with Access Check
- Assess PostgreSQL Database Sizes Quickly and Easily
- Unveiling Your PostgreSQL Server - A Diagnostic Powerhouse
- Keep Your PostgreSQL Database Clean, Identify Idle Connections
- Query the PostgreSQL Configuration
- pg_is_in_recovery — Monitor PostgreSQL Standby Status
- ALTER SEQUENCE RESTART WITH in PostgreSQL — Examples
- Monitor Running Queries in PostgreSQL using pg_stat_activity
- Monitor PostgreSQL Active Sessions with pg_stat_activity
- PostgreSQL Error Handling Settings via pg_settings
- PostgreSQL File Location Settings Query via pg_settings
- Inspect PostgreSQL Lock Management Settings with pg_settings
- PostgreSQL Logging Configuration Query via pg_settings
- Monitor PostgreSQL Memory Settings with pg_settings
- PostgreSQL Table Row Count Estimates with SQL
- List PostgreSQL Tables by Size with SQL
- PostgreSQL WAL Settings Query Guide
- log_parser_stats, log_planner_stats, log_executor_stats — PostgreSQL
- PostgreSQL SSL Settings Query Guide
- PostgreSQL Resource Settings Query Guide
- PostgreSQL Replication Settings Query Guide
- PostgreSQL Query Planning Settings Query Guide
- PostgreSQL Preset Options Settings Query Guide
- PostgreSQL Miscellaneous Settings Query Guide
- Count PostgreSQL Sessions by State with SQL
- Kill Idle PostgreSQL Sessions with SQL
- GRANT SELECT on All Tables in PostgreSQL — with Examples
- pg_stat_user_tables — Find Insert-Only Tables in PostgreSQL
- Detect Soft Delete Patterns in PostgreSQL
- List PostgreSQL Object Comments with SQL
- List Foreign Key Constraints in PostgreSQL
- List PostgreSQL Enum Types and Their Values with SQL
- List All Views in a PostgreSQL Database with SQL
- Find PostgreSQL Tables Without a Primary Key
- List PostgreSQL Partitioned Tables with SQL
- List All Schemas in Your PostgreSQL Database
- pg_stat_database — Query PostgreSQL Database Statistics
- List PostgreSQL Roles and Their Privileges
- Scrubbing Email PII in PostgreSQL for GDPR Compliance
- List Installed Extensions in PostgreSQL
- List PostgreSQL Collations with pg_collation and ICU
- PostgreSQL Replica Identity for Logical Replication
- Monitor PostgreSQL Vacuum Progress with pg_stat_progress_vacuum
- Monitor PostgreSQL Wait Events Using pg_stat_activity
- Monitor PostgreSQL Replication Lag with pg_stat_replication
- List PostgreSQL Wait Events with the pg_wait_events View
- PostgreSQL Column-Level Permissions Audit Query
- List All PostgreSQL Triggers with Their State
- timestamptz and tzdata: Avoid Shifted PostgreSQL Timestamps
- Inspect PostgreSQL Sequences with the pg_sequences View
- List PostgreSQL Functions with pg_proc
- Query PostgreSQL Tablespace Info with pg_tablespace
- Audit PostgreSQL Authentication with pg_hba_file_rules
- List PostgreSQL Materialized Views with pg_matviews
- Audit Row-Level Security Policies with pg_policies
- List PostgreSQL Extension Objects with pg_describe_object