Programming Languages Bug Report

Connection is not available, request timed out: one leaked connection per failed export

A Spring Boot service ran fine for days, then every request failed with HikariCP timeouts until a restart. The pool was not too small. An exception path in a CSV export never returned its connection. How leak detection found the exact line, and why try-with-resources fixed it.

Ingrid Solberg Ingrid Solberg @ingridsolberg · November 30, 2026 · 7 min read · 35 Views
Banner: database connection pool exhausted by a leaked connection

Our reporting service, a Spring Boot application, would run normally for two to four days and then fail completely. Every request returned 500 with the same exception:

org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection
Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available,
request timed out after 30000ms (total=20, active=20, idle=0, waiting=47)
	at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:686)
	at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:179)

Restarting the pods fixed it until the next time. The first response from the team was to raise maximumPoolSize from 10 to 20, which only made the failures arrive a day or two later.

The numbers in the exception tell most of the story: active=20, idle=0. All twenty connections were checked out. But the database told a different story:

SELECT state, count(*) FROM pg_stat_activity
WHERE usename = 'reporting' GROUP BY state;
 state | count
-------+-------
 idle  |    20

Twenty connections open from the service, all idle on the database side, not running anything. The pool believed they were in use; the database saw nobody using them. That combination almost always means connections were borrowed from the pool and never returned. A leak.

Watching the pool over time

HikariCP publishes metrics through Micrometer. Plotting hikaricp_connections_active over a few days showed a staircase: active connections rose by one at irregular intervals and never came back down. Each step lined up with an error in the application log:

WARN  ExportService - export 88213 failed: java.io.IOException: Broken pipe

A CSV export failed when the user closed their browser tab mid-download, and each such failure seemed to cost one connection.

Leak detection

HikariCP can report a connection held longer than a threshold, along with the stack trace of where it was borrowed. We enabled it in staging:

spring:
  datasource:
    hikari:
      leak-detection-threshold: 60000   # ms

Then we started an export and closed the browser tab after a second. A minute later:

WARN  com.zaxxer.hikari.pool.ProxyLeakTask - Connection leak detection triggered for
org.postgresql.jdbc.PgConnection@3c4e2a1f on thread http-nio-8080-exec-7, stack trace follows
java.lang.Exception: Apparent connection leak detected
	at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:127)
	at com.example.reporting.ExportService.streamOrders(ExportService.java:58)
	at com.example.reporting.ExportController.export(ExportController.java:34)

ExportService.java:58. Exact line.

The leaking code

public void streamOrders(long accountId, OutputStream out) throws IOException, SQLException {
    Connection conn = dataSource.getConnection();                       // line 58
    PreparedStatement ps = conn.prepareStatement(
        "SELECT id, reference, total, created_at FROM orders WHERE account_id = ? ORDER BY id");
    ps.setLong(1, accountId);
    ps.setFetchSize(1000);
    conn.setAutoCommit(false);                                          // needed for cursor fetch
    ResultSet rs = ps.executeQuery();

    Writer w = new OutputStreamWriter(out, StandardCharsets.UTF_8);
    while (rs.next()) {
        w.write(toCsvLine(rs));                                         // throws when the client disconnects
    }
    w.flush();

    rs.close();
    ps.close();
    conn.close();                                                       // never reached on exception
}

The method used plain JDBC because it streams large result sets with a cursor, which the ORM layer did not support well. On the happy path everything was closed at the end. When the client disconnected, w.write threw IOException: Broken pipe, the method exited immediately, and conn.close() never ran.

With a pool, close() does not close the physical connection. It returns it to the pool. If it is never called, the pool considers the connection in use forever. Every disconnect during an export permanently removed one connection from the pool, until there were none left.

Why raising the pool size did not help

A bigger pool just means more connections to leak before running out. It delays the outage; it cannot prevent it. Pool size is a performance setting. If the active count only ever grows, the problem is a leak, not capacity.

HikariCP's own guidance on pool sizing is also worth remembering here: a small pool is usually faster than a large one, because the database has a limited number of cores and disks. Raising the pool to hide a leak makes the database worse off too.

Environment

Item Value
Runtime Java 21, Spring Boot 3.3, HikariCP 5.1
Database PostgreSQL 16
Pool maximumPoolSize 10, then 20; connectionTimeout 30 s
Trigger client disconnect during CSV export streaming

1. try-with-resources

Java's try-with-resources closes every resource declared in its header, in reverse order, whether the block completes normally or throws. It is the standard and safe way to use JDBC objects:

