Video in progress

40 microservice instances connect to one PostgreSQL and `too many clients` errors appear. How do you plan connections?

; pgbouncer.ini
[pgbouncer]
pool_mode = transaction
max_client_conn = 4000
default_pool_size = 40
server_reset_query =

I add up the pool size of every instance and compare it with the number of active connections the database can really handle. Usually the fix is to shrink the instance pools and put PgBouncer in transaction mode in between. More connections don't give speed, quite the opposite.

📖 Answer

The math is simple: 40 instances × the Hikari default of 10 = 400 connections. If autoscaling goes up to 80 instances, that's 800. In PostgreSQL every connection is a separate process, several MB of memory, and on a 16-core server only about 30-50 queries run effectively at the same time. The rest fight each other for CPU and locks.

So there are two layers:

  • The instance pool is small: 5-10. I match Hikari's maximumPoolSize not to the thread count but to the number of parallel queries to the database.
  • PgBouncer in transaction mode multiplexes thousands of client connections onto 40-60 server connections.

The cost of transaction mode is that session state isn't kept:

  • SET (at session level), advisory locks tied to the session, LISTEN/NOTIFY and temp tables don't work or work wrong. SET LOCAL works.
  • Server-side prepared statements: PgJDBC creates a named statement after 5 executions (prepareThreshold=5), and if the next transaction lands on a different server connection you get prepared statement "S_1" does not exist. PgBouncer 1.21+ supports this with max_prepared_statements; on older versions you set prepareThreshold=0.

Before deciding, I look at pg_stat_activity grouped by state: often 350 of the 400 connections are idle, which means the problem is the pool size, not the database.