Video in progress

20 pods, each with a HikariCP pool of 20 connections. During a deploy or autoscaling, Postgres throws "too many clients". How do you fix it?

Connections grow with the pod count: 20×20=400, and more with the surge during a rolling update and with the HPA. You need to shrink the pool in each pod, add a pooler such as PgBouncer if necessary, and compute pod count, surge and pool size as one shared budget.

📖 Answer

The arithmetic: Postgres has max_connections = 500, and part of it is reserved for superusers and replication. Hikari's default is minimumIdle = maximumPoolSize, so every pod opens 20 connections right at startup. In the normal state that is 400. A rolling update with maxSurge: 25% adds 5 more pods: 500. If the HPA raises it to 30 under load: 600. The DB rejects new connections at exactly the worst moment.

More connections do not buy speed either. Postgres starts a separate process per connection, and active queries several times the number of cores squeeze each other. HikariCP's well-known advice says the same: keep the pool small, roughly cores × 2 + disks, and that is for the whole DB, not for each pod.

What I do:

  1. A budget: maxReplicas × (1 + surge share) × pool_size + reserve < max_connections. I write the formula into the Helm chart or the review checklist.
  2. Shrink the pool: 5-10 connections are enough for most services. The measure is Hikari's hikaricp_connections_pending metric: if there are almost no waiting threads, the pool is too big. Setting minimumIdle lower also smooths out the wave at startup.
  3. A pooler: PgBouncer in transaction mode collapses thousands of client connections into a few dozen real DB connections. The cost: session state (SET, session-level advisory locks, LISTEN) does not work, and for prepared statements you need to check PgBouncer 1.21+ and the pgJDBC settings.
  4. Deploy strategy: give maxSurge as an exact number, not a percentage, and balance it with maxUnavailable.
  5. Virtual threads: if you turn them on in Java 21, thousands of requests hit the pool at once. The pool becomes the natural limit, which is good, but you must watch connectionTimeout and the wait queue.

You need an alert too: if connections in pg_stat_activity reach 80% of max_connections, fire it immediately, without waiting for the next deploy to fail.