Answer#
Axum clones the state for every request, so the state type must be cheap to clone: a struct of Arcs, or handles such as a database pool that are already shared internally.
use axum::{body::{to_bytes, Body}, extract::State, http::Request, routing::{get, post}, Router};
use std::sync::{atomic::{AtomicU64, Ordering}, Arc, RwLock};
use tower::ServiceExt;
#[derive(Clone)]
struct AppState {
hits: Arc<AtomicU64>, // a counter needs no lock
notes: Arc<RwLock<Vec<String>>>, // many readers or one writer
}
async fn hit(State(s): State<AppState>) -> String {
format!("hit {}", s.hits.fetch_add(1, Ordering::Relaxed) + 1)
}
async fn add(State(s): State<AppState>, body: String) -> &'static str {
s.notes.write().unwrap().push(body); // the guard is dropped at the end of this statement, before any .await
"added"
}
async fn all(State(s): State<AppState>) -> String { s.notes.read().unwrap().join(", ") }
#[tokio::main]
async fn main() {
let state = AppState { hits: Arc::new(AtomicU64::new(0)), notes: Arc::new(RwLock::new(vec![])) };
let app = Router::new().route("/hit", get(hit)).route("/notes", post(add).get(all)).with_state(state);
for (m, uri, body) in [("GET", "/hit", ""), ("GET", "/hit", ""), ("POST", "/notes", "first"), ("POST", "/notes", "second"), ("GET", "/notes", "")] {
let req = Request::builder().method(m).uri(uri).body(Body::from(body)).unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let text = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{m} {uri} -> {}", String::from_utf8_lossy(&text));
}
}GET /hit -> hit 1
GET /hit -> hit 2
POST /notes -> added
POST /notes -> added
GET /notes -> first, secondAtomicU64needs no lock for a simple counter.RwLocklets many handlers read at once and one write;Mutexis the simpler choice when reads and writes are mixed and short.- The lock guard in
addlives only for one statement. Astd::syncguard is notSend, so holding it over an.awaitmakes the handler's future unsendable and the route fails to compile (the thread on theHandlertrait error shows what that looks like). If you must hold a lock across an await, usetokio::sync::Mutex.
Common mistakes#
- Cloning the data itself (
Vec,String) into the state instead of anArcof it. Each request would then see its own copy. - Doing slow work (a database call) while holding a lock, which makes all other handlers wait.
Related questions#
Can I use several state types?#
Keep one state struct with a field per resource. Axum also lets a handler extract a part of the state; the documentation describes the FromRef trait for that.
Sources#
- axum,
State: https://docs.rs/axum/0.8.9/axum/extract/struct.State.html (read 2026-12-05) - Tokio tutorial, shared state: https://tokio.rs/tokio/tutorial/shared-state (read 2026-12-05)