SteelReed

Search

Search posts, questions…

4. Database & SQL

Connection pooling and HikariCP: internals, settings and sizing

Why connection pools exist, how HikariCP waits for a connection, the settings that matter, sizing with Little's Law, PgBouncer transaction pooling, @Transactional holding connections, virtual threads, HTTP client pools and the metrics to watch, with measured experiments.

18 Nov 20268 min readSenior

–

1. The problem

A payment service runs 20 pods with a pool of 10 each, against PostgreSQL with max_connections = 100. After scaling, new pods fail with too many connections. The next week the payment gateway slows by 2 seconds, the logs fill with SQLTransientConnectionException ... (total=10, active=10, waiting=180), while DB CPU sits at 15%.

2. Key idea

Creating connections is expensive (about 1.1 ms to open on loopback versus 0.045 ms to borrow, before TLS and fork), using them is cheap. A pool only needs enough for connections that are busy: by Little's Law, 2,000 transactions/s × 5 ms held = 10 connections. A bigger pool just moves the queue into the DB, where every query slows down together.

Setting Default How to set it
maximumPoolSize 10 (DB cores × 2) + disks, divided by instance count
connectionTimeout 30 s 1–3 s, shorter than the request timeout
maxLifetime 30 min shorter than MySQL wait_timeout, firewalls, NAT (AWS NAT: 350 s idle)
keepaliveTime 2 min ~60 s if network devices close idle connections
leakDetectionThreshold off enable when you suspect something holds connections too long

2.1 When to grow the pool, when to do something else?

Approach Use when Don't use when
Raise maximumPoolSize pending is high and the DB has spare CPU the DB is saturated, or the total exceeds max_connections
Hold connections for less time usage p99 is high: long transactions, external calls
PgBouncer transaction mode many instances, short transactions you need session-level SET, advisory locks, LISTEN/NOTIFY
Short connectionTimeout you want overload to fail fast batch jobs that accept long waits

With virtual threads, threads are nearly free, so the pool becomes the main back-pressure point; don't size the pool by thread count.

3. In Java

JAVA
// Wrong: the connection is held for the whole 50 ms–30 s HTTP call
@Transactional
public void pay(long orderId) {
    Order o = orders.findById(orderId).orElseThrow();
    PaymentResult r = gateway.charge(o);
    o.markPaid(r.reference());
}
 
// Right: call out first, a short transaction only to write
public void pay(long orderId) {
    Order o = orders.findById(orderId).orElseThrow();     // no transaction needed
    PaymentResult r = gateway.charge(o);                  // no connection held
    tx.executeWithoutResult(s -> orders.markPaid(orderId, r.reference()));
}
// 200 virtual threads, pool 10, 50 ms call: 1,112 ms -> 55 ms; with connectionTimeout 500 ms: 102 errors -> 0

Record a "payment in progress" state before the call to avoid duplicates; see the idempotency post. Set spring.jpa.open-in-view=false for APIs, since by default the connection can be held until the response is written. Other languages: Go's database/sql has SetMaxOpenConns; Node.js pg.Pool has max.

PgBouncer, HTTP clients and metrics
  • PgBouncer transaction mode: a real connection belongs to a client for one transaction. What breaks: session-level SET (use SET LOCAL), advisory locks, temp tables, prepared statements (pgjdbc switches to named statements after 5 uses: prepared statement "S_1" does not exist). Fix: PgBouncer 1.21+ with max_prepared_statements, or prepareThreshold=0.
  • HTTP clients pool too: Apache HttpClient 5 defaults to 25 total and 5 per route. Fire 50 concurrent requests at one host and 45 wait.
  • Metrics (hikaricp.connections.* via Micrometer): pending > 0 for a while, active near max, rising acquire p99 (pool or DB congestion), rising usage p99 (long holds).

4. Working with AI

Hand to AI: sizing the pool from throughput and hold time, finding every HTTP or Kafka call inside @Transactional, building a dashboard from Hikari metrics.

Check yourself in AI-written code:

  • Pods × maximumPoolSize + jobs + admin < max_connections.
  • connectionTimeout is a few seconds, not the 30 s default, for APIs.
  • maxLifetime is shorter than every DB, proxy and network timeout.
  • No HTTP calls, sleeps or external lock waits inside @Transactional.
  • open-in-view is off; there are alerts on pending and usage.

5. Exercises

Exercise 1: Review a "raise the pool to 50" proposal

Dashboard: pending 180, active = max = 10, usage p99 2.1 s, DB CPU 15%. The AI proposes maximumPoolSize: 50 for 20 pods. The DB has 8 cores, SSD, max_connections = 100. What do you answer?

Solution 1
  • 20 × 50 = 1,000 connections, 10× max_connections: new pods won't even start.
  • DB CPU 15% with usage p99 2.1 s: connections are held long, the DB isn't slow. Look for external calls inside transactions (usually the payment gateway).
  • Fix the root as in section 3. Then recompute: an 8-core DB suggests ~17 busy connections for the whole fleet; with 20 pods that's 2–5 each, or put PgBouncer in between.

Exercise 2: Read a Connection reset error

Every morning, the first request after a quiet night fails with Connection reset, and later requests are fine. The service sits behind an AWS NAT Gateway with default Hikari settings. Diagnose and fix.

Solution 2
  • The NAT Gateway drops connections idle for more than 350 s without telling either side. Hikari's default maxLifetime is 30 minutes, so the pool hands out dead connections.
  • Fix: keepaliveTime ~60 s to touch idle connections, maxLifetime shorter than every timeout on the path (e.g. 5 minutes). Check MySQL wait_timeout and PgBouncer server_idle_timeout too.

Summary

  • A pool pays the connection cost once; when exhausted it waits connectionTimeout, then fails.
  • Connections needed ≈ throughput × hold time: short holds matter more than a big pool.
  • Total across instances < max_connections; too many instances means PgBouncer.
  • maxLifetime shorter than every DB and network timeout.
  • No HTTP calls inside @Transactional; turn off open-in-view.

Further reading: Transactions, isolation levels and locking.


Self-compiled notes from official documentation and hands-on practice.

Practice interview questions on this topic

All SQL & Query Tuning questions →

Loading comments…
Next on the roadmapLocks in InnoDB: from the global lock to gap locks, read through data_locks