Connection pool size

Learn how to choose max_connections and min_connections for a sqlx pool, what happens when the pool runs out, and how to read pool size under load

The pool size is the number of connections a PgPool may hold, set by max_connections and min_connections. The maximum is the ceiling the pool never passes, and the minimum is the floor it never drops below. Picking the two numbers is the one sizing decision a database application makes, and it is a trade: too small, and requests wait for a connection that never comes; too large, and the database drowns in connections it cannot serve.

Where This Fits

The options page explained what each pool setting does, including the two size settings. This page is about choosing their values. The defaults, ten at most and zero at least, are fine for learning, and the project runs on five and one. But a beginner who understands why those numbers are what they are can change them with confidence when traffic grows, instead of guessing. The pool exhaustion behaviour shown here is also the most common production failure a small application meets, and recognising it early is worth more than any tuning rule.

Think of a ticket counter with a fixed number of windows. The maximum is the number of windows: ten windows serve ten customers at once, and the eleventh waits in line. The minimum is the number of windows kept staffed even when the hall is empty: one staffed window means the first customer is served at once, with no wait for a clerk to arrive. More windows serve more customers, but each window costs a clerk, and a hall with a hundred windows and ten clerks is no faster than a hall with ten.

The Smallest Working Version

The project sets its size in create_pool:

src/db.rs
use sqlx::postgres::{PgPool, PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .min_connections(1)
        .connect(database_url)
        .await
}

Five connections at most, one kept warm. With that pool, five handlers can run queries at the same time, and the sixth waits. The wait is bounded by the acquire timeout, ten seconds in the project's configuration, after which the request fails instead of waiting forever.

The default, when neither number is set, is ten at most and zero at least. The project lowers the maximum to five because a learning application serves one user at a time, and five is already more than it needs. The project raises the minimum to one because a warm connection makes the first request fast. Both numbers are choices, not requirements, and the rest of this page explains how to make them.

What Happens When the Pool Runs Out

The behaviour is easiest to see with the smallest possible pool: one connection, and a two-second wait. A short program borrows the only connection, then asks for a second one while the first is still held:

let pool = PgPoolOptions::new()
    .max_connections(1)
    .acquire_timeout(Duration::from_secs(2))
    .connect("postgres://postgres:password@127.0.0.1:5432/ch12_sqlx")
    .await?;
let first = pool.acquire().await?;
let second = pool.acquire().await;

The output, measured against a real database:

pool size after connect: 1
first connection acquired, pool size: 1
second acquire failed after 2.001668702s: pool timed out while waiting for an open connection
third acquire after release: true

Three facts are visible in those four lines. The pool holds one connection after connecting, because connect opens one eagerly. The first borrow succeeds at once, and the pool size stays at one, because the pool cannot grow past its maximum of one. The second borrow waits the full two seconds of the acquire timeout, then fails with pool timed out while waiting for an open connection. And once the first connection is released, a third borrow succeeds immediately.

The error message is the key detail. It does not say the database is down, and it does not say the query is wrong. It says the pool timed out waiting for an open connection, which means the pool was full and no connection came back in time. That message is the signature of a pool that is too small for its load, and it points at the size, not at the database.

Pool Timed Out Means the Pool Was Full:

The error pool timed out while waiting for an open connection means every connection was busy for the whole acquire timeout. It is a sizing problem, not a database problem. The database was reachable the entire time; it simply had no free connection to lend. Check the maximum, check how long handlers hold connections, and check for a connection that was borrowed and never returned.

How a Request Waits

When a handler asks the pool for a connection and none is free, the request does not fail at once. It joins a queue, and the pool lends it the next connection that comes back. The queue is fair by default, which means requests are served in the order they arrived, so a request that has waited longest is served first. A request that waits longer than the acquire timeout leaves the queue with the timeout error.

The wait is invisible to the handler code. The handler calls a query function with &pool, and the query function waits inside the pool until a connection is available, then runs. The handler sees only the total time: a query that normally takes five milliseconds takes five milliseconds plus the wait when the pool is busy. That added time is latency the user feels, and it grows as the pool fills, which is why a full pool shows up first as slow responses, and only later as timeout errors.

Choosing the Maximum

There is no formula that gives the right maximum from the traffic alone, because the answer depends on the database as well as the application. Three considerations shape it, and a beginner can reason about each one separately.

The first is concurrency: how many queries run at the same time. A handler that runs one query per request needs one connection per concurrent request. Five requests at once need five connections, and ten need ten. A handler that runs two queries one after another still needs only one connection at a time, because the connection returns to the pool between queries only if the code lets go of it; a query function borrows and returns per call, so sequential queries in one handler reuse one connection in turn. The number that matters is the number of queries running at the same instant, not the number of requests per second.

The second is the database's own limit. PostgreSQL accepts a fixed number of connections, set by its max_connections server setting, commonly 100. Every pool in every application and every tool that connects counts against that limit. A single application with a pool of 100 would take the whole server for itself, and two such applications would exhaust it together. The application's pool must be small enough to leave room for everything else: other applications, administrative connections, and the migration commands.

The third is memory. Each PostgreSQL connection costs the server memory for its backend process, and each connection costs the application a small amount of memory too. A pool of ten costs little. A pool of a hundred costs noticeably more, on both sides, and the extra connections sit idle most of the time if the traffic does not need them. A pool that is larger than the traffic is waste, not safety.

