FAQ - Help and questions

How do I share a database pool or counter between axum handlers with State?

#axum#state#concurrency#arcpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Put shared values in a struct that derives Clone, give it to Router::with_state, and read it in handlers with the State extractor. Wrap mutable data in Arc<Mutex<..>> or Arc<RwLock<..>>, use atomics for counters, and never hold a standard-library lock guard across an await.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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));
    }
}
text
GET /hit -> hit 1
GET /hit -> hit 2
POST /notes -> added
POST /notes -> added
GET /notes -> first, second
  • AtomicU64 needs no lock for a simple counter.
  • RwLock lets many handlers read at once and one write; Mutex is the simpler choice when reads and writes are mixed and short.
  • The lock guard in add lives only for one statement. A std::sync guard is not Send, so holding it over an .await makes the handler's future unsendable and the route fails to compile (the thread on the Handler trait error shows what that looks like). If you must hold a lock across an await, use tokio::sync::Mutex.

Common mistakes#

  • Cloning the data itself (Vec, String) into the state instead of an Arc of 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet