wrkm.app
Search
Databases

Kiran Kambale: PostgreSQL Monitoring Is Not the Same as Understanding an Incident

Why should every database engineer be asking one question after the alert fires: what actually happened?Most of the production incident ends the same way. The graphs turn green, the alert resolves, the chat channel goes quiet. Then someone asks the question that matters most: "What actually happened?" Most teams are very good at detecting problems. Far fewer are good at answering that question. This post is about the gap between the two, why it exists, and how we can start closin

Editor
Dec 1, 2026 · 10 min read
Kiran Kambale: PostgreSQL Monitoring Is Not the Same as Understanding an Incident

Why should every database engineer be asking one question after the alert fires: what actually happened?Most of the production incident ends the same way. The graphs turn green, the alert resolves, the chat channel goes quiet. Then someone asks the question that matters most:

"What actually happened?"

Most teams are very good at detecting problems. Far fewer are good at answering that question. This post is about the gap between the two, why it exists, and how we can start closing it.

Monitoring tells you that. Investigation tells you why.

Modern PostgreSQL environments generate enormous amounts of operational data: metrics, logs, statistics views, wait events, alerts. Monitoring systems are excellent at one job: telling you something needs attention.

But an alert is a starting point, not an explanation. Consider a production application that suddenly slows down. The dashboard shows higher query times, some sessions waiting, a few transactions open longer than expected. The engineer now has to reconstruct a story:

What happened before the slowdown started?

Which sessions and queries were involved?

Was one transaction blocking others?

What changed between normal behaviour and the incident?

What evidence supports the suspected cause, and what is only an assumption?

No single metric answers these. They need context, correlation and evidence.

The core problem: evidence is perishable

Here is the uncomfortable part. Most of what PostgreSQL shows you about right now is gone a few minutes later.

A view like pg_stat_activity is a live picture. By the time an engineer connects, the blocking transaction may have committed, the idle session may have disconnected, and the lock wait may have cleared. The database is healthy again, and the best clues have left the building.

-- 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;

Run this during an incident and it is gold. Run it ten minutes after and it is a picture of a different, calmer database. That is why incident investigations so often turn into guesswork.

(A note on access: seeing other users' queries in these views needs the right privileges, for example membership in pg_read_all_stats. Always follow least privilege.)

Six real-world scenarios

  1. Blocking sessions: which transaction is actually responsible?

Application requests suddenly get slow. Monitoring reports lock waits. But counting blocked sessions is only the beginning. The engineer needs to know who is holding the lock, since when, and what they are 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;

Notice what this reveals: the blocker is often not running anything. It is a session sitting idle inside an open transaction, still holding locks. One forgotten transaction can create a queue of waiting sessions across several workloads.

The important question is not how many sessions are blocked. It is what is holding them up, and what evidence explains it.

  1. Idle in transaction: the quiet troublemaker

Sessions that are idle in transaction look harmless. They use no CPU and run no query. But they can hold locks, hold back vacuum from cleaning dead rows, and eat 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;

The last_statementcolumn is a clue, not a verdict. It tells you what the session last ran, not necessarily what the application was doing when it stalled.

  1. Sudden query slowdown: what changed?

No deployment, no obvious trigger, and a query that used to take milliseconds now takes seconds. A slow query is a symptom. The investigation is figuring out 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;

That second query matters more than it looks. If statistics were reset recently, comparing "before" and "after" can be misleading. Good investigation checks the validity of its own evidence. ( pg_stat_statements_info is available from PostgreSQL 14.)

  1. Connection exhaustion: where did the connections go?

The application reports connection errors. The database is up, but it is out of slots. Raising max_connections may only hide the real issue.

-- 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';

If most sessions are idle, think about pooling. If many are idle in transaction, think about application behaviour. The same error message, "too many connections", can come from completely different root causes.

  1. Replication lag: is the standby behind, and since when?

A read replica serves stale data. Is it a network problem, a heavy 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 shows lag now. The question that matters for an investigation is: when did the lag begin, and what else changed at that moment?

  1. Autovacuum and dead tuples: a slow-burning incident

Not every incident is sudden. Sometimes a table quietly accumulates dead rows for days until performance falls off a cliff.

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;

Now connect this to scenario 2. An idle-in-transaction session from days ago may be the reason vacuum could not clean up. Two "separate" problems, one connected story. That is exactly the kind of link a single dashboard panel will never show you.

Bonus: the managed-cloud version

On AWS RDS, a Multi-AZ failover shows up as an event. The database comes back and applications reconnect. But why did it happen? Host health, storage, maintenance, a customer-requested change? Infrastructure events and PostgreSQL activity are two different perspectives on the same incident.

Importantly, a query running before a failover does not mean that query caused it. Evidence must be correlated, not assumed.

What if we simply kept the evidence?

Here is the idea that changed how I think about this. If live views are perishable, then the simplest improvement is not a smarter dashboard. It is to keep what the database showed us, with timestamps, so an investigation can look backwards.

Even a deliberately minimal version of the idea shows 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 the question "what was happening at 02:14?" has an answer, even if you ask it 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 cautions, because real systems demand them. Stored query text can contain sensitive values, so retention and access need real thought. And collection must be lightweight and read-only, because an investigation tool must never become the next incident.

Observed, suggested, unverified

There is a habit I now consider the heart of good incident work. Separate three things:

What was directly observed. For example, session 4127 held a lock for 11 minutes.

What the evidence suggests. For example, the blocking session was idle in a transaction, which is consistent with an application not committing.

What still needs to be verified. For example, which application code path left the transaction open?

A blocked query does not prove it caused an outage. High CPU does not say which activity produced it. A failover does not prove PostgreSQL workload triggered it. A good investigation never blurs these lines, and it never invents a metric it did not collect.

What I want to do about it

This is the question I keep coming back to, and the one I think every database team should sit with:

After an incident, can we reconstruct what happened, in what order, with what evidence, and with what still unknown?

My goal is to make that question easier to answer for DBAs, support engineers and SREs. Not by adding another wall of graphs, but by treating an incident as something to be reconstructed from evidence: a timeline, correlated signals, and clearly labelled hypotheses that point to where to investigate next. Monitoring stays essential. It just shouldn't be the end of the story.

Why this matters beyond one incident

When an incident is understood, a team gets real value from it:

Recurring patterns become visible, because the "mystery" from March looks a lot like the one from October.

Troubleshooting becomes repeatable instead of heroic.

Gaps in monitoring become obvious.

Engineers spend less time re-investigating and more time preventing.

When an incident is not understood, it simply waits to return.

Final thoughts

PostgreSQL already exposes a remarkable amount of information about itself. The opportunity is in preserving it, connecting it, and interpreting it honestly while the incident is still fresh.

An alert tells us something needs attention. Evidence lets us investigate. Context helps us understand.

So the next time your dashboard turns green, don't close the tab just yet. Ask the better question: what actually happened?

Written from the perspective of PostgreSQL production support and database engineering.

Further reading

PostgreSQL Monitoring Statistics

pg_stat_statements

Amazon RDS Multi-AZ failover

Amazon RDS event monitoring

  The post PostgreSQL Monitoring Is Not the Same as Understanding an Incident appeared first on CYBERTEC PostgreSQL | Services & Support.

Kaynak: Planet PostgreSQL

#PostgreSQL
Share

From other categories