Skip to content

Troubleshooting · Databases

Database connection pool exhausted? 7 causes, ranked

7 causes, most common first · last reviewed

TL;DR

The pool is rarely too small; something is holding connections too long. Usually that is a long or idle transaction, often one that makes a remote call while the connection is checked out. Look at hikaricp.connections.pending and active, then list Postgres sessions by transaction age in pg_stat_activity.

On this page

Quick triage: the first five minutes

  1. Read the pool's state: active, idle, pending and maximum. Pending above zero means threads are queueing for a connection.

    Shell
    for m in active idle pending max; do
      curl -s localhost:8080/actuator/metrics/hikaricp.connections.$m | jq -c '{name, v: .measurements[0].value}'
    done
    In Prometheus: hikaricp_connections_active, _idle, _pending and _max, labelled by pool.
  2. List what the connections are doing on the database, oldest transaction first.

    SQL
    SELECT pid, application_name, state, wait_event_type, wait_event,
           now() - xact_start AS xact_age, left(query, 80) AS query
    FROM pg_stat_activity
    WHERE datname = current_database() AND pid <> pg_backend_pid()
    ORDER BY xact_start NULLS LAST
    LIMIT 20;
    Many 'idle in transaction' rows, or transactions minutes old, are your answer.
  3. Compare total connections with the server limit, across every instance of every app using this database.

    SQL
    SELECT count(*) AS used, current_setting('max_connections') AS max
    FROM pg_stat_activity;

The causes, ranked

Most common first. The ranking is a judgement from how these failures usually turn out, not a measured statistic.

Most common

1. Transactions hold connections too long

What it looks like

  • The application logs show an SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.
  • Database CPU is low; queries themselves are fast.
  • hikaricp.connections.usage (time a connection is held) is far longer than any single query.

How to confirm it

A connection stays checked out for the whole transaction, including everything the code does between statements. Look for @Transactional methods that call HTTP services, publish messages, or loop over work. In pg_stat_activity they show as long xact_age with state 'idle in transaction' between statements.

SQL
SELECT state, count(*), max(now() - xact_start) AS oldest
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state;

Fix it now

Move remote calls and slow work outside the transaction, and keep transactions to the statements that must be atomic. Do not open a transaction for requests that only read one row.

SQL
-- Safety net: end sessions that sit idle inside a transaction
ALTER ROLE app SET idle_in_transaction_session_timeout = '60s';
ALTER ROLE app SET statement_timeout = '15s';
Applies to new sessions for that role; existing connections keep their settings until they reconnect.

Prevent it

Alert on hikaricp.connections.usage at a high percentile, not only on errors. Review where transactions start, especially when a service is refactored.

Common

2. Connections are leaked and never returned

What it looks like

  • Active connections climb steadily over hours and never fall back, even at night.
  • A restart fixes it for a while, then it returns.
  • Errors appear first on one instance, the one that has been up longest.

How to confirm it

Turn on HikariCP's leak detection. It logs a stack trace, starting with 'Connection leak detection triggered', when a connection is held longer than the threshold, showing where it was borrowed.

Fix it now

Fix the code the stack trace points to: a connection, statement or result set opened outside try-with-resources, or a code path that returns early without closing. Restart affected instances to recover meanwhile.

Config
spring.datasource.hikari.leak-detection-threshold=20000

Prevent it

Use try-with-resources or the framework's templates for all JDBC access, and keep leak detection on in staging with a threshold just above your longest legitimate transaction.

Common

3. The pool is smaller than the work in flight

What it looks like

  • Pending connections rise exactly when traffic peaks and drain when it falls.
  • Many more request threads than pool connections: for example 200 server threads against HikariCP's default maximumPoolSize of 10.
  • Connection usage time is short, but acquire time grows.

How to confirm it

Compare hikaricp.connections.acquire with hikaricp.connections.usage. Long waits with short holds mean genuine contention for too few connections; long holds mean the previous causes.

Fix it now

Raise maximumPoolSize moderately, and lower connectionTimeout so callers fail fast instead of piling up for 30 seconds. HikariCP's own pool-sizing guidance favours small pools; more connections than the database can run in parallel only add queueing on the server.

Config
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.connection-timeout=3000

Prevent it

Size pools from measured concurrency, cap request concurrency to match, and load-test with the same pool settings as production.

Common

4. All instances together exceed the database's max_connections

What it looks like

  • New instances fail to start or fail health checks after a scale-out or deploy.
  • The database log shows: FATAL: sorry, too many clients already.
  • Errors begin when autoscaling adds instances, not when traffic per instance rises.

