Video in progress

Strong Junior 🏗️ System design

When you scale service instances from 2 to 10, why does the DB start throwing "too many connections" errors?

Each instance has its own connection pool, so the total number of connections is multiplied by the number of instances. 10 × 50 = 500 connections can exceed the DB limit.

📖 Answer

HikariCP defaults to maximumPoolSize = 10. Many people set it to 50 "to make it faster". With 2 instances, 100 connections — PostgreSQL can handle that. Then traffic grows and autoscaling starts 10 pods: 500 connections. In PostgreSQL max_connections is usually around 100–200, and every connection is a separate process that eats memory.

The result: new pods can't connect while starting up, or the DB itself slows down.

What to do:

  • keep the pool small. A number of connections close to the DB's CPU core count often gives the best throughput; 200 parallel queries won't speed up an 8-core DB;
  • do the math in advance: max_instances × pool_size < max_connections − reserve;
  • with many instances, put PgBouncer in between — it turns thousands of client connections into a few dozen real ones.
spring:
  datasource:
    hikari:
      maximum-pool-size: 10
      connection-timeout: 3000   # the wait shouldn't be unlimited