Connection Pooling: HikariCP Standalone Configuration

Opening a database connection costs a network handshake, authentication and session setup. A connection pool opens a few connections once and lends them out, so each request borrows one in microseconds. HikariCP is the pool Spring Boot uses by default. This page explains how a pool works, then runs HikariCP 6.3 against H2: reuse, state reset, exhaustion, leaks, sizing and configuration.

Share

Contents

How a connection pool works

A physical database connection is a TCP connection with an authenticated session behind it, and on many databases a server process or thread as well. Creating one takes several network round trips and, with TLS, a handshake; closing one throws all of that away. A connection pool keeps a set of open physical connections and lends them out. Your code calls getConnection() and receives a proxy that wraps a physical connection. Calling close() on the proxy does not disconnect: it resets the connection's state and hands it back to the pool for the next borrower.

HikariCP keeps connections in a structure it calls a ConcurrentBag: a thread that returns a connection is likely to get the same one next time without touching shared state, which keeps borrowing cheap under contention. A background housekeeping task retires connections that have been idle too long or have reached their maximum lifetime, and opens new ones to keep the pool at its configured size.

Connection pools for Java
PoolUsed byNotes
HikariCPSpring Boot's default since 2.0Small, fast, few settings; the subject of this page
Apache Commons DBCP2Many older applicationsMany settings, including statement pooling
Tomcat JDBC poolTomcat-based applicationsCan be used outside Tomcat
AgroalQuarkusIntegrates with Quarkus transactions
Oracle UCPOracle databasesOracle RAC and failover features

The programs use HikariCP 6.3.3 with H2 2.3 in memory on JDK 21. H2 runs in the same process, so connections are far cheaper than against a real server, which makes every pooling effect on this page an underestimate. SLF4J's simple logger sends HikariCP's warnings to standard output so they appear in the outputs.

Borrowing and returning connections

A HikariDataSource is a DataSource: code calls getConnection() and close() exactly as without a pool. The program checks that two borrows get the same physical connection, then compares 2,000 queries through the pool with 2,000 queries that each open a new connection. After a warm-up round, the best of 3 rounds is shown; this is a rough comparison on a 2-CPU Linux machine.

Java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class PoolBasics {

    static final String URL = "jdbc:h2:mem:pool;DB_CLOSE_DELAY=-1";

    static HikariDataSource pool() {
        HikariConfig cfg = new HikariConfig();
        cfg.setJdbcUrl(URL);
        cfg.setUsername("sa");
        cfg.setPassword("");
        cfg.setPoolName("demo");
        cfg.setMaximumPoolSize(4);              // at most 4 physical connections
        cfg.setMinimumIdle(4);                  // keep them open (a fixed-size pool)
        cfg.setConnectionTimeout(1000);        // wait at most 1 s for a free connection
        return new HikariDataSource(cfg);
    }

    static int query(Connection c) throws Exception {
        try (Statement st = c.createStatement(); ResultSet rs = st.executeQuery("SELECT 1")) {
            rs.next();
            return rs.getInt(1);
        }
    }

    public static void main(String[] args) throws Exception {
        try (HikariDataSource ds = pool()) {
            // close() on a pooled connection returns it to the pool; the physical one stays open
            Object first;
            try (Connection c = ds.getConnection()) {
                first = c.unwrap(Connection.class);
                query(c);
            }
            Object second;
            try (Connection c = ds.getConnection()) {
                second = c.unwrap(Connection.class);
            }
            System.out.println("same physical connection reused: " + (first == second));

            // Cost of a pooled borrow versus opening a new connection each time:
            // one warm-up round, then the best of 3 rounds for each
            int n = 2000;
            long pooled = Long.MAX_VALUE;
            long direct = Long.MAX_VALUE;
            for (int round = 0; round < 4; round++) {
                long t0 = System.nanoTime();
                for (int i = 0; i < n; i++) {
                    try (Connection c = ds.getConnection()) {
                        query(c);
                    }
                }
                long t1 = System.nanoTime();
                for (int i = 0; i < n; i++) {
                    try (Connection c = DriverManager.getConnection(URL, "sa", "")) {
                        query(c);
                    }
                }
                long t2 = System.nanoTime();
                if (round > 0) {
                    pooled = Math.min(pooled, t1 - t0);
                    direct = Math.min(direct, t2 - t1);
                }
            }
            System.out.printf("%,d queries: pooled %d ms, new connection each time %d ms%n", n,
                    pooled / 1000000, direct / 1000000);

            var mx = ds.getHikariPoolMXBean();
            System.out.println("pool state: total=" + mx.getTotalConnections() + " active="
                    + mx.getActiveConnections() + " idle=" + mx.getIdleConnections());
        }
    }
}

