Fixing too many connections errors in PostgreSQL

When PostgreSQL rejects new sessions with FATAL: sorry, too many clients already, the fix is usually in how connections are opened, held and pooled, not only in a higher max_connections. This page covers the diagnosis, the settings, PgBouncer and the trade-offs.

On this page

Why PostgreSQL says too many clients already and when teams need a fix

The error FATAL: sorry, too many clients already means PostgreSQL has no free connection slot for a new client, usually during a traffic peak or right after a deploy that changed how applications open sessions. Each client connection is served by its own PostgreSQL backend process, and each backend holds memory and catalog state for as long as it stays open. The ceiling is set by max_connections, and a share of those slots is held back through superuser_reserved_connections, so ordinary application roles can be refused while an administrator still gets in. Before changing either setting, confirm the current values and the count of open sessions with pg_stat_activity and the max_connections value in your running cluster.

In most incidents the limit is hit because connections are being opened and held in the wrong way, not because the database lacks capacity. Common causes include application pools that scale with each web worker or pod, connections that leak because code paths never return them, idle sessions left open for hours, and retry loops that open new sessions while failed ones are still counted. Raising max_connections alone often makes the server slower and gives the same error at a higher number. The decisions that matter are how many connections each application may hold, whether a pooler such as PgBouncer should sit between applications and the server, and which idle timeouts should end sessions that nobody is using.

Bring in a partner when the fix touches several teams or systems at once: pool sizing across many services, a pooler placed in front of a high availability setup, or a change that must be rolled out without interrupting production. Also consider outside help when the error recurs after a deploy and nobody on your team can show which application opened the sessions. Confirm with your own team whether you have the access, monitoring and change window to make these changes safely, and agree on the expected connection counts in writing before any work starts.

How client connections reach PostgreSQL backends through a pooler

The diagram starts with application pools that open client connections. Traffic either goes directly to the PostgreSQL postmaster, which starts one backend process per connection, or passes through an optional PgBouncer layer that holds a smaller set of server connections open to PostgreSQL. The check that matters most is where the limit applies: max_connections caps backend processes at the server, and the pool mode in PgBouncer decides how long a server connection stays attached to one client. Superuser and monitoring roles draw from reserved slots.

Client traffic from application pools reaching PostgreSQL backends, with and without a pooler.

How to tell idle, leaked and genuinely busy connections apart

Idle sessions are connections that are open and waiting for a client to send a query. A pool or application that opens connections and never returns them to a pool, or that opens a new connection per request, produces a large set of idle backends. Those sessions consume a slot and some memory each, but they are not doing work. To see them, run SELECT state, count(*) FROM pg_stat_activity WHERE backend_type = 'client backend' GROUP BY state; and look for a large idle count. Then break the count down by client address and application name:

  • Group by client address: SELECT client_addr, application_name, count(*) FROM pg_stat_activity WHERE state = 'idle' GROUP BY 1, 2 ORDER BY 3 DESC; shows which host or pool owns the idle sessions. A single address with many idle sessions usually points to one application instance or a pool that is too large.
  • Check connection age: compare backend_start with the current time. Sessions that are hours old and idle suggest connections are not being recycled.
  • Check state_change: the time since the last state change tells you how long a session has been idle, which separates a pool keeping warm connections from a leak.
  • Compare with the pool settings: confirm the pool's maximum size and idle timeout in each application. Multiple instances, each with its own pool, multiply the total.
  • Confirm the application's behavior: ask owners whether connections are closed on errors and whether the pool validates them.

Check whether the idle count falls after a rolling restart of one application. If it does, the cause is in that application's pooling, not in the server limit.

Which connection settings fit which cause

This table compares the settings that change how many connections PostgreSQL accepts or holds open, from the server limit to application pools and PgBouncer. Read each row for what the setting changes, what it costs in memory or risk, and the cause it fits best. The main takeaway is that raising limits treats the symptom, while pooling and idle timeouts address why connections pile up.

