Database connection pooling

suggest change

Opening a database connection is expensive. The driver opens a TCP connection, often negotiates TLS, authenticates (SCRAM in PostgreSQL takes several round trips), and the server sets up a session; PostgreSQL even starts a new operating system process for every connection. Doing this for every HTTP request wastes time on both sides and can exhaust the server's connection limit.

A connection pool opens a small number of connections up front and lends them out. Your code "closes" a connection when it is done, and the pool takes it back for the next borrower instead of closing it.

On the JVM the standard pool is HikariCP. Spring Boot uses it by default, and Ktor and Exposed apps usually use it too. This article covers:

The basics of JDBC (statements, result sets, transactions) are covered in JDBC from Kotlin; database-specific details are in PostgreSQL.

Dependencies

// build.gradle.kts
dependencies {
    implementation("com.zaxxer:HikariCP:7.1.0")
    implementation("org.postgresql:postgresql:42.7.14")

    // HikariCP logs through SLF4J; add a binding to see its warnings
    runtimeOnly("org.slf4j:slf4j-simple:2.0.17")
}

The examples use a local PostgreSQL server with a database shop and user app. Any JDBC database works; only the URL and the driver change.

How much a pool saves

This program runs SELECT 1 200 times, first opening a fresh connection with DriverManager each time, then borrowing one from a pool:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import java.sql.Connection
import java.sql.DriverManager
import kotlin.time.measureTime

const val URL = "jdbc:postgresql://localhost:5432/shop"
const val USER = "app"
const val PASSWORD = "secret"

fun selectOne(conn: Connection): Int =
    conn.prepareStatement("SELECT 1").use { ps ->
        ps.executeQuery().use { rs -> rs.next(); rs.getInt(1) }
    }

fun main() {
    val n = 200

    val direct = measureTime {
        repeat(n) {
            DriverManager.getConnection(URL, USER, PASSWORD).use { selectOne(it) }
        }
    }

    val ds = HikariDataSource(HikariConfig().apply {
        jdbcUrl = URL
        username = USER
        password = PASSWORD
        maximumPoolSize = 5
    })
    ds.use {
        ds.connection.use { selectOne(it) } // let the pool open its first connection
        val pooled = measureTime {
            repeat(n) {
                ds.connection.use { selectOne(it) }
            }
        }
        println("DriverManager: $n queries in ${direct.inWholeMilliseconds} ms")
        println("HikariCP:      $n queries in ${pooled.inWholeMilliseconds} ms")
    }
}
DriverManager: 200 queries in 8307 ms
HikariCP:      200 queries in 45 ms

The query is the same; the difference is the cost of connecting. Starting a backend process is especially slow on Windows, where this was measured. On Linux connecting is faster, but still typically costs a few milliseconds per connection, compared with microseconds to borrow from a pool.

Creating a pool

HikariDataSource implements javax.sql.DataSource, so code that takes a DataSource or a Connection doesn't need to know about Hikari:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import javax.sql.DataSource

fun createDataSource(): HikariDataSource {
    val config = HikariConfig().apply {
        jdbcUrl = "jdbc:postgresql://localhost:5432/shop"
        username = System.getenv("DB_USER") ?: "app"
        password = System.getenv("DB_PASSWORD") ?: "secret"
        poolName = "shop-db"
        maximumPoolSize = 4
    }
    return HikariDataSource(config)
}

fun backendPid(ds: DataSource): Int =
    ds.connection.use { conn ->
        conn.createStatement().use { st ->
            st.executeQuery("SELECT pg_backend_pid()").use { rs -> rs.next(); rs.getInt(1) }
        }
    }

fun printPool(ds: HikariDataSource) {
    val pool = ds.hikariPoolMXBean
    println("active=${pool.activeConnections} idle=${pool.idleConnections} total=${pool.totalConnections}")
}

fun main() {
    createDataSource().use { ds ->
        ds.connection.use { conn ->
            println("connection class: ${conn.javaClass.simpleName}")
            println("unwrapped:        ${conn.unwrap(org.postgresql.PGConnection::class.java).javaClass.simpleName}")
        }
        val pids = List(5) { backendPid(ds) }
        println("server process ids: $pids")
        printPool(ds)
        Thread.sleep(1000)
        printPool(ds)
    }
}
connection class: HikariProxyConnection
unwrapped:        PgConnection
server process ids: [25896, 25896, 25896, 25896, 25896]
active=0 idle=1 total=1
active=0 idle=4 total=4

