A PostgreSQL connection-pool exhaustion error does not automatically mean your pool is too small. It means every connection your application is allowed to borrow is busy, leaked, blocked, or reserved by another workload.
Raising the limit can make the database slower before it makes the error disappear.
The right response is to identify which layer is exhausted, find what is holding connections, and fix the cause. Only then should you change pool sizes or PostgreSQL's max_connections.
First: What Is Actually Exhausted?
"Connection pool exhausted" can describe several different failures.
| Layer | Typical symptom | What it means |
|---|---|---|
| Application pool | Timeout acquiring a connection, Pool exhausted, Connection is not available | Your application has no idle client connection to hand to a request |
| PostgreSQL server | too many clients already / remaining connection slots are reserved | PostgreSQL has reached its allowed connection count |
| Pooler such as PgBouncer | Requests queue or time out at the pooler | The pooler cannot assign an available server connection quickly enough |
| Database work | Pool waits rise while slow queries or long transactions run | Connections are not leaked, but they are held for too long |
PostgreSQL's max_connections limits concurrent server connections. Its default is commonly 100, and increasing it raises PostgreSQL resource requirements, including shared-memory usage. It is also a start-time setting, so it is not something to casually increase during an incident.
The important distinction is this:
A connection pool is a queue in front of a finite database resource. If requests borrow connections faster than they return them, the queue grows until it times out.
The Mistake: Increasing the Pool First
Suppose an API has:
- 10 application replicas
- A pool size of 20 per replica
- One PostgreSQL primary with
max_connections = 100
Your theoretical application demand is:
10 replicas × 20 connections = 200 connections
Even before workers, migrations, dashboards, admin tools, read replicas, or background jobs connect, the application can request twice what the database allows.
Increasing every pool from 20 to 40 does not fix the underlying mismatch. It can create 400 potential database connections, increase queueing inside PostgreSQL, consume memory, and make query latency worse.
A pool limit is not throughput. It is a concurrency limit.
Diagnose the Incident in Order
1. Identify the Exact Error
Do not treat these errors as interchangeable.
Application pool exhaustion
Timeout acquiring a connection from the pool
Usually means the application pool is saturated. The database may still have free capacity.
PostgreSQL connection exhaustion
too many clients already
Usually means PostgreSQL itself has no available server-connection slots.
Reserved PostgreSQL connection slots
remaining connection slots are reserved for non-replication superuser connections
PostgreSQL has reached the usable part of max_connections; reserved slots remain for administrative access.
Unexpected connection termination
Connection terminated unexpectedly
This may be a network problem, failover, database restart, proxy failure, or process problem rather than pool exhaustion.
Start by recording:
- The exact error text
- The affected service and deployment version
- Current request rate
- Pool active, idle, and waiting counts
- PostgreSQL connection count
- Slow-query and transaction-duration data
- Recent deploys
- Traffic spikes
- Database failover or dependency incidents
2. Check Whether PostgreSQL Is Actually Full
Connect with an administrative role and inspect active sessions:
SELECT
state,
count(*) AS connections
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state
ORDER BY connections DESC;
Then inspect non-idle sessions:
SELECT
pid,
usename,
application_name,
client_addr,
state,
wait_event_type,
wait_event,
backend_start,
xact_start,
query_start,
now() - query_start AS query_age,
now() - xact_start AS transaction_age,
left(query, 300) AS query
FROM pg_stat_activity
WHERE datname = current_database()
AND state <> 'idle'
ORDER BY xact_start NULLS LAST, query_start;
Look for:
- Queries running far longer than normal
- Transactions open for minutes or hours
- Sessions waiting on locks
- Many sessions in
idle in transaction - An unexpected
application_name - A sudden rise in connections from one deployment, worker type, or job
An application pool can be full even if PostgreSQL is not. Conversely, PostgreSQL can be full because many services each have modest-looking pool settings.
3. Look for idle in transaction Sessions
This state is especially dangerous:
SELECT
pid,
usename,
application_name,
client_addr,
now() - xact_start AS transaction_age,
wait_event_type,
wait_event,
left(query, 300) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY xact_start;
An idle in transaction session has started a transaction and then stopped doing useful work.
It can:
- Hold locks longer than expected
- Prevent cleanup of dead tuples
- Delay vacuum-related work
- Occupy a pool connection while doing nothing
- Cause other requests to queue behind it
Common causes include:
- Opening a transaction before calling a slow external API
- Awaiting a network request while a transaction is open
- A code path that begins a transaction but never commits or rolls back
- A process paused by a debugger or job runner
- An ORM session left open across request boundaries
Keep database transactions short. Never hold one open while waiting for an HTTP call, queue message, filesystem operation, user interaction, or lengthy computation.
The Four Common Root Causes
1. A Connection Leak
A leak occurs when code borrows a connection but fails to return it on every execution path.
In Node.js with node-postgres, this is dangerous:
const client = await pool.connect();
await client.query(
"INSERT INTO orders (user_id, total) VALUES ($1, $2)",
[userId, total]
);
client.release();
If client.query() throws, client.release() never runs.
Use try/finally:
const client = await pool.connect();
try {
await client.query(
"INSERT INTO orders (user_id, total) VALUES ($1, $2)",
[userId, total]
);
} finally {
client.release();
}
For transactions, release the connection even when rollback fails:
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query(
"UPDATE accounts SET balance = balance - $1 WHERE id = $2",
[amount, sourceAccountId]
);
await client.query(
"UPDATE accounts SET balance = balance + $1 WHERE id = $2",
[amount, destinationAccountId]
);
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK").catch(() => {});
throw error;
} finally {
client.release();
}
For simple one-query operations, prefer the pool directly:
const result = await pool.query(
"SELECT id, email FROM users WHERE id = $1",
[userId]
);
That avoids manually checking out a client.
With node-postgres, pool.waitingCount represents requests queued because all clients are checked out. It is a useful saturation signal, not merely an error counter.
2. Slow Queries Hold Connections Too Long
No leak is required for a pool to fail.
Imagine:
- Pool size: 20
- Normal query time: 20 ms
- A newly deployed query takes 3 seconds
- Traffic: 50 requests per second
At 3 seconds per request, a small number of slow database operations can occupy every connection.
Incoming requests wait, latency rises, request timeouts occur, retries begin, and the database receives even more work.
Find long-running queries:
SELECT
pid,
application_name,
usename,
state,
now() - query_start AS running_for,
wait_event_type,
wait_event,
left(query, 500) AS query
FROM pg_stat_activity
WHERE state = 'active'
ORDER BY query_start;
Then inspect the query plan outside the incident path:
EXPLAIN (ANALYZE, BUFFERS)
SELECT
o.id,
o.created_at,
o.total
FROM orders o
WHERE o.customer_id = 42
ORDER BY o.created_at DESC
LIMIT 50;
Look for:
- Sequential scans over unexpectedly large tables
- Large sort operations
- Nested loops over many rows
- Lock waits
- Queries missing a selective index
- Queries fetching much more data than the API returns
Do not increase the pool to hide a slow query. You may simply allow more copies of the same expensive query to run concurrently.
3. Connection Multiplication Across Replicas
A pool size that looks safe locally can become unsafe after scaling.
| Workload | Replicas | Pool per replica | Potential PostgreSQL connections |
|---|---|---|---|
| API service | 8 | 15 | 120 |
| Background workers | 4 | 10 | 40 |
| Admin/dashboard | 2 | 5 | 10 |
| Migration/job process | 1 | 5 | 5 |
| Total | 175 |
If PostgreSQL supports 100 application connections, this system can oversubscribe it before a traffic spike.
Inventory every connection-producing process:
- Web/API replicas
- Queue workers
- Cron jobs
- Data-import scripts
- Rails, Django, Spring, Node, Go, and Python processes
- Preview environments
- Admin dashboards
- BI/reporting tools
- Migration runners
- Other services sharing the database
Give each service an explicit connection budget.
A practical starting formula is:
pool per replica ≤
database connection budget
÷
maximum concurrent replicas
Then reserve capacity for:
- Database administration
- Migrations
- Background jobs
- Monitoring
- Failover/restart bursts
- Other applications sharing the same database
4. Long Transactions and Lock Waits
A connection can be active but not making progress because it is waiting for another transaction.
Find lock-related waits:
SELECT
pid,
application_name,
usename,
state,
wait_event_type,
wait_event,
now() - query_start AS waiting_for,
left(query, 300) AS query
FROM pg_stat_activity
WHERE wait_event_type = 'Lock'
ORDER BY query_start;
A common chain looks like this:
- Request A starts a transaction.
- Request A updates a row and performs slow non-database work.
- Request B needs the same row and waits for A's lock.
- More requests queue behind B.
- Connections stay checked out.
- The pool exhausts even though CPU usage may look normal.
Avoid this:
await client.query("BEGIN");
await client.query(
"UPDATE orders SET status = $1 WHERE id = $2",
["processing", orderId]
);
await callSlowPaymentProvider();
await client.query("COMMIT");
Prefer a design that keeps the transaction bounded:
await client.query("BEGIN");
await client.query(
"UPDATE orders SET status = $1 WHERE id = $2",
["payment_pending", orderId]
);
await client.query("COMMIT");
const payment = await callPaymentProvider();
await pool.query(
"UPDATE orders SET status = $1 WHERE id = $2",
[payment.ok ? "paid" : "payment_failed", orderId]
);
For workflows requiring reliable event publication, use an idempotent workflow and, where appropriate, a transactional outbox rather than holding a database transaction open across a remote call.
Pool Metrics You Should Alert On
The pool itself should be observable. Errors are a late signal.
Track these metrics per service instance:
| Metric | Why it matters | Alerting interpretation |
|---|---|---|
| Active/checked-out connections | Shows current pool utilization | Sustained near-max usage matters more than a brief spike |
| Idle connections | Shows available headroom | Near zero plus queued requests indicates saturation |
| Waiting requests | Shows callers blocked for a connection | Alert early; this is often the best pool-exhaustion signal |
| Connection acquisition latency | Shows how long requests wait before touching SQL | Rising acquisition time often precedes user-visible latency |
| Query duration | Finds work holding connections | Break down by query or endpoint where possible |
| Transaction duration | Finds dangerous long transactions | Alert on unusually old transactions |
| PostgreSQL connection count | Detects total server pressure | Group by application name and database |
idle in transaction count | Detects a high-risk anti-pattern | Usually worth a low-threshold alert |
| Lock waits | Identifies blocked work masquerading as pool pressure | Correlate with long transactions and deploys |
In Node.js, expose at least:
metrics.gauge(
"postgres.pool.total",
pool.totalCount
);
metrics.gauge(
"postgres.pool.idle",
pool.idleCount
);
metrics.gauge(
"postgres.pool.waiting",
pool.waitingCount
);
waitingCount is explicitly defined by node-postgres as the number of queued requests waiting when all clients are checked out.
A Safe Sizing Approach
There is no universal "correct pool size."
The right number depends on:
- Database CPU and memory
- Query cost and duration
- Number of application replicas
- Read/write mix
- Workload bursts
- Whether a pooler sits in front of PostgreSQL
- Other services sharing the same database
You can still reason about a starting point.
If a service needs 100 database operations per second and an operation holds a connection for 50 ms on average:
100 operations/sec × 0.05 sec
= 5 concurrently held connections
That is a starting estimate, not a configuration command.
Tail latency matters. A few 2-second queries can consume much more capacity than the average suggests.
Use a conservative per-instance pool, measure waiting time and query time under realistic load, then scale deliberately.
A large pool should be justified by observed demand, not used as a default.
Where PgBouncer Helps and Where It Does Not
PgBouncer can reduce the number of direct PostgreSQL connections, especially when many application processes create short-lived or bursty connections.
Its pooling modes matter:
| PgBouncer mode | When the server connection returns | Main implication |
|---|---|---|
| Session pooling | When the client disconnects | Closest to normal PostgreSQL session behavior |
| Transaction pooling | At transaction end | Better reuse, but session-dependent behavior can break |
| Statement pooling | After each statement | Most aggressive, but multi-statement transactions are not allowed |
Transaction pooling is powerful, but audit your application before switching.
Features that rely on session-level state may not behave as expected when the next transaction uses a different server connection. Examples can include:
- Session settings
- Temporary tables
- Session-scoped advisory locks
- Some prepared-statement assumptions
PgBouncer also does not repair:
- A connection leak in application code
- Slow or blocked queries
- Long-running transactions
- Incorrect retry behavior
- A database that lacks CPU, I/O, or memory capacity
It changes connection reuse. It does not make expensive database work disappear.
Incident Checklist
When the pool exhausts in production:
- Stop increasing limits blindly. Record the exact error, request rate, deployment state, and pool metrics first.
- Check PostgreSQL session states. Group
pg_stat_activitybystateandapplication_name. - Find old transactions. Investigate
idle in transactionand transactions older than your normal request duration. - Find slow or waiting queries. Check active query age, lock waits, and recent query-plan changes.
- Check replica multiplication. Calculate total possible connections across web replicas, workers, jobs, and tools.
- Inspect recent code paths. Look for connections not released in error paths, transactions spanning external calls, and new queries.
- Reduce load safely if necessary. Rate-limit expensive endpoints, pause nonessential workers, or shed low-priority work.
- Fix the cause. Release connections reliably, shorten transactions, improve queries, and set an explicit connection budget.
- Only then tune limits. Increase a pool or server limit only after measuring the database's ability to handle additional concurrent work.
The Key Takeaway
PostgreSQL pool exhaustion is often a symptom, not the root cause.
Before increasing max_connections or application pool sizes, determine whether connections are being leaked, held by slow queries, blocked by locks, trapped inside long transactions, or multiplied across too many application replicas.
Find what is holding the connection first. Raise the limit only when the database can actually handle the additional concurrency.



