Monitoring and Tuning

Topics Covered

The Statistics System

Cumulative counters

pg_stat_activity

Table and index statistics

Database wide statistics

I/O statistics

WAL and checkpoint statistics

Replication and progress views

The cache hit ratio and its limits

Collecting and storing metrics

Statistics storage

Finding unused indexes

Sequential scans on large tables

Dead tuples and vacuum lag

Transaction id age

Logs as a data source

Host metrics

Monitoring the monitoring

Statistics on standbys

Postgres records a great deal about itself: what every session is doing, how often each table is scanned, how much each index is used, how much WAL is written and how often checkpoints run. These cumulative statistics views are the raw material of monitoring and tuning. This section explains the main views, how their counters work and how to turn cumulative counters into the rates and ratios that matter.

Cumulative counters

Most statistics views expose counters that only grow, such as the number of sequential scans on a table or blocks read from disk, since the last reset. A single reading means little; the useful numbers are differences between two readings divided by the time between them: scans per second, blocks read per second. Monitoring systems sample the views periodically and compute these rates. pg_stat_reset functions zero the counters, which breaks rate calculations if done casually.

A cumulative counter only becomes useful as the difference between two samples over the time between them.

Loading problem...

pg_stat_activity

pg_stat_activity has one row per server process: the database and user, client address, the current query or last query, the state such as active, idle or idle in transaction, when the transaction and the query started, and the wait event if waiting. It is the first place to look during an incident: what is running, for how long, and what it is waiting on. Long running transactions and sessions idle in transaction stand out immediately.

Table and index statistics

pg_stat_user_tables counts sequential and index scans, rows inserted, updated, deleted and HOT updated, live and dead tuple estimates, and the last vacuum and analyze times per table. pg_stat_user_indexes counts scans per index. pg_statio_user_tables and pg_statio_user_indexes count blocks read from disk versus found in shared buffers. Together they show which tables are scanned sequentially, which indexes are unused and where vacuum is falling behind.

Database wide statistics

pg_stat_database aggregates per database: commits and rollbacks, blocks read and hit, temporary files and bytes, deadlocks, conflicts on standbys and, since version 14, session counts and time spent active and idle in transaction. A rising rollback rate or temporary file volume is visible here before it shows up anywhere else.

I/O statistics

Since version 16, pg_stat_io breaks down I/O by backend type, such as client backends, autovacuum, the background writer and checkpointer, and by context such as normal, vacuum and bulk read: reads, writes, extends, hits, evictions and fsyncs. It answers questions earlier versions could not, such as whether client backends are being forced to write dirty buffers themselves, a sign that the background writer and checkpointer are not keeping up.

WAL and checkpoint statistics

pg_stat_wal reports WAL records, full page images and bytes generated, and how often WAL buffers were full. pg_stat_checkpointer, split out of pg_stat_bgwriter in version 17, counts timed and requested checkpoints, buffers written and the time spent writing and syncing. Many requested checkpoints mean max_wal_size is too small for the write rate; a high fraction of full page images suggests checkpoints are too frequent.

Replication and progress views

pg_stat_replication and pg_replication_slots show replication state on the primary, pg_stat_wal_receiver on standbys. Progress views, pg_stat_progress_vacuum, pg_stat_progress_create_index, pg_stat_progress_analyze, pg_stat_progress_cluster and pg_stat_progress_basebackup, show how far long operations have advanced, letting operators estimate when a vacuum or index build will finish instead of guessing.

The cache hit ratio and its limits

The fraction of block requests served from shared buffers, blks_hit over blks_hit plus blks_read, is a popular metric. It is useful as a trend, a sudden drop shows the working set no longer fits, but misleading as an absolute target: reads counted as misses may be served by the operating system page cache, and a ratio of 99 percent can still mean thousands of disk reads per second on a busy server. Rates of actual reads per second matter more.

Collecting and storing metrics

A monitoring agent, such as postgres_exporter for Prometheus or an agent of a commercial monitoring service, queries these views every 10 to 60 seconds and stores the results as time series. Dashboards show rates and trends; alerts fire on thresholds. Keeping at least weeks of history makes it possible to compare an incident with normal behavior and to see slow trends such as table growth or rising dead tuples.

Statistics storage

Before version 15, statistics were collected by a separate collector process via UDP messages and written to files, and could be lost under load. Since version 15, they are kept in shared memory, more reliable and faster to read, and written to disk on clean shutdown. After a crash or immediate shutdown, counters reset, which monitoring must handle as a counter reset rather than a huge negative rate.

Finding unused indexes

An index with idx_scan at zero in pg_stat_user_indexes over a long period, on the primary and every replica, is probably unused, and costs write time, WAL, vacuum work and cache space. Before dropping it, check that it does not enforce a unique or primary key constraint, that statistics were not reset recently and that no replica uses it for reads, since each server keeps its own counters.

Scan counters collected over weeks, on every server, reveal indexes that only cost writes and space.

Sequential scans on large tables

A large table with a high rate of sequential scans and few index scans usually means queries are missing an index or filtering on a column without one. seq_tup_read divided by seq_scan gives rows read per scan, and a large value on a big table is a strong signal. Small tables are scanned sequentially by design, since scanning a few pages is cheaper than using an index, so the check matters only for tables with many pages.

Dead tuples and vacuum lag

n_dead_tup and n_live_tup in pg_stat_user_tables, together with last_autovacuum, show whether vacuum keeps up. A table whose dead tuples keep climbing between vacuums, or whose last autovacuum is days old despite heavy updates, needs tuned per table autovacuum settings, as covered in the vacuum lesson. Tracking the ratio of dead to live tuples over time is a simple bloat early warning.

Transaction id age

age of datfrozenxid in pg_database, and of relfrozenxid per table, shows how close each database and table is to forced anti wraparound vacuum. Alerting when age exceeds, for example, half of autovacuum_freeze_max_age leaves time to investigate blockers such as long transactions or abandoned slots before Postgres has to act. This is one of the few alerts that protects against a full outage.

Logs as a data source

The server log complements the statistics views: log_checkpoints records each checkpoint with its timing and buffers written, log_autovacuum_min_duration records autovacuum runs, log_lock_waits records lock waits, log_temp_files records spills and log_connections and log_disconnections record session activity. Parsing logs with a tool such as pgBadger produces reports of slow queries, errors and activity patterns that views alone do not provide.

Host metrics

Postgres statistics should be read together with host metrics: CPU usage and run queue, memory usage and page cache size, disk I/O operations, throughput and latency, network throughput and free disk space. Many database symptoms are host level problems, such as a noisy neighbor on shared storage, and many host level symptoms have database causes. Dashboards that place both side by side shorten diagnosis.

Monitoring the monitoring

Monitoring queries themselves use resources: a query over pg_stat_statements with thousands of entries every 10 seconds, or table statistics across tens of thousands of partitions, can cost noticeable CPU. Choosing sensible intervals, limiting per table metrics to large tables and checking the cost of monitoring queries in pg_stat_statements keeps observability from becoming a load problem of its own.

Statistics on standbys

Each standby keeps its own statistics for the queries it serves: pg_stat_activity, pg_stat_statements and index scan counts reflect only local activity, while table modification counters stay near zero because changes arrive through replay. Monitoring must therefore collect from every server, label metrics by role and avoid assuming that the primary alone tells the whole story of how the data is used.

Sample counters, compute rates

Statistics views expose cumulative counters; monitoring samples them and turns differences into rates. Use pg_stat_activity for what is happening now, table and index views for access patterns and vacuum, pg_stat_io for I/O sources, pg_stat_wal and the checkpointer view for write behavior and progress views for long operations.