Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Monitor PostgreSQL by collecting session counts from pg_stat_activity, tracking per-database block counters from pg_stat_database, and checking replica state and WAL positions in pg_stat_replication. Page on sustained conditions tied to connection headroom, user-facing latency, replica tolerance, or missing telemetry—not on a universal cache-hit percentage or a single lag number.

Choose what to collect and where

PostgreSQL’s built-in statistics views provide the underlying metrics. You can query them with a scheduled collector or use an observability platform that collects metrics and routes alerts. Compare an implementation’s metric coverage, PostgreSQL-version and managed-service compatibility, permissions, retention, dashboards, alert routing, operating burden, and cost. PostgreSQL’s documentation describes its statistics views and operating-system monitoring tools; it does not endorse a particular monitoring platform.

PostgreSQL 18 is the current released documentation version consulted here; versions 17, 16, 15, and 14 are also listed as supported. The detailed statistics semantics cited below are documented in the PostgreSQL 19 development documentation, so verify view fields and behavior against your deployed major version and provider.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to monitor PostgreSQL connections

pg_stat_activity is the live session and process view. Trend total sessions and group them by database, state, user, and application so a rising count can be traced to a workload rather than treated as an unexplained server-wide number.

SELECT datname, state, count(*) AS sessions
FROM pg_stat_activity
GROUP BY datname, state
ORDER BY datname, state;

Track active, idle, and idle-in-transaction sessions separately. Compare client sessions with configured max_connections, and display remaining headroom. If your architecture uses a pooler, distinguish PostgreSQL backend connections from application-side pool usage; they describe different layers.

There is no universally safe connection percentage or pool size. Set the operating limit and warning threshold from measured peak demand, capacity to scale or shed load, and reserved access for maintenance, failover, migrations, and operators. Include sustained growth and rapid connection increases in alert logic: either can predict exhaustion, while a one-sample spike may be transient.

How to interpret PostgreSQL cache hit ratio

A conventional per-database calculation uses PostgreSQL’s block-hit and block-read counters:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
SELECT datname,
       100.0 * blks_hit / NULLIF(blks_hit + blks_read, 0) AS cache_hit_pct,
       stats_reset
FROM pg_stat_database
WHERE datname IS NOT NULL;

The ratio is the percentage of counted block accesses found in PostgreSQL shared buffers rather than counted as reads. It is not a measurement of the entire storage cache hierarchy: PostgreSQL’s I/O counters do not distinguish data fetched from disk from data already present in the operating system’s kernel page cache.

Use the ratio as a workload clue, not a pass/fail score. pg_stat_database counters accumulate, and the ratio’s population can change after a restart or statistics reset. Show stats_reset with the metric and track counter deltas or rates over time. Interpret changes alongside latency and operating-system I/O; the appropriate baseline depends on working set, query patterns, workload, and latency objectives.

How to check PostgreSQL replication lag

On the primary, pg_stat_replication reports WAL senders connected to directly attached standbys. It does not show downstream standbys in the primary’s rows. Inspect each expected standby or application and, where available, collect its state, LSN positions, time-based lag fields, and reply time.

SELECT application_name, state,
       sent_lsn, write_lsn, flush_lsn, replay_lsn,
       write_lag, flush_lag, replay_lag, reply_time
FROM pg_stat_replication;

LSN positions show progress through the write-ahead log; the write, flush, and replay positions help distinguish where progress is occurring. The time-based fields describe recent intervals for writing, flushing, or replaying WAL. They do not predict how long a lagging replica will take to catch up.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On an idle, caught-up standby, a recent lag measurement can persist briefly and later become NULL. Decide how your dashboard represents that value—missing, zero, or last-known—and separately track whether the expected replica is present and whether its telemetry is fresh. Do not treat an idle-state NULL alone as a failure.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Set alerts that lead to useful action

Thresholds should reflect measured peak load and the service’s recovery and consistency requirements. Establish a sustained warning for degradation and page faster when there is immediate outage risk; choose intervals that give on-call staff time to act before the relevant limit is crossed.

  • Connection headroom: Warn as use approaches the operating limit. Page when remaining capacity threatens the time needed to scale, shed load, or recover. Put the dominant applications and session states on the dashboard.
  • Connection pressure: Alert on sustained active-session growth, prolonged idle-in-transaction sessions, or a sharp increase in connection attempts if your collection setup supports it.
  • Cache and I/O symptoms: Correlate counter trends with latency and operating-system I/O. Page on a user-facing latency or I/O objective breach, not a cache percentage by itself.
  • Replica health: Monitor expected replica presence and streaming state. Combine LSN progress, time-based indicators, and telemetry freshness; alert on sustained lag that exceeds the application’s read-consistency or recovery tolerance.
  • Monitoring health: Alert when the collector cannot connect, required statistics are hidden, a metric stops updating, or scrape timestamps become stale. A quiet graph is not evidence of a healthy database if collection has failed.

Make statistics visibility and freshness explicit

Ordinary roles can see full details for their own sessions, but details for other sessions may be null. Superusers and roles granted pg_read_all_stats can see full session information. Grant the monitoring role only the privileges needed for its queries, then verify its output using that role—not an administrator account. Otherwise, a permissions gap can look like an empty or healthy system.

Statistics are not an instantaneous event stream. Cumulative values are accumulated locally and flushed to shared memory at intervals, and a transaction can retain a statistics snapshot or cached values. Keep collection queries short, monitor scrape freshness, and interpret cumulative totals as trends rather than real-time events.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For version-specific details, consult the PostgreSQL 18 monitoring documentation and verify statistics behavior and available fields against your installed version. The detailed semantics referenced here appear in the PostgreSQL 19 cumulative statistics documentation, which is development documentation and may change before release. Managed-service permissions and exposed fields can also vary by provider.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.