PgPoolOptions
Learn how PgPoolOptions configures a sqlx connection pool, what max_connections, min_connections, acquire_timeout, idle_timeout, and max_lifetime do, and what each one defaults to
PgPoolOptions is the builder that configures a PostgreSQL connection pool before it is created. A builder is a value that collects settings one method call at a time, then builds the finished thing with a final call. Every setting on a pool, how many connections it may hold, how long a request waits for one, how long idle connections live, is set on the options and frozen when the pool is created. After that, the settings cannot change.
Where This Fits
The pool page created a pool with one setting changed, max_connections(5), and left everything else at its default. This page opens up the builder that call started from. The builder is where the pool's behaviour is decided, and the defaults it ships with are sensible for learning and light use, which is why the project ran fine while ignoring them. Knowing what each setting does turns the pool from a magic value into a tuned one, and the pool size discussion builds directly on the two size settings here.
Think of the options as the dials on a machine. The machine is the pool, and the dials set its limits before it starts running. Once the machine is running, the dials are locked: you cannot reach in and turn them. That is why the code sets every option before calling connect. The order is always the same: new options, turn the dials, connect.
The Smallest Working Version
The builder chain from the project, with each setting on its own line:
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(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
}
PgPoolOptions::new() makes an empty builder holding the defaults. Each method after it takes the builder, changes one setting, and returns the builder, so the calls chain. .connect(database_url).await is the final call: it takes the finished settings, opens the pool, and returns it. The chain reads like a sentence, and the order of the settings does not matter, only that they all come before connect.
Every method takes self by value, which is why the chain works: each call consumes the builder and hands back a new one with the change applied. A beginner who tries to store the builder in a variable, call a setter, and then use the variable again gets a compiler error about a moved value. The fix is to keep chaining, or to reassign the variable each time with let options = options.max_connections(5);.
The Defaults, Measured
The defaults come from the SQLx source, and a small program that prints the getters confirms them at runtime:
let options = PgPoolOptions::new();
println!("max_connections default: {}", options.get_max_connections());
println!("min_connections default: {}", options.get_min_connections());
println!("acquire_timeout default: {:?}", options.get_acquire_timeout());
println!("idle_timeout default: {:?}", options.get_idle_timeout());
println!("max_lifetime default: {:?}", options.get_max_lifetime());
max_connections default: 10
min_connections default: 0
acquire_timeout default: 30s
idle_timeout default: Some(600s)
max_lifetime default: Some(1800s)
Each setting also has a getter, named get_ plus the setting name, which reads the value back from an options value before it is connected. The getters exist so a program can inspect its own configuration, and they are how the numbers above were checked rather than trusted from memory.
| Setting | Default | What it controls |
|---|---|---|
max_connections | 10 | Most connections the pool may hold at once |
min_connections | 0 | Fewest connections the pool keeps open |
acquire_timeout | 30 seconds | Longest a request waits for a connection |
idle_timeout | 10 minutes | Longest a connection sits unused before closing |
max_lifetime | 30 minutes | Longest a connection lives before closing |
The documentation calls these defaults a sane configuration for testing and light-duty applications, and suggests production applications change at least max_connections. The rest of this page explains each row of that table in turn.
max_connections
max_connections sets the ceiling: the most connections the pool may hold open at the same time. When every connection is busy and a new request needs one, the pool cannot open another past this number, so the request waits. The default is 10, and the project sets 5, which is plenty for learning and for a small server.
PgPoolOptions::new()
.max_connections(5)
The number is a u32, an unsigned 32-bit integer, so it cannot be negative, and setting it to 0 is legal but useless: a pool that may hold no connections can never serve a query. The setting is a trade between concurrency and database load. More connections let more queries run at once, but each connection costs the database memory and a backend process. The pool size page works through how to pick the number.
min_connections
min_connections sets the floor: the fewest connections the pool keeps open at all times. When the pool starts, it opens this many connections right away, and when an old connection is closed for age or idleness, the pool opens a replacement to stay at the floor. The default is 0, which means the pool opens connections only when requests need them, and the first request pays the cost of opening the first connection.
PgPoolOptions::new()
.min_connections(1)
Setting the floor to 1 means the pool always holds at least one warm connection, so the first request after a quiet period never waits for a new connection to open. The cost is one connection held open even when nobody is using the app. For a small server the cost is negligible, and the project sets the floor to 1 for that reason. A larger floor, such as 5, warms more connections at startup, which makes startup slower but the first burst of traffic faster.
The floor is clamped to the ceiling: if min_connections is set higher than max_connections, the pool treats the floor as equal to the ceiling rather than erroring. Setting both to the same number gives a fixed-size pool, one that opens every connection at startup and never grows or shrinks.
acquire_timeout
acquire_timeout sets the longest a request waits for a connection when the pool is full. A request that needs a connection and finds none free waits, and if no connection comes back within this duration, the wait ends with an error instead of waiting forever. The default is 30 seconds.
PgPoolOptions::new()
.acquire_timeout(Duration::from_secs(10))
The timeout covers the whole wait, including the time spent opening a new connection if the pool has room to grow. It is a Duration, Rust's type for a span of time, built here from a number of seconds. Shorter values fail faster, which is kinder to a user waiting on a slow request and to a system that should shed load instead of queueing it. Longer values tolerate brief spikes, where a burst of requests drains the pool for a few seconds and then subsides.
The error a timed-out wait produces was measured on a pool with one connection and a two-second timeout: a second request for a connection failed after almost exactly two seconds with pool timed out while waiting for an open connection. That message is the acquire timeout speaking, and it means the pool was full, not that the database was down. The distinction matters, because the fix for a full pool is a bigger pool or fewer concurrent requests, while the fix for a down database is a different investigation entirely.
idle_timeout
idle_timeout sets the longest a connection may sit unused before the pool closes it. A connection that has been returned to the pool and not borrowed again within this duration is reaped, which is the pool's word for closing an idle connection to free resources. The default is 10 minutes, wrapped in Some, because the setting is an Option<Duration>: a duration means reap after that long, and None means never reap for idleness.
PgPoolOptions::new()
.idle_timeout(Duration::from_secs(300))
Five minutes is the value the project uses. The reaping runs on a background task inside the pool, so it happens without any code asking for it. A connection reaped for idleness is not an error: the pool simply opens a fresh one when the next request needs it, and the only cost is the connection setup time on that one request. The setting matters most for applications with uneven traffic, where a burst opens many connections and a long quiet period follows: without reaping, the burst's connections would sit open, holding database resources for nothing.
max_lifetime
max_lifetime sets the longest a connection may live, from the moment it is opened, before the pool closes it. The default is 30 minutes, also an Option<Duration>, and passing None means a connection lives until it is reaped for idleness or the pool closes.
PgPoolOptions::new()
.max_lifetime(Duration::from_secs(1800))
Lifetime and idleness are different clocks. Idleness measures the time since the connection was last used. Lifetime measures the time since the connection was opened, whether it was busy or idle the whole time. A connection that is used constantly never trips the idle timeout, because it is never idle, but it still trips the lifetime timeout after thirty minutes. That is deliberate: long-lived connections can accumulate server-side state, stale settings, or unnoticed problems, and recycling them on a schedule keeps the pool healthy. A connection closed for age is replaced like any other, and the replacement is invisible to the application.
The documentation advises against None for lifetime, because a connection that lives forever can hold resources and state without bound. Thirty minutes is a reasonable default, and the project keeps it.
connect and connect_with
The builder ends in one of two calls. connect takes a URL string, parses it, and opens the pool:
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(database_url)
.await?;
connect_with takes a PgConnectOptions value instead, which is the parsed form of a connection string with settings applied in code:
use sqlx::postgres::PgConnectOptions;
let options = PgConnectOptions::new()
.host("127.0.0.1")
.port(5432)
.username("postgres")
.password("password")
.database("ch12_sqlx");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect_with(options)
.await?;
Most programs use connect, because the URL string already carries the host, port, user, password, and database name, and the program reads that string from the environment. connect_with is for programs that need an option the URL cannot express, or that build the connection details from separate configuration values instead of one string. Both return the same PgPool, and both fail the same way when the database is unreachable.
The Settings You Rarely Touch
Three more settings exist on the builder, and a beginner can leave all three alone. They are named here so their names are familiar when they appear in other code.
test_before_acquire is on by default, and it makes the pool run a cheap check on a connection before lending it, to catch connections the server has already closed. Turning it off saves a round trip per checkout and risks lending a dead connection.
after_connect runs a callback each time the pool opens a new connection, for setup such as running a SET statement on the fresh connection. before_acquire and after_release run callbacks around each checkout and return, for bookkeeping or per-request setup.
acquire_slow_threshold is two seconds by default, and it controls when the pool logs a warning that acquiring a connection took a long time. It is a diagnostic, not a limit: crossing it logs, it does not fail the request.
Reading the Settings Back
The getters pair with the setters, one per setting, and they read from the options value before connect is called. After connect, the options value is consumed and the pool holds the settings internally, so the getters are only available beforehand. That is why configuration is inspected in the builder chain, not on the finished pool:
let options = PgPoolOptions::new()
.max_connections(5)
.min_connections(1);
println!("max: {}", options.get_max_connections());
println!("min: {}", options.get_min_connections());
let pool = options.connect(database_url).await?;
max: 5
min: 1
Printing the settings at startup is a small habit that pays off the first time a pool behaves unexpectedly: the output shows what the pool was actually configured with, instead of what the programmer remembers writing.
Common Beginner Mistakes
Setting Options After connect
// Wrong - connect consumes the builder, so there is nothing left to set
let pool = PgPoolOptions::new().connect(database_url).await?;
let pool = pool.max_connections(5);
PgPool has no max_connections method. The settings live on the options, and connect consumes the options to build the pool. The fix is to set everything before connect, in the same chain. The compiler catches this one immediately, because the method does not exist on the pool type, but the error can confuse a beginner who thinks of the pool and its options as one thing. They are two types, and the options type is the one with the dials.
Chaining on a Stored Builder Without Reassigning
// Wrong - max_connections takes self by value, so options is moved
let options = PgPoolOptions::new();
options.max_connections(5);
let pool = options.connect(database_url).await?;
Each setter consumes the builder and returns a new one, so calling a setter without using its return value moves the builder away and leaves the variable unusable. The compiler reports a use of a moved value. The fix is to chain the calls, or to reassign: let options = options.max_connections(5);.
Setting min_connections Above max_connections
// Wrong in intent - the floor is clamped to the ceiling, silently
PgPoolOptions::new()
.max_connections(2)
.min_connections(5)
This compiles and runs, and the pool quietly treats the floor as 2. SQLx chose not to panic or error here, which means a typo in the numbers produces a pool that behaves differently from what the programmer intended, with no error to point at it. The rule is to keep the floor at or below the ceiling, and to double check both numbers when the pool is first configured.
The Full Builder in One Place
Here is the project's pool creation with every setting from this page in the chain:
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(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
}
Five connections at most, one kept warm, ten seconds to wait for a free one, five minutes of idleness before reaping, thirty minutes of life before recycling. Those numbers suit a learning project and a small server, and they are easy to change later because they sit in one function, in one file, behind one builder chain.
Summary
The options builder is where a pool stops being a default and starts being a decision. The insight worth keeping is that the five settings answer five different questions: how many connections at most, how many at least, how long to wait, how long to sit idle, and how long to live. Each question has its own dial, its own default, and its own failure mode when set badly.
The numbers on this page are the pool's own behaviour, but the most consequential number, the maximum, deserves a page to itself. How big a pool should be depends on the traffic, the database, and the shape of the handlers, and that is a sizing question, not a settings question.