For a small application, the project's five is a reasonable starting point, and the default ten is reasonable too. The number grows when timeout errors appear under real load, and it grows a little at a time, with the error rate watched after each change. A pool that never times out is large enough, and a pool that times out is not.

Choosing the Minimum

The minimum is the number of connections the pool opens at startup and keeps open through quiet periods. The default is zero, which means the pool starts empty and opens connections on demand. The project sets one, which means the pool opens one connection at startup and keeps it.

A minimum above zero buys warm starts. The first request after a quiet period finds a connection already open, so it pays no connection setup cost. A minimum of zero makes that first request pay the setup, which is a few milliseconds on a local database and longer over a network. For an application with steady traffic the difference is invisible, because the pool rarely empties. For an application with bursty traffic, long quiet gaps between bursts, the warm connection smooths the start of each burst.

A minimum also costs. Each warm connection holds a database backend for the lifetime of the application, even when nothing is happening. One warm connection costs almost nothing. Ten warm connections for an application that serves one request a minute wastes nine backends. The rule is to keep the minimum small, one or two, unless the first-request latency after idle periods is a measured problem.

Setting the minimum equal to the maximum gives a fixed-size pool: every connection opens at startup, and the pool never grows or shrinks. That shape suits applications with steady, predictable traffic, where the warmup cost is paid once and the size never changes. It suits learning less well, because the startup is slower and the pool hides the growth behaviour a beginner is trying to see.

Reading the Size Under Load

Two methods report the pool's state while it runs. pool.size() returns how many connections the pool currently holds, busy or idle. pool.num_idle() returns how many of those are idle, waiting for work. Together they show whether the pool is keeping up: a size that sits at the maximum with zero idle means the pool is saturated, and requests are queueing.

println!("pool size: {}", pool.size());
println!("idle: {}", pool.num_idle());

A pool that has just connected reports a size of one, because connect opens a single connection eagerly, and an idle count of one, because nothing has borrowed it yet. Under a burst, the size climbs toward the maximum as the pool opens connections, and the idle count falls to zero. After the burst, the size falls back slowly as the idle timeout reaps connections the traffic no longer needs, down to the minimum.

Watching those two numbers during a load test is the most direct way to choose a size. If the size never reaches the maximum, the pool is larger than the traffic needs. If it sits at the maximum with timeouts, the pool is smaller than the traffic needs. The numbers decide, not a rule of thumb.

The Shape of a Leak

The worst pool failure is a leak: a connection borrowed and never returned. The pool lends a connection to code that holds it past the end of its work, and the pool counts it as busy forever. One leak in a pool of five leaves four usable connections. Five leaks leave none, and every later request times out with the pool-full error, even though the database is healthy and the traffic is light.

The query functions in this chapter cannot leak, because they borrow a connection for the duration of one call and return it when the call finishes. A leak needs a manual acquire, which returns a connection the calling code must drop or return itself. The rule is to hold a manually acquired connection for as short a time as possible, and to let it go, by dropping it, before doing any long work such as calling another service. If the pool fills and the database is idle, a leak is the first thing to look for.

Common Beginner Mistakes

Raising the Maximum to Fix Slow Queries

A pool timeout under load looks like a pool problem, and sometimes it is. But a handler whose query takes ten seconds holds a connection for ten seconds, and ten such handlers fill a pool of ten even though the traffic is small. Raising the maximum to fifty hides the symptom and moves the load to the database, which now runs fifty slow queries at once. The fix for a slow query is a faster query, and the pool size page for a healthy application is the one where connections turn over quickly.

Setting the Maximum to the Database Limit

A pool of 100 against a database that allows 100 connections leaves nothing for anything else: no migration command, no administrative session, no second application. The database refuses the 101st connection, and the refusal looks like a pool failure from the application's side. Keep the application's share well below the server's limit, and remember that every pool and every tool counts.

Copying a Large Number From a Tutorial

Tutorials for large services show pools of fifty or a hundred, because those services need them. A small application that copies the number gets the memory cost and the database load without the traffic that justifies it. Start at five or ten, watch the size under real load, and grow only when the measurements say so. The right number is the smallest one that never times out.

A Larger Pool in One Place

Here is the pool creation with a larger size, for an application whose traffic has outgrown five connections:

src/db.rs
use sqlx::postgres::{PgPool, PgPoolOptions};
use std::time::Duration;

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(20)
        .min_connections(2)
        .acquire_timeout(Duration::from_secs(10))
        .idle_timeout(Duration::from_secs(300))
        .max_lifetime(Duration::from_secs(1800))
        .connect(database_url)
        .await
}

Twenty at most, two kept warm. The rest of the settings are unchanged, because the size is the only thing the traffic outgrew. Change one number, watch the timeout errors and the pool size, and change it again only if the measurements ask for it.

Summary

Pool size is a bet on concurrency: the maximum says how many queries may run at once, and the minimum says how many connections stay warm between bursts. The insight worth keeping is that the pool's own error message tells you which side of the bet is wrong. A timeout while waiting for a connection means the pool was full, and the fix is a bigger pool, a faster query, or a shorter hold, in that order of suspicion.

The pool now has an address, a size, and a set of behaviours. What it does not yet have is a query worth running, and the two macros that check queries before they run are where the chapter turns from plumbing to the actual database work.