On this page
- Why these eight gauges
- Gauge 1: backends vs max_connections
- Gauge 2: idle-in-transaction sessions
- Gauge 3: buffer cache hit ratio
- Gauge 4: blocking locks
- Gauge 5: deadlocks since stats reset
- Gauge 6: transaction-ID freeze age
- Gauge 7: replication lag (or no replica at all)
- Gauge 8: inactive replication slots
- Watch the same eight gauges in Prism
Why these eight gauges
A Postgres outage is rarely a surprise in hindsight. Connection slots fill, a session sits idle in a transaction, a replica stops applying WAL, or freeze age walks toward wraparound. These eight gauges are the ones that fire first.
I (Marcos) ran every Check below on a fresh `postgres:16.11-bookworm` container on 2026-12-05. Config-file holes (TLS off, `trust` in pg_hba) stay on [/blog/postgres-security-101](/blog/postgres-security-101).
Gauge 1: backends vs max_connections
PostgreSQL starts one client backend per session. Background workers (checkpointer, walwriter, autovacuum launcher, …) also appear in `pg_stat_activity` and are not connection slots. When the non-reserved slots are gone, new clients get `FATAL: too many connections` — including health checks and the exporter. Prism warns at 80% and pages at 95%.
Check: percent of client slots in use
This image ships `max_connections = 100` and `superuser_reserved_connections = 3`, so 97 slots are for ordinary clients. Count only `backend_type = 'client backend'`. You care when the ratio climbs and stays there, not about a single admin `psql`.
What to look for: On postgres:16.11-bookworm this returned max_conn=100, superuser_reserved=3, client_backends=1, pct_of_nonreserved=1.0. The unfiltered `count(*)` on the same image is 6 because it includes five background workers. Treat 80% as a warning and 95% as imminent refusal of new clients.
Fix: find the hogs, then reap idle transactions
Group by user and application before you raise `max_connections` (that one needs a restart). Set a timeout so abandoned sessions give the slot back on reload.
Verify it worked: SHOW idle_in_transaction_session_timeout; -- 10min (was 0)
Note: A pg_monitor login cannot ALTER SYSTEM — we got `permission denied to set parameter "idle_in_transaction_session_timeout"`. Keep the exporter on pg_monitor; run this Fix as an operator.
Gauge 2: idle-in-transaction sessions
`idle in transaction` means BEGIN happened and nobody COMMITted. That session holds locks and an MVCC snapshot, so VACUUM cannot reclaim rows. Left alone, this is the on-ramp to wraparound.
Check: who is sitting in an open transaction?
A fresh image returns zero rows. I opened `BEGIN; SELECT 42;` and left the session connected: one `postgres` backend, query `SELECT 42;`, state `idle in transaction`.
What to look for: Zero rows is healthy. Any row that is minutes old is a finding. Prism warns when more than five such sessions sit for ten minutes.
Fix: terminate the abandoned session
After the timeout GUC from gauge 1, you can still clear what is already stuck. This ends the backend; the client must reconnect.
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction'
AND state_change < now() - interval '5 minutes';Verify it worked: SELECT count(*) FROM pg_stat_activity WHERE state = 'idle in transaction'; -- 0
Note: prometheus_exporter could not terminate the superuser backend: `permission denied to terminate process`. pg_monitor does not include pg_signal_backend.
Gauge 3: buffer cache hit ratio
Hit ratio is `blks_hit / (blks_hit + blks_read)` since stats reset. A healthy OLTP cache sits at 99%+. When it drops through 95% for half an hour, disk latency owns p99. That is an outage you feel as "the database is slow" before it is down.
Check: hit ratio per database
Skip template databases. On this image `postgres` started at 95.50% (5820 hit / 274 read) and rose to 98.52% after the rest of the lab writes.
What to look for: Below 95% for a sustained window is the warning Prism fires. A tiny hit_pct on a database you just created is a cold cache, not a finding.
Fix: see which tables miss, then ANALYZE
`shared_buffers` on this image is 128MB. Changing it needs a restart — do not treat ALTER SYSTEM as enough. Find cold heaps first, then refresh planner stats.
Verify it worked: SHOW shared_buffers; -- 128MB on this image; a restart is required to raise it
Note: The exporter could SELECT the views and could not INSERT into a user table (`permission denied for table blog_lab_rows`). That is the deny-case you want.
Gauge 4: blocking locks
One un-granted lock is a queue. DDL taking AccessExclusive, or a long UPDATE holding a row, stacks every new waiter behind it. That is the classic self-DDoS: p99 spikes, then the pool is empty.
Check: locks that are not granted
Fresh image: zero rows. I held `UPDATE blog_lock … WHERE id = 1` in one session and issued the same UPDATE in another: waiter `ShareLock` on `transactionid`, `granted = f`, `wait_event_type = Lock`.
What to look for: Zero rows is healthy. Any `granted = f` row is a waiter. Read the query before you cancel anything.
Fix: find the blocker, then cancel that pid
`log_lock_waits` is `off` on this image. Turn it on so the logs name the blocker. `pg_blocking_pids(pid)` on a waiter returns the pid holding the lock. Cancel that one pid by hand — a blanket `pg_cancel_backend` on every `wait_event_type = 'Lock'` row kills the waiters and leaves the blocker running. `pg_terminate_backend` is the last resort.
Verify it worked: SHOW log_lock_waits; -- on (was off)
Note: Exporter cancel of a superuser backend failed: `permission denied to cancel query`. deadlock_timeout is already 1s on this image (the default).
Gauge 5: deadlocks since stats reset
The deadlock detector aborts one of two transactions that wait on each other. The client sees `ERROR: deadlock detected`. A zero counter is not a rate of zero forever — it is the count since `pg_stat_reset()`. Prism's `PostgresDeadlocks` alert is a warning on a non-zero rate over five minutes, and it excludes `datname = 'postgres'` (the image's default database, and often the one you poked in a lab).
Check: deadlock counter per database
Fresh `postgres` database: `deadlocks = 0`. Two sessions that updated row 1 then row 2 in opposite order, run twice, moved the counter from 0 to 2.
SELECT datname, deadlocks, xact_commit, xact_rollback
FROM pg_stat_database
WHERE datname NOT LIKE 'template%';What to look for: `deadlocks = 0` on a quiet cluster. A rising counter means the application is taking locks in two orders. Check xact_rollback in the same row — aborted work is wasted WAL.
Fix: log the deadlock graph
You cannot SQL-away an application lock-order bug. You can make the next one visible. `deadlock_timeout` is already `'1s'` on this image — that is the default, not a knob you need to set. `log_lock_waits` was off until gauge 4.
ALTER SYSTEM SET log_lock_waits = on;
SELECT pg_reload_conf();Verify it worked: SHOW deadlock_timeout; SHOW log_lock_waits; -- 1s (default) / on
Note: Same deny-case as gauge 1: the exporter cannot ALTER SYSTEM. Read the DETAIL lines in the log after the next abort; they name both pids.
Gauge 6: transaction-ID freeze age
Postgres transaction IDs are 32-bit. On PG 16 the cluster does not drop into single-user mode — it stops assigning XIDs about three million before wraparound, and writes fail with `database is not accepting commands to avoid wraparound data loss`. That is a hard outage with a long fuse. Prism pages above 1.5 billion.
Check: freeze age vs autovacuum_freeze_max_age
This image: `xid_age` 13 (later 39), `freeze_max_age` 200000000, `pct_of_freeze` 0.00. `SHOW autovacuum` returned `on`. You are not close. The number still belongs on a dashboard because wraparound is silent until it is not.
What to look for: A few dozen to a few thousand XIDs on a new cluster is normal. Percent of freeze_max_age in the double digits is when you start hunting the oldest `relfrozenxid`.
Fix: freeze the oldest table
Replace `blog_lab_rows` with the `relname` that has the oldest `age(relfrozenxid)`. I froze the lab table; `age(relfrozenxid)` went to 0 and VERBOSE reported a new relfrozenxid 28 XIDs ahead of the previous value.
Verify it worked: SELECT relname, age(relfrozenxid) FROM pg_class WHERE relname = 'blog_lab_rows'; -- age 0
Note: Exporter VACUUM printed `WARNING: permission denied to vacuum "blog_lab_rows", skipping it`. Do not freeze a multi-terabyte table in the foreground without a window.
Gauge 7: replication lag (or no replica at all)
Lag is a timestamp, not a vibe. On the primary, `pg_stat_replication` lists connected standbys. Zero rows means no standby is connected — that is not "zero lag". On a standby, `now() - pg_last_xact_replay_timestamp()` is the replay lag Prism pages above 60s.
Check: standbys from the primary, replay from the standby
This single-node image returned zero rows from `pg_stat_replication`, `wal_level = replica`, `pg_is_in_recovery() = f`, and a NULL replay timestamp. That is a primary with nobody streaming.
What to look for: Primary with no standby: 0 rows, in_recovery=f, replay_lag NULL. If you expected a replica, this is the outage. If you did not, empty is correct.
Fix: believe empty, then count replicas
Do not page on empty. Do page if the topology promised a standby and the view is empty, or if replay_lag on a standby crosses a minute. Confirm wal_level can even ship WAL (`replica` or `logical`).
SHOW wal_level;
SELECT count(*) AS replicas FROM pg_stat_replication;Verify it worked: SHOW wal_level; -- replica on this image; replicas count 0
Note: The exporter can SELECT both views (it saw replicas=0). Creating a slot as that role failed: `permission denied to use replication slots`.
Gauge 8: inactive replication slots
An inactive slot holds WAL on the primary with no max age. That is the quiet disk-fill outage: writes fail, then Postgres will not start. Prism warns when a slot stays inactive for 30 minutes.
Check: slot activity and retained WAL
Fresh image: zero rows. `pg_create_physical_replication_slot('blog_demo_slot')` produced `slot_type=physical`, `active=f`, `restart_lsn` NULL — no consumer has reserved WAL yet. Logical slots need `wal_level=logical`; this image is `replica`.
SELECT slot_name, slot_type, active,
restart_lsn,
pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS retained_bytes
FROM pg_replication_slots;What to look for: Zero rows is healthy if you do not use slots. `active = f` on a named slot is a finding. Once restart_lsn is set, retained_bytes is the WAL you are hoarding.
Fix: drop the slot only if the consumer is gone
If the replica or decoder is supposed to be there, restart it. If you decommissioned it and left the slot, drop the slot. I dropped `blog_demo_slot`; the view went back to zero rows.
SELECT pg_drop_replication_slot('blog_demo_slot');Verify it worked: SELECT count(*) FROM pg_replication_slots; -- 0
Note: Exporter drop failed: `permission denied to use replication slots` / Only roles with the REPLICATION attribute may use replication slots. Keep it that way.
Watch the same eight gauges in Prism
You now have the SQL. The point of a Monitoring 101 page is that you should not have to re-run it by hand. Prism scrapes `pg_stat_*` with the same `pg_monitor` login the deny-cases used, and the alerts for these gauges already ship.
Create that login, grant `pg_monitor` plus `CONNECT`, and paste the DSN at [/monitor/install](/monitor/install). Per-query stats (`pg_stat_statements`) are a later sibling — enable the extension when you want those panels, not as a substitute for these eight. Hardening still lives on [/blog/postgres-security-101](/blog/postgres-security-101).