PgPool

Learn what a PgPool connection pool is, how to create one with PgPool connect, share it through Axum state, and close it cleanly

A PgPool is a pool of open PostgreSQL connections that an Axum application shares between its handlers. A pool is a collection of connections kept ready in advance, so a handler that needs the database borrows one, runs its query, and returns it, instead of opening a fresh connection for every request. PgPool is the type for PostgreSQL pools in SQLx, and it is the single value the whole application passes around to reach the database.

Where This Fits

The feature pages put the PostgreSQL driver and the Tokio runtime into the project. This page builds the first thing those features exist for: the pool. The pool is created once in main, stored as router state, and borrowed by every handler that touches the database. Everything after this page, the options, the connection string, the queries, and the migrations, either configures this pool or uses it.

Think of the pool as a rack of shared bicycles at a station. A rider takes a bike, rides it, and returns it to the rack for the next rider. Nobody owns a bike permanently, and nobody waits for a new bike to be built. The rack holds a fixed number of bikes, and if every bike is out, the next rider waits until one comes back. The pool is the rack, the connections are the bikes, and the handlers are the riders.

The Smallest Working Version

A pool is created from a connection string with one call:

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)
        .connect(database_url)
        .await
}

PgPoolOptions::new() builds a configuration, .max_connections(5) sets the size, and .connect(database_url).await opens the pool. The .await pauses while the first connection is negotiated with the server. If the database answers, the call returns a PgPool. If it does not, the call returns a sqlx::Error describing what went wrong.

Call it from main and hand the result to app:

src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect(
        "DATABASE_URL must be set, for example postgres://postgres:password@127.0.0.1:5432/ch12_sqlx",
    );
    let pool = create_pool(&database_url)
        .await
        .expect("failed to create the database 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(pool)).await.unwrap();
}

Run the server with a real database behind it:

DATABASE_URL=postgres://postgres:password@127.0.0.1:5432/ch12_sqlx cargo run
Server running at http://127.0.0.1:3000

That line means the pool connected. No query has run yet, but the first connection is open, the server is listening, and the app is ready to serve requests that use the database.

The Startup Line Means the Pool Connected:

If the server prints its startup line, the pool opened its first connection successfully. If the database were unreachable or the credentials wrong, create_pool would return an error and main would stop with the expect message before the server ever started. A running server is proof the pool works.

Why a Pool Instead of One Connection

A single connection can only run one query at a time. A web server handles many requests at once, so one connection would force every request to wait in line behind the others. A pool holds several connections, and each request borrows one, so several queries run at the same time.

Opening a connection is also slow compared to running a query. A new connection needs a TCP handshake, an authentication exchange, and server-side setup. Doing that for every request would add that cost to every response. A pool pays the cost once per connection, when the connection is first opened, and then reuses the connection for hundreds of queries. The reuse is the whole point: the pool trades a little memory for a large saving in per-request time.

The pool also protects the database. Without a limit, a burst of traffic could open hundreds of connections at once, and PostgreSQL has a limit on how many it accepts. The pool caps the count at max_connections, so the database sees a bounded, predictable load no matter how many requests arrive. The pool size page works through that number in detail.

Creating a Pool, Step by Step

Pool creation has two spellings, and the difference matters. The first is PgPool::connect, which builds a pool with default options from a URL string:

let pool = PgPool::connect(database_url).await?;

The second is PgPoolOptions::new().connect(database_url).await, which builds a pool from options the program sets first. Both do the same work of opening connections; the options version just lets the program change the settings before connecting. The project uses the options version because it sets max_connections, and every later page adds settings to the same builder chain.

Both calls are async, and both return a Result. The error side is a sqlx::Error, and the program decides what to do with it. In main, an error stops the program, because a web server with no database cannot serve its routes. In a test or a background job, the same error might be logged and retried instead.

There is a third spelling, PgPool::connect_lazy, which builds a pool value without opening any connection:

let pool = PgPool::connect_lazy(database_url)?;

A lazy pool opens its first connection only when a query first needs one. That is useful in tests that build a router without a database, and it is a trap in production: the server starts, prints its startup line, and then fails on the first real request, because the connection error that connect would have caught at startup arrives later, inside a handler. The rule is simple: use connect in the real server so a bad database stops startup loudly, and use connect_lazy only where no database is available by design.

