Video in progress

How do you choose the pool size in HikariCP, and what does the "Connection is not available, request timed out" error mean?

The pool size should be a small number close to the database's core count; a big pool doesn't make the database faster. The timeout error means a thread couldn't get a free connection within connectionTimeout: usually the cause is a slow query, a long transaction, or a leak.

📖 Answer

Many people say "there's a lot of load, let's make the pool 200". In reality the database truly runs in parallel only about as many queries as it has cores, and the rest wait in line for CPU and disk. The rough formula in the HikariCP docs: pool = cores * 2 + number of disks. For an 8-core database, 10-20 connections are often enough.

On top of that, several services and several instances connect to one PostgreSQL server. 6 pods × 50 connections = 300, which can exceed max_connections. Every PG connection takes its own process and memory.

spring:
  datasource:
    hikari:
      maximum-pool-size: 15
      connection-timeout: 3000     # ms; 30s default, a user won't wait that long
      leak-detection-threshold: 20000

If I see Connection is not available, I check in this order:

  1. Hikari metrics: hikaricp_connections_active, pending. If active is always at max, connections aren't being returned.
  2. pg_stat_activity: which queries run for a long time, and whether any are idle in transaction.
  3. Whether there is an external HTTP call or a file upload inside a transaction. This is the most common cause.
  4. The stack trace in the leak-detection-threshold log, which shows which code is holding on to the connection.

Increasing the pool is the last resort; first you need to shorten the time a connection is held.