Video in progress

When the service autoscaled from 4 replicas to 20, the DB fell over with "too many connections". How do you plan connection pool size together with the replica count?

Total connections = number of replicas × pool size, and that adds up separately for every service. I calculate it from the DB's max_connections, leaving headroom for admin and migrations; I keep the pool small, tie the HPA's maxReplicas to that calculation, and add a pooler like PgBouncer if needed.

📖 Answer

The math is simple, but often nobody does it. HikariCP's default is maximumPoolSize = 10. 4 pods × 10 = 40, no problem. On a sale day the HPA scaled to 20 pods: 200 connections. 3 more services are connected to that same PostgreSQL, and max_connections = 200. New pods fail at startup, and the old ones can't get a connection either. Autoscaling sped up the outage instead of helping.

The plan:

DB max_connections          = 300
superuser/admin/migrations  = -20
other services              = -80
for order-service           = 200
maxReplicas                 = 20
=> maximumPoolSize          <= 10

The pool has to be small. PostgreSQL starts a separate process for every connection, and many more active queries than the DB has cores get in each other's way. The HikariCP authors' starting formula is roughly DB cores × 2 + number of disks, meaning dozens of active connections for the whole cluster, not hundreds. If more threads than pool slots wait for a connection inside a pod, that's normal; limit the wait with connectionTimeout.

spring:
  datasource:
    hikari:
      maximum-pool-size: 10
      minimum-idle: 2
      connection-timeout: 2000

In HikariCP, minimum-idle defaults to the same value as maximum-pool-size. If you make it smaller, the DB doesn't hold 200 idle connections when 20 pods are idle.

If you really need many replicas, put PgBouncer (transaction pooling) between the application and the DB. It squeezes 500 client connections into 50 real DB connections. The price: in transaction mode, session-level things (SET, advisory locks, and in old versions server-side prepared statements) don't work, and with PgJDBC you may need prepareThreshold=0.

The HPA's maxReplicas is set based on DB capacity. "Unlimited scaling" works for CPU, not for DB connections. The same applies when you move to virtual threads: threads become unlimited, connections don't.