What the output shows:

Create one pool per database per application and share it, for example as a singleton or through dependency injection. A pool per request or per repository defeats the purpose.

The important settings

Setting Default Meaning
jdbcUrl, username, password where and how to connect
maximumPoolSize 10 the most connections the pool will open, idle and in use together
minimumIdle = maximumPoolSize idle connections to keep ready; leave it equal to max for a fixed-size pool
connectionTimeout 30000 ms how long getConnection() waits for a free connection before throwing
idleTimeout 600000 ms when an idle connection above minimumIdle is closed; unused for a fixed-size pool
maxLifetime 1800000 ms a connection is retired and replaced after this age, once it is no longer in use
keepaliveTime 120000 ms how often idle connections are pinged so firewalls don't drop them
validationTimeout 5000 ms the longest time the liveness check may take
leakDetectionThreshold 0 (off) log a warning when a connection is held longer than this
connectionInitSql none SQL run once on every new physical connection
autoCommit true the auto-commit state every borrowed connection starts with
initializationFailTimeout 1 ms how long the constructor tries to connect before failing; negative skips the check
poolName HikariPool-N name used in logs, thread names and metrics

All times are in milliseconds. A configuration for a production service could look like this:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import com.zaxxer.hikari.pool.HikariPool
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds

fun productionConfig(url: String) = HikariConfig().apply {
    jdbcUrl = url
    username = "app"
    password = "secret"
    poolName = "shop-db"

    maximumPoolSize = 10                                  // hard upper limit
    minimumIdle = 10                                      // = max: a fixed-size pool (recommended)
    connectionTimeout = 5.seconds.inWholeMilliseconds     // wait for a free connection
    validationTimeout = 2.seconds.inWholeMilliseconds     // isValid() check on borrow
    idleTimeout = 10.minutes.inWholeMilliseconds          // only used when minimumIdle < max
    maxLifetime = 25.minutes.inWholeMilliseconds          // retire connections before the server/firewall does
    keepaliveTime = 2.minutes.inWholeMilliseconds         // ping idle connections
    leakDetectionThreshold = 30.seconds.inWholeMilliseconds

    // run once for every new physical connection
    connectionInitSql = "SET statement_timeout = '30s'"

    // passed through to the PostgreSQL driver
    addDataSourceProperty("ApplicationName", "shop-api")
    addDataSourceProperty("reWriteBatchedInserts", "true")
}

fun main() {
    HikariDataSource(productionConfig("jdbc:postgresql://localhost:5432/shop")).use { ds ->
        ds.connection.use { conn ->
            conn.createStatement().use { st ->
                st.executeQuery(
                    "SELECT current_setting('statement_timeout'), current_setting('application_name')"
                ).use { rs -> rs.next(); println("timeout=${rs.getString(1)} app=${rs.getString(2)}") }
            }
        }
    }

    // the database is down / unreachable: fail at startup, not on the first request
    try {
        HikariDataSource(productionConfig("jdbc:postgresql://localhost:1/shop"))
    } catch (e: HikariPool.PoolInitializationException) {
        println("startup failed: ${e.message}")
        println("cause: ${e.cause?.javaClass?.simpleName}")
    }
}
timeout=30s app=shop-api
startup failed: Failed to initialize pool: Connection to localhost:1 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
cause: PSQLException

Notes on these values:

Don't hard-code credentials; read them from Environment variables or a configuration file. HikariConfig also has a constructor that takes a java.util.Properties object or the path to a properties file, where the keys have the same names as the properties (jdbcUrl, maximumPoolSize, dataSource.ApplicationName, ...).

When the pool runs out

If every connection is in use, getConnection() blocks until one is returned. After connectionTimeout it gives up and throws SQLTransientConnectionException. Here a pool of 2 connections serves 4 threads that each hold a connection for 1.5 seconds:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import java.sql.SQLTransientConnectionException
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

