dataiotech Labs
Scripts Library/postgresql/#12
Script #12
postgresql
Monitoringread-onlyMin Version: 10

PostgreSQL Connection Usage vs max_connections

Groups connections by state and shows how close you are to max_connections. Helps decide whether you need a connection pooler.

#connections#max_connections#pg_stat_activity
postgresql · sql
SELECT state, count(*) AS sessions,
       max(now() - state_change) AS longest_in_state
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY state
ORDER BY sessions DESC;

SELECT count(*) AS used,
       current_setting('max_connections')::int AS max_connections,
       round(100.0 * count(*) / current_setting('max_connections')::int, 1) AS used_pct
FROM pg_stat_activity;
Operational Notes & Remediation Guidance

If usage exceeds 80%, evaluate deploying a connection pooler such as PgBouncer.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 10).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.

Engineering Triad: Related Runbooks & Incident Response

Which production incidents and emergency drills execute this script as a diagnosis step?

Runbook Library (63)
Related Alerts & Metrics
M1PostgreSQL Connection SaturationPostgreSQL