Monitoring with pg_stat views & pg_stat_statements
Find the slowest and most frequent queries on a running server.
By Invicly Tech, , in SQL & PostgreSQL. About 10 minutes to read.
In short
Postgres records what it is doing in pg_stat views. pg_stat_activity shows live sessions, and the pg_stat_statements extension aggregates every query shape so you can find the slowest and most frequent queries.
Explained simply
A database is a black box until you ask it what it is doing. Postgres keeps live counters about itself in system views whose names start with pg_stat. They tell you who is connected, what is running right now, which tables are read most and which queries cost the most.
pg_stat_activity is the "right now" view. It has one row per connection: who it is, which query it runs, how long it has been running, and whether it is waiting for something, like a lock.
pg_stat_statements is the "over time" view. It is an extension that groups every query by its shape (with the values replaced by $1, $2) and adds up how often it ran and how long it took in total. That turns "the database feels slow" into a ranked list of queries to fix.
Good monitoring answers three questions fast: is the database healthy right now, what changed, and which queries should I look at first?
Press Play on a diagram to walk through it one step at a time.
- 1Enable extension
shared_preload_libraries, then CREATE EXTENSION
- 2Let traffic run
Stats collect per normalised query
- 3Sort by total time
calls times mean time = real load
- 4EXPLAIN the top few
Find the slow plan node
- 5Fix & reset stats
pg_stat_statements_reset(), then compare
- What is running now?
- pg_stat_activity
- pg_locks
- Which queries cost most?
- pg_stat_statements
- Which tables need indexes or vacuum?
- pg_stat_user_tables
- Which indexes are unused?
- pg_stat_user_indexes
- How healthy is the database?
- pg_stat_database
- pg_stat_replication
In depth
Reading pg_stat_activity
Each row is one backend process. Useful columns: pid (process ID, used to cancel it), usename and application_name (who; set application_name in your connection string so you can tell services apart), client_addr, state, wait_event_type and wait_event, xact_start (when the transaction began), query_start, and query (the current or last statement).
The state column matters most. active means running a query now. idle means connected and doing nothing, which is fine. idle in transaction means a transaction is open but no query is running: the app forgot to commit or is doing slow work in the middle. Those sessions hold locks and old snapshots. idle in transaction (aborted) means an error happened and nobody has rolled back yet.
wait_event_type tells you why an active query is not using the CPU: Lock (waiting for another transaction), IO (reading from disk), LWLock (internal contention), or Client (waiting for the app to read results). The backend_type column separates client backends from autovacuum and other background workers.
- state = 'active' with old query_start: long query
- state = 'idle in transaction' for minutes: fix the app
- wait_event_type = 'Lock': use pg_blocking_pids
- Set application_name per service
Setting up and using pg_stat_statements
The module must be loaded at server start: add pg_stat_statements to shared_preload_libraries in postgresql.conf, restart, then run CREATE EXTENSION pg_stat_statements in the database where you want to read it. Managed services usually have it preloaded already. It is cheap enough that most production servers leave it on.
It keeps one row per query shape (identified by queryid), per user and database, up to pg_stat_statements.max entries (5,000 by default). Key columns: calls, total_exec_time and mean_exec_time (in milliseconds), rows, and shared_blks_hit and shared_blks_read for cache behaviour.
Rank by total_exec_time to find where the server spends its time. Rank by calls to find chatty N+1 patterns. Rank by mean_exec_time to find individually slow queries, and by shared_blks_read for queries that read a lot from disk. After a fix, call pg_stat_statements_reset() so new numbers are not mixed with old ones, or compare snapshots taken before and after.
- Where the server's time goes
- Best first view
- Fixes here help the most
- Chattiest queries
- Spots N+1 loops
- Candidates for batching or caching
- Slowest single runs
- Reports and missing indexes
- What users feel on one page
Table, index and database statistics
pg_stat_user_tables has one row per table: seq_scan and idx_scan (how often each kind of scan happened), n_live_tup and n_dead_tup, and the last vacuum and analyze times. A big table with a high seq_scan count usually means a missing index.
pg_stat_user_indexes shows idx_scan per index, so you can find unused ones. pg_statio_user_tables shows heap_blks_hit and heap_blks_read, from which you get a cache hit ratio; busy OLTP databases usually sit above 99 percent.
pg_stat_database gives per-database totals: commits, rollbacks, deadlocks, temp_files and temp_bytes (queries spilling to disk). pg_stat_replication shows replicas and their lag. PostgreSQL 16 added pg_stat_io, which breaks I/O down by backend type and context.
These counters are cumulative since the last reset, so look at how they change over time, not at the raw number. That is exactly what monitoring tools do.
Logs, alerts and tools
Some answers are easier to get from the server log. log_min_duration_statement = '500ms' logs every statement slower than half a second with its duration. log_lock_waits = on logs waits longer than deadlock_timeout. log_temp_files = 0 logs every temp file, which shows sorts that spill. log_autovacuum_min_duration shows slow vacuums. Most of these can be changed with ALTER SYSTEM and a reload, without restarting.
For dashboards and alerts, most teams scrape the pg_stat views on a schedule: Prometheus with postgres_exporter and Grafana, or pgwatch, pganalyze, Datadog and similar services. pg_activity gives a top-like live view in the terminal.
Useful alerts: connections near max_connections, sessions idle in transaction for more than a few minutes, replication lag, rising age(datfrozenxid), failed backups, disk space, and a sudden jump in the total time of one query.
- 1Grafana dashboards and alerts
Graphs, thresholds, paging
- 2Prometheus
Stores the time series
- 3postgres_exporter
Turns pg_stat views into metrics
- 4pg_stat views + pg_stat_statements
Counters inside Postgres
- 5Server log
Slow statements, lock waits, temp files
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Query pg_stat_activity~40m
- 2Enable pg_stat_statements~40m
- 3Find slowest and most frequent queries~40m
Key points
- pg_stat_activity shows each connection's state, query and wait event.
- "idle in transaction" sessions hold locks and block vacuum.
- Rank by total_exec_time to find the biggest overall cost.
- A fast query called a million times can matter more than one slow report.
Key terms
Tap a card to flip it. 0/5 known
Examples
-- postgresql.conf: shared_preload_libraries = 'pg_stat_statements'
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT calls,
round(total_exec_time) AS total_ms,
round(mean_exec_time, 2) AS mean_ms,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
SELECT pid, state, wait_event_type, now() - query_start AS running_for, query
FROM pg_stat_activity WHERE state <> 'idle';A five-minute health check during an incident
Users report slow pages. Step 1: count connections by state; 180 of 200 connections are active, so the server is saturated. Step 2: list the longest-running active queries; dozens are the same report query, each running for 40 seconds. Step 3: cancel them with pg_cancel_backend, which stops the query but keeps the connection. Step 4: afterwards, look up that query in pg_stat_statements and EXPLAIN it to fix the cause.
SELECT state, count(*) FROM pg_stat_activity
WHERE backend_type = 'client backend' GROUP BY state;
SELECT pid, now() - query_start AS running_for, wait_event_type,
application_name, left(query, 80) AS query
FROM pg_stat_activity
WHERE state = 'active' AND pid <> pg_backend_pid()
ORDER BY query_start
LIMIT 10;
SELECT pg_cancel_backend(pid) FROM pg_stat_activity
WHERE state = 'active' AND query LIKE 'SELECT /* monthly_report */%'
AND now() - query_start > interval '30 seconds';A weekly top-queries report
Every Monday the team reviews the queries that used the most database time. Step 1: select the top 10 by total time, with calls, mean time, the share of all time, and cache hit percentage. Step 2: pick the top two to investigate with EXPLAIN. Step 3: after deploying fixes, reset the statistics so next week's report shows only new behaviour.
SELECT queryid, calls,
round(total_exec_time) AS total_ms,
round(mean_exec_time, 2) AS mean_ms,
round(100 * total_exec_time / sum(total_exec_time) OVER (), 1) AS pct_time,
round(100.0 * shared_blks_hit
/ nullif(shared_blks_hit + shared_blks_read, 0), 1) AS hit_pct,
left(query, 70) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
-- after fixes are deployed:
SELECT pg_stat_statements_reset();Quick reference
- shared_preload_libraries = 'pg_stat_statements' (restart), then CREATE EXTENSION pg_stat_statements;
- ORDER BY total_exec_time DESC: where time goes; ORDER BY calls DESC: N+1 suspects
- SELECT state, count(*) FROM pg_stat_activity GROUP BY state;
- pg_cancel_backend(pid) stops a query; pg_terminate_backend(pid) closes the session
- log_min_duration_statement = '500ms' log slow statements
- seq_scan high on a big table in pg_stat_user_tables suggests a missing index
- Add application_name=checkout to connection strings to tell services apart
- Counters are cumulative: compare over time or reset with pg_stat_statements_reset()
Common mistakes
- Creating the extension without preloading the library, so it errors.
- Only looking at mean time and missing very frequent queries.
- Never resetting stats, so old behaviour hides recent changes.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
List all sessions that have been idle in transaction for more than 5 minutes, with user, application and the last query.
- Exercise 2medium
Find the 5 most frequently called queries and the 5 with the highest mean time, using pg_stat_statements.
- Exercise 3hard
Compute the table cache hit ratio for the database, and list the 5 large tables with the most sequential scans.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does pg_stat_statements slow down the server?
- The overhead is small for most workloads, which is why it is commonly left on in production. Very high query rates with many distinct queries see a little more cost.
- Why do I see $1 instead of real values in pg_stat_statements?
- Queries are normalised so that the same statement with different values is grouped together. To see real values for one slow run, use the server log or auto_explain.
- How do I see the database size?
- SELECT pg_size_pretty(pg_database_size(current_database())); for the whole database, or pg_total_relation_size('table') for one table including its indexes and TOAST data.