Skip to content

Connection pools

Before a query can run, the application needs a connection to the database. Opening one takes a network connection, authentication and the setup of a session, and the networking module counted the round trips for the first of those. Microsoft’s documentation for SqlClient, the .NET provider for SQL Server, says that pooling avoids a network connection, authentication and session setup for every operation: opening a connection checks a pool for a usable one, and closing it resets the connection and returns it.

The server has its own reason to care. PostgreSQL uses a process-per-user model: every client connects to exactly one backend process, and the postmaster spawns a new backend process every time a connection is requested. Its max_connections setting, which is typically 100 by default, bounds how many can exist, and the documentation says PostgreSQL sizes certain resources, shared memory among them, directly from that value. A connection is not free for the server to hold, and the server will not accept more than its limit.

A connection pool is the application’s answer: a bounded set of open connections that requests borrow, use and return. A request that finds one free starts at once. If every connection is busy, it waits.

Mental model. A connection pool is a queue in front of a few servers, and the servers are its connections. The pool’s size is the number of queries that can be in flight, and the time a request spends waiting for a connection is queueing time, exactly as in the performance module.

The queueing lab from the performance module is this model. Read its controls this way. Servers sharing the queue is the number of connections in the pool. Service time is how long a query holds a connection. The arrival rate is the number of queries per second that the application sends, and it stays at 100 in everything below. Mean time in the system is the time from asking for a connection until the query is done.

Requests arrive at a service with a few servers that share one queue. Raise the arrival rate toward what the servers can serve and watch the time a request spends in the system: it rises slowly at first and then sharply. Change the number of servers, the service time, and how much it varies.

100 req/s
Servers sharing the queue
4
20 ms
1
ClientsHealthy<1%ServiceBusy50%
ClientsHealthy<1%ServiceBusy50%

Each dot stands for many requests. The numbers show the real rate.

No bottleneck: every component has headroom.

Response time at this load

Utilisation
50%Busy
Mean time in the system
21.7 ms1.1× the service time
99th percentile
95.3 ms95th percentile: 63 ms
Requests in the system
2.20.2 of them waiting

Little's Law: 100 requests per second × 21.7 ms = 2.2 requests in the system on average.

Time in the system as utilisation rises

  • Mean
  • 95th percentile
  • 99th percentile

A line that leaves the top of the chart keeps going up: the time grows without limit as utilisation approaches 100%.

Use the left and right arrow keys to move along the curve, and shift with an arrow to move ten points. The reading is announced.

What each level of utilisation costs, with your other settings
UtilisationMeanTimes the service time95th percentile99th percentile
50% · your load21.7 ms1.1× the service time63 ms95.3 ms
70%27.1 ms1.4× the service time75 ms109.9 ms
80%34.9 ms1.7× the service time94.8 ms137.9 ms
90%59.4 ms3× the service time163.3 ms243.9 ms
95%109.1 ms5.5× the service time310.4 ms471.3 ms
99%509 ms25× the service time1.51 s2.31 s
0 ms
Metrics
ComponentStateUtilisationOffered (req/s)Served (req/s)Rejected (req/s)p50p95p99
ClientsHealthy<1%10010000 ms0 ms0 ms
ServiceBusy50%100100016 ms63 ms95 ms
Traffic
100 req/s
Successful
100 req/s
Error rate
0%
Mean latency
22 ms

Illustrative values, not benchmarks of any real product.

Model notes

Assumptions

  • Requests arrive at random, as a Poisson process, at a constant average rate.
  • Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
  • Service times are random with the stated mean; by default they are exponentially distributed.
  • Each node is analysed separately, with the traffic it receives treated as Poisson.
  • Requests arrive independently at random, at a steady average rate, and are served in the order they arrive from one shared queue.

Simplifications

  • Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
  • Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
  • A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
  • A request calls its dependencies one after another. Parallel fan-out is not modelled.
  • When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
  • Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
  • Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
  • A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
  • A caller’s timeout counts the mean time its dependencies take, not their full distribution.
  • The curve is the steady state: it assumes the arrival rate has stayed the same for long enough to settle. A real system takes time to build a queue, and a short burst can fill one even below capacity.
  • Service times are exponential in shape. The variability control changes the mean wait, by a factor of (1 + variability) ÷ 2, and not the shape of the tail.

Parameter values are illustrative. They are not benchmarks of any real product.

At the starting settings, the pool has 4 connections and a query takes 20 ms. The pool can serve 4 ÷ 0.020 = 200 queries per second, so at 100 it is 50% utilised. Little’s Law gives the connections in use: 100 × 0.020 = 2.0 on average, half the pool. The lab shows 2.2 requests in the system, 0.2 of them waiting, and a mean time of 21.7 ms: the 20 ms of the query and 1.7 ms of waiting for a connection.

Now make the queries slower, one setting at a time. Raise Service time and read the Utilisation and Mean time in the system at the top of the lab.

Service time Utilisation Mean time in the system
20 ms 50% 21.7 ms
30 ms 75% 45.3 ms
36 ms 90% 106.9 ms
38 ms 95% 207.4 ms
40 ms 100% no steady state

A query that is 50% slower, 30 ms instead of 20, more than doubles the time a request spends in the system. At 38 ms it is almost ten times what it was. At 40 ms the 4 connections can serve exactly 100 queries per second, the demand, and the lab says that demand is at or above what the servers can serve and that there is no steady state: the queue keeps growing, and so does the time spent in it.

