Spring Boot "PSQLException: FATAL: sorry, too many clients already" when running tests

Since there hasn't been a suggested answer I am posting my solution. Short version: decrease the connection pool size in test properties:

spring.datasource.hikari.maximum-pool-size=2

Longer version: Spring Boot 2 uses HikariCP by default for connection pooling, which has a default value of 10 for connection pool size (as of Jan 2019). While running a lot of ITs the Spring context is created multiple times, which means each context acquires 10 connections from the database. As far as I've observed, tests allocate connections faster than they are released. Therefore, max_connections limit allowed by the database server (which is typically 100 by default) is reached at some point, which leads to that "too many clients" error.

By limiting the connection pool size to 2 in test properties I was able to fix that problem.


You should change the minimum-idle property, instead of maximum-pool-size

spring.datasource.hikari.minimum-idle=5

The default value for maximum-pool-size is 10, and minimum-idle defaults to the same value as max-pool-size. Changing it to a smaller value than max-pool-size did the trick for me.

My hunch is, the application tries to make a lot of connections to the db when executing tests as they run in parallel. These connections, however, are used for very short period and one connection can easily be reused by multiple test instances. By specifying the minimum-idle property to a smaller value than max-pool size, we are telling HikariCP to add additional connections only when the number of idle connections falls below that threshold. This prevents the connection pool from saturating, and consequently, encountering too many clients scenario.

However, HikariCP did recommend to not set this minimum-idle value, in order to maximise performance and responsiveness to spike demands. I faced my issue when trying to run the tests, hence I have changed the property solely for test env.

I've found Hikari's Github Page to be quite helpful. Over there they have listed all these parameters with brief explanations. Do take a look!