fun main() {
    val ds = HikariDataSource(HikariConfig().apply {
        jdbcUrl = "jdbc:postgresql://localhost:5432/shop"
        username = "app"
        password = "secret"
        poolName = "tiny"
        maximumPoolSize = 2
        connectionTimeout = 1000 // ms to wait for a free connection (default 30000)
    })
    val pool = ds.hikariPoolMXBean
    val executor = Executors.newFixedThreadPool(4)

    repeat(4) { i ->
        executor.submit {
            try {
                ds.connection.use { conn ->
                    conn.createStatement().use { it.execute("SELECT pg_sleep(1.5)") }
                    println("task $i done")
                }
            } catch (e: SQLTransientConnectionException) {
                println("task $i failed: ${e.message}")
            }
        }
    }

    Thread.sleep(300)
    println("active=${pool.activeConnections} idle=${pool.idleConnections} " +
        "waiting=${pool.threadsAwaitingConnection}")

    executor.shutdown()
    executor.awaitTermination(10, TimeUnit.SECONDS)
    ds.close()
}
active=2 idle=0 waiting=2
task 1 failed: tiny - Connection is not available, request timed out after 1001ms (total=2, active=2, idle=0, waiting=0)
task 2 failed: tiny - Connection is not available, request timed out after 1001ms (total=2, active=2, idle=0, waiting=0)
task 0 done
task 3 done

Which tasks get a connection depends on thread scheduling. The threadsAwaitingConnection value is the most useful number to monitor: if it is often above zero, either the pool is too small or connections are held too long.

The usual causes of exhaustion are not a pool that is too small, but:

Choosing the pool size

It's tempting to make the pool large, but a database can only do as much work at a time as it has CPU cores and disk bandwidth. More connections than that just make queries wait inside the database instead of in the pool, while each connection still costs server memory.

How much a bigger pool helps depends on what the queries do. With queries that mostly wait (here pg_sleep(0.1), standing in for lock waits or slow I/O), throughput grows with the pool size:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.time.measureTime

fun run(poolSize: Int, tasks: Int) {
    HikariDataSource(HikariConfig().apply {
        jdbcUrl = "jdbc:postgresql://localhost:5432/shop"
        username = "app"
        password = "secret"
        maximumPoolSize = poolSize
    }).use { ds ->
        // open all connections up front so we measure only the queries
        List(poolSize) { ds.connection }.forEach { it.close() }

        val executor = Executors.newFixedThreadPool(tasks)
        val took = measureTime {
            repeat(tasks) {
                executor.submit {
                    ds.connection.use { conn ->
                        conn.createStatement().use { it.execute("SELECT pg_sleep(0.1)") }
                    }
                }
            }
            executor.shutdown()
            executor.awaitTermination(1, TimeUnit.MINUTES)
        }
        println("pool size %2d: %d tasks in %4d ms".format(poolSize, tasks, took.inWholeMilliseconds))
    }
}

fun main() {
    for (size in listOf(1, 2, 5, 10, 20)) run(size, tasks = 20)
}
pool size  1: 20 tasks in 2181 ms
pool size  2: 20 tasks in 1091 ms
pool size  5: 20 tasks in  427 ms
pool size 10: 20 tasks in  216 ms
pool size 20: 20 tasks in  110 ms

Replacing the query with CPU-bound work (SELECT count(*) FROM generate_series(1, 2000000)) and running 48 tasks on a 16-core (24-thread) machine gives a different picture:

pool size  1: 48 tasks in 14100 ms
pool size  2: 48 tasks in 8737 ms
pool size  4: 48 tasks in 4841 ms
pool size  8: 48 tasks in 2394 ms
pool size 16: 48 tasks in 1825 ms
pool size 32: 48 tasks in 1594 ms
pool size 48: 48 tasks in 1368 ms

Up to about the number of cores, doubling the pool halves the time; after that, extra connections add little, because the database server has no more CPU to give them. In this test the database ran on the same machine as the client. With a real network, disk I/O and many application instances, the useful size is usually smaller still.

Practical rules:

Monitoring the pool

ds.hikariPoolMXBean gives the live numbers used in the examples above:

Property Meaning
activeConnections currently borrowed
idleConnections open and ready to lend
totalConnections active + idle
threadsAwaitingConnection threads blocked in getConnection()

