skip to content

Monitoring & Diagnostics

PostgreSQL exposes its own health through pg_stat_activity, the cumulative statistics views, pg_stat_statements and the server log. Interviewers hand you a slow database and ask where to look.

part ofPostgreSQLread it →
on this pageshow

explore

questions

15

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, what do log_statement and log_min_duration_statement each log, and which one catches slow queries?

level: juniorimportance: must knowfreq 68%

basics

~20 s

log_statement logs statements by class (none, ddl, mod, all) before they run, with no duration. log_min_duration_statement logs every completed statement that ran at least its threshold, in milliseconds (-1 disables it). Only the second one catches slow queries.

open as a page

In PostgreSQL, how do you find which tables of a database take the most disk space, and why sort by pg_total_relation_size rather than pg_relation_size?

level: juniorimportance: must knowfreq 62%

basics

~20 s

Select pg_total_relation_size(relid) from pg_stat_user_tables, order by that bigint and wrap it in pg_size_pretty only for display. It counts the heap, its free space and visibility maps, TOAST and every index; pg_relation_size returns just the main fork.

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

In PostgreSQL, how do you use pg_stat_statements to find the query costing the most total time, and why not rank by mean_exec_time?

level: middleimportance: must knowfreq 72%

basics

~20 s

Query pg_stat_statements ordered by total_exec_time, which is calls times mean time per normalised query. A 3 ms query run two million times outweighs one 45-second report, so ranking by mean finds slow queries rather than expensive ones.

open as a page

In PostgreSQL, which pg_stat_user_tables counters suggest a table is missing an index, and how do you avoid false alarms when reading them?

level: middleimportance: must knowfreq 66%

basics

~20 s

Look for large tables where seq_scan is high, seq_tup_read divided by seq_scan is close to the row count, and idx_scan is low or NULL. Then confirm with the actual queries, because small tables, exports and batch jobs scan sequentially by design.

open as a page

In PostgreSQL, how do you compute the shared-buffer hit ratio from pg_stat_database and pg_statio_user_tables, and what does blks_read not tell you?

level: middleimportance: should knowfreq 48%

basics

~20 s

The ratio is blks_hit / (blks_hit + blks_read) in pg_stat_database, or each heap, index and TOAST hit/read pair per table in pg_statio_user_tables. A blks_read is a block requested from the kernel, which may still come from the OS page cache, not disk.

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 18, how would you configure auto_explain to log plans of slow queries in production without heavy instrumentation overhead?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Set auto_explain.log_min_duration to a threshold. With log_analyze on, instrumentation runs for every sampled statement, slow or not, so use log_timing = off and a sample_rate below 1. Turn on log_buffers yourself: it stays off by default in 18.

open as a page

On a PostgreSQL 18 server, what do log_lock_waits, log_temp_files and log_connections add to the log, and how should log_line_prefix support them?

level: seniorimportance: should knowfreq 45%

basics

~20 s

log_lock_waits logs any lock wait longer than deadlock_timeout, with holders and queue. log_temp_files logs temporary files above a size in kB. log_connections, a list since 18, logs connection stages and setup time. log_line_prefix adds user, database, application and query ID.

open as a page

With the pgAudit extension on PostgreSQL, how do session and object audit logging differ, and why is log_statement = 'all' not enough for an audit?

level: seniorimportance: should knowfreq 30%

basics

~20 s

log_statement records only the text a client sent, so dynamic SQL and substatements are lost. pgAudit session logging records classes of statements (pgaudit.log = 'read, write, ddl'). Object logging records SELECT and DML on whatever the pgaudit.role role has been granted.

open as a page

On a PostgreSQL server, why is calling pg_stat_reset() before a load test risky, and how should you measure cumulative-statistics changes over a time window instead?

level: seniorimportance: should knowfreq 30%

basics

~20 s

pg_stat_reset() zeroes every counter of the current database, including the dead-tuple and modification counts autovacuum uses to decide when to vacuum and analyze, so needed maintenance can be skipped. Snapshot the views with now(), run the test, and subtract instead.

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

In PostgreSQL 18, how do you use pg_stat_io to tell whether client backends are writing out and evicting shared buffers themselves, and what changed in the view in 18?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

Filter pg_stat_io to client backend, relation, normal context: many writes or fsyncs suggest backends flush dirty pages the checkpointer and background writer should handle, and high evictions hint at small shared buffers. PostgreSQL 18 replaced op_bytes with byte columns and added WAL rows.

open as a page