PostgreSQL Connection Pool Exhaustion: Diagnosis and Fixes
A PostgreSQL connection pool timeout can arrive while the database is still answering queries. The service health check passes, the database CPU chart looks ordinary, and yet requests fail because they cannot acquire a connection. Increasing the pool size may buy time, or it may transfer the queue into the database and make recovery harder.
The practical objective is to identify where work is waiting, determine why existing connections are not becoming available, and restore a sustainable level of concurrency. This guide treats connection exhaustion as an end-to-end capacity problem rather than a single configuration error.
Identify which limit has been reached
There are several distinct resources between an incoming request and PostgreSQL. An application pool controls how many connections its workers can borrow. A proxy such as PgBouncer may accept client connections and assign a smaller collection of server connections to them. PostgreSQL itself limits the number of simultaneous connections.
These limits are related but not interchangeable. A request can fail at application checkout even if PostgreSQL has room for additional sessions. Conversely, the application may try to open a new connection and receive a server-side rejection. A proxy can accept the client but make its query wait for a backend.
For example, SQLAlchemy's pool error guidance identifies unreturned connections and excessively long transactions as possible underlying causes of pool checkout failures. A checkout timeout should therefore be interpreted as a symptom, not proof that PostgreSQL needs a larger connection limit.
Start by recording the exact exception, the layer that emitted it, and the affected service or worker. Distinguish connection acquisition time from network connection establishment and SQL execution. If the error occurs only in one background worker deployment, a global database change is unlikely to be the most targeted response.
Inspect PostgreSQL before changing configuration
Use a controlled administrative connection and inspect the configured ceiling and reservations. PostgreSQL's connection configuration documentation explains that ordinary roles cannot use all connection slots when reserved capacity applies, and that resource allocation depends on the configured maximum.
SELECT name, setting
FROM pg_settings
WHERE name IN (
'max_connections',
'reserved_connections',
'superuser_reserved_connections'
)
ORDER BY name;
The absence of a setting on an older release should be interpreted according to that release's documentation. Do not treat the returned maximum as a budget that applications may consume in full. Administrative sessions, monitoring, maintenance and other direct clients need room as well.
Next, inspect the distribution of client backends:
SELECT datname, usename, application_name,
state, count(*) AS sessions
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY datname, usename, application_name, state
ORDER BY sessions DESC;
The PostgreSQL activity statistics documentation describes the state and wait information available for backend processes. A client backend in the idle state is not necessarily leaking: it may be a healthy connection sitting in an application pool. An idle transaction deserves separate attention because the transaction remains open even though no statement is currently executing.
Look for concentrations by service identity. If every connection uses the same generic application name, attributing pressure to a deployment becomes harder. Assign meaningful names to web workers, migration processes and batch consumers. Use a monitoring role with suitable privileges; ordinary users may not see all details of other sessions.
Find long-held transactions and blocked work
Inspect transaction age independently from query age. The application can hold a connection while doing work that PostgreSQL does not see as a running statement.
SELECT pid, application_name, state,
now() - xact_start AS transaction_age,
now() - state_change AS state_age,
wait_event_type, wait_event
FROM pg_stat_activity
WHERE backend_type = 'client backend'
AND xact_start IS NOT NULL
ORDER BY xact_start;
A backlog of sessions waiting on locks suggests that the useful next step is to investigate the blocking transactions. The system information functions include pg_blocking_pids, which can help identify those dependencies.
SELECT pid, pg_blocking_pids(pid) AS blockers
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';
A running statement can also be waiting for something. Do not equate the active state with continuous CPU consumption. Correlate wait events with system CPU, disk latency and application traces before choosing a remedy.
During an incident, capture evidence before restarting services. A restart can destroy the connection history and briefly relieve pressure without removing the triggering condition. Restrict access to diagnostic outputs that contain database identities or query details.
Fix ownership of connections in application code
A reliable design gives each acquired connection an explicit owner and a bounded lifetime. The owner must return it when the request finishes, including exception and cancellation paths. Use the framework's context management or equivalent cleanup mechanisms rather than relying on eventual object destruction.
In Python with SQLAlchemy, a transaction context provides a convenient scope:
from sqlalchemy import create_engine, text
engine = create_engine(
database_url,
pool_size=8,
max_overflow=2,
pool_timeout=2,
)
def update_job(job_id):
with engine.begin() as conn:
conn.execute(
text("UPDATE jobs SET processed = true WHERE id = :id"),
{"id": job_id},
)
These numbers are illustrative, not recommended defaults. The SQLAlchemy pooling documentation describes the relationship between base capacity and overflow. Keep the engine associated with the process lifecycle rather than constructing a new pool for each request.
Avoid calling a slow remote API while holding an open transaction unless the consistency model truly requires it. Moving unrelated work outside the transaction can shorten the period for which the database connection is unavailable. Where the operation coordinates external side effects, an outbox or a durable workflow may be appropriate, but it changes the consistency contract and needs its own failure handling.
Align deadlines with the work that must finish
PostgreSQL provides separate controls for statement execution, lock acquisition and sessions left idle inside a transaction. The client connection defaults documentation explains these settings. Apply them deliberately by role or workload, rather than selecting a single global timeout for unrelated jobs.
An illustrative API role could use the following settings after validation against its actual latency requirements:
ALTER ROLE api_user SET statement_timeout = '3s';
ALTER ROLE api_user SET lock_timeout = '500ms';
ALTER ROLE api_user SET idle_in_transaction_session_timeout = '10s';
These statements affect defaults for new sessions. A pool retaining existing sessions may require a controlled recycle before the new defaults are visible. A migration role or reporting workload may need very different settings.
The application deadline needs to leave enough room for acquisition, execution and cleanup. A statement timeout does not cap the time a request spends in the application checkout queue. Likewise, a checkout timeout does not limit the duration of a connection that has already been borrowed. Coordinate cancellation propagation and rollback behavior so timed-out requests do not leave expensive work running unnecessarily.
Separate connection budgets from throughput budgets
A useful starting point is to maintain a capacity inventory for each database endpoint. For direct application pools, multiply the maximum pool capacity by the maximum number of processes that can exist concurrently, including deployment overlap. For multiplexed traffic, count the maximum server-side capacity of each pooler instead of adding the client pool limits to those same backend connections. Include clients that bypass the pooler.
Treat the resulting total as a worst-case allocation, not a performance target. Test several concurrency levels with the same request mix, data volume and query plans. Observe completed operations, tail latency, acquisition waits and errors. Stop increasing concurrency when it no longer delivers worthwhile throughput or breaches the service's latency requirements.
Reserve separate admission budgets for interactive requests and expensive background jobs if they compete for the same database. This does not guarantee isolation inside PostgreSQL: the workloads may still contend for storage or locks. It does provide a way to limit how much pressure one caller can place on the connection boundary.
For a service with an external queue, make the worker's concurrency limit consistent with the number of database leases it can sustain. Otherwise a worker can pull jobs far faster than it can execute them, converting an observable message backlog into a less transparent pool backlog.
Size pools across the entire deployment
Connection capacity must be allocated across workers, not just services. A deployment with several worker processes per replica can have several independent application pools. Rolling deployments may temporarily run old and new processes together. Scheduled jobs, autoscaling and administrative clients add further demand.
Consider a hypothetical service with four replicas, each running three processes, each with a pool maximum of ten connections. The service can demand 120 connections under full occupancy. If a rolling deployment temporarily doubles those processes, its potential demand doubles too. This is a capacity envelope, not a prediction that the connections will all be opened.
Calculate the budget for every component that connects to a given primary or replica. Reserve operational headroom. Then measure performance under representative concurrency and adjust based on completed throughput and latency rather than simply filling every available slot.
The amount of connection capacity needed is also affected by the time a request holds its lease. A slower query, a lock wait, or an unrelated network request inside a transaction can increase occupancy without an increase in incoming traffic. Reducing that duration may be more productive than adding connections.
Diagnose PgBouncer separately
When PgBouncer is present, connect to its administrative console and inspect the relevant pools:
SHOW POOLS;
SHOW STATS;
SHOW DATABASES;
The PgBouncer administration reference documents client wait counts and the longest current wait in a pool. Rising waits can indicate inadequate server-pool capacity or a database that cannot complete work quickly enough. Compare these values with PostgreSQL activity rather than interpreting them in isolation.
The PgBouncer configuration reference distinguishes client admission limits from server-side pool sizes. Server pools are ordinarily separated by database and user, so adding another database or role can change the potential aggregate backend demand. Account for all pooler instances as well.
Transaction pooling can help when applications have many logical clients but short transactions. However, the application must be compatible with backend reassignment. The PgBouncer feature compatibility matrix is a useful starting point for checking session-bound behavior. Run integration tests against the actual pooling mode rather than relying on an application test suite that connects directly to PostgreSQL.
Test pooling mode and maintenance assumptions
Session pooling retains the backend assignment for the client session; transaction pooling can reuse it after transaction completion. The trade-off is not just performance. Features that assume the same backend across transactions require specific compatibility checks. Test temporary objects, session-level settings, notifications and the driver's prepared-statement behavior against the deployed version and configuration.
Include pooler maintenance in the operational plan. The PgBouncer changelog records security maintenance in 2026. Version pinning is useful for reproducibility, but it should not prevent patch upgrades. A pooler is part of the database authentication path and deserves equivalent attention to its credentials, network exposure and upgrade process.
What a documented shared-pool failure tells us
GitHub's October 2026 availability report describes an incident in which a shared database connection pool reached its limit and requests across the service failed. The relevant lesson is the potential blast radius of shared capacity. The report is not presented here as a PostgreSQL-specific case study, nor does it establish the optimal size of another system's pool.
An architecture review should identify the services that can consume a shared pool and what happens when one workload expands unexpectedly. A limit that is reasonable for an individual consumer may be unsafe when all consumers draw from the same resource. Document the owner of the shared limit, the admission mechanism, and how operators can temporarily reduce nonessential demand without restarting the database.
Restore service without amplifying the incident
First, limit new work. Pause nonessential jobs, reduce queue consumer concurrency, or apply admission control to expensive endpoints. Where possible, preserve capacity for customer-critical operations and administrative access.
Next, inspect whether a specific transaction or workload is blocking progress. PostgreSQL's administrative functions distinguish query cancellation from session termination. Cancellation targets a running query; termination disconnects the session. Neither is a substitute for application cleanup, and terminating a session can abort its transaction. Check the target and its owner before using either action.
Use bounded retries with backoff and jitter. A synchronized wave of retries can refill the same queue immediately. Avoid retrying an operation whose commit outcome is unknown unless the business operation has suitable idempotency or reconciliation.
Finally, compare before and after evidence: acquisition latency, failed acquisitions, successful transaction rate and database wait distributions. The service is not recovered merely because one timeout counter stopped increasing.
Make exhaustion visible before requests fail
Instrument the application pool for checked-out connections, waiting borrowers, checkout latency, timeout counts and lease duration. At the proxy, track waiting clients and available server connections. In PostgreSQL, monitor client session counts, long-running transactions and wait events alongside hardware saturation.
Alert on a sustained increase in acquisition latency or backlog relative to the normal workload. A high connection count without waiting can be benign; a smaller pool with a rapidly growing queue can be an urgent problem. The useful alert tells the operator whether work is being admitted faster than it is completing.
Build a repeatable load test that includes slow SQL, lock contention and an interrupted request. Verify that connection usage returns to its baseline after the test. Include rolling deployment and database restart scenarios so connection creation and retry behavior are visible.
Pool exhaustion is ultimately a failure of capacity or connection lifecycle management at some layer. The durable solution is to make that layer observable, allocate its resources explicitly, and ensure callers release what they borrow. A pool should be a controlled boundary that protects the database and exposes excess demand, not an invisible queue that only becomes visible when requests fail.