Output of the borrowing comparison:

Output
same physical connection reused: true
2,000 queries: pooled 7 ms, new connection each time 67 ms
pool state: total=4 active=0 idle=4
  • The second borrow received the same underlying connection: unwrap(Connection.class) returned the same physical object, because close() only handed it back.
  • Even with H2 in the same process, where "connecting" involves no network at all, opening a connection per query was roughly 5 to 15 times slower across runs. Against a database server, a new connection also costs a TCP handshake, often TLS, and authentication, typically several milliseconds or more each, so the gap grows by orders of magnitude.
  • getHikariPoolMXBean() exposes the pool's counters; HikariCP can also publish them to Micrometer or Prometheus. After the loop all 4 connections were idle, because every borrow was returned.

What the pool resets on return

Because connections are shared, whatever one borrower changes would leak to the next. The program uses a pool of exactly one connection, so every borrow gets the same one, and has the first borrower change auto-commit and the isolation level and leave a transaction open.

Java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class StateReset {

    static int rows(Connection c) throws SQLException {
        try (Statement st = c.createStatement();
             ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM note")) {
            rs.next();
            return rs.getInt(1);
        }
    }

    public static void main(String[] args) throws Exception {
        HikariConfig cfg = new HikariConfig();
        cfg.setJdbcUrl("jdbc:h2:mem:reset;DB_CLOSE_DELAY=-1");
        cfg.setUsername("sa");
        cfg.setMaximumPoolSize(1);                 // one connection, so every borrow reuses it
        try (HikariDataSource ds = new HikariDataSource(cfg)) {
            try (Connection c = ds.getConnection(); Statement st = c.createStatement()) {
                st.execute("CREATE TABLE note (txt VARCHAR(20))");
            }

            // Borrower 1 changes session settings and leaves a transaction open
            Object physical;
            try (Connection c = ds.getConnection()) {
                physical = c.unwrap(Connection.class);
                System.out.println("pooled connection class: " + c.getClass().getSimpleName());
                c.setAutoCommit(false);
                c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                try (Statement st = c.createStatement()) {
                    st.executeUpdate("INSERT INTO note VALUES ('uncommitted')");
                }
                System.out.println("borrower 1: autoCommit=" + c.getAutoCommit() + ", isolation="
                        + c.getTransactionIsolation() + ", rows it sees=" + rows(c));
            }                                      // close() without commit

            // Borrower 2 gets the same physical connection, in a clean state
            try (Connection c = ds.getConnection()) {
                System.out.println("same physical connection: " + (c.unwrap(Connection.class)
                        == physical));
                System.out.println("borrower 2: autoCommit=" + c.getAutoCommit() + ", isolation="
                        + c.getTransactionIsolation() + ", rows=" + rows(c));
            }

            // Statements left open by a borrower are closed when the connection is returned
            Statement leaked;
            try (Connection c = ds.getConnection()) {
                leaked = c.createStatement();
            }
            System.out.println("statement left open by borrower 3 is closed: " + leaked.isClosed());

            // Using the proxy after close() fails, even though the physical connection lives on
            Connection returned = ds.getConnection();
            returned.close();
            try {
                returned.createStatement();
            } catch (SQLException e) {
                System.out.println("using a returned connection: " + e.getMessage());
            }
        }
    }
}

Output:

Output
pooled connection class: HikariProxyConnection
borrower 1: autoCommit=false, isolation=8, rows it sees=1
same physical connection: true
borrower 2: autoCommit=true, isolation=2, rows=0
statement left open by borrower 3 is closed: true
using a returned connection: Connection is closed
  • The connection handed out is a HikariProxyConnection, which records changes to session settings.
  • Borrower 1 switched to autoCommit=false and isolation 8 (SERIALIZABLE), inserted a row and returned the connection without committing. Borrower 2 got the same physical connection back with autoCommit=true, isolation 2 (READ_COMMITTED), and 0 rows: the pool rolled back the open transaction and restored the defaults.
  • A Statement left open by a borrower was closed when its connection was returned, so forgotten statements do not pile up on long-lived physical connections.
  • The proxy is dead after close(): using it threw "Connection is closed", even though the physical connection lives on in the pool. Keeping a reference to a returned connection is a bug that the proxy turns into a clear error.

