Pool size tuning
Learn how to choose the right max_connections and min_connections for a sqlx pool, how pool size relates to Postgres limits and traffic, and how to measure whether a pool is too small or too large
Pool size tuning is choosing how many database connections a server keeps open at once. The pool is a set of connections the server reuses instead of opening a new one for every request. The size is the number of connections in that set. Too small, and requests wait in line for a free connection. Too large, and the database spends its memory and time managing connections instead of answering queries. Tuning is finding the size where requests rarely wait and the database is never overwhelmed.
Where This Fits
The pool was built earlier with two numbers, a ceiling of 5 and a floor of 1, and those numbers were chosen for learning. The settings behind them were explained one by one. This page is about choosing the numbers for a real server: how to think about them, how to measure whether they are right, and how to change them without guessing.
Think of a taxi rank outside a station. The rank holds a fixed number of taxis. If too few taxis wait there, passengers queue on the pavement. If too many wait there, they block the road and the station cannot move. The right number depends on how many passengers arrive and how long each ride takes. A database pool is the same problem with connections instead of taxis.
The Smallest Working Version
The smallest version is the pool from the project, with its two size settings on their own lines and the rest left at their defaults. Create a project with this Cargo.toml and this src/db.rs.
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres"] }
tokio = { version = "=1.54.1", features = ["full"] }
// src/db.rs
use sqlx::postgres::{PgPool, PgPoolOptions};
use std::time::Duration;
pub async fn create_pool(database_url: &str) -> PgPool {
PgPoolOptions::new()
.max_connections(5)
.min_connections(1)
.acquire_timeout(Duration::from_secs(10))
.idle_timeout(Duration::from_secs(300))
.max_lifetime(Duration::from_secs(1800))
.connect(database_url)
.await
.expect("failed to create the database pool")
}
The defaults the builder starts from are worth keeping in one place, because every tuning decision is a change away from them:
| Setting | Default | Project value |
|---|---|---|
max_connections | 10 | 5 |
min_connections | 0 | 1 |
acquire_timeout | 30 seconds | 10 seconds |
idle_timeout | 10 minutes | 5 minutes |
max_lifetime | 30 minutes | 30 minutes |
The project runs on 5 and 1, which is plenty for a learning server and for a small production service with light traffic. The rest of this page explains how to know when those numbers stop being enough, and what to change them to.
The Concept Behind Pool Size
A database connection is expensive to open. The client and the server shake hands, agree on encryption, check the password, and set up session state. That work takes milliseconds, and a server that did it for every request would spend more time connecting than querying. A pool pays that cost once per connection and then reuses the connection for many requests. A request borrows a connection, runs its query, and returns the connection to the pool. The next request borrows the same connection.
The pool size is the number of connections that can be borrowed at the same time. If ten requests arrive at once and the pool holds five connections, five requests run their queries and five wait. The waiting requests are not rejected. They sit in a queue until a connection comes back, or until the acquire timeout passes. That queue is invisible to the user, who only sees a slow response. A pool that is too small does not fail loudly. It fails slowly, which is harder to notice and harder to diagnose.
The database has its own limit on the other side. Every connection costs the database a backend process and memory, and Postgres has a setting, max_connections, that caps how many connections the whole database will accept, usually 100 on a default install. Every pool on every server that talks to that database shares that budget. A single server with a pool of 50 and a second server with a pool of 60 together ask for 110 connections, and the database refuses the extra 10. Tuning a pool in isolation, without counting the other pools, is how a service that works alone fails the moment a second copy is deployed.
A beginner can picture a library with a fixed number of desks. Readers borrow a desk, read, and leave. If there are too few desks, readers queue at the door. If there are too many desks, the library spends all its money on furniture and has no room for books. The pool size is the number of desks, and the database is the library.
How to Think About max_connections
The ceiling is the number that matters most, and it is set by three things: how many requests run at the same time, how long each query takes, and how many connections the database can afford. A server that handles twenty requests at once, where each request runs one fast query, needs only a handful of connections, because each connection is borrowed for a few milliseconds and returned. A server that handles twenty requests at once, where each request runs a slow query that takes a second, needs twenty connections, because each connection is held for the whole second.
A useful way to think about it is to multiply. If the server receives 100 requests per second and each request holds a connection for 50 milliseconds, the average number of connections in use is 100 times 0.05, which is 5. A pool of 5 handles the average load with no waiting. A pool of 10 handles a burst twice the average. A pool of 50 handles a burst ten times the average, and it costs the database fifty connections to do it. The arithmetic is rough, but it turns a guess into a reasoned starting point, and the measurement section below turns the starting point into a tuned number.
There is a ceiling above the ceiling. The sum of every pool that talks to one database must stay below the database's own max_connections, with room left over for an administrator to connect and investigate when something goes wrong. A common rule is to leave at least a few connections free for that purpose. A database with a limit of 100, serving two servers, might give each server a pool of 20, leaving 60 connections unused, which sounds wasteful until the day a third server is added or a migration needs a connection of its own.
Count Every Pool, Not Just Yours:
The database sees every connection from every pool: the web server, the background worker, the migration runner, and the developer's own psql session. A pool size that fits on one server can break the database when a second server starts. Add up all the pools before raising any one of them.
How to Think About min_connections
The floor is the number of connections the pool keeps open even when nobody is using the server. Its default is 0, which means the pool opens connections only when requests need them. The project sets it to 1, so one connection is always warm and the first request after a quiet period never waits for a new connection to open.
The floor trades a small constant cost against a small occasional delay. One warm connection costs the database one backend process sitting idle, which is almost nothing. The delay it avoids is the time to open a fresh connection, a few milliseconds, paid by the first request after every quiet spell. For a server with steady traffic the floor barely matters, because connections are always in use and the pool never shrinks to the floor. For a server with bursty traffic, long quiet periods followed by sudden bursts, the floor removes the cold-start delay from the first request of each burst.
Setting the floor equal to the ceiling makes a fixed-size pool: every connection opens at startup, and the pool never grows or shrinks. That shape suits a server with predictable, steady load, because the cost of opening connections is paid once at startup and never again. It suits a small server badly, because it pays the full connection cost even when the server is idle, and it makes startup slow. A beginner should keep the floor low, 1 or 2, and let the pool grow to meet traffic rather than pre-opening connections it may never use.
The Three Timeouts That Shape Tuning
Pool size is not the only dial. Three durations shape how a pool behaves under pressure, and tuning the size without understanding them leads to wrong conclusions.
acquire_timeout is the longest a request waits for a connection when the pool is full. The project sets it to 10 seconds, shorter than the 30-second default. A request that waits past it fails with the error pool timed out while waiting for an open connection. That error is the signal that the pool is too small for the load, or that a query is holding connections for too long. Shortening the timeout makes the failure appear sooner, which is kinder to users, who get an error in seconds instead of waiting half a minute, and kinder to operators, who see the problem in the logs instead of watching slow requests pile up.
idle_timeout is the longest a connection sits unused before the pool closes it. The project sets it to 5 minutes. A connection that is returned to the pool and not borrowed again within five minutes is closed, freeing its database resources. Without this, a burst of traffic would leave dozens of idle connections open for hours, holding database memory for nothing.
max_lifetime is the longest a connection lives before the pool closes it, even if it is busy. The project keeps the default of 30 minutes. Rotating connections this way protects against slow leaks, like a database that gradually uses more memory per connection, and against stale state, like a connection that has been idle so long the network between the server and the database has quietly dropped it.
Measuring Whether the Pool Is the Right Size
Tuning without measuring is guessing, and the measurement is easy. Postgres keeps a view called pg_stat_activity that lists every connection to the database right now, including which ones are running a query and which ones are sitting idle. A query against that view shows the pool in action.
SELECT count(*) AS total,
count(*) FILTER (WHERE state = 'active') AS active,
count(*) FILTER (WHERE state = 'idle') AS idle
FROM pg_stat_activity
WHERE datname = 'axum_ch22';
Run it while the server is handling traffic, and the numbers tell a story. If total sits at the ceiling and active is close to total, the pool is full and requests are waiting. If total sits well below the ceiling and idle is most of it, the pool is larger than the traffic needs. If total never rises above 1 or 2, the traffic is light and the pool could be smaller.
The Measurement Query Counts Itself:
The query against pg_stat_activity runs on a database connection of its own, and that connection is included in the total it reports. A total of 3 while the server is idle means the pool holds 2 connections and the measurement query holds the third. Subtract the querying session before judging the pool.
Signs the Pool Size Is Right:
If total stays comfortably below the ceiling during the busiest hour, most connections are idle between bursts, and the logs show no acquire timeout errors, the pool size is working. A pool that never fills and never times out needs no tuning, and raising its ceiling would only spend database resources for nothing.
A second measurement is the acquire time: how long a request waits for a connection. Sqlx can log it, and the log line appears when a request waits longer than the threshold the pool is configured with. A server whose logs show frequent slow acquires has a pool that is too small for its bursts, even if the average load looks fine. Averages hide bursts, and bursts are what fill a pool.
The live check on this machine used a pool with a ceiling of 2 and a timeout of 2 seconds. Two connections were borrowed and held, and a third borrow failed after almost exactly 2 seconds with the timeout error. After the two connections were returned, a query ran normally, and the connection count in pg_stat_activity showed the pool holding its connections. That run proves the mechanism the whole page relies on: a full pool waits, a timeout ends the wait, and a returned connection serves the next request.
Tuning for Different Kinds of Load
Different traffic shapes want different pools, and the table below gives starting points, not rules. Every row is a guess to measure against, and the measurement section above is how the guess is checked.
| Traffic shape | Starting ceiling | Starting floor | Why |
|---|---|---|---|
| Light, a few requests a second | 5 | 1 | The project values, plenty for learning and small services |
| Steady, tens of requests a second | 10 | 2 | The sqlx default ceiling, a warm pair for the first burst |
| Bursty, quiet then sudden spikes | 20 | 1 | Room for the spike, a low floor so quiet periods cost little |
| Heavy, hundreds of requests a second | 50 | 5 | Many connections in use at once, a warm set for the steady load |
The heavy row comes with a warning: a pool of 50 only works if the database can afford 50 connections from this server plus every other pool that talks to it. On a small Postgres with a limit of 100, two servers with pools of 50 leave nothing for anyone else. The answer to heavy load is often not a bigger pool but a connection pooler in front of the database, which is a separate piece of infrastructure and outside this page.
Making the Size Configurable
A pool size written as a fixed number in code has to change with every environment, and the number that fits a laptop does not fit a production server. The size belongs in configuration, read from the environment at startup, so the same binary runs with a pool of 5 in development and a pool of 20 in production.
// src/db.rs
use sqlx::postgres::{PgPool, PgPoolOptions};
use std::time::Duration;
pub async fn create_pool(database_url: &str) -> PgPool {
let max_connections: u32 = std::env::var("POOL_MAX_CONNECTIONS")
.unwrap_or_else(|_| "5".to_string())
.parse()
.expect("POOL_MAX_CONNECTIONS must be a number");
let min_connections: u32 = std::env::var("POOL_MIN_CONNECTIONS")
.unwrap_or_else(|_| "1".to_string())
.parse()
.expect("POOL_MIN_CONNECTIONS must be a number");
PgPoolOptions::new()
.max_connections(max_connections)
.min_connections(min_connections)
.acquire_timeout(Duration::from_secs(10))
.idle_timeout(Duration::from_secs(300))
.max_lifetime(Duration::from_secs(1800))
.connect(database_url)
.await
.expect("failed to create the database pool")
}
The environment variable holds the number as text, the code parses it into a u32, and a value that is not a number stops the program at startup with a clear message. That fail-fast behaviour is deliberate: a bad pool size is a configuration error, and it is better to refuse to start than to run with a silently wrong pool. The fallback values, 5 and 1, match the project, so a developer who sets nothing gets the learning configuration.
Run it with a bigger pool:
POOL_MAX_CONNECTIONS=20 POOL_MIN_CONNECTIONS=2 cargo run
The server starts with a ceiling of 20 and a floor of 2, and nothing in the code changed. That is the point of configuration: the number is a setting, not a fact about the program.
The Pool Size Flow
The sequence below shows what happens when a request needs a connection and the pool is full.
Request arrives, handler needs a connection
|
v
Pool has a free connection -> borrow it at once
|
v
Pool is full -> request waits in the queue
|
v
A connection is returned -> waiting request takes it
|
v
No connection returns before acquire_timeout -> error
|
v
Handler returns the connection to the pool
The queue is the part beginners forget. A full pool does not reject requests. It makes them wait, and the waiting is invisible except as slow responses. The timeout is the only thing that turns a wait into a visible error, which is why the timeout error is the most useful signal in pool tuning: it names the problem, a full pool, instead of letting it hide as slowness.
Testing Pool Behaviour
A test can prove the timeout behaviour without a running server: build a pool with a ceiling of 1 and a short timeout, borrow the only connection, and check that a second borrow fails with the timeout error.
// tests/pool_test.rs
use sqlx::postgres::PgPoolOptions;
use std::time::Duration;
#[tokio::test]
async fn second_acquire_times_out_when_pool_is_full() {
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let pool = PgPoolOptions::new()
.max_connections(1)
.acquire_timeout(Duration::from_secs(1))
.connect(&database_url)
.await
.unwrap();
let held = pool.acquire().await.unwrap();
let result = pool.acquire().await;
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("timed out"));
drop(held);
pool.close().await;
}
The test holds the pool's only connection in held, then tries to borrow a second one. The second borrow waits one second and fails, and the assertion checks that the error message mentions the timeout. Dropping held returns the connection, and pool.close() shuts the pool down cleanly at the end of the test. The test needs a real database, so it reads DATABASE_URL from the environment and fails clearly when the variable is missing.
Run it against a local Postgres:
DATABASE_URL=postgres://postgres:password@localhost/axum_ch22 cargo test --test pool_test
Common Beginner Mistakes
Setting the ceiling to a huge number
// Wrong - the database cannot afford this, and neither can the server
PgPoolOptions::new().max_connections(1000)
A ceiling of 1000 asks the database for a thousand connections, and a default Postgres refuses most of them. Even if the database accepted them, each connection costs memory and a backend process, and the server would spend its time managing connections instead of answering queries. The fix is to start at 5 or 10, measure, and raise the number only when the measurement shows requests waiting.
Setting the floor higher than the ceiling
// Wrong - the floor is clamped to the ceiling, so this is just a pool of 5
PgPoolOptions::new()
.max_connections(5)
.min_connections(10)
Sqlx does not reject this. It clamps the floor down to the ceiling, so the pool behaves as if the floor were 5. The code compiles and runs, and the mistake is invisible until someone reads the settings and wonders why the pool never holds 10 connections. The fix is to keep the floor below the ceiling, and to treat a floor equal to the ceiling as a deliberate fixed-size pool, not an accident.
A Pool of Zero Connections Serves Nothing:
max_connections(0) is legal Rust and a useless pool. A pool that may hold no connections can never serve a query, and every request fails at once. The compiler does not catch it, because 0 is a valid u32. Always check that the ceiling is at least 1, and at least as large as the number of connections the server needs at its busiest moment.
Raising the pool size to fix slow queries
A slow query holds its connection for the whole time it runs. Raising the pool size lets more slow queries run at once, which makes the database slower still, because it is now running more slow queries in parallel. The fix for slow queries is a faster query, an index, or a smaller result, not a bigger pool. Raise the pool when requests wait for a connection while queries are fast. Fix the query when connections are held for a long time.
Tuning the pool and ignoring the database limit
A pool of 20 on each of ten servers is 200 connections, and a database with a limit of 100 refuses half of them. The servers that fail to connect report pool errors at startup, and the ones that succeed work fine, which makes the failure look random. The fix is to add up every pool before changing any of them, and to keep the total below the database limit with room to spare.
Final Complete Example
Here is everything from this page in one place: the configurable pool builder, the main entry point that uses it, and the measurement query that checks the result.
// src/db.rs
use sqlx::postgres::{PgPool, PgPoolOptions};
use std::time::Duration;
pub async fn create_pool(database_url: &str) -> PgPool {
let max_connections: u32 = std::env::var("POOL_MAX_CONNECTIONS")
.unwrap_or_else(|_| "5".to_string())
.parse()
.expect("POOL_MAX_CONNECTIONS must be a number");
let min_connections: u32 = std::env::var("POOL_MIN_CONNECTIONS")
.unwrap_or_else(|_| "1".to_string())
.parse()
.expect("POOL_MIN_CONNECTIONS must be a number");
PgPoolOptions::new()
.max_connections(max_connections)
.min_connections(min_connections)
.acquire_timeout(Duration::from_secs(10))
.idle_timeout(Duration::from_secs(300))
.max_lifetime(Duration::from_secs(1800))
.connect(database_url)
.await
.expect("failed to create the database pool")
}
// src/main.rs
use axum::{routing::get, Router};
// The library declares the module with `pub mod db;` in src/lib.rs,
// which is what makes `axum_project::db::create_pool` reachable here.
#[tokio::main]
async fn main() {
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let pool = axum_project::db::create_pool(&database_url).await;
let app = Router::new()
.route("/", get(|| async { "Hello!" }))
.with_state(pool);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
-- Check the pool while the server runs
SELECT count(*) AS total,
count(*) FILTER (WHERE state = 'active') AS active,
count(*) FILTER (WHERE state = 'idle') AS idle
FROM pg_stat_activity
WHERE datname = 'axum_ch22';
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres"] }
tokio = { version = "=1.54.1", features = ["full"] }
Run it, send it traffic, and watch the measurement query while it runs. The numbers in that query are the answer to the tuning question, and they change as the traffic changes, which is why tuning is a habit, not a one-time choice.
Summary
The decision framework this page leaves behind has three steps, and they repeat in a loop. First, pick a starting size from the traffic shape, small for light load, larger for heavy load, and never above what the database can afford in total. Second, measure with pg_stat_activity and with the acquire timeout errors in the logs, and watch for the two signs: requests waiting means too small, idle connections piling up means too large. Third, change one number at a time, and measure again. A pool tuned that way fits the server it runs on, and it keeps fitting as the traffic grows, because the loop never stops.
The deeper insight is that pool size is a shared budget, not a private setting. Every connection a pool holds is a connection the database cannot give to anyone else, and every pool on every server draws from the same account. A server that tunes its pool without counting the others is spending money it does not have. Count the total, leave room for the administrator, and let the measurement, not the guess, set the number.