SettingWhat it changesMemory and riskWhen it fits
max_connectionsSets the hard ceiling on client sessions the server accepts; changing it requires a server restartEach backend process uses memory on top of shared buffers, so a higher ceiling raises peak RAM use and can worsen contentionOnly after you have confirmed legitimate concurrent demand that pooling cannot absorb
superuser_reserved_connectionsHolds back slots for superuser sessions so administrators can still connect when the server is fullReduces slots available to applications; the reserved count does not add capacityKeep a small reserve so you can log in and kill sessions during an incident
idle_in_transaction_session_timeoutTerminates sessions left idle inside an open transaction after the configured intervalStops leaked transactions from holding slots and blocking vacuum, but can abort work an application expected to finishFits applications that open transactions and wait on external calls or user input
Application pool maximumCaps how many connections each application instance opens to the databaseTotal connections equal instances multiplied by pool size, so scaling out can exceed the server limit unexpectedlyFits when you can count instances and size each pool from the server's total budget
PgBouncer transaction poolingLends a server connection to a client only for the duration of a transactionMany client connections map to few server backends; session features such as temporary tables and advisory locks need careFits short-transaction web workloads with many clients that are mostly idle
PgBouncer session poolingHolds one server connection for the life of each client sessionLower reuse than transaction mode, so the backend count tracks client count more closelyFits applications that depend on session state and cannot run in transaction mode
Confirm before changingCheck the PostgreSQL version, pool mode support in your driver and ORM, and current settings in your environmentAsk your DBA or platform team to confirm limits, memory per backend and any failover target limits before a changeUse this before raising any limit so the change matches the actual cause

When PgBouncer solves the problem and when it does not

PgBouncer solves the problem when many client connections are mostly idle and the real pressure is the number of server backends PostgreSQL has to keep open. PgBouncer is a lightweight connection pooler that lets many client connections share a smaller set of server connections. It is a good fit when application pods, workers or serverless functions each open their own pool and the total crosses max_connections. It does not fix a query that holds a connection for seconds, a pool that is too large in the application, or a workload that needs far more concurrent work than the database can run efficiently. Check first whether the count of active sessions in pg_stat_activity is high or whether most sessions are idle. Idle sessions are the usual PgBouncer case.

The pool mode decides what breaks. In session pooling, a client keeps one server connection until it disconnects, so almost everything works but the savings are small. In transaction pooling, the server connection returns to the pool after each transaction, which gives the largest reduction but means session state does not carry between transactions. Prepared statements, temporary tables, advisory locks taken at session level, SET commands and LISTEN subscriptions can each leak across unrelated clients or disappear unexpectedly. Statement pooling is stricter still and rules out multi-statement transactions. Confirm which of these features your ORM, migration tool and driver use before choosing a mode, and test the application against the chosen mode in staging.

Check the PgBouncer release you deploy as well. The project published version 1.26.1 on October 14, 2026, with security fixes, so confirm on the PgBouncer site that you are running the current release and plan a regular update path. Pooling also adds a component to patch, monitor and make highly available, so a single PgBouncer instance can become a new point of failure. Decide who owns its configuration, how its statistics are scraped and what happens to clients during a restart before it goes into production.

Setting up pooling and limits without an outage

This sequence moves an application from direct connections to a pooled path with measured limits, so each change is verified before the next one starts. Every step ends with a check that shows whether the server is still within its connection budget and whether errors are falling.

  1. Capture current connection counts and sources

    The database owner queries pg_stat_activity grouped by application name, client address, user and state, and records the peak count over a normal business cycle. Include the value of max_connections, the superuser_reserved_connections setting, and the count of errors in the server log that contain the 'too many clients' message. This baseline shows which applications hold the most sessions and how many are idle. The step is done when the team has a written table of connections per source and the current error rate.

  2. Find and fix leaked and idle transactions

    The application owners review the sources with the highest idle counts and look for connections that are never returned to a pool, transactions left open after an error, and code paths that open a session per request. Fixes usually sit in the application: closing connections in finally blocks, committing or rolling back on every path, and reusing a single pool per process. Check the result by repeating the pg_stat_activity query after a deploy and confirming that the idle-in-transaction count falls and stays down.

  3. Size each application pool against the server budget

    Start from the server budget: max_connections minus the superuser reserve and the connections needed for monitoring, backups and administration. Divide the remaining budget among applications and their instances, keeping each pool's maximum below its fair share so that one service cannot starve the others. Confirm the arithmetic in a written sheet, and ask the application vendor or team how their driver handles pool exhaustion, timeouts and reconnects. The step is done when the total of all pool maximums fits inside the budget with margin for deployments that briefly run two sets of instances.

  4. Deploy PgBouncer in a staging path

    The platform team installs PgBouncer on a host or pod that can reach the database, configures a pool mode that matches how the application uses transactions and session state, and points a staging copy of one application at it. Review the PgBouncer documentation for the pool mode choice, since session-level features such as prepared statements and advisory locks behave differently under transaction pooling. Test the staging application with its full test suite and a load replay. The step is done when staging runs without errors and the server connection count stays well under the budget.

  5. Move production traffic in stages

    The team moves one application at a time from direct connections to the PgBouncer endpoint, starting with a service that has low risk and clear metrics. After each move, the team watches the PgBouncer SHOW POOLS and SHOW STATS output, the application error rate and latency, and the PostgreSQL server log for new errors. Roll back by pointing the service's connection string back to the database if errors rise. The step is done when every application runs through the pooler for a full normal cycle without new errors.

  6. Confirm the limits and error rate after cutover

    With all traffic through the pooler, the team reviews the server connection count, the client wait times reported by PgBouncer, and the count of 'too many clients' errors in the logs. If the server count sits well below max_connections and the errors are gone, the team leaves max_connections unchanged or lowers it toward the real budget. Confirm that the pooler and application pool maximums still add up to the planned budget. The step is done when the written baseline from the first step shows the target error rate and no regressions.

  7. Adjust max_connections and idle timeouts

    Only after the pooler is stable, the DBA changes max_connections if the measured budget differs from the current value, which requires a server restart. Set idle_in_transaction_session_timeout and, where the application can tolerate it, idle session limits so that abandoned sessions are closed by the server. Test each change in staging first and record the restart window with the change owner. The step is done when the settings file matches the documented budget and a test session that sits idle is closed by the server at the configured timeout.

  8. Document the budget and alert on it

    The team writes down the connection budget, the owner of each pool, and the procedure for adding a new application, then adds alerts on total server connections, PgBouncer client wait, and the 'too many clients' log message. Review the alert thresholds against the baseline captured earlier. Confirm with the monitoring owner that the alerts reach a person who can act on them. The step is done when a new application cannot be connected without an approved pool size, and an alert test fires as expected.

