How-to guide
PostgreSQL monitoring: key metrics and alerts
Most application slowdowns end at the database. These are the PostgreSQL signals worth watching, with the queries that show them.
4 min read12 sectionsUpdated
On this page
SELECT state, count(*) FROM pg_stat_activity GROUP BY state;
SHOW max_connections;
-- sessions idle in a transaction hold locks and block vacuum
SELECT pid, now() - xact_start AS open_for, left(query, 80)
FROM pg_stat_activity
WHERE state = 'idle in transaction' AND now() - xact_start > interval '5 minutes';Total time matters more than mean time: a 5 ms query run 2 million times a day costs more than a 2 s report run twice. Pair this with traces to see which endpoints run each query; see how to find slow database queries.
-- on the primary: lag per replica
SELECT application_name, state, write_lag, flush_lag, replay_lag FROM pg_stat_replication;
-- who is waiting on whom
SELECT blocked.pid AS blocked_pid, blocking.pid AS blocking_pid, left(blocked.query, 60) AS blocked_query
FROM pg_stat_activity blocked
JOIN pg_stat_activity blocking ON blocking.pid = ANY(pg_blocking_pids(blocked.pid));-- buffer cache hit ratio (aim for > 99% on OLTP workloads)
SELECT round(100.0 * sum(blks_hit) / nullif(sum(blks_hit) + sum(blks_read), 0), 2) AS cache_hit_pct FROM pg_stat_database;
-- tables with many dead rows (vacuum falling behind)
SELECT relname, n_dead_tup, n_live_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;
-- database sizes
SELECT datname, pg_size_pretty(pg_database_size(datname)) FROM pg_database ORDER BY pg_database_size(datname) DESC;| Alert | Threshold to start with |
|---|---|
| Connections in use | Above 80% of max_connections for 5 minutes |
| Replication lag | Above 30 s (or your RPO) for 5 minutes |
| Disk used | Above 80%, and growing |
| Long transactions | Any transaction open longer than 15 minutes |
| Database reachable | A read-only query fails from outside the host |
| Query latency | p95 database time per request rising in APM |
In VitalRix
A ready-made Postgres check connects and runs a read-only query on a schedule, so you know the database answers from the network your app uses. APM shows database call volume, p95 and slow calls per statement from traces, and dashboards can chart the metrics above sent through OpenTelemetry. See synthetic monitoring.
| Metric | Query or source | Starting alert |
|---|---|---|
| Connections vs max_connections | count(*) from pg_stat_activity | Above 80% |
| Long-running queries | pg_stat_activity where state = 'active' and now() - query_start > interval '5 minutes' | Any, on an OLTP database |
| Idle in transaction | pg_stat_activity where state = 'idle in transaction' | Older than a few minutes: it blocks vacuum and holds locks |
| Replication lag | now() - pg_last_xact_replay_timestamp() on a replica | Above 30 seconds, or your read-consistency budget |
| Cache hit ratio | blks_hit / (blks_hit + blks_read) in pg_stat_database | Below 99% on a hot OLTP database |
| Deadlocks | deadlocks in pg_stat_database | Any increase |
| Transaction ID age | age(datfrozenxid) from pg_database | Above about 1 billion: wraparound protection is approaching |
| Disk and WAL size | Filesystem and pg_wal directory | Above 80% full |
-- the slowest statements by total time (needs the pg_stat_statements extension)
SELECT round(total_exec_time) AS total_ms, calls, round(mean_exec_time, 1) AS mean_ms, left(query, 80) AS query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;
-- who is blocking whom
SELECT pid, pg_blocking_pids(pid) AS blocked_by, state, left(query, 60) FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;What the incidents look like
- Connections run out during a traffic spike or a connection leak, and the application logs "too many clients already". Put a pooler (PgBouncer) in front and size application pools so their sum stays under max_connections.
- One slow query takes the database down: a missing index after a new feature, or a plan change after statistics changed. pg_stat_statements and traces with database spans point at it.
- Autovacuum falls behind on a busy table: dead tuples pile up, the table bloats and queries slow down week by week. Watch n_dead_tup in pg_stat_user_tables.
- A replica lags during heavy writes, and reads from it return stale data. Alert on lag, and route consistency-sensitive reads to the primary.
- Deadlocks from two code paths updating the same rows in different orders. See PostgreSQL deadlock detected.
What is a good cache hit ratio?
For typical web workloads, above 99%. Lower values mean the working set does not fit in shared_buffers and the OS cache, so reads go to disk.
Should I use a connection pooler?
With many application instances, yes. PgBouncer or a built-in pooler keeps the number of real connections well below max_connections.
Related reading
- PostgreSQL high CPU usage: how to find the cause: Diagnose PostgreSQL high CPU: use pg_stat_statements to rank queries by total time, spot missing indexes and stale statistics, and read EXPLAIN properly.
- MySQL monitoring: key metrics and alerts: Monitor MySQL: connections and threads, query throughput, slow queries, InnoDB buffer pool, replication lag and disk, with the SQL for each check.
- PostgreSQL replication lag: causes and how to fix it: Diagnose PostgreSQL replication lag: use pg_stat_replication to tell send, write and replay delays apart, and fix slow replicas, long queries and WAL pile-ups.
- How to monitor Fly.io: How to monitor apps on Fly.io: multi-region uptime checks, machine health, the built-in Prometheus metrics, Postgres clusters, OpenTelemetry traces and alerts.
- Nginx monitoring: status, logs and alerts: Monitor Nginx with stub_status and JSON access logs: active and dropped connections, request rate, 5xx share, upstream time and alerts to set.
- PostgreSQL idle in transaction: find and fix it: Find and fix PostgreSQL idle in transaction sessions: why they block vacuum and hold locks, which application patterns cause them and which timeout to set.
Watch your own site and services with VitalRix
Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.