The reset is a safety net, not a design: finish your transactions explicitly, as shown on the transactions page.

When the pool runs dry

A pool has a fixed maximum. The program limits it to 2 connections, takes both without returning them (a leak), and asks for a third. Leak detection is set to 2 seconds.

Java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLTransientConnectionException;
import java.util.ArrayList;
import java.util.List;

public class PoolExhaustion {

    public static void main(String[] args) throws Exception {
        HikariConfig cfg = new HikariConfig();
        cfg.setJdbcUrl("jdbc:h2:mem:small");
        cfg.setUsername("sa");
        cfg.setPoolName("small");
        cfg.setMaximumPoolSize(2);
        cfg.setConnectionTimeout(500);
        cfg.setLeakDetectionThreshold(2000);     // warn if a connection is held over 2 s

        try (HikariDataSource ds = new HikariDataSource(cfg)) {
            // A "leak": two connections taken and not returned
            List<Connection> held = new ArrayList<>();
            held.add(ds.getConnection());
            held.add(ds.getConnection());
            System.out.println("active connections: "
                    + ds.getHikariPoolMXBean().getActiveConnections());

            long t0 = System.nanoTime();
            try (Connection third = ds.getConnection()) {
                System.out.println("unexpected: got " + third);
            } catch (SQLTransientConnectionException e) {
                System.out.println("third request after " + (System.nanoTime() - t0) / 100000000
                        * 100 + " ms: " + e.getMessage());
            }

            Thread.sleep(2500);                  // let leak detection report the held connections
            for (Connection c : held) {
                c.close();
            }
            try (Connection c = ds.getConnection()) {
                System.out.println("after returning them: got a connection again, valid: "
                        + c.isValid(1));
            }
        }
    }
}

Output:

Output
active connections: 2
third request after 500 ms: small - Connection is not available, request timed out after 500ms (total=2, active=2, idle=0, waiting=0)
WARN com.zaxxer.hikari.pool.ProxyLeakTask - Connection leak detection triggered for conn0: url=jdbc:h2:mem:small user=SA on thread main, stack trace follows
java.lang.Exception: Apparent connection leak detected
	at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:99)
	at PoolExhaustion.main(PoolExhaustion.java:22)
WARN com.zaxxer.hikari.pool.ProxyLeakTask - Connection leak detection triggered for conn1: url=jdbc:h2:mem:small user=SA on thread main, stack trace follows
java.lang.Exception: Apparent connection leak detected
	at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:99)
	at PoolExhaustion.main(PoolExhaustion.java:23)
after returning them: got a connection again, valid: true
  • The third request waited the full connectionTimeout of 500 ms and then failed with SQLTransientConnectionException. The message shows the pool state: 2 total, 2 active, 0 idle. In a web application this appears as requests that all hang and then fail together. The default timeout is 30 seconds.
  • After 2 seconds, leak detection logged a warning for each held connection, with the stack trace of the code that borrowed it, which points straight at the missing close(). Leak detection is off by default; set the threshold above your slowest legitimate transaction.
  • Once the connections were closed, the pool worked again.

The usual cause is a code path that borrows a connection without try-with-resources, often in error handling. With frameworks, it is a transaction that stays open while the code waits for a slow remote call.

How big should the pool be?

Every query holds a connection for as long as it runs, so a pool of N connections can serve at most N queries at a time. The program runs 20 threads that each execute 10 queries taking 20 ms, using an H2 function that sleeps, with pools of 2, 5, 10 and 20 connections. Each pool is filled before timing starts.