Security and operational risks when changing connection behavior

Every change that adds a pooler, raises connection limits or shares sessions alters who can connect, how they authenticate and what the logs show. The cards below cover the security and operational checks to complete before the change reaches production, so the fix for connection errors does not create a new exposure.

Exposed PgBouncer admin console

PgBouncer provides an administrative console reached through a special database name, and anyone who can authenticate to it can inspect and change pooler state. Confirm that the admin users list is limited to operators, that the listen address is not reachable from application networks or the internet, and that the console is not reachable through a path that skips your firewall rules. Treat the pooler host as a privileged system in your access reviews.

PgBouncer docs

Pooler authentication in pg_hba.conf

Clients connecting through a pooler are authenticated twice: once by PgBouncer and once by PostgreSQL when the pooler opens a server connection. The PostgreSQL authentication docs describe the methods available in pg_hba.conf, including SCRAM, certificate and LDAP, and PgBouncer's auth_type setting must match what the server accepts for the pooler's own user. Confirm the rule that matches the pooler's address, and that MD5 password authentication is not the method for new pooled users, since PostgreSQL 18 deprecates it in favor of SCRAM.

Authentication methods

TLS between pooler and server

Client traffic to the pooler and the pooler's connections to PostgreSQL are separate links, and each needs its own encryption decision. Without TLS on the second link, database credentials and query results cross the network in a form that can be read by anyone with access to that path. Confirm the hostssl rules in pg_hba.conf, the certificate chain the pooler validates, and that the pooler and database hosts sit on a segment where traffic is encrypted end to end.

Lost audit attribution on shared users

When many application instances or pooled clients share one database role, PostgreSQL logs show that role, not the person or service that ran the query. This weakens investigations and access reviews. Ask whether each application or team can use its own role, whether the pooler's connection settings preserve the identity the server needs, and whether application name fields are set so logs can be traced back to a service.

Monitoring gaps behind the pooler

Once a pooler sits in the path, server-side views such as pg_stat_activity show pooled server connections rather than individual clients, so per-client waits and client addresses can disappear from dashboards. Check that the pooler's own statistics are collected, that wait time between client and pooler is measured, and that alerts on connection saturation fire before clients receive too many clients errors. Confirm these gaps before the change reaches production, not after the first incident.

Settings that differ between pool modes

Pooling modes decide which session features survive reuse. Session-level state such as prepared statements, temporary tables and session settings may not carry over when a server connection is shared between clients, which can produce errors or wrong results that look like application bugs. Review the pool mode for each database and user, list the features the application relies on, and test them through the pooler in a staging environment before changing the default.

Questions teams ask before bringing in outside help

What drives the cost of fixing too many connections errors?

The cost follows the amount of work in the written scope, mainly the number of applications that connect to the database, how many connection pools those applications already run, and how many environments (development, staging, production) need the same change. Each application that needs pool sizing or timeout changes adds review and testing, and each environment adds a deployment cycle. A design that includes a pooler such as PgBouncer and failover-aware routing takes more design and verification time than a settings-only fix. Ask for a quote that lists each application, each environment and whether the pooler is in scope. Because DeployOpen does not publish prices, the quote is the reliable figure to compare.

