Connection pooling
A connection pool keeps a set of open database connections and lends them out. Creating a TCP connection and authenticating on every request is too slow. HikariCP is the usual pool in Spring Boot.
Detailed Explanation
A Connection is expensive: handshake, auth, session state. A pool (DataSource) creates a few connections at start, hands one to you on getConnection, and takes it back on close. Your code still looks like open/close. The pool wraps the connection so close is a return, not a socket shutdown.
Size the pool from the database's max_connections and the number of app instances. A pool of 50 on 10 instances is 500 sessions. Too large, and the database queues. Too small, and request threads wait on getConnection. Hikari's default of 10 is a starting point, not a law.
Leak detection (leakDetectionThreshold) logs a stack if a connection is borrowed too long. That is usually a missing try-with-resources or a connection held across a remote call. Never hold a connection while you call another HTTP API.
You reach for a pool in every server process. You skip a pool in a one-shot CLI that opens one connection. You do not create a new HikariDataSource per request.
The cost of a pool that grows without a cap is a downed database. The cost of autoCommit surprises after a returned dirty connection is why pools reset state (or you must). The cost of testing against a pool of 1 is hidden races. The cost of sharing one connection across threads is corruption.
Validation queries (SELECT 1) catch dead connections. Hikari uses JDBC4 isValid when it can.
Think of the pool as a set of parking spaces next to the database, not as "more threads". Application threads wait for a space. If every request also waits on a slow partner API while holding a space, the lot fills and healthy requests queue behind it. Return the connection before you do anything that is not SQL. In Spring, @Transactional borrows a connection for the whole method; keep that method on the database work only.
Code Examples
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
public class Pool {
static HikariDataSource create(String url, String user, String pass) {
HikariConfig cfg = new HikariConfig();
cfg.setJdbcUrl(url);
cfg.setUsername(user);
cfg.setPassword(pass);
cfg.setMaximumPoolSize(10);
return new HikariDataSource(cfg);
}
static void ping(HikariDataSource ds) throws Exception {
try (Connection c = ds.getConnection()) {
System.out.println(c.isValid(2));
}
}
}Common Gotchas
`close()` on a pooled connection returns it
you still must call it.
Pool size × instances must fit `max_connections`
Pool size × instances must fit `max_connections`
Threads must not share one borrowed connection
Threads must not share one borrowed connection