Expose these through your health or metrics endpoint. For Micrometer (used by Spring Boot and Ktor's metrics plugin) set config.metricRegistry = meterRegistry before creating the pool, and Hikari publishes gauges and timers such as hikaricp.connections.active and hikaricp.connections.acquire (time spent waiting for a connection). Set isRegisterMbeans = true to also see the pool in JMX tools like JConsole and VisualVM.

You can also change maximumPoolSize, minimumIdle, connectionTimeout and the credentials at runtime through ds.hikariConfigMXBean, but most settings are fixed once the pool is running.

Detecting connection leaks

A connection that is never closed is never returned. The pool can't reclaim it, because your code might still be using it. Each leak permanently shrinks the pool until every request times out. leakDetectionThreshold logs a warning, with the stack trace of where the connection was borrowed, when a connection is held longer than the threshold:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource

fun main() {
    val ds = HikariDataSource(HikariConfig().apply {
        jdbcUrl = "jdbc:postgresql://localhost:5432/shop"
        username = "app"
        password = "secret"
        poolName = "leaky"
        maximumPoolSize = 2
        leakDetectionThreshold = 2000 // ms; minimum allowed is 2000
    })

    val conn = ds.connection // borrowed, but never closed
    conn.createStatement().use { it.execute("SELECT 1") }

    Thread.sleep(3000)
    println("active after 3 s: ${ds.hikariPoolMXBean.activeConnections}")
    conn.close()
    ds.close()
}
[leaky:housekeeper] WARN com.zaxxer.hikari.pool.ProxyLeakTask - Connection leak detection triggered for org.postgresql.jdbc.PgConnection@6043cd28 on thread main, stack trace follows
java.lang.Exception: Apparent connection leak detected
	at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:99)
	at LeakKt.main(leak.kt:14)
	at LeakKt.main(leak.kt)
active after 3 s: 1

The warning only reports; the connection stays borrowed. Choose a threshold longer than your slowest legitimate transaction (for example 30 to 60 seconds in production) to avoid false alarms. The fix for leaks is always the same: borrow connections only with use { }, which closes them even when an exception is thrown.

Connection state is reset, mostly

A pooled connection is shared by many borrowers over its lifetime, so whatever one borrower changes, the next one may see. On return, Hikari resets the state that was changed through the JDBC API, and rolls back an uncommitted transaction:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import java.sql.Connection

fun Connection.count(): Long =
    createStatement().use { st ->
        st.executeQuery("SELECT count(*) FROM orders").use { rs -> rs.next(); rs.getLong(1) }
    }

fun main() {
    HikariDataSource(HikariConfig().apply {
        jdbcUrl = "jdbc:postgresql://localhost:5432/shop"
        username = "app"
        password = "secret"
        maximumPoolSize = 1 // so every borrow gets the same physical connection
    }).use { ds ->
        ds.connection.use { conn ->
            conn.createStatement().use { it.execute("CREATE TABLE IF NOT EXISTS orders (id SERIAL PRIMARY KEY, item TEXT)") }
        }

        // borrower 1 changes connection state and forgets to commit
        ds.connection.use { conn ->
            conn.autoCommit = false
            conn.transactionIsolation = Connection.TRANSACTION_SERIALIZABLE
            conn.createStatement().use { it.executeUpdate("INSERT INTO orders (item) VALUES ('book')") }
            println("inside: ${conn.count()} order(s)")
        } // close() returns the connection; the open transaction is rolled back

        // borrower 2 gets the same physical connection back in its default state
        ds.connection.use { conn ->
            println("after:  ${conn.count()} order(s)")
            println("autoCommit=${conn.autoCommit} " +
                "serializable=${conn.transactionIsolation == Connection.TRANSACTION_SERIALIZABLE}")
        }

        // session settings changed with SQL are NOT reset
        ds.connection.use { conn ->
            conn.createStatement().use { it.execute("SET statement_timeout = '2s'") }
        }
        ds.connection.use { conn ->
            conn.createStatement().use { st ->
                st.executeQuery("SHOW statement_timeout").use { rs -> rs.next(); println("statement_timeout=${rs.getString(1)}") }
            }
        }
    }
}
inside: 1 order(s)
after:  0 order(s)
autoCommit=true serializable=false
statement_timeout=2s

Hikari restores autoCommit, readOnly, transactionIsolation, catalog, schema and the network timeout to the pool's configured values, and clears warnings. It doesn't know what you did with SQL: SET commands, temporary tables, prepared server-side state and session variables survive into the next borrow. Put session settings that every connection should have into connectionInitSql; use SET LOCAL inside a transaction for per-request settings, since PostgreSQL undoes those at commit or rollback.

Still commit explicitly. The automatic rollback is a safety net, not a substitute for a transaction helper that commits on success.

Pools and coroutines

JDBC calls block a thread, so in coroutine code they run on Dispatchers.IO. Dispatchers.IO allows 64 threads by default, far more than a typical pool has connections. When 100 coroutines run queries against a pool of 5, up to 64 threads block inside getConnection(), and those that wait longer than connectionTimeout fail. Limiting the dispatcher to the pool size makes surplus coroutines wait as suspended coroutines instead, without a timeout and without holding threads:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.sql.Connection
import java.sql.SQLTransientConnectionException
import java.util.concurrent.atomic.AtomicInteger
import kotlin.time.measureTime