How long does a connection limit fix take?

Duration depends on how many services are involved and whether the fix changes application code, configuration or infrastructure. A narrow change, such as lowering pool sizes in one service and setting an idle session timeout, is usually much shorter than adding PgBouncer in front of several applications that also need failover-aware routing. Failover planning matters because PostgreSQL does not detect a failed primary or redirect clients on its own, so an external tool and its routing rules must be tested before cutover. The fixed-scope agreement sets the timeline in writing before work starts, so ask for the schedule per service and per environment.

What does the client need to provide for this work?

The work needs read access to PostgreSQL logs and to pg_stat_activity so the team can see which clients hold connections, in what state, and from which hosts. It also needs access to the deployment pipelines for each application, because pool sizes and timeouts usually live in application configuration that must ship through normal release processes. An owner must be named for application changes, since the database team cannot change code in other teams' services. Finally, the client should provide the current max_connections value, the pool settings in use, and the list of environments. Missing any of these usually extends the discovery phase.

Can our internal team fix too many connections errors alone?

Often yes, for a single application with a clear leak or an oversized pool, because the diagnosis uses standard PostgreSQL views and the settings are documented. The work becomes harder when many applications share one server, when connections come from serverless or batch jobs, or when a pooler, failover and TLS settings must change together. Internal teams should confirm they can read pg_stat_activity, test pool changes outside production, and roll back a configuration change quickly. An outside review can help when the team wants a written scope, a tested change plan and a second set of eyes on the pooler design.

Does the work include a connection pooler like PgBouncer?

Adding a pooler is a common part of the fix, and it is included only when the written scope names it. PgBouncer is a lightweight connection pooler for PostgreSQL, and its current release line is maintained with security fixes, so the version to install should be confirmed on its project site before deployment. Pooling mode, authentication setup and the transaction behavior of each application need checking, because some session-level features do not survive transaction pooling. Ask the provider which pooling modes were tested against your applications.

What happens to authentication and security when a pooler is added?

A pooler sits between applications and PostgreSQL, so its authentication settings and the database's client authentication rules must agree. PostgreSQL documents several authentication methods, and the chosen method must be supported on both hops. Passwords should use SCRAM rather than MD5, since PostgreSQL 18 deprecated MD5 password authentication. Connection encryption and access rules in pg_hba.conf should be reviewed as part of the change, and any credentials stored in the pooler configuration should follow your secrets handling standard. Confirm these items in the written scope.

Can DeployOpen guarantee that connection errors will stop?

No. DeployOpen plans, implements and documents the changes in the agreed scope, and tests them against your environment before they are relied on. Whether errors stop also depends on application behavior, traffic patterns and capacity that the team controls after handover. The written scope should state what is tested, what is delivered and what the client must verify in production. Ask for the verification steps and the handover material before signing.

How DeployOpen works on this

DeployOpen approaches too many connections errors as a capacity and application design problem inside your own infrastructure, not as a single setting to raise. We first map where connections come from, then agree a fixed scope in writing, build the fix in your environment, and hand over documentation and runbooks your team can operate.

How we scope

  • Inventory every client that connects, including application pools, batch jobs, admin tools and monitoring agents.
  • Record current max_connections, reserved superuser slots and peak concurrent sessions from your own pg_stat_activity history.
  • Agree in writing whether the scope covers PgBouncer, idle timeout settings, pool sizing or application code changes.

How we build

  • Configure a pooler such as PgBouncer in your infrastructure, choosing pool mode with your application's transaction behavior in mind.
  • Set idle and transaction timeouts and size each application pool against the server limit, documenting the arithmetic used.
  • Test failure paths in a staging copy, including pooler restarts, pool exhaustion and application retry behavior under load.

How we hand over

  • Deliver the configuration files, pool sizing worksheet and change log covering every setting that was altered.
  • Provide alert rules for connection usage and waiting clients, with thresholds agreed with your operations team.
  • Run a walkthrough with your DBAs and developers so they can explain the connection path and rollback steps.

How we support

  • Engagements are fixed-scope, so deliverables and timelines are agreed before work starts. A quote follows from the written scope.
  • Ongoing support, PgBouncer upgrades and periodic connection reviews are available as a retainer.
  • Ask us to confirm which PgBouncer and PostgreSQL versions are in scope, and check their current support status before upgrading.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.