Sharing the Pool With Handlers

The pool is created once and shared with every handler through Axum state. State is Axum's mechanism for giving handlers access to a value the application owns: the value is stored on the router, and each handler asks for it with the State extractor.

src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::get};
use sqlx::postgres::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users", get(handlers::list_users))
        .route("/users/{id}", get(handlers::get_user))
        .with_state(pool)
}

.with_state(pool) stores the pool on the router. A handler then takes it with State(pool):

src/handlers.rs
use axum::{
    Json,
    extract::{Path, State},
};
use serde::Serialize;
use sqlx::postgres::PgPool;

use crate::errors::AppError;

#[derive(Debug, Serialize)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

pub async fn list_users(State(pool): State<PgPool>) -> Result<Json<Vec<User>>, AppError> {
    let users = sqlx::query_as!(
        User,
        "SELECT id, name, email FROM users ORDER BY id"
    )
    .fetch_all(&pool)
    .await
    .map_err(|_| AppError::InternalError)?;
    Ok(Json(users))
}

State<PgPool> in the handler's arguments tells Axum to clone the stored pool and hand it to the handler. Cloning a pool is cheap: the pool is a handle, and clones share the same connections underneath. The handler never creates a pool, never opens a connection, and never closes one. It borrows a connection from the shared pool for the duration of one query, and the pool takes it back when the query finishes.

Cloning a Pool Does Not Clone the Connections:

PgPool implements Clone, and cloning it is cheap because the clone shares the same pool internals. Two handlers that each hold a clone are borrowing from the same set of connections, not from two separate sets. That is why one pool, stored once as state, is enough for the whole application.

What the Pool Does During a Request

The query in the handler above goes through four steps inside the pool, and a beginner who can picture them can reason about every pool behaviour that follows.

handler calls fetch_all(&pool)
        |
        v
pool lends an idle connection, or opens a new one
        |
        v
query runs on that connection, rows come back
        |
        v
connection returns to the pool, ready for the next request

First, the pool looks for an idle connection, one that is open and not in use. If it finds one, it lends it immediately. If every connection is busy and the pool has room to grow, it opens a new one. If every connection is busy and the pool is at its maximum, the request waits until a connection comes back. That wait is bounded by the acquire timeout, which is thirty seconds by default, and the pool size page shows what happens when the wait runs out.

Second, the query runs on the borrowed connection. The connection is dedicated to that one query for the duration: no other handler can use it at the same time. That exclusivity is what makes the query safe. Two handlers never share one connection mid-query, so their rows can never mix.

Third, when the query finishes, the connection goes back to the pool. It stays open, ready for the next request. The pool keeps it because opening it again would cost time, and the next request is likely to arrive soon.

Fourth, nothing in the handler manages any of this. The handler passes &pool to the query, and the pool handles lending, waiting, and returning. The only decision the handler makes is which query to run.

Checking the Pool in a Running Server

The handlers above are testable with real HTTP requests once the users table exists and holds rows. With two rows in the table, the server answers like this:

curl http://127.0.0.1:3000/users
[{"id":1,"name":"Asha","email":"asha@example.com"},{"id":2,"name":"Ravi","email":"ravi@example.com"}]
curl http://127.0.0.1:3000/users/1
{"id":1,"name":"Asha","email":"asha@example.com"}

A request for a missing user returns the shared error shape:

curl http://127.0.0.1:3000/users/99
{"error":"resource not found"}

The 404 with that body is the AppError::NotFound variant from the error handling chapter, returned when the query finds no row. The pool, the handler, and the error type each do one job, and the response shows all three working together: the pool supplied the connection, the handler ran the query and mapped the missing row to NotFound, and the error type rendered the response.

Reading the Pool State

Three small methods report what the pool is doing, and they are useful for checking a suspicion without adding logging. pool.size() returns how many connections the pool currently holds, open and in use or idle. pool.num_idle() returns how many of those are idle. pool.is_closed() returns whether the pool has been closed. A tiny program that prints them shows the pool waking up:

let pool = PgPool::connect(database_url).await?;
println!("pool size: {}", pool.size());
println!("pool closed: {}", pool.is_closed());
pool size: 1
pool closed: false

A freshly connected pool holds one connection: connect opens one eagerly, so the first query does not pay the connection cost. The size grows toward the maximum only as concurrent requests demand more connections, and idle connections are reaped on a schedule the options page describes. Watching size() climb under load and fall back when traffic stops is the most direct way to see the pool doing its job.

