Connection Pooling: Reusing the Line

Connection Pooling: Reusing the Line in Java: Opening a database connection is expensive — a TCP handshake, authentication, and session setup, often 50–200 ms.

Concept Explanation

Opening a database connection is expensive — a TCP handshake, authentication, and session setup, often 50–200 ms. Doing that per web request would make your API crawl.

A connection pool opens a set of connections once at startup and lends them out. close() no longer destroys the connection; it returns it to the pool for reuse.

Without pooling:  request -> open (150ms) -> query (2ms) -> destroy
With pooling:     request -> borrow (0.1ms) -> query (2ms) -> return

HikariCP is the fastest mainstream pool and the default in Spring Boot.


Setup

HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/shop");
config.setUsername("app_user");
config.setPassword(System.getenv("DB_PASSWORD"));   // never hard-code

config.setMaximumPoolSize(10);
config.setMinimumIdle(2);
config.setConnectionTimeout(30_000);   // wait up to 30s for a free connection
config.setIdleTimeout(600_000);
config.setMaxLifetime(1_800_000);      // recycle after 30 min

HikariDataSource dataSource = new HikariDataSource(config);

// Borrow and return
try (Connection conn = dataSource.getConnection()) {
    // ... use it ...
}   // returns to the pool, does not close the socket

Sizing the Pool

Bigger is not better. A common starting formula:

pool size = (CPU cores * 2) + effective spindle count

Most applications are well served by 10–20. A pool of 200 usually means threads queueing on the database anyway, just with more memory wasted.

Critically, maximumPoolSize across all your instances must stay below the database's max_connections. Ten app pods with a pool of 50 each need 500 connections — most defaults are 151.


In Spring Boot

No Java config needed:

spring.datasource.url=jdbc:mysql://localhost:3306/shop
spring.datasource.username=app_user
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.max-lifetime=1800000

Common Mistakes

  1. Not closing connections: Without try-with-resources they are never returned, the pool drains, and every request hangs on connectionTimeout. This is the classic pool leak.
  2. Creating a DataSource per request: The pool must be a long-lived singleton, built once at startup.
  3. Oversizing: A pool larger than the database allows causes connection-refused errors under load.
  4. maxLifetime above the database timeout: The pool hands out sockets the server already dropped. Keep it a little below the DB's wait_timeout.

Best Practices

  • Always try-with-resources: It is the entire defence against leaks.
  • Credentials from the environment, never from source.
  • Monitor active vs idle counts: Hikari exposes metrics; a permanently maxed pool is your signal to investigate slow queries, not to raise the cap.

Practice Exercises

  1. The Benchmark: Time 100 queries with DriverManager.getConnection() per query, then with a Hikari pool. Compare.
  2. The Leak: Deliberately borrow connections without closing them until the pool exhausts, and read the timeout exception.
  3. The Tuning Note: Look up your database's max_connections, then calculate a safe maximumPoolSize for running six application instances.