Connection pooling
A connection pool keeps a set of live database connections and lends them out. Creating a TCP+TLS+auth session per request is too slow and will exhaust the database.
Detailed Explanation
Opening a Postgres connection is a handshake: TCP, TLS, authentication, session setup. Doing that on every HTTP request is hundreds of milliseconds and a burst of connections that max_connections will refuse. A pool opens a bounded number, reuses them, and queues callers when all are busy.
In Rust, SQLx's Pool, Diesel's r2d2 / deadpool, and SeaORM's wrapper around SQLx are the usual types. You create the pool at startup, store it in Arc / Axum State, and every handler borrows a connection for the duration of the query or transaction. PoolOptions::max_connections should be set on purpose. The default may be fine for a laptop and too high for a database that already has 20 app replicas.
Pool exhaustion looks like latency, then timeouts. The cause is often a transaction held across a slow call, or a leak that never returns the connection (less common in RAII Rust, still possible if you forget or store a connection in a struct that lives forever). idle_timeout and max_lifetime recycle connections so a load balancer or a server-side timeout does not leave you with a dead socket.
The pool is not a second database. It does not cache rows. It caches sockets. Application-level caching is moka, Redis, or your own map.
When you create a pool: process startup, one pool per database. When you open a one-off connection: a CLI, a migration. When you raise max_connections: after you know the database can take it and that you are not just hiding a leak.
Code Examples
struct Pool {
max: u32,
busy: u32,
}
impl Pool {
fn checkout(&mut self) -> bool {
if self.busy < self.max {
self.busy += 1;
true
} else {
false
}
}
}
fn main() {
let mut pool = Pool { max: 2, busy: 0 };
println!("{}", pool.checkout()); // prints: true
println!("{}", pool.checkout()); // prints: true
println!("{}", pool.checkout()); // prints: false
}Common Gotchas
Default pool size times replica count is a thundering herd
20 apps × 10 connections is 200 sessions. Set `max_connections` with the database in mind.
A long transaction is a borrowed connection
The pool cannot lend that slot. This is how a slow handler starves the rest.
One pool at startup
A pool per request is the anti-pattern the pool exists to prevent.
Health checks and `max_lifetime` handle dead sockets
A connection that survived a database failover may need to be dropped, not reused forever.