How to confirm it

Multiply instances by maximumPoolSize for every service using the database, add admin tools and replicas, and compare with max_connections. During a rolling deploy, old and new instances overlap, so the peak is higher than the steady state.

SQL
SELECT usename, application_name, count(*)
FROM pg_stat_activity
GROUP BY 1, 2
ORDER BY 3 DESC;

Fix it now

Reduce per-instance pool size, cap the number of instances, or put a pooler such as PgBouncer in transaction mode between the apps and Postgres, which lets many client connections share few server connections.

Prevent it

Keep a written connection budget per service, and include deploy overlap and maximum autoscaling in it. Keep superuser_reserved_connections so administrators can still connect when the limit is hit.

Less common

5. Queries are waiting on locks

What it looks like

  • Many sessions are active but waiting, with wait_event_type 'Lock'.
  • One long-running transaction or migration started shortly before the pool emptied.
  • Throughput on one table drops to near zero while others are fine.

How to confirm it

Find the blockers. A single session holding a lock can stall every connection that touches the same rows or table.

SQL
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type,
       now() - xact_start AS xact_age, left(query, 60) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;

Fix it now

End the blocking session if it is safe to do so (pg_cancel_backend first, pg_terminate_backend if needed), then fix whatever started it: a migration taking a heavy lock at peak, or a batch job updating rows in a different order from the app.

SQL
SELECT pg_cancel_backend(12345);     -- cancel the running query
SELECT pg_terminate_backend(12345);  -- end the session

Prevent it

Set lock_timeout for migrations, run schema changes off-peak, and update rows in a consistent order.

Less common

6. The database itself got slower

What it looks like

  • Database CPU or I/O is high, and every query takes longer.
  • The slowdown follows a data change, a new query, or a plan change after statistics were updated.
  • All pools on all services degrade together.

How to confirm it

If pg_stat_statements is enabled, compare mean execution time per query against a normal period; the top entry is usually the culprit.

SQL
SELECT calls, round(mean_exec_time::numeric, 1) AS mean_ms, left(query, 70) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Fix it now

Fix or kill the expensive query, add the missing index, or roll back the change that introduced it. A bigger pool makes this worse by sending more concurrent work to an already saturated database.

Prevent it

Track query latency per statement over time, and review query plans for new queries before release.

Rare but nasty

7. Connections die silently

What it looks like

  • Bursts of errors such as 'This connection has been closed' or I/O errors after quiet periods or a failover.
  • The pool reports connections as available, but using them fails.
  • A firewall, NAT gateway or proxy sits between the app and the database.

How to confirm it

Compare HikariCP's maxLifetime and keepaliveTime with the idle timeout of anything in the network path and with the database's own timeouts. Connections older than a middlebox's idle timeout can be dropped without either side noticing.

Fix it now

Set maxLifetime a little shorter than the shortest idle timeout in the path, and enable keepalive so idle connections are exercised.

Config
spring.datasource.hikari.max-lifetime=1500000
spring.datasource.hikari.keepalive-time=120000

Prevent it

Write down every timeout between the app and the database, and recheck them after network or failover changes.

See it happen in a real outage

90-second puzzles built from public postmortems. Diagnose it first; the company is revealed after you answer.

Related concepts

FAQ

What does 'Connection is not available, request timed out after 30000ms' mean?

A thread asked HikariCP for a connection and none became free within connectionTimeout, which defaults to 30 seconds. Every connection was checked out the whole time. Find out what is holding them before changing the pool size.

Should I just increase maximumPoolSize?

Only if connections are held briefly and threads genuinely queue for them. If transactions are long, leaked or blocked on locks, a bigger pool fills just the same, and it adds load to a database that may already be the bottleneck.

How do I find connection leaks in HikariCP?

Set leakDetectionThreshold (in milliseconds) above your longest legitimate transaction. HikariCP then logs a stack trace showing where each connection held longer than that was borrowed.

What is 'idle in transaction' in Postgres?

A session that has opened a transaction and is not running a statement, usually because the application is doing other work before committing. It holds its connection and any locks it has taken. idle_in_transaction_session_timeout ends such sessions after a set time.

All troubleshooting guides

Reference documentation: HikariCP: configuration (README) ↗ · HikariCP wiki: About Pool Sizing ↗ · PostgreSQL documentation: the cumulative statistics system (pg_stat_activity) ↗ · PostgreSQL documentation: connections and client connection defaults ↗ · Report a problem

Commands and settings are checked against the documentation linked above. Defaults change between versions; check the documentation for the version you run.