Closing the Pool

pool.close().await shuts the pool down: it stops lending connections, closes the open ones, and makes is_closed() return true. A web server rarely calls it, because the process exiting closes everything anyway, but tests and command line tools use it to finish cleanly:

let pool = PgPool::connect(database_url).await?;
// ... run queries ...
pool.close().await;
println!("pool closed: {}", pool.is_closed());
pool closed: true

One behaviour catches beginners out: close waits for connections that are currently checked out. If a handler is still holding a connection when close is called, the call waits until that handler returns its connection. That is the safe behaviour, because closing a connection mid-query would corrupt the query, but it means a program that forgets to return a connection can hang at shutdown. The fix is to let the checked-out work finish first, then close.

Close Waits for Checked Out Connections:

pool.close().await does not force connections shut while a query is running. It waits for every borrowed connection to come back first. If a shutdown hangs at close, look for a connection that was borrowed and never returned, not for a broken pool.

What Happens When the Database Is Unreachable

Pool creation fails in three different ways, and the error message names the cause. A wrong password is rejected by the server:

error returned from database: password authentication failed for user "axumdocs"

A database name that does not exist is rejected the same way:

error returned from database: database "no_such_db" does not exist

A wrong port or a stopped server behaves differently. The pool does not fail at once. It keeps trying to open its first connection in the background, and the connect call waits until the acquire timeout runs out, thirty seconds by default, then fails with:

pool timed out while waiting for an open connection

That thirty-second wait surprises beginners who expect an instant refusal. The pool is not stuck; it is retrying, because a database that is starting up or briefly unreachable is common, and an instant failure would be wrong for those cases. The wait is bounded, the message names the cause, and the fix is the address: check the host and the port, confirm the server is running, and try again.

Common Beginner Mistakes

Creating a Pool Per Request

// Wrong - a new pool for every request defeats the purpose
async fn list_users() -> Result<Json<Vec<User>>, AppError> {
    let pool = PgPool::connect("postgres://postgres:password@127.0.0.1:5432/ch12_sqlx").await
        .map_err(|_| AppError::InternalError)?;
    // ...
}

A pool per request opens fresh connections for every request, which is exactly the cost the pool exists to avoid, and it leaks the old pools when the handler returns. The pool is created once in main and shared through state. If a handler contains the words PgPool::connect or PgPoolOptions::new, the pool is in the wrong place.

Storing the Connection String Instead of the Pool

A beginner sometimes stores the URL string as state and builds a pool inside each handler. That has the same cost as the mistake above, plus a new failure mode: every request can fail independently at connection time. State holds the pool, not the string. The string is read once, in main, and never appears in a handler.

Forgetting That State Must Be Clone

Axum state must be cheap to clone, because every request gets its own copy. PgPool is cheap to clone, which is why it works as state. A type that is not cheap to clone, such as a single PgConnection, cannot be state in the same way. If the compiler complains that a state type does not implement Clone, the fix is to wrap the value in something shareable, and for database access that something is the pool.

The Full Wiring in One Place

Here is everything from this page together: the pool creation, the state wiring, and one handler that uses them. The error module is unchanged from the error handling chapter.

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)
        .connect(database_url)
        .await
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::get};
use sqlx::postgres::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users", get(handlers::list_users))
        .route("/users/{id}", get(handlers::get_user))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect(
        "DATABASE_URL must be set, for example postgres://postgres:password@127.0.0.1:5432/ch12_sqlx",
    );
    let pool = create_pool(&database_url)
        .await
        .expect("failed to create the database 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(pool)).await.unwrap();
}

Start the server, request /users, and the JSON list comes back. That round trip exercises the whole chain: the URL, the pool, the state, the handler, and the query.

Summary

A pool is a shared shelf of open connections, and PgPool is the handle the application holds onto it. The most important insight on this page is where the pool lives: created once in main, stored once as router state, borrowed briefly by each handler, and never created anywhere else. Every pool bug a beginner meets comes from breaking that rule, either by creating pools in handlers or by holding connections past their use.

The pool on this page uses mostly default settings, with only its size changed. The settings themselves, what each one does and what it defaults to, are the subject of the options page, where the builder chain from create_pool gets its full explanation.