expression

Axum: shared mutable state across requests

Cloning an Arc shares ownership of the same allocation. Atomic fetch_add increments a simple counter without holding a lock across await. Relaxed ordering is enough for this independent metric; it does not synchronize other application data. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 1 2 total 2 Common mistake: Assuming that cloning a plain integer or struct automatically shares mutable state.

Formal Syntax & Structure

rust syntaxrust
State(counter): State<Arc<AtomicUsize>>

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{extract::State, routing::post};    use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};    async fn hit(State(c): State<Arc<AtomicUsize>>) -> String { (c.fetch_add(1, Ordering::Relaxed) + 1).to_string() }    let counter = Arc::new(AtomicUsize::new(0));    let app: Router = Router::new().route("/hit", post(hit)).with_state(counter.clone());    for _ in 0..2 {        let r = app.clone().oneshot(Request::builder().method("POST").uri("/hit").body(Body::empty()).unwrap()).await.unwrap();        println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 32).await.unwrap()).unwrap());    }    println!("total {}", counter.load(Ordering::Relaxed));}
Rust Reference