DB crate async support
Learn which Rust database crates are async and which are sync, what blocking means inside an Axum handler, and how to use each one correctly
Async support is the first thing to check when picking a database crate for an Axum app, because Axum itself is async. A crate either speaks async, with .await on every database call, or it speaks sync, with calls that block the thread until the database answers. The three crates in this chapter split across that line, and the split decides how each one is used inside a handler.
Where This Fits
The previous pages introduced three tools: sqlx, SeaORM, and diesel. Each page showed its own query style, but none of them stopped to compare how the query runs. This page lines the three up on one question: when the handler calls the database, does the thread wait, or does it go and do other work? The answer shapes the handler code, the pool, and the failure modes.
Think of it like two kinds of phone calls. An async call puts you on hold with music: you wait, but the line stays open for other calls. A sync call is a conversation where you cannot do anything else until the other person stops talking. Both get the answer. The difference is what the thread does while it waits.
Async and Sync in Plain Words
Async code can pause. When an async function reaches .await, it stops at that point and hands control back to the runtime, which is the program that schedules async work. The runtime, Tokio in an Axum app, runs other tasks on the same thread while the first one waits for the network. When the database answers, the runtime wakes the paused task up and it continues. A single thread can juggle many waiting requests this way.
Sync code cannot pause. When a sync function calls the database, the thread sits inside that call until the answer arrives. The thread does nothing else in the meantime. If the database takes 50 milliseconds, the thread is busy for 50 milliseconds. That is called blocking: the thread is blocked, stuck waiting, and unavailable for other work.
Neither style is wrong on its own. Blocking is only a problem when the blocked thread was supposed to be doing something else, and in an Axum app the async worker threads are exactly those threads. A blocking call on one of them stalls every request assigned to that thread.
The Comparison
| Crate | Sync or async | How a query runs | What you write |
|---|---|---|---|
| sqlx | Async-first | Awaited, on the Tokio runtime | .fetch_all(&pool).await |
| SeaORM | Async-first | Awaited, on the Tokio runtime, through sqlx | .all(&db).await |
| diesel | Sync only | Blocking, on the calling thread | .load(&mut conn) with no .await |
| diesel-async | Async | Awaited, on the Tokio runtime | .load(&mut conn).await |
sqlx and SeaORM are async-first: they were written for async Rust, and every database call returns a future that must be awaited. diesel is sync by design: it predates async Rust, and its API has no futures at all. diesel-async is a separate crate that adds async execution to diesel's query builder, so a project can keep diesel's queries and run them without blocking.
sqlx - Async by Construction
Every sqlx database call is async. The pool methods, the query execution, and the row decoding all happen behind .await.
async fn sqlx_count(pool: &PgPool) -> Result<i64, sqlx::Error> {
let row: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
.fetch_one(pool)
.await?;
Ok(row.0)
}
sqlx::query_as(...) builds the query. .fetch_one(pool) starts it and returns a future. .await pauses the handler until Postgres answers, and the worker thread serves other requests in the meantime. The async fn on the outside is what makes .await legal inside. An async fn is a function that can pause; a plain fn cannot contain .await at all.
sqlx needs the runtime-tokio feature to know which runtime to pause on. Without it, the async calls have no runtime to hand control to, and sqlx panics at runtime the first time a query runs. With the feature enabled, sqlx finds the Tokio runtime Axum already started and uses it. The runtime-async-std feature is the same idea for the async-std runtime. An Axum app always uses runtime-tokio, because Axum itself runs on Tokio.
SeaORM - Async Through sqlx
SeaORM is async for the same reason sqlx is: it runs its queries through sqlx. Every SeaORM query method returns a future, and the .await sits at the end of the same method chain that builds the query.
async fn seaorm_count(db: &sea_orm::DatabaseConnection) -> Result<u64, sea_orm::DbErr> {
user::Entity::find().count(db).await
}
user::Entity::find() builds the query. .count(db) starts it and returns a future. .await pauses until the count comes back. The shape is identical to sqlx, because underneath it is sqlx: SeaORM builds the SQL with SeaQuery, hands it to sqlx, and awaits the same way.
SeaORM picks its runtime the same way sqlx does, with a feature flag. runtime-tokio is the flag for an Axum app. The flag is passed down to sqlx, so the two crates agree on the runtime. Enabling runtime-async-std in a Tokio app would point SeaORM at a runtime the app never starts, so the rule is simple: match the flag to the app, and an Axum app means Tokio.
There is one exception to the async rule. A separate crate called sea-orm-sync provides the full SeaORM API without an async runtime, for lightweight command line programs that use SQLite and have no server to keep responsive.
sea-orm-sync Is Not for Axum Apps:
sea-orm-sync exists so a small tool can reuse SeaORM entities without starting a runtime at all. It is not the default, and it is not for Axum apps, which always have a runtime running.
diesel - Sync, With a Bridge to Async Handlers
diesel has no async API. A diesel query is an ordinary function call that returns when the database answers.
fn diesel_count(conn: &mut PgConnection) -> QueryResult<i64> {
dusers.count().get_result(conn)
}
There is no .await, no future, and no runtime involved. The thread that calls diesel_count waits inside get_result until Postgres replies. In a command line tool or a test, that is fine. In an Axum handler, the thread is an async worker thread, and waiting inside it stalls the other requests assigned to that thread.
The bridge is tokio::task::spawn_blocking. It moves a closure onto a separate pool of threads reserved for blocking work, runs it there, and returns a future the handler awaits. The database still blocks a thread, but it blocks a thread from the blocking pool, not an async worker.
async fn diesel_count_from_handler(pool: Pool<ConnectionManager<PgConnection>>) -> i64 {
tokio::task::spawn_blocking(move || {
let mut conn = pool.get().expect("pool checkout");
diesel_count(&mut conn).unwrap_or(0)
})
.await
.unwrap_or(0)
}
The closure owns the pool handle, checks out one connection, and runs the sync query. The .await after spawn_blocking waits for the blocking thread to finish, while the async worker thread stays free. The closure cannot contain .await itself: it runs on a plain thread with no runtime, so anything inside it must be sync code. That boundary is the whole pattern. Sync inside, async outside, one function call between them.
A Sync Call in a Handler Compiles and Hurts Quietly:
Calling diesel directly inside an async fn handler compiles without complaint. Nothing warns you at build time. The cost shows up under load, as requests that wait behind a blocked worker thread. Every diesel call in async code goes through spawn_blocking, with no exceptions for quick queries, because a quick query on a dead database still blocks.
diesel-async - The Same Builder, Awaited
diesel-async is a separate crate that gives diesel's query builder an async execution path. The query construction does not change. The connection type and the run trait change, and .await appears at the end.
async fn diesel_async_count(url: &str) -> Result<i64, Box<dyn std::error::Error>> {
use diesel_async::{AsyncConnection, AsyncPgConnection, RunQueryDsl};
let mut conn = AsyncPgConnection::establish(url).await?;
let n: i64 = dusers.count().get_result(&mut conn).await?;
Ok(n)
}
AsyncPgConnection::establish opens the connection asynchronously, and .get_result(&mut conn).await runs the same count() query the sync version runs, without blocking a thread. The RunQueryDsl trait here comes from diesel_async, not from the diesel prelude: the two traits have the same method names, and importing the wrong one is a common compile error. Import diesel_async::RunQueryDsl in any file that awaits diesel queries.
The pooling story changes with the crate. The sync r2d2 pool does not fit async code, because checking a connection out of it blocks. diesel-async instead works with async pool crates, including deadpool and bb8, each enabled by a feature flag on diesel-async. A project moving from sync diesel to diesel-async changes its pool at the same time as its connection type.
What Blocking Costs, in Plain Terms
Blocking costs responsiveness, not correctness. A blocked thread still gets the right answer. The damage is to everything else that thread was supposed to do. An Axum server runs a fixed set of worker threads, usually one per CPU core. Each worker juggles many requests by pausing at .await points. A blocking call removes one worker from the juggling set for the whole query. One blocked worker is a small loss. Several blocked workers at once is a server that stops answering new requests while it waits on the database.
This is why the async question matters more than the query style question. Two crates can build the same SQL, and the one that awaits will behave better under load than the one that blocks on a worker thread. That is a qualitative difference, not a number: it shows up as requests that stall, not as a faster or slower query.
Async path (sqlx, SeaORM, diesel-async)
|
v
Handler awaits -> worker thread takes another request
|
v
Database answers -> runtime wakes the handler up
|
v
Handler finishes and responds
Sync path inside a handler (plain diesel)
|
v
Handler calls the database -> worker thread waits
|
v
Other requests on that thread wait too
|
v
Database answers -> handler finishes and responds
Sync path through spawn_blocking (plain diesel, done right)
|
v
Handler awaits spawn_blocking -> worker thread takes another request
|
v
Blocking thread waits on the database
|
v
Blocking thread finishes -> runtime wakes the handler up
Choosing Between Them
The choice follows from what the app already is. An Axum app is async, so the path of least resistance is an async crate: sqlx or SeaORM, with .await directly in the handler and no bridging code. A project that already has diesel queries, or a team that prefers diesel's type-level checking, has two honest options: wrap every query in spawn_blocking, or adopt diesel-async and await the same queries. Both are real solutions. The first keeps the sync crate and pays one wrapper per query. The second changes the crate and the pool, and removes the wrapper.
One more consideration is the runtime itself. sqlx and SeaORM both need their runtime-tokio feature in an Axum app, and diesel-async runs on Tokio too. There is no combination in this chapter where the database crate runs on a different runtime from the web framework. If a feature flag ever offers a choice of runtimes, the answer is the one the app already uses.
Testing It
Async database code is tested with async tests, and sync code with sync tests. The two shapes sit side by side in one test file.
use sqlx::SqlitePool;
#[tokio::test]
async fn async_sqlx_probe() {
let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
let row: (i64,) = sqlx::query_as("SELECT 1").fetch_one(&pool).await.unwrap();
assert_eq!(row.0, 1);
}
#[test]
fn sync_diesel_probe() {
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
let mut conn = SqliteConnection::establish(":memory:").unwrap();
let row: i32 = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1"))
.get_result(&mut conn)
.unwrap();
assert_eq!(row, 1);
}
The async test uses #[tokio::test], which starts a Tokio runtime for the test. The sync test uses a plain #[test], because diesel needs no runtime. This test file was run while this page was written and passes. The important detail is the mismatch to avoid: a #[tokio::test] around sync diesel code works but hides nothing, while an async sqlx call inside a plain #[test] fails to compile, because there is no runtime to await on.
Both Tests Passing:
If the async probe returns 1 and the sync probe returns 1, the two runtimes are set up correctly: Tokio runs the async test, and diesel runs without any runtime at all. A failure in the async test points at the runtime setup, while a failure in the sync test points at the query.
Common Beginner Mistakes
Forgetting .await
An async call without .await returns a future that never runs. The compiler warns about the unused future, but the code compiles, and the query silently never happens. The handler returns as if the database call succeeded, usually with an empty result. Every sqlx, SeaORM, and diesel-async database call ends in .await. If a query seems to do nothing, check the end of the line first.
// Wrong - the future is created and dropped, the query never runs
sqlx::query("DELETE FROM users WHERE id = $1").bind(1_i64).execute(&pool);
// Right - the future runs to completion
sqlx::query("DELETE FROM users WHERE id = $1").bind(1_i64).execute(&pool).await?;
Trying to await a sync call
.await only works on a future. A diesel query returns a plain value, not a future, so writing .await after it is a compile error. The error message says the value is not a future, which is the compiler telling you the call already finished. The fix is either to remove the .await and keep the call sync, which is correct only outside a handler, or to wrap the call in spawn_blocking, which is correct inside one.
Awaiting inside spawn_blocking
The closure passed to spawn_blocking runs on a plain thread, and .await is not allowed inside it. The compiler rejects it. If the closure needs an async call, the code is structured wrong: the async work belongs outside the closure, and only the sync database call belongs inside. Move the .await out, keep the blocking call in.
Mixing the run traits
diesel and diesel-async both define a RunQueryDsl trait with the same method names. A file that imports the diesel prelude and then awaits a query gets a confusing error, because the sync trait's methods return values, not futures. In a file that uses diesel-async, import diesel_async::RunQueryDsl and be careful that the prelude import does not also bring the sync one into scope.
Blocking the Runtime Is a Silent Failure:
Nothing in the compiler or in Tokio stops a handler from blocking a worker thread. There is no error, no warning, and no panic. The server just gets slower as more requests arrive. Treat any sync database call in async code as a bug, even when it works in testing, because testing rarely has enough concurrent requests to show the stall.
Final Complete Example
Here is one router with two handlers that do the same job two ways: an async sqlx handler that awaits directly, and a diesel handler that runs its sync query on a blocking thread. The shared state holds both a sqlx pool and a diesel pool, one for each handler.
use axum::{extract::State, routing::get, Router};
use diesel::pg::PgConnection;
use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool};
use sqlx::PgPool;
diesel::table! {
users (id) {
id -> Integer,
name -> Text,
email -> Text,
}
}
#[derive(Debug, Queryable, Selectable)]
#[diesel(table_name = users)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
}
#[derive(Clone)]
struct AppState {
sqlx_pool: PgPool,
diesel_pool: Pool<ConnectionManager<PgConnection>>,
}
async fn count_sqlx(State(state): State<AppState>) -> String {
let row: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
.fetch_one(&state.sqlx_pool)
.await
.unwrap_or((0,));
format!("sqlx count: {}", row.0)
}
async fn count_diesel(State(state): State<AppState>) -> String {
let pool = state.diesel_pool.clone();
let n = tokio::task::spawn_blocking(move || {
let mut conn = pool.get().expect("pool checkout");
users::table.count().get_result::<i64>(&mut conn).unwrap_or(0)
})
.await
.unwrap_or(0);
format!("diesel count: {}", n)
}
#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let sqlx_pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect("postgres://postgres:password@localhost:5432/demo")
.await?;
let manager = ConnectionManager::<PgConnection>::new("postgres://postgres:password@localhost:5432/demo");
let diesel_pool = Pool::builder().max_size(5).build(manager).unwrap();
let state = AppState { sqlx_pool, diesel_pool };
let app = Router::new()
.route("/count-sqlx", get(count_sqlx))
.route("/count-diesel", get(count_diesel))
.with_state(state);
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();
Ok(())
}
[package]
name = "axum-async-compare-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
sqlx = { version = "0.9", features = ["postgres", "runtime-tokio"] }
diesel = { version = "2.4", features = ["postgres", "r2d2"] }
curl http://127.0.0.1:3000/count-sqlx and curl http://127.0.0.1:3000/count-diesel return the same number through two different paths. The sqlx handler awaits directly. The diesel handler awaits spawn_blocking, and the blocking thread does the waiting. The handlers, the pools, and the query shapes in this example were compile-checked against sqlx 0.9.0 and diesel 2.4.0 while this page was written. Running it end to end needs a live Postgres server with a users table.
Summary
The single idea to carry out of this page is that async is a property of the call, not of the query. sqlx, SeaORM, and diesel-async return futures you await, and the worker thread stays useful while the database thinks. Plain diesel returns a value, and the thread that called it waits. In an Axum app, that difference decides the handler shape: await directly, or wrap the call in spawn_blocking and await the wrapper.
The decision framework is short. When the app is async and the crate is async, write the query and await it. When the app is async and the crate is sync, either bridge every call with spawn_blocking or switch the crate to its async form. There is no third option where a sync call inside a handler is fine, because the compiler will not catch it and the server will pay for it quietly. With the execution model settled, the next question is what the compiler itself can check about the query before the program ever runs.