Skip to content

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

Key points

  • Connections near max_connections cause sudden failures.
  • pg_stat_statements shows which queries cost the most in total.
  • Replication lag decides how stale your replicas and backups are.
  • Disk and long-running transactions are slow-burning risks.

Connections

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

Expensive queries

sql
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time::numeric, 1) AS mean_ms, left(query, 100)
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;

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.

Replication and locks

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

Cache, bloat and disk

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

Alerts worth setting

AlertThreshold to start with
Connections in useAbove 80% of max_connections for 5 minutes
Replication lagAbove 30 s (or your RPO) for 5 minutes
Disk usedAbove 80%, and growing
Long transactionsAny transaction open longer than 15 minutes
Database reachableA read-only query fails from outside the host
Query latencyp95 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.

The PostgreSQL metrics that matter

MetricQuery or sourceStarting alert
Connections vs max_connectionscount(*) from pg_stat_activityAbove 80%
Long-running queriespg_stat_activity where state = 'active' and now() - query_start > interval '5 minutes'Any, on an OLTP database
Idle in transactionpg_stat_activity where state = 'idle in transaction'Older than a few minutes: it blocks vacuum and holds locks
Replication lagnow() - pg_last_xact_replay_timestamp() on a replicaAbove 30 seconds, or your read-consistency budget
Cache hit ratioblks_hit / (blks_hit + blks_read) in pg_stat_databaseBelow 99% on a hot OLTP database
Deadlocksdeadlocks in pg_stat_databaseAny increase
Transaction ID ageage(datfrozenxid) from pg_databaseAbove about 1 billion: wraparound protection is approaching
Disk and WAL sizeFilesystem and pg_wal directoryAbove 80% full
sql
-- 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.

Frequently asked questions

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.

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.