skip to content

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%

answer

  1. sample many times, then count
  2. class first, then event name
  3. Lock is not LWLock
  4. ClientRead on idle is normal
  5. NULL while active: on CPU

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.

solid answer

~40 s

One snapshot is noise, so I sample active client backends every second for a minute and count by `wait_event_type` and `wait_event`. `Lock` (`relation`, `transactionid`, `tuple`) means sessions queue for heavyweight locks: go to `pg_blocking_pids()`. `LWLock` (`LockManager`, `BufferMapping`, `WALInsert`) is contention on shared-memory structures, with no session to kill. `IO` (`DataFileRead`, `WalSync`) is waiting on reads or flushes, often a plan reading too much. `IPC` / `SyncRep` waits for a synchronous standby. `Client` / `ClientRead` is normal for idle sessions. An `active` row with NULL waits is executing, typically on CPU. Grouping by `query_id` ties waits to statements, and since 17 `pg_wait_events` describes every event.

code

sql · 12 lines
sql
SELECT coalesce(a.wait_event_type, 'none') AS wait_type,
       coalesce(a.wait_event, 'none')      AS wait_event,
       count(*)                            AS sessions,
       min(w.description)                  AS what_it_means
FROM pg_stat_activity a
LEFT JOIN pg_wait_events w
       ON w.type = a.wait_event_type AND w.name = a.wait_event
WHERE a.state = 'active'
  AND a.backend_type = 'client backend'
  AND a.pid <> pg_backend_pid()
GROUP BY 1, 2
ORDER BY sessions DESC;

go deeper

for a junior

Recall that wait_event_type is the class and wait_event the specific wait point, and that both are NULL when a backend is not waiting.

for a middle

Explain the main classes, why ClientRead on idle sessions is normal, and why Lock waits lead to pg_blocking_pids while LWLock waits do not.

for a senior

Show a sampling method that counts waits over time, reads NULL as CPU, ties waits to statements through query_id, and avoids the one-picture-per-transaction trap.

for a principal

Discuss building wait-event sampling into permanent monitoring, choosing sample rates and retention, and how wait profiles steer decisions about CPU, storage and connection capacity.

## Two columns, two levels Every row of `pg_stat_activity` carries `wait_event_type`, the **class** of thing a backend is waiting for, and `wait_event`, the **specific wait point** within that class. Both are NULL when the backend is not waiting. Wait events turn a vague 'the database is slow' into a statement about where sessions spend their time, and the class tells you which tool to reach for next. ## Sample, don't glance A single query of the view is one instant and mostly noise. Useful triage samples many times and counts: 1. Filter to `state = 'active'` client backends, excluding your own session with `pg_backend_pid()`. 2. Group by `wait_event_type` and `wait_event` and count. 3. Repeat every second or so for a minute (psql's `\watch` does this) and see which buckets dominate. Run each sample in its own transaction: within one transaction PostgreSQL collects the activity data on first access and shows the same picture until the transaction ends, unless you call `pg_stat_clear_snapshot()`. ## The classes and what they point at | `wait_event_type` | Example `wait_event` | Sessions are waiting for | Next step | |---|---|---|---| | `Lock` | `relation`, `transactionid`, `tuple`, `extend` | A heavyweight lock held or requested by another session | `pg_blocking_pids()` to find the root | | `LWLock` | `LockManager`, `BufferMapping`, `BufferContent`, `WALInsert`, `WALWrite` | A lightweight lock protecting a shared-memory structure | Reduce contention; there is no session to end | | `IO` | `DataFileRead`, `WalSync`, `AioIoCompletion` | A read, write or flush to complete | Check plans, cache fit and storage latency | | `IPC` | `SyncRep` | Another server process, e.g. a synchronous standby's confirmation | Check what it waits on | | `Client` | `ClientRead`, `ClientWrite` | The application to send a command or read results | Look at the application | | `Timeout` | `PgSleep` | A deliberate sleep | Usually intentional | | `BufferPin` | `BufferPin` | Exclusive access to a buffer another process has pinned | Look for long-open cursors | | `Activity` | `WalWriterMain` | A background process idling in its main loop | Normal | Readings that come up often: - **`Client` / `ClientRead` on idle sessions is normal**: an idle backend waits for its next command. On an `idle in transaction` row it means the application is holding a transaction open while doing something else. - **`ClientWrite` on active sessions** means the server has results ready and the client is not reading them fast enough. - **`Lock` and `LWLock` are different worlds.** Heavyweight locks are taken on tables, rows and transactions and can be traced to a blocking session; lightweight locks guard internal shared-memory structures for very short periods, and a pile-up on one points at contention, not at a culprit. `LockManager`, for instance, is contention on the shared state that records heavyweight locks, typically when many sessions each lock many relations. - **`IO` / `DataFileRead`** means pages were not in `shared_buffers`. That may be slow storage, but just as often a plan that reads far more data than it should. In PostgreSQL 18, with asynchronous I/O, a backend waiting for an I/O that another process (such as an I/O worker) is completing shows `AioIoCompletion`. ## Reading NULL An `active` row with both wait columns NULL is **not waiting on any instrumented event**. Usually that means it is executing on CPU: evaluating expressions, sorting in memory, hashing. A sample dominated by NULL waits points to CPU-bound queries, and the question becomes which queries and why (plans and statistics belong to their own topics). Two caveats: not every code path reports a wait event, and PostgreSQL does not synchronize a row's columns, so brief inconsistencies between them are possible. ## From a wait to a statement A wait profile is more actionable when tied to statements: - **Group by `query_id` too.** It identifies the normalized statement and matches `pg_stat_statements.queryid`. It is NULL unless query identifiers are computed, which with the default `compute_query_id = auto` happens once a module such as `pg_stat_statements` asks for it (that setting and the extension belong to the query-statistics topic). - **Look events up in SQL.** Since PostgreSQL 17 the `pg_wait_events` view lists every wait event with a description, so a join on type and name explains an unfamiliar event without leaving psql.

  • Why does running the same pg_stat_activity query twice inside one PostgreSQL transaction show identical rows?
    Information about the current queries of all sessions is collected when first requested in a transaction and the same picture is shown until the transaction ends. Run each sample as its own statement in autocommit mode, or call `pg_stat_clear_snapshot()` between samples.
  • Many active PostgreSQL sessions show wait_event_type 'LWLock' and wait_event 'LockManager'. Is pg_blocking_pids() the right tool?
    No. `LockManager` is a lightweight lock guarding the shared state that records heavyweight locks; sessions are contending to update that bookkeeping, typically because each locks many relations at a high rate. `pg_blocking_pids()` covers heavyweight lock requests only and returns empty arrays here. The fix is in the workload: fewer relations touched per query, fewer concurrent sessions.
  • How do you connect a wait profile to the statements causing it?
    Add `query_id` to the grouping and join it to `pg_stat_statements.queryid`. It is only populated when query identifiers are computed, which the default `compute_query_id = auto` does once `pg_stat_statements` is loaded; those settings belong to the query-statistics topic.

  • An active session with a NULL wait_event must be stuck.
  • LWLock waits are cleared by terminating the session pg_blocking_pids names.
  • Many idle sessions waiting on ClientRead mean the server is overloaded.
  • One pg_stat_activity snapshot shows where the time goes.
  • Any IO wait proves the disks are too slow.

Assumes PostgreSQL 18; the pg_wait_events view exists since 17, and the AioIoCompletion wait comes with 18's asynchronous I/O.