Java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class PoolSizing {

    // Stands in for a query that takes 20 ms inside the database
    public static int slowQuery() throws InterruptedException {
        Thread.sleep(20);
        return 1;
    }

    public static void main(String[] args) throws Exception {
        int threads = 20;
        int queriesPerThread = 10;
        System.out.println(threads + " threads x " + queriesPerThread
                + " queries of 20 ms = " + threads * queriesPerThread + " queries");
        for (int size : new int[] {2, 5, 10, 20}) {
            HikariConfig cfg = new HikariConfig();
            cfg.setJdbcUrl("jdbc:h2:mem:size" + size + ";DB_CLOSE_DELAY=-1");
            cfg.setUsername("sa");
            cfg.setMaximumPoolSize(size);
            cfg.setConnectionTimeout(30000);
            try (HikariDataSource ds = new HikariDataSource(cfg)) {
                try (Connection c = ds.getConnection(); Statement st = c.createStatement()) {
                    st.execute("CREATE ALIAS SLOW_QUERY FOR 'PoolSizing.slowQuery'");
                }
                while (ds.getHikariPoolMXBean().getIdleConnections() < size) {
                    Thread.sleep(10);                       // let the pool open all connections
                }
                AtomicInteger maxWaiting = new AtomicInteger();
                ExecutorService pool = Executors.newFixedThreadPool(threads);
                long t0 = System.nanoTime();
                List<Future<Long>> waits = new ArrayList<>();
                for (int t = 0; t < threads; t++) {
                    waits.add(pool.submit(() -> {
                        long waited = 0;
                        for (int q = 0; q < queriesPerThread; q++) {
                            long w0 = System.nanoTime();
                            try (Connection c = ds.getConnection()) {
                                waited += System.nanoTime() - w0;
                                maxWaiting.accumulateAndGet(ds.getHikariPoolMXBean()
                                        .getThreadsAwaitingConnection(), Math::max);
                                try (Statement st = c.createStatement()) {
                                    st.execute("CALL SLOW_QUERY()");
                                }
                            }
                        }
                        return waited;
                    }));
                }
                long totalWait = 0;
                for (Future<Long> f : waits) {
                    totalWait += f.get();
                }
                long elapsed = (System.nanoTime() - t0) / 1000000;
                pool.shutdown();
                System.out.printf("pool size %2d: %5d ms total, average wait for a connection"
                        + " %4d ms, up to %2d threads waiting%n", size, elapsed,
                        totalWait / 1000000 / (threads * queriesPerThread), maxWaiting.get());
            }
        }
    }
}

Output (times will differ slightly):

Output
20 threads x 10 queries of 20 ms = 200 queries
pool size  2:  2074 ms total, average wait for a connection  114 ms, up to 19 threads waiting
pool size  5:   839 ms total, average wait for a connection   45 ms, up to 16 threads waiting
pool size 10:   450 ms total, average wait for a connection   15 ms, up to 11 threads waiting
pool size 20:   218 ms total, average wait for a connection    0 ms, up to  0 threads waiting
  • The total time follows a simple rule: 200 queries of 20 ms need 4,000 ms of connection time, divided by the pool size. With 2 connections that is about 2,000 ms; with 20 it is about 200 ms. The measured times came close, a little above the ideal because of thread scheduling and pool overhead.
  • With a small pool, threads spend most of their time waiting for a connection, up to 19 of the 20 at once with 2 connections. Waiting threads are invisible in CPU graphs, so monitor getThreadsAwaitingConnection() or the equivalent pool metric.
  • The catch: the test queries only sleep, so more parallel queries never slowed each other down. A real database has a fixed number of CPU cores and disks, and beyond a point extra concurrent queries just compete. That is why the HikariCP authors recommend small pools, roughly twice the database's core count plus its disks, shared across all application instances. Measure with your real workload before raising the size.

Defaults and configuration checks

HikariCP has few settings, and most defaults are sensible. The program prints them from a fresh HikariConfig, then starts a pool with a lifetime that is too short and an initialization statement, and finally tries two configurations that cannot work.