public void streamOrders(long accountId, OutputStream out) throws IOException, SQLException {
    String sql = "SELECT id, reference, total, created_at FROM orders WHERE account_id = ? ORDER BY id";

    try (Connection conn = dataSource.getConnection();
         PreparedStatement ps = conn.prepareStatement(sql)) {

        conn.setAutoCommit(false);
        ps.setLong(1, accountId);
        ps.setFetchSize(1000);

        try (ResultSet rs = ps.executeQuery();
             Writer w = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
            while (rs.next()) {
                w.write(toCsvLine(rs));
            }
        } finally {
            conn.rollback();     // read-only transaction; end it before the connection returns to the pool
        }
    }
}

If the write throws, the ResultSet, writer, statement and connection are all closed, and the connection goes back to the pool. Ending the transaction explicitly matters as well: HikariCP rolls back a connection returned with an open transaction when auto-commit was disabled, but being explicit makes the intent clear and avoids relying on pool behaviour.

2. Prefer the framework's abstractions where possible

Most of the service already used Spring's JdbcTemplate, which acquires and releases connections for you. For streaming, JdbcTemplate.queryForStream returns a Stream that holds the connection until the stream is closed, so it must itself be used in try-with-resources:

try (Stream<Order> orders = jdbc.queryForStream(sql, orderMapper, accountId)) {
    orders.forEach(o -> writeCsv(w, o));
}

We moved the export to this, inside a @Transactional(readOnly = true) method so the cursor fetch works. Either version is correct; the important thing is that the resource is scoped by the language, not by a close() call at the end of the method.

3. Keep leak detection on in production

We left leak-detection-threshold enabled in production at 120 seconds, above the longest legitimate export. It only logs, it does not close anything, and its overhead is negligible. A future leak will now produce a stack trace within two minutes of the first occurrence, instead of an outage days later.

4. Pool size back to normal

With the leak gone, we set maximumPoolSize back to 10 and checked that the pool was never saturated under peak load, using the hikaricp_connections_pending metric.

1. A test that disconnects mid-stream. The test writes to an output stream that throws after a few rows, then checks the pool:

@Test
void exportReturnsConnectionWhenClientDisconnects() throws Exception {
    HikariPoolMXBean pool = hikari.getHikariPoolMXBean();
    int before = pool.getActiveConnections();

    OutputStream failing = new FailingOutputStream(5_000);   // throws IOException after 5000 bytes
    assertThrows(IOException.class, () -> exportService.streamOrders(ACCOUNT_ID, failing));

    assertEquals(before, pool.getActiveConnections());
}

On the old code, active connections increased by one each run. On the new code, they return to the starting value.

2. Repeated disconnects in staging. A script started and aborted 500 exports in a row. Active connections stayed between 0 and 3 and returned to 0 afterwards. Leak detection logged nothing.

3. Production. Two weeks after the deploy, the active connection graph had no staircase, the service had not been restarted, and hikaricp_connections_timeout_total stayed at zero.

4. Static analysis. We enabled the SpotBugs rule OBL_UNSATISFIED_OBLIGATION and the IntelliJ inspection for JDBC resources not closed in try-with-resources. SpotBugs flagged two more methods with the same shape in an older module, which we fixed.

5. Security implications. Any user could trigger the leak by starting exports and cancelling them, which made it a cheap denial of service against the whole reporting service. The fix removes that, and exports are now also rate-limited per user.

Takeaways

  • active at the maximum while the database shows the connections idle means a leak, not a small pool.
  • Raising the pool size only delays an outage caused by a leak.
  • Always acquire JDBC resources in try-with-resources so exception paths return the connection.
  • Keep HikariCP's leakDetectionThreshold enabled; it points to the exact line that borrowed the connection.

References: HikariCP configuration, HikariCP: About Pool Sizing, Java try-with-resources, Spring JdbcTemplate.

Add a label

#java #spring-boot #connection-pooling #hikaricp #jdbc
Written by
Ingrid Solberg @ingridsolberg

I work on performance and capacity for a marketplace with heavy read traffic and sharp daily peaks. My days are split between caches, Redis, document stores, connection pools and the load tests that tell us whether any of it will hold. Most of the problems I write about looked like scaling issues and turned out to be something smaller: a cache that refilled itself with stale data, a single command that froze Redis, a pool drained by one leaked connection, a load test that measured its own generator instead of the system. I try hard to measure before changing anything, so each post includes how we gathered numbers, what they showed and how we confirmed the fix under realistic load. I also include the optimisations that made things worse, because those taught me the most.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.