Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

Connection pool exhaustion incidents recur across services. Investigation shows JDBC connections and HTTP responses not closed on error paths. How do you fix this at scale?

We fix it on three levels at once. Prevent leaks by making try-with-resources mandatory for every AutoCloseable, enforced by static analysis such as IDE resource-leak inspections, Sonar's resource rule or Error Prone's checks, and by preferring framework templates such as JdbcTemplate and RestClient that manage resources for us. Detect leaks by enabling HikariCP's leakDetectionThreshold in staging and production with alerts, and publish active and pending connection metrics for every pool. Then keep it fixed by adding leak checks to the shared code review guidelines and to postmortem templates.

Why this question is asked

Pool exhaustion incidents look like outages of the database or of a downstream service, but the cause is usually in our own code: a connection or HTTP response that was never returned on an error path. Each leak is small, and the pool hides it until the last connection is gone, then every request waits and times out. When incidents recur across many services, fixing one bug at a time is not enough. Interviewers ask this scenario to see whether we can turn a code-level lesson into an organization-wide fix. In this answer, we will recap how pools exhaust, reproduce a typical leak, then go through prevention with static analysis and templates, detection with leak thresholds and metrics, and the process changes that keep it fixed.

1How a Pool Runs Out

A connection pool keeps a fixed number of open connections, say 10, and lends them to threads. A thread borrows one with getConnection() and returns it by calling close(), which for a pooled connection means give it back rather than really disconnect. If code never calls close(), the connection stays borrowed forever from the pool's point of view.

The same applies to HTTP clients. Apache HttpClient and the JDK client keep a pool of connections per host, and a response whose body is never consumed or closed keeps its connection busy. Each leaked connection lowers the pool's real size by one, until all are gone. From then on, every request waits for a connection until a timeout, for example HikariCP's connectionTimeout of 30 seconds, and fails.

Step throughFrom one leak per error to an outage
  1. Error path skips close()connection stays borrowed
  2. Pool has 9 of 10 leftnobody notices
  3. Errors continue, leaks add upa downstream slowdown causes many errors
  4. Pool has 0 left
  5. Every request waits 30 sthen fails: connection is not available
  6. Incident looks like a database outagebut the database is idle

6 steps in order. Play them, or step through them one at a time.

2A Typical Leak on an Error Path

The leaks found in the investigation usually look like code that closes resources only on success.

Java
Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement("select * from orders where id = ?");
ps.setLong(1, id);
ResultSet rs = ps.executeQuery(); // throws SQLException on a timeout
Order o = map(rs); // or map() throws on bad data
rs.close(); ps.close(); c.close(); // never reached on an error: connection leaked
// The fixed version
try (Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement("select * from orders where id = ?")) {
ps.setLong(1, id);
try (ResultSet rs = ps.executeQuery()) {
return map(rs);
}
} // all three closed on every path

Notice that the happy path of the leaky code passes every test, because tests rarely force the query to time out. That is why these leaks reach production and why the fix must be systematic rather than relying on reviewers spotting each case.

3Prevention 1: Enforce Try-With-Resources With Static Analysis

A rule that every AutoCloseable must be managed by try-with-resources, or returned to a caller who manages it, is easy to state and can be checked by tools. IntelliJ and Eclipse have resource-leak inspections, Sonar has a rule that resources should be closed, and Error Prone has checks for types annotated as must-be-closed. We pick one tool that runs in CI for every service, start it in reporting mode to measure the existing findings, fix the ones on database and HTTP code first, and then make new findings fail the build.

Tools have false positives, for example a resource handed to an object that closes it later, so we allow a suppression with a comment explaining who owns the resource. Each suppression is then a visible decision rather than an accident.

4Prevention 2: Prefer Templates That Manage Resources

The best way to avoid forgetting close() is not to call it at all. Spring's JdbcTemplate and JdbcClient borrow the connection, create the statement, run our mapping code and close everything, on every path. Spring Data repositories and JPA with @Transactional manage connections through the transaction. RestClient's retrieve().body(...) reads the response and releases the connection; only the lower-level exchange methods hand us a response we must close.

Java
Order o = jdbc.queryForObject(
"select * from orders where id = ?", orderRowMapper, id); // nothing to close
Order o2 = restClient.get().uri("/orders/{id}", id)
.retrieve()
.body(Order.class); // response released for us

Our guideline says raw JDBC and raw HTTP responses are allowed only inside shared adapters with tests for error paths, and application code uses templates.

