Detection is solved; explanation is not
Production incidents usually end the same way: charts return to normal, the alert clears, the channel falls silent. The question that matters rarely gets a satisfying answer — what actually happened? Teams are generally strong at noticing that something went wrong and much weaker at reconstructing why. PostgreSQL environments produce large volumes of operational data — metrics, logs, statistics views, wait events, alerts — and monitoring tools do one job well: flagging that something needs attention. An alert marks a starting point, not an explanation.
Take an application that suddenly slows down. The dashboard shows longer query times, some sessions waiting, a few transactions open longer than expected. Turning that into a story requires context, correlation and evidence: what preceded the slowdown, which sessions and queries were involved, whether one transaction blocked others, what differed from normal behaviour, and which parts of the suspected cause are assumption rather than proof. No single metric answers any of these.
Evidence has a short shelf life
Most of what PostgreSQL reports about "now" is gone within minutes. pg_stat_activity is a live snapshot: by the time an engineer connects, the blocking transaction may have committed, the idle session may have disconnected, the lock wait may have cleared. The database looks healthy again and the best clues have vanished.
-- A live view. It tells you about this moment only.
SELECT pid, usename, state, wait_event_type, wait_event,
now() - xact_start AS xact_age,
left(query, 80) AS query
FROM pg_stat_activity
WHERE backend_type = 'client backend'
ORDER BY xact_start NULLS LAST;
Executed during the incident, that query is invaluable. Executed ten minutes later, it describes a different, calmer database — which is why investigations so often degrade into guesswork. Seeing other users' queries in these views also requires appropriate privileges, such as membership in pg_read_all_stats; least privilege still applies.
Six scenarios and the question behind each
Which transaction is actually blocking?
Requests slow down and monitoring reports lock waits, but counting blocked sessions is only the start. You need the holder of the lock, since when, and what it is doing.
SELECT blocked.pid AS blocked_pid,
blocked.usename AS blocked_user,
now() - blocked.query_start AS waiting_for,
left(blocked.query, 60) AS blocked_query,
blocking.pid AS blocking_pid,
blocking.state AS blocking_state,
now() - blocking.xact_start AS blocking_xact_age,
left(blocking.query, 60) AS blocking_last_query
FROM pg_stat_activity AS blocked
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid) ON true
JOIN pg_stat_activity AS blocking ON blocking.pid = b.pid
ORDER BY waiting_for DESC;
Frequently the blocker is running nothing at all — it sits idle inside an open transaction, still holding locks. A single forgotten transaction can queue up waiting sessions across several workloads. The useful question is not how many sessions are blocked but what is holding them up and what evidence explains it.
The quiet trouble with idle transactions
Idle-in-transaction sessions burn no CPU and run no query, yet they can retain locks, prevent vacuum from cleaning dead rows, and consume connection slots.
SELECT pid, usename, application_name, client_addr,
now() - xact_start AS xact_age,
now() - state_change AS idle_for,
left(query, 80) AS last_statement
FROM pg_stat_activity
WHERE state IN ('idle in transaction', 'idle in transaction (aborted)')
ORDER BY xact_start;
Treat last_statement as a clue rather than a verdict: it shows what the session last ran, not necessarily what the application was doing when it stalled.
A query slows down with no deployment in sight
A slow query is a symptom; the work is finding what changed around it.
-- Which statements consumed the most time?
SELECT queryid,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(total_exec_time::numeric, 2) AS total_ms,
rows,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
-- Can we even trust a comparison? Check when stats were last reset.
SELECT stats_reset FROM pg_stat_statements_info;
The second query matters because recent statistics resets make before-and-after comparisons misleading — a sound investigation validates its own evidence. pg_stat_statements_info has been available since PostgreSQL 14.
Where did the connections go?
The database is up but out of slots, and the application reports connection errors. Raising max_connections may only mask the underlying problem.
-- Who is using the connections, and in what state?
SELECT usename, application_name, state, count(*) AS sessions
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY usename, application_name, state
ORDER BY sessions DESC;
-- How close to the limit are we?
SELECT count(*) AS in_use,
current_setting('max_connections')::int AS max_allowed
FROM pg_stat_activity
WHERE backend_type = 'client backend';
Predominantly idle sessions point toward pooling; many idle-in-transaction sessions point toward application behaviour. The same "too many connections" error can have completely different root causes.
Is the standby lagging, and since when?
A read replica returns stale data: network issue, write burst, or a long-running query on the standby?
-- On the primary
SELECT application_name, client_addr, state,
pg_wal_lsn_diff(sent_lsn, replay_lsn) AS replay_gap_bytes,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
This measures lag now. For the investigation, what matters is when the lag began and what else changed at that moment.
Dead tuples as a slow-burning incident
Not every incident is sudden. A table can accumulate dead rows for days before performance drops sharply.
SELECT relname,
n_live_tup,
n_dead_tup,
round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
last_autovacuum,
last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;
Connect this to the idle-in-transaction case: a session left open days earlier may be exactly why vacuum could not clean up. Two apparently separate problems, one story — the kind of link no single dashboard panel reveals.
Managed clouds add a second perspective
On AWS RDS, a Multi-AZ failover appears as an event; the database returns and applications reconnect. The open question is why it happened — host health, storage, maintenance, a customer-requested change — and infrastructure events versus PostgreSQL activity are two views of the same incident. A query running before a failover does not mean the query caused it: correlate evidence, don't assume it.
Keep the evidence instead of only watching the present
If live views expire, the simplest improvement is not a smarter dashboard but retaining what the database showed, with timestamps, so investigations can look backwards. Even a deliberately minimal version illustrates the difference:
CREATE TABLE evidence_activity ( captured_at timestamptz NOT NULL DEFAULT now(), pid int, usename name, application_name text, state text, wait_event_type text, wait_event text, xact_start timestamptz, query_start timestamptz, blocking_pids int[], query text ); -- Run on a schedule, for example every 10 to 30 seconds INSERT INTO evidence_activity SELECT now(), pid, usename, application_name, state, wait_event_type, wait_event, xact_start, query_start, pg_blocking_pids(pid), query FROM pg_stat_activity WHERE backend_type = 'client backend' AND pid <> pg_backend_pid();
Now "what was happening at 02:14?" remains answerable the next morning:
SELECT captured_at, pid, usename, state, wait_event, blocking_pids, left(query, 60) AS query FROM evidence_activity WHERE captured_at BETWEEN '2026-11-20 02:10' AND '2026-11-20 02:20' AND (cardinality(blocking_pids) > 0 OR state LIKE 'idle in transaction%') ORDER BY captured_at, pid;
Two constraints come with this. Stored query text may contain sensitive values, so retention and access need serious thought. And collection must stay lightweight and read-only — an investigation tool must never become the next incident.
Separate observation, inference and open questions
Sound incident work rests on keeping three categories distinct:
- Directly observed — for example, session 4127 held a lock for 11 minutes.
- Suggested by the evidence — for example, the blocking session was idle in a transaction, consistent with an application failing to commit.
- Still to be verified — for example, which code path left the transaction open.
A blocked query does not prove it caused an outage, high CPU does not identify the activity behind it, and a failover does not prove PostgreSQL workload triggered it. Good investigation never blurs these lines and never invents a metric it did not collect.
The test that matters after every incident
Can we reconstruct what happened, in what order, with what evidence, and with what still unknown?
Answering that for DBAs, support engineers and SREs means treating an incident as something reconstructed from evidence: a timeline, correlated signals, and clearly labelled hypotheses pointing to where to investigate next. Monitoring remains essential — it just shouldn't be the end of the story. Understanding an incident also pays off across future ones: recurring patterns become visible, troubleshooting turns repeatable rather than heroic, monitoring gaps stand out, and engineers spend less time re-investigating and more time preventing. An incident that is not understood simply waits to return.
PostgreSQL already exposes a remarkable amount of information about itself; the opportunity lies in preserving it, connecting it, and interpreting it honestly while the incident is fresh. An alert tells us something needs attention, evidence lets us investigate, and context helps us understand. So when the dashboard turns green, don't close the tab yet — ask what actually happened.



