Answer#
Opening a database connection is slow, so web programs keep a pool of open connections and lend one to each query. In sqlx the pool is cloneable and safe to share, so it goes straight into the axum state.
use axum::{body::{to_bytes, Body}, extract::State, http::{Request, StatusCode}, routing::get, Router};
use sqlx::{sqlite::{SqliteConnectOptions, SqlitePoolOptions}, SqlitePool};
use std::time::Duration;
use tower::ServiceExt;
#[derive(Clone)]
struct AppState { db: SqlitePool } // a pool is cheap to clone: it is a handle to shared connections
async fn count(State(s): State<AppState>) -> Result<String, StatusCode> {
let n: i64 = sqlx::query_scalar("SELECT count(*) FROM notes")
.fetch_one(&s.db)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(format!("{n} notes"))
}
#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let path = std::env::temp_dir().join("rs-sqlx-demo.db");
let _ = std::fs::remove_file(&path);
let options = SqliteConnectOptions::new().filename(&path).create_if_missing(true);
let pool = SqlitePoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3)) // fail with an error instead of waiting forever
.connect_with(options)
.await?;
sqlx::query("CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)").execute(&pool).await?;
sqlx::query("INSERT INTO notes (body) VALUES (?), (?)").bind("first").bind("second").execute(&pool).await?;
let app = Router::new().route("/count", get(count)).with_state(AppState { db: pool });
let res = app.oneshot(Request::get("/count").body(Body::empty()).unwrap()).await.unwrap();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{}", String::from_utf8_lossy(&body));
Ok(())
}2 notesmax_connections(5)caps how many connections exist at once. When all are in use, the next query waits.acquire_timeoutturns an endless wait into an error after three seconds, which your handler can turn into a 503 or 500..fetch_one(&s.db)passes the pool as the executor; sqlx borrows a connection for that one query and returns it.- SQLite is used because it needs no server. Other databases use their own feature (
postgres,mysql) and pool type, with the same style of code; this thread ran only SQLite.
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio", "sqlite"] }Common mistakes#
- Calling
SqlitePool::connectinside a handler. Every request would then create its own pool. - Setting
max_connectionshigher than the database accepts. Check your database's connection limit. - Building SQL with
format!and user input. Use.bind(value)as in the example: the value travels separately from the SQL text.
Related questions#
What happens to a request when the pool is empty?#
It waits up to the acquire timeout, then the query returns an error (PoolTimedOut), which is your cue to log it and answer with an error status.
Does a pool help with SQLite in a file?#
It lets several connections read at once; writes to one SQLite file are still serialized by the database. This thread did not measure either.
Sources#
- sqlx,
PoolOptions: https://docs.rs/sqlx/0.8.6/sqlx/pool/struct.PoolOptions.html (read 2026-12-05) - sqlx documentation: https://docs.rs/sqlx/0.8.6/sqlx/ (read 2026-12-05)