Skip to content

Database connection pool: how to size and configure it for load

B2Bnetwork team · · 6 min

System performance

In brief

A database connection pool should be small and fixed in size, calculated from traffic and connection hold time rather than from the number of users. A pool that is too small makes threads wait while the database has spare capacity. One that is too large floods the database with parallel queries and slows everyone down. Three more settings matter: the timeout for acquiring a connection, a maximum connection lifetime shorter than network and database limits, and the total across all instances compared with the database limit.

What a connection pool is and why its size matters

A connection pool is a set of database connections opened in advance, which the application borrows for a query or transaction and then returns. Opening a connection is expensive: authentication, often TLS, and in PostgreSQL a new server process. The pool removes that cost from every request.

Pool size works like a valve. A database has limited CPU cores and disks, so beyond a certain number of parallel queries it stops getting faster and loses time to context switching and lock contention. The HikariCP project wiki shows this with an example and gives a formula it attributes to the PostgreSQL project as a starting point:

`connections = (core count × 2) + effective spindle count`

For a database server with 8 cores and data that fits in memory, that is about 16 connections in total, not per application instance. The formula is where tuning starts, not where it ends: the authors recommend confirming it with a load test.

How to calculate pool size from traffic

The other side of the calculation is what the application needs. Little's law says that the average number of busy connections equals throughput multiplied by the average connection hold time. An example for online banking, with illustrative numbers:

QuantityValue
Peak traffic that uses the database400 requests per second
Average connection hold time per request20 ms
Average busy connections400 × 0.02 = 8
Headroom for traffic variation and slower queries× 1.5 to 2
Pool size for the whole application12–16 connections

Two conclusions follow. First, hold time matters as much as traffic: a transaction that calls an external API for 300 ms holds its connection fifteen times longer. Shortening transactions often beats enlarging the pool. Second, the result covers the whole system, so with four instances each gets a share.

We cover throughput calculations in more depth in the article on capacity planning for transaction systems.

Settings to choose deliberately

Using HikariCP, the default pool in Spring Boot applications, as the example. Default values come from the project documentation:

SettingDefaultWhat to set
maximumPoolSize10the calculated result divided by the number of instances
minimumIdlesame as maximumPoolSizeleave it: the documentation recommends a fixed-size pool
connectionTimeout30 sshorter, for example 2–5 s, so overload ends in a fast error instead of a queue of threads
maxLifetime30 mina few seconds below the idle limit of the firewall, load balancer or database
keepaliveTime2 minbelow any idle limit on the path to the database
leakDetectionThreshold0 (disabled)enable it in tests to see connections the code never returns
spring:
  datasource:
    hikari:
      maximum-pool-size: 8
      connection-timeout: 3000
      max-lifetime: 1740000
      keepalive-time: 120000
      leak-detection-threshold: 20000

The most common mistake is a connectionTimeout that is too long. Under overload, threads wait 30 seconds each, the server exhausts its thread pool and stops answering even requests that never needed the database. The second is a maxLifetime longer than the firewall's idle limit: the firewall silently drops the connection and the application finds out only on the next query.

Many instances, autoscaling and a connection proxy

The database has its own connection limit. In PostgreSQL it is set by max_connections, typically 100 by default, and changing it requires a server restart. Calculate the total like this: pool size × the maximum number of application instances, plus batch jobs, reporting tools, migrations and administrative connections.

Autoscaling exceeds that total easily. A pool of 20 connections with 3 pods is 60, but with 10 pods at peak it is already 200, which is more than the default limit. When you set the maximum number of replicas in Kubernetes, look at the database too; we cover this in the article on autoscaling in Kubernetes.

With many small instances, a connection proxy such as PgBouncer for PostgreSQL helps: applications connect to it and it keeps a smaller pool to the database. In the default session mode, a database connection returns to the pool only after the client disconnects. In transaction mode it returns after every transaction, which saves the most, but it does not work with features that assume a persistent session. Compare the list of such features with your code before changing the mode.

How to verify the pool in a load test

Track the pool's own metrics in the test, next to response times:

  1. Collect the number of active, idle and pending connections and the time spent waiting for a connection. HikariCP exposes them through Micrometer and JMX.
  2. Run the test at the forecast peak and check whether threads wait for connections. Growing wait time while the database CPU is idle means the pool is too small or transactions are too long.
  3. Repeat the test with a gradually larger pool. When throughput stops growing and query times in the database rise, you have passed the optimum.
  4. Force a slow database, for example with a long lock on a popular table, and check that the application rejects requests quickly instead of hanging.
  5. Restart the database or fail it over to a replica during the test and measure how quickly the pool rebuilds its connections.
  6. In an endurance test, watch whether the number of active connections returns to baseline. Steady growth is a connection leak.

Pool symptoms alongside other bottlenecks are described in the article on database bottlenecks. An example of testing before a major change in a bank's system is the project on performance testing online banking before a core migration.

Questions and answers

What connection pool size should I start with?

Calculate the average number of busy connections as traffic times hold time, add headroom and compare the result with the formula from the HikariCP wiki for the database server. The result is usually a dozen or a few dozen connections for the whole system, not hundreds. Confirm the starting value with a test, increasing the pool gradually and watching throughput.

Why does a bigger pool make the application slower?

Because the database can only do as much work at once as its cores and disks allow. Extra connections do not speed up queries; they add context switching, lock contention and per-session memory. Each query takes longer and total throughput drops.

What does a timeout when acquiring a connection from the pool mean?

That no connection was released for the whole connectionTimeout. The cause can be a pool that is too small, but more often it is long transactions, slow queries or code that does not return connections. Enable leak detection, check the longest transactions in the database, and only then change the pool size.

Do microservices need PgBouncer?

Not always. With a few instances and small pools the total fits within the database limit. A proxy helps when there are many instances, when autoscaling changes their number a lot, or when serverless functions open short-lived connections. Before enabling transaction mode, check that the application does not rely on session-level database features.

What it looks like in a project

Your system slows down under load? We'll find where it loses time.

Let's talk

Read more: System performance