Skip to content

Connections by state

Open sessions grouped by state, against max_connections. Many idle sessions mean the pool is too big; many active ones mean the server is too small.

PostgreSQL · SQL
SELECT COALESCE(state, 'unknown') AS state,       COUNT(*) AS sessions,       (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS max_connectionsFROM pg_stat_activityWHERE backend_type = 'client backend'GROUP BY stateORDER BY sessions DESC

This query is part of the "PostgreSQL health" pack: connect the database in DataRunner and install the whole pack at once, with queries and dashboard.

What this query shows

PostgreSQL starts one process per connection, and the server has a hard cap, max_connections. When you hit it, new clients get the error "sorry, too many clients already". The total matters less than what the sessions are doing.

The query counts client backends in pg_stat_activity grouped by state and shows max_connections next to them. Run it when the application reports connection errors, after a deploy that changes the pool size, or as a PostgreSQL monitoring check.

How to read each column

  • state: active (running a statement), idle (connected and waiting), idle in transaction (inside a transaction doing nothing), idle in transaction (aborted), fastpath function call, disabled. unknown means the state is hidden from your role.
  • sessions: how many client backends are in that state.
  • max_connections: the server limit. It repeats on every row.

Add the sessions column up and compare it with max_connections. Remember that superuser_reserved_connections (3 by default) are kept for administrators, so regular users reach the limit a little earlier.

Healthy and worrying numbers

As rules of thumb: total sessions under 70% of max_connections is comfortable, above 80% leaves little room for a spike. Many idle sessions mean the application pools are bigger than needed. Many active sessions, more than the server has CPU cores, mean the server is too small or the queries too slow.

Any steady count of idle in transaction deserves attention. Those sessions hold locks and block vacuum, so look at the open transactions query as the next step.

What to do about it

With many idle sessions, the cheapest fix is a smaller pool in each application. Several services each holding 50 connections add up fast. A pooler such as PgBouncer in transaction mode lets thousands of clients share a few dozen server connections.

For idle in transaction, set a timeout so abandoned sessions do not stay forever.

ALTER DATABASE mydb SET idle_in_transaction_session_timeout = '5min';

Raising max_connections is the last resort. Each connection uses memory, and a larger value needs a restart.

SHOW max_connections;
ALTER SYSTEM SET max_connections = 200;
-- restart PostgreSQL to apply

Limits of this query

  • Only backend_type = 'client backend' is counted. Background workers, autovacuum workers and WAL senders have their own limits and are left out.
  • Without a superuser or pg_read_all_stats role, the state of other users' sessions can show as unknown.
  • It counts one server. Replicas have their own max_connections.
  • It is a snapshot. A spike that lasts a few seconds can pass between two runs.

Run it on a schedule in DataRunner

Connect the database to DataRunner, paste this query or start from the template, approve the SQL, then pick a schedule and a channel. Every 15 minutes follows the trend, and a daily summary is enough if you only need the shape. Each run executes the query on your database and delivers the result as CSV, Excel, PDF or inline HTML by e-mail, Slack, Telegram, Discord, WhatsApp (beta), a signed webhook or Google Sheets.

Every run is kept in the run history, so you can set today's result next to last week's. A schedule carries its own time zone, so a Monday at 8:00 is your Monday.

If the database sits in a private network, the bridge agent opens the connection from the inside out, so you do not need to open an inbound port.

Frequently asked questions

How do I check the number of connections in PostgreSQL?
Count rows in pg_stat_activity where backend_type is client backend and group them by state, as this template does. Compare the total with SHOW max_connections. The default limit is 100.
What does "too many clients already" mean?
The server has reached max_connections, and nothing more can connect until sessions close. Connections reserved for superusers can still get in. Find which application holds the most sessions, then shrink its pool or put a pooler in front.
Should I just increase max_connections?
Only after pooling and idle sessions are handled. Each connection costs memory, and more concurrent active sessions than CPU cores rarely makes the server faster. The change also needs a restart.
What is the difference between idle and idle in transaction?
An idle session is connected and not inside a transaction, which is harmless in small numbers. An idle in transaction session opened a transaction and stopped, so it keeps locks and holds back VACUUM.