Java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConfigCheck {

    public static void main(String[] args) throws Exception {
        // The defaults, read from a fresh configuration object
        HikariConfig d = new HikariConfig();
        System.out.println("maximumPoolSize       " + d.getMaximumPoolSize());
        System.out.println("minimumIdle           " + d.getMinimumIdle() + " (-1: same as max)");
        System.out.println("connectionTimeout     " + d.getConnectionTimeout() + " ms");
        System.out.println("idleTimeout           " + d.getIdleTimeout() + " ms");
        System.out.println("maxLifetime           " + d.getMaxLifetime() + " ms");
        System.out.println("keepaliveTime         " + d.getKeepaliveTime() + " ms");
        System.out.println("validationTimeout     " + d.getValidationTimeout() + " ms");
        System.out.println("leakDetectionThreshold " + d.getLeakDetectionThreshold() + " ms");

        // Out-of-range values are corrected with a warning when the pool starts
        HikariConfig cfg = new HikariConfig();
        cfg.setJdbcUrl("jdbc:h2:mem:cfg");
        cfg.setUsername("sa");
        cfg.setPoolName("cfg");
        cfg.setMaximumPoolSize(3);
        cfg.setMaxLifetime(10000);                       // below the 30 s minimum
        cfg.setConnectionInitSql("SET SCHEMA PUBLIC");    // runs once per new connection
        try (HikariDataSource ds = new HikariDataSource(cfg)) {
            System.out.println("maxLifetime after start: " + ds.getMaxLifetime() + " ms");
            try (Connection c = ds.getConnection(); Statement st = c.createStatement();
                 ResultSet rs = st.executeQuery("SELECT CURRENT_SCHEMA")) {
                rs.next();
                System.out.println("schema set by connectionInitSql: " + rs.getString(1));
            }
            // Some settings can change at run time through the config MXBean
            ds.getHikariConfigMXBean().setMaximumPoolSize(5);
            System.out.println("maximumPoolSize changed at run time to "
                    + ds.getMaximumPoolSize());
        }

        // A configuration that cannot work fails early: in the setter or at start-up
        HikariConfig bad = new HikariConfig();
        try {
            bad.setMaximumPoolSize(0);
        } catch (IllegalArgumentException e) {
            System.out.println("setMaximumPoolSize(0): " + e.getMessage());
        }
        bad.setJdbcUrl("jdbc:nosuchdb:test");
        try (HikariDataSource ds = new HikariDataSource(bad)) {
            System.out.println("unexpected: " + ds);
        } catch (RuntimeException e) {
            System.out.println("unknown JDBC URL: " + e.getClass().getSimpleName() + ": "
                    + e.getMessage());
        }
    }
}

Output:

Output
maximumPoolSize       10
minimumIdle           -1 (-1: same as max)
connectionTimeout     30000 ms
idleTimeout           600000 ms
maxLifetime           1800000 ms
keepaliveTime         120000 ms
validationTimeout     5000 ms
leakDetectionThreshold 0 ms
WARN com.zaxxer.hikari.HikariConfig - cfg - maxLifetime is less than 30000ms, setting to default 1800000ms.
maxLifetime after start: 1800000 ms
schema set by connectionInitSql: PUBLIC
maximumPoolSize changed at run time to 5
setMaximumPoolSize(0): maxPoolSize cannot be less than 1
unknown JDBC URL: RuntimeException: Failed to get driver instance for jdbcUrl=jdbc:nosuchdb:test
  • The defaults are 10 connections, a 30-second connection timeout, 10 minutes idle timeout, a 30-minute maximum lifetime and a 2-minute keepalive. minimumIdle of -1 means "same as the maximum", a fixed-size pool, which is what the HikariCP authors recommend.
  • A maxLifetime of 10 seconds is below HikariCP's 30-second minimum, so it logged a warning and used the default instead. Read start-up warnings: a setting you think is active may have been replaced.
  • connectionInitSql runs once on each new physical connection, here to set the schema. It is the right place for session settings that every borrower needs.
  • Some settings, such as the maximum pool size, can be changed at run time through getHikariConfigMXBean(), which helps when tuning a running system.
  • A pool size of 0 was rejected by the setter, and a URL no driver accepts failed when the pool was created, not at the first query.
Key HikariCP settings
SettingDefaultAdvice
maximumPoolSize10Small, sized from the database's cores, across all application instances combined
minimumIdleSame as maximumLeave it for a fixed-size pool
connectionTimeout30 sLower it so overload fails fast rather than piling up waiting requests
maxLifetime30 minKeep it shorter than any timeout the database or a firewall imposes on connections
keepaliveTime2 minKeeps idle connections from being cut by network equipment
leakDetectionThreshold0 (off)Enable in test and staging, or in production while investigating
dataSourcePropertiesNoneDriver settings, such as MySQL's cachePrepStmts

Choosing pool settings

Common situations
SituationWhat to do
Spring Boot applicationHikariCP is already configured; set spring.datasource.hikari.* properties
Plain Java applicationOne HikariDataSource for the life of the application, closed at shutdown
Requests hang, then fail togetherLook for leaks with leakDetectionThreshold; check long transactions
Many threads waiting for connectionsFirst make queries and transactions shorter, then consider a larger pool
Many application instancesDivide the database's connection budget between them
Connections dropped by firewallsLower maxLifetime and keep keepaliveTime on
Tests and scriptsDriverManager is fine; see JDBC basics