Now put Service time back to 20 ms and take connections away. Set Servers sharing the queue to 3: utilisation is 67% and the mean time is 28.9 ms. Set it to 2 and the lab reports no steady state, because 2 connections serve 100 queries per second at 20 ms. This is what a connection leak does. A request that borrows a connection and never returns it removes one connection from the pool for good, and a second leak halves a pool of 4. Microsoft’s guidance is to open late and dispose early, with every connection, command and reader disposed on every path, for this reason.

What happens if the queries get slower and nobody notices?

Section titled “What happens if the queries get slower and nobody notices?”

The queries slow from 20 ms to 50 ms, perhaps because a table has grown and a query that used an index now scans, as in the last lesson. The pool of 4 can serve 4 ÷ 0.050 = 80 queries per second. Demand is 100. The lab shows 125% utilisation and no steady state.

Follow the queue with arithmetic. It grows by 100 − 80 = 20 requests every second. A new request waits for as many requests as are ahead of it, served 80 a second. SqlClient’s default Connect Timeout is 15 seconds, and the documentation says that when all connections are in use, later opens wait for a connection to return, and that if the wait exceeds the timeout, the open fails. A wait of 15 seconds means 15 × 80 = 1,200 requests ahead, which the queue reaches after 1,200 ÷ 20 = 60 seconds.

For a minute everything seems to work, only slower and slower. Then, in this simple model, requests start to fail: each one that has waited 15 seconds gives up, which is about 20 a second, one request in five, and the ones that are served have waited close to 15 seconds. The error says nothing about the real cause. Microsoft’s guide lists what a pool timeout can mean: a connection leak, slow queries, blocked transactions, too much concurrency, pool fragmentation, or a database capacity limit. The lab can show the first two. The first thing to look at is the plan of the slowest query.

Set Service time to 40 ms again and raise Servers sharing the queue to 8. The lab is calm: 50% utilisation and a mean time of 40.6 ms, with almost no waiting. In the model, the problem is gone.

The model cannot tell you whether it is true. In the lab each connection is an independent server that takes 40 ms whatever the others are doing. In a real database, eight queries running at once share the same processor cores, the same disks and the same locks, so a larger pool can leave every query slower, and the queue just moves from the pool to the inside of the database. The HikariCP guide to pool sizing, written for a Java pool, makes the point with a demonstration by Oracle’s Real-World Performance group: reducing the connection pool size alone, with no other change, decreased the response times of the application from about 100 ms to about 2 ms. It gives a formula that it says the PostgreSQL project provides as a starting point: the number of CPU cores times 2, plus the effective spindle count, which for its example of a 4-core machine with one hard disk is 9. Treat it as a first guess to measure around, not a law.

So the order of questions is: why did the queries get slower, can the database run more of them at once, and only then, how big should the pool be. Putting the queries back to 20 ms with the original 4 connections brings the lab back to 50%.

A pool belongs to one process. Microsoft’s documentation says that connection pools are local to the application process and are not shared across instances, containers or hosts, and that the database’s connection limit must handle the maximum pool size multiplied by every pool in every application instance. The budget is the pool size times the number of instances.

PostgreSQL’s default max_connections is typically 100, and superuser_reserved_connections defaults to 3: once the active connections reach 100 − 3 = 97, new connections are accepted only for superusers. With 10 connections in each instance’s pool, 9 instances use 90 and fit. The tenth would bring the total to 100, and the application can no longer connect. An autoscaling group adds instances exactly when the load rises, so the budget can break at the worst possible moment, and the instances that cannot connect cannot serve anything.

The remedies trade something. Smaller pools per instance reduce the headroom of each one. A separate pooler in front of the database lets many clients share few server connections: PgBouncer, a connection pooler for PostgreSQL, offers transaction pooling, in which a server connection is assigned to a client only during a transaction and then put back. If 400 client connections shared 20 server connections, that would be 20 times fewer connections on the database. The price, in its documentation, is that transaction pooling breaks a few session-based features of PostgreSQL, such as SET, LISTEN and prepared statements.

Three questions on the budget, a slow query and a leak.

Connection pools: check

This quiz needs JavaScript to check your answers.

Question 1 of 3

Each application instance keeps a pool of 10 connections to a PostgreSQL server whose max_connections is 100 and whose superuser_reserved_connections is 3.

How many instances can run with full pools before the database stops accepting ordinary connections?

Enter a number and choose its unit.

instances
Question 2 of 3

An API sends 100 queries per second through a pool of 4 connections. The queries took 20 ms. After a data load they take 40 ms, and requests start to time out while waiting for a connection.

What is the best first move?

Choose one answer.

Question 3 of 3

A pool of 4 connections serves 100 queries per second of 20 ms each. A bug in one code path borrows a connection and never returns it, each time that path runs.

Which statements are true?

Choose every answer that applies.

  • A connection costs a network connection, authentication and a session to open, and a process on the PostgreSQL server to hold, so applications keep a pool and servers limit how many connections they accept.
  • A pool is a queue with as many servers as connections. At 100 queries per second and 20 ms per query, 4 connections are 50% busy; at 40 ms they cannot keep up.
  • A slow query raises utilisation and then removes the steady state. A leaked connection shrinks the pool for good: 4 connections become 3, and 2 cannot serve 100 queries per second at 20 ms.
  • A larger pool is not a faster database: the database’s cores and disks set how many queries really run at once. Find out why the queries slowed down before resizing the pool.
  • The connection budget is the pool size times the number of instances, against max_connections (typically 100) less the 3 reserved. Autoscaling can break it, and a pooler in transaction mode can relieve it at a price.

Next: the recap of this module, a checklist for the data layer, and a quiz.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.