5Detection: Leak Thresholds and Pool Metrics

Prevention will never be perfect, so we also detect leaks early. HikariCP's leakDetectionThreshold, in milliseconds, logs a warning with the stack trace of the code that borrowed a connection when it has been out longer than the threshold. Set to, say, 30000 in staging and production (spring.datasource.hikari.leak-detection-threshold in Spring Boot), it points directly at the leaking line. The threshold should be longer than the slowest legitimate transaction to avoid false alarms, and we alert on the log line.

Every pool also publishes metrics. HikariCP exposes active, idle and pending connection counts through Micrometer, such as hikaricp.connections.active and hikaricp.connections.pending, and HTTP client pools have similar gauges. Dashboards per service show active connections creeping upward while traffic is flat, which is the signature of a leak, and an alert on pending connections above zero for several minutes warns us before the pool is empty.

What to monitor for each pool
SignalWhat it showsAlert when
Leak detection logstack of the code holding a connectionany occurrence
Active connectionsconnections borrowed nownear max while traffic is flat
Pending threadsthreads waiting for a connectionabove 0 for 5 minutes
Connection timeoutsrequests that gave up waitingany increase
HTTP pool leased countHTTP connections in usenear max per route

6Keeping It Fixed: Reviews and Postmortems

The last step is making the lesson part of how teams work. The shared code review guidelines get a short section on resources: every AutoCloseable is in try-with-resources or owned by something that closes it, raw JDBC and raw HTTP responses are reviewed by someone from the platform team, and new code that adds a pool must add its metrics and leak detection. The postmortem template gets a question: was any resource not released on an error path, and which check should have caught it? If the answer names a gap, such as a tool that missed a pattern, the follow-up action improves the tool, not only the one service.

Over a quarter, we can measure progress with the number of static analysis findings, the number of leak detection warnings per week, and the number of pool exhaustion incidents, which should fall to zero.

7Follow-up questions

Would a bigger pool fix the problem?

No. It only delays exhaustion, because a leak keeps growing until any pool size is used up, and a bigger pool can overload the database when traffic is high. Pool size should be set from database capacity and concurrency, and leaks fixed at the source.

Is leak detection safe to run in production?

Yes, it is cheap in HikariCP: it schedules a check when a connection is borrowed and cancels it when the connection returns. The main risk is noise from a threshold that is shorter than legitimate long transactions, so set it with care.

What about connections held too long rather than leaked?

Long transactions, or calls to slow external services while holding a connection, exhaust a pool the same way. Leak detection finds them too, and the fix is to keep transactions short and never make remote calls inside them.

8Conclusion

In this answer, we saw that pool exhaustion comes from connections and HTTP responses not returned on error paths, small leaks that add up until every request waits. We fixed it at scale by enforcing try-with-resources with static analysis such as IDE inspections, Sonar or Error Prone, by preferring templates like JdbcTemplate and RestClient that manage resources, by enabling HikariCP's leakDetectionThreshold with alerts and publishing active and pending connection metrics per pool, and by adding resource checks to the code review guidelines and postmortem template.

What to say in the interviewAbout 80 seconds aloud

Open with

These incidents look like database outages, but the database is idle; the pool is empty because connections were borrowed and never closed on error paths, so each failure leaks one, and eventually every request waits for connectionTimeout and fails.

Then, if they want more

Since it recurs across services, I would fix it systematically on three levels. Prevention: make try-with-resources mandatory for every AutoCloseable and enforce it with static analysis in CI, IDE resource-leak inspections, Sonar's resource rule or Error Prone, starting in report mode and then failing new findings.

And steer application code towards templates that manage resources, JdbcTemplate or JdbcClient for SQL and RestClient's retrieve for HTTP, so raw JDBC and raw responses only live in shared, tested adapters.

Detection: enable HikariCP's leakDetectionThreshold in staging and production, longer than the slowest legitimate transaction, which logs the stack trace of the code that borrowed the connection, and alert on it. Publish active and pending connection metrics per pool, and alert when pending stays above zero or active creeps up while traffic is flat.

Process: add resource handling to the shared review guidelines and a question to the postmortem template about which check should have caught the leak, so each incident improves the tooling, not just one service.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Connection pool exhaustion incidents recur across services. Investigation shows JDBC...": https://scrivio-interview-library.netlify.app/java/exceptions/dc84a51e12/