class Db(val ds: HikariDataSource, private val dispatcher: CoroutineDispatcher) {
    suspend fun <T> query(block: (Connection) -> T): T =
        withContext(dispatcher) { ds.connection.use(block) }
}

suspend fun slowQueries(db: Db, n: Int) = coroutineScope {
    val failed = AtomicInteger()
    val took = measureTime {
        (1..n).map {
            async {
                try {
                    db.query { conn -> conn.createStatement().use { it.execute("SELECT pg_sleep(0.1)") } }
                } catch (e: SQLTransientConnectionException) {
                    failed.incrementAndGet()
                }
            }
        }.awaitAll()
    }
    println("  $n queries in ${took.inWholeMilliseconds} ms, $failed timed out")
}

fun main() = runBlocking {
    val ds = HikariDataSource(HikariConfig().apply {
        jdbcUrl = "jdbc:postgresql://localhost:5432/shop"
        username = "app"
        password = "secret"
        maximumPoolSize = 5
        connectionTimeout = 1000
    })
    ds.use {
        println("Dispatchers.IO:")
        slowQueries(Db(ds, Dispatchers.IO), 100)

        println("Dispatchers.IO.limitedParallelism(5):")
        slowQueries(Db(ds, Dispatchers.IO.limitedParallelism(ds.maximumPoolSize)), 100)
    }
}
Dispatchers.IO:
  100 queries in 1746 ms, 29 timed out
Dispatchers.IO.limitedParallelism(5):
  100 queries in 2181 ms, 0 timed out

limitedParallelism creates a view of Dispatchers.IO that runs at most 5 blocks at once, so at most 5 coroutines ever ask the pool for a connection. Create the dispatcher once, next to the pool, and route all database work through it.

Keep a whole transaction inside one withContext block, and don't share a Connection between coroutines. See Coroutines for the basics.

Using a pool with Exposed

Exposed opens a connection for every transaction { } block. Pass it a pool instead of a URL so those connections are reused:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.jdbc.Database
import org.jetbrains.exposed.v1.jdbc.SchemaUtils
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.transactions.transaction

object Products : Table("products") {
    val id = integer("id").autoIncrement()
    val name = varchar("name", 100)
    override val primaryKey = PrimaryKey(id)
}

fun main() {
    val ds = HikariDataSource(HikariConfig().apply {
        jdbcUrl = "jdbc:postgresql://localhost:5432/shop"
        username = "app"
        password = "secret"
        maximumPoolSize = 5
    })
    val db = Database.connect(ds) // Exposed borrows from the pool for every transaction

    transaction(db) {
        SchemaUtils.create(Products)
        Products.insert { it[name] = "Keyboard" }
        Products.insert { it[name] = "Mouse" }
    }
    val names = transaction(db) { Products.selectAll().map { it[Products.name] } }
    println(names)
    println("active=${ds.hikariPoolMXBean.activeConnections} idle=${ds.hikariPoolMXBean.idleConnections}")

    ds.close()
}
[Keyboard, Mouse]
active=0 idle=5

This needs org.jetbrains.exposed:exposed-core and exposed-jdbc (1.6.0). After each transaction block the connection goes back to the pool, so active is 0. Exposed manages commit and rollback, so leave the pool's autoCommit at its default or set isAutoCommit = false; both work.

Shutting down

HikariDataSource is Closeable. Close it when the application stops so the database server can release the sessions right away instead of waiting for them to time out:

import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource

fun main() {
    val ds = HikariDataSource(HikariConfig().apply {
        jdbcUrl = "jdbc:postgresql://localhost:5432/shop"
        username = "app"
        password = "secret"
    })
    Runtime.getRuntime().addShutdownHook(Thread {
        println("closing pool ${ds.poolName}")
        ds.close() // closes idle connections and aborts ones still in use
    })

    // ... run the server ...
    println("closed=${ds.isClosed} running=${ds.isRunning}")
}
closed=false running=true
closing pool HikariPool-1

close() doesn't wait for queries in progress to finish; stop accepting new work and let in-flight requests complete first (see Signals and graceful shutdown). Frameworks such as Ktor and Spring close the pool for you if you register it with their lifecycle.

Gotchas

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents