Skip to content

Lesson 12 of 14 · 26m

JDBC, HikariCP, and Transactions: Where Requests Meet the Database

Pool leaks that look like outages, PreparedStatement's real injection boundary, and the transactional proxy traps nobody tests.

At 4 p.m. every endpoint starts returning 500 after exactly thirty seconds. The database is healthy — queries from psql answer instantly. The pool stats show all ten connections "in use," and they never come back: one code path forgets to close its Connection on an error branch, and under load the leak eats the pool faster than requests drain. This is the JDBC boundary, and it is where most enterprise Java services actually die.

The pool is the boundary

Opening a TCP connection, doing a TLS handshake, and authenticating against Postgres per request is too slow to do per-request — so you don't. HikariCP has been Spring Boot's default pool since Boot 2.0 (2018): maximumPoolSize defaults to 10, connectionTimeout to 30 seconds. Those two defaults are the whole incident above — ten connections that never return, and a 30-second wait before the caller finds out.

The wrong mental model is "the pool manages itself." It manages check-out; correctness — returning the connection — is on you:

try (var conn = dataSource.getConnection();
     var ps = conn.prepareStatement(
         "SELECT id, email FROM users WHERE id = ?")) {
    ps.setLong(1, userId);
    try (var rs = ps.executeQuery()) {
        return rs.next() ? map(rs) : Optional.empty();
    }
}

try-with-resources is the fix for the leak — the close runs on every exit path, including the exception the original author didn't handle. When the leak still happens, set spring.datasource.hikari.leak-detection-threshold=60000 (ms): Hikari logs the stack trace of the borrower, and the dump names the method that forgot.

PreparedStatement is the injection fix — mostly

PreparedStatement sends SQL text and parameter values separately over the wire protocol; the values never become SQL. That kills SQL injection at the mechanism level — TalkTalk's 2015 breach (£400k ICO fine) ran through string-concatenated SQL on legacy pages, the textbook version of this exact bug.

The honest caveat: bind parameters work for values, not identifiers. You can't ?-bind a table name, a column in ORDER BY, or a LIMIT offset in some drivers. Identifier inputs get a whitelist — if (!ALLOWED_COLUMNS.contains(sort)) throw ... — and LIKE patterns get their wildcards escaped, because % in a bound value is still a wildcard, not an injection.

Transactions: the proxy you're actually calling

@Transactional works through a Spring proxy — the annotation only applies when the call enters the bean from outside. A method calling its own @Transactional method bypasses the proxy entirely: no transaction, no warning, no test failure in the happy path. The second trap is quieter: rollbackFor defaults to RuntimeException and Error — a checked exception commits the transaction. If your domain exception is checked, you rolled back nothing and learned about it from a support ticket.

Keep the transaction on the database, off the network: a remote call inside a transaction holds the connection — and any row locks it took — while the remote service decides whether to answer. Fetch outside, transact inside. And setQueryTimeout exists per-statement; without it a slow query holds its connection as long as the database feels like keeping it, which under a pile-up is the same failure as a leak at a different speed.

Try this

Run a service with a borrowed connection on an error path — conn obtained, exception thrown before close(). Watch leak-detection-threshold name the method in the logs. Then fix it with try-with-resources and prove the pool drains.

Pitfalls

  • maximumPoolSize=10 is not a suggestion to raise — under a connection leak a bigger pool just takes longer to fill. Fix the leak.
  • connectionTimeout=30000 is the worst number in the incident: the caller learns about an exhausted pool only after half a minute of silence. Size it to your latency budget, not the default.
  • N+1 queries: a findAll plus per-row find is a loop in SQL clothing — read the generated SQL (spring.jpa.show-sql, or better, a datasource proxy) before calling it "done."

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.