Sharing State with Mutex
Learn how to share mutable state safely in Axum using Arc and Mutex, with practical counter examples and common pitfalls.
Sharing data between multiple parts of a program is one of the most common needs in a web server. But sharing data that also needs to change raises a difficult question: how do you let many requests read and write the same value without them stepping on each other's toes? Axum solves this with a combination of two tools: Arc for sharing and Mutex for safe mutation. Arc lets many handlers hold a pointer to the same piece of data. The problem is that Arc only provides shared read access: you can't modify the data through an Arc because Rust's ownership rules prevent multiple places from having mutable access at the same time. That's where Mutex comes in. A Mutex wraps your data and only hands out one mutable reference at a time, enforced by a lock.
What a Mutex Actually Does
A Mutex (short for mutual exclusion) is like a single key to a room. Only the handler holding the key can go inside and change what's in the room. When it's done, it leaves the room and puts the key back so someone else can enter. In Rust terms, calling .lock() on a Mutex returns a guard - a special object that proves you hold the lock. While that guard exists, no one else can obtain a mutable reference to the data. When the guard is dropped (which happens automatically at the end of its scope), the lock is released.
This makes Arc<Mutex<T>> the go‑to pattern for shared mutable state in Axum. The Arc part lets many tasks share ownership of the Mutex. The Mutex part makes sure only one task can mutate the inner T at a time.
Why not use a plain reference?:
Rust's compiler statically prevents data races by refusing to compile code where two threads could mutate the same data without synchronization. Mutex is the standard synchronization primitive that turns "interior mutability" into safe, compile‑time checked code.
Setting Up Axum State with Arc<Mutex<T>>
Let's build a tiny Axum application that keeps a shared counter. Every time a client sends a request to /increment, the counter goes up by one. We'll store the counter as Arc<Mutex<i32>> and give it to all handlers via Axum's State extractor.
First, make sure your Cargo.toml includes axum and tokio. For a minimal example:
[package]
name = "axum-mutex-example"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Now create src/main.rs:
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() {
// Create the shared counter wrapped in Arc and Mutex
let counter = Arc::new(Mutex::new(0));
// Build the router and pass the state
let app = Router::new()
.route("/increment", get(increment_handler))
.with_state(counter);
// Start the server
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn increment_handler(
State(counter): State<Arc<Mutex<i32>>>,
) -> String {
// Lock the mutex to get mutable access
let mut num = counter.lock().unwrap();
*num += 1;
format!("Counter is now: {}", *num)
}
When you run this and visit http://127.0.0.1:3000/increment several times, you'll see the number increase each time: first 1, then 2, then 3, and so on.
Let's break down what's happening. In main, we wrap an integer in Mutex::new(0) and then wrap that in Arc::new. The Arc allows the same Mutex to be cloned cheaply (it only clones a pointer, not the data) so it can be shared with every request. with_state(counter) registers this Arc<Mutex<i32>> as application state.
The handler uses the State extractor to get a clone of the Arc. Inside, counter.lock() attempts to acquire the lock. If no other request currently holds the lock, it succeeds immediately and returns a MutexGuard. That guard gives us a mutable reference to the inner i32 via dereferencing (*num += 1). When num goes out of scope at the end of the function, the guard is dropped and the lock is released automatically - even if we forget to explicitly unlock.
Reading State Without Modifying
Sometimes you only need to read the current value, not change it. You still have to lock the mutex because you need shared access to the data, and the lock ensures no one is writing while you read. Here's how you might return the current counter value:
async fn get_counter_handler(
State(counter): State<Arc<Mutex<i32>>>,
) -> String {
let num = counter.lock().unwrap();
format!("Current counter: {}", *num)
}
Add this handler to the router:
let app = Router::new()
.route("/increment", get(increment_handler))
.route("/count", get(get_counter_handler))
.with_state(counter);
Now /count shows the current value without changing it. Notice that even though we don't mutate, we still use .lock(). That's because reading the value while someone else is writing could lead to a torn read (seeing a half‑updated value). The lock guarantees consistency.
A Complete Working Example
For clarity, here is the entire main.rs with both handlers. This is what your file should look like after adding the read endpoint:
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() {
let counter = Arc::new(Mutex::new(0));
let app = Router::new()
.route("/increment", get(increment_handler))
.route("/count", get(get_counter_handler))
.with_state(counter);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn increment_handler(
State(counter): State<Arc<Mutex<i32>>>,
) -> String {
let mut num = counter.lock().unwrap();
*num += 1;
format!("Counter is now: {}", *num)
}
async fn get_counter_handler(
State(counter): State<Arc<Mutex<i32>>>,
) -> String {
let num = counter.lock().unwrap();
format!("Current counter: {}", *num)
}
Everything works?:
Run the server and open two browser tabs: one at /increment and one at /count. Click refresh on /increment a few times, then go to /count - the number should match the last increment. This confirms the shared state is working across requests.
Understanding Locking and the MutexGuard
The line let mut num = counter.lock().unwrap(); deserves a closer look. lock() returns a Result<MutexGuard<T>, PoisonError<T>>. In normal code, unwrap() is fine because poisoning only happens when a panic occurs while the lock is held. We'll talk about poisoning in the mistakes section, but for now just know that .unwrap() works for all normal cases.
The MutexGuard<T> behaves like a smart pointer: you can use *num to access the inner value. The guard also implements DerefMut, so you can modify the inner data directly. In the increment handler we do *num += 1;, which first dereferences the guard to get an i32, increments it, and writes it back. The guard is dropped automatically at the end of the scope, releasing the lock.
A common question is: what if you need to hold the lock while doing something that takes time, like reading from a file or making a network call? The answer is that you cannot hold a std::sync::Mutex guard across an .await point in a handler at all. The guard is not Send, so the handler's future cannot satisfy the Handler trait and the code does not compile. More on that in the pitfalls section below.
Sharing More Complex Data: HashMap Example
A counter is simple, but real applications often need to store more complex data, like a map of users or a cache. Mutex works with any type T. Let's replace the integer with a HashMap<String, String> that stores key‑value pairs.
We'll create two endpoints:
POST /set/{key}/{value}to insert a key-value pairGET /get/{key}to retrieve the value for a key
Because we're using HashMap, we need to import it. Also, Axum's path parameters will give us the key and value as strings. We'll use axum::extract::Path for that.
Here's the updated main.rs. We'll keep it concise but complete:
use axum::{
extract::{Path, State},
routing::{get, post},
Router,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
type SharedMap = Arc<Mutex<HashMap<String, String>>>;
#[tokio::main]
async fn main() {
let map: SharedMap = Arc::new(Mutex::new(HashMap::new()));
let app = Router::new()
.route("/set/{key}/{value}", post(set_handler))
.route("/get/{key}", get(get_handler))
.with_state(map);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn set_handler(
State(map): State<SharedMap>,
Path((key, value)): Path<(String, String)>,
) -> String {
let mut map = map.lock().unwrap();
map.insert(key, value);
"Value set".to_string()
}
async fn get_handler(
State(map): State<SharedMap>,
Path(key): Path<String>,
) -> String {
let map = map.lock().unwrap();
match map.get(&key) {
Some(value) => value.clone(),
None => "Key not found".to_string(),
}
}
You can test this with curl:
curl -X POST http://127.0.0.1:3000/set/name/Alice
curl http://127.0.0.1:3000/get/name
The first command stores "name" -> "Alice" and prints Value set. The second returns Alice. Try multiple concurrent requests, the mutex ensures the map is never corrupted. Asking for a missing key returns Key not found.
Use {param}, Not :param, in Axum 0.8:
In axum 0.8, path parameters use the brace syntax {key}, as in /get/{key}. The older colon syntax /get/:key from axum 0.7 is rejected: the router panics at startup with Path segments must not start with ':'. For capture groups, use '{capture}'.
Type alias makes it cleaner:
Notice we defined type SharedMap = Arc<Mutex<HashMap<String, String>>>;. This makes the handler signatures easier to read and reduces repetition. You'll see this pattern often in real Axum codebases.
Handling Errors Gracefully
In production code you don't want to call .unwrap() on lock() because a poisoned mutex would make the handler panic and drop the request instead of answering it. Instead, handle the PoisonError and return a meaningful response. Here's how you can rewrite the increment handler to return a Result. Only the imports and the handler change; the rest of the file stays as in the complete example above.
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Router,
};
use std::sync::{Arc, Mutex};
async fn increment_handler(
State(counter): State<Arc<Mutex<i32>>>,
) -> Result<String, Response> {
let mut num = counter.lock()
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Mutex poisoned").into_response())?;
*num += 1;
Ok(format!("Counter is now: {}", *num))
}
This way, if a previous panic left the mutex poisoned, the handler returns a 500 Internal Server Error instead of panicking itself. For most examples in this page we use unwrap() for brevity, but in a real application you should handle errors properly.
Common Mistakes and Misconceptions
1. Forgetting to Lock Before Accessing
A frequent beginner error is trying to use the inner value directly without locking:
// This will NOT compile
let value = *counter; // error: cannot move out of an `Arc`
Or trying to mutate without a lock:
*counter += 1; // error[E0368]: binary assignment operation `+=` cannot be applied to type `std::sync::Mutex<i32>`
The whole point of Mutex is to force you to lock first. The compiler will remind you if you forget.
2. Holding a std::sync::Mutex Guard Across .await
This is the most serious mistake when using std::sync::Mutex in async code, and the compiler catches it for you. Consider a handler that locks the mutex, then awaits something (like a database query), and only then releases the lock:
async fn bad_handler(
State(counter): State<Arc<Mutex<i32>>>,
) -> String {
let mut num = counter.lock().unwrap();
// Some async operation that takes time
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
*num += 1;
format!("Counter is now: {}", *num)
}
This code does not compile. The error is:
error[E0277]: the trait bound `fn(State<Arc<Mutex<i32>>>) -> _ {bad_handler}: Handler<_, _>` is not satisfied
The reason is that std::sync::MutexGuard is not Send: it cannot be moved between threads. Axum requires every handler's future to be Send, because the runtime may move it between worker threads at any .await point. A future that holds a std guard across an .await cannot meet that requirement, so the Handler trait is not satisfied and compilation stops. There is no runtime deadlock to debug here, the compiler refuses the program before it ever runs.
The fix depends on what you need. If the lock is only guarding a quick update, drop the guard before the .await: do the locked work, let the guard go out of scope, and only then await. If you genuinely need to hold a lock while awaiting, use tokio::sync::Mutex instead. Its guard is Send, and its lock() is async, so waiting for the lock yields to the runtime instead of blocking a thread.
A std Mutex guard across an await is a compile error:
If you must hold a lock while performing asynchronous work, use tokio::sync::Mutex instead. That type is designed to be held across .await because it yields to the runtime while waiting. But be aware that even tokio::sync::Mutex should be held for as short a time as possible to avoid contention. This page focuses on std::sync::Mutex, which is the right choice for quick, non-async critical sections.
3. Poisoning
A mutex becomes poisoned when a panic occurs while the lock is held. The idea is that if a thread panics in the middle of updating data, the data might be left in an inconsistent state. The next call to lock() returns an Err(PoisonError) instead of panicking, signaling that you should be careful. In simple examples using unwrap() will panic; in production you should handle this error explicitly, as shown above.
4. Deadlocks from Re‑entrant Locking
Rust's std::sync::Mutex is not re‑entrant. If a thread tries to lock the same mutex twice (for example, by calling a function that locks it while already holding the guard), it will deadlock. This can happen accidentally if you call a helper function that locks the mutex from inside another locked section. Always be aware of the lock scope and avoid nesting locks on the same mutex.
Multiple Mutexes and Structuring State
As your application grows, you may have several independent pieces of shared state. Instead of one big Mutex around a giant struct, it's usually better to have separate Arc<Mutex<...>> for each independent resource. That way, different handlers that touch different resources don't block each other. For example, a user cache and a configuration store could be two separate Arc<Mutex<...>> values passed together using a single AppState struct. For now, remember that one Mutex protects one piece of data, and you can pass multiple Arc<Mutex<...>> objects to Axum by combining them into a struct.
When Not to Use Mutex
Before reaching for a Mutex, consider if there is a simpler alternative:
- For counters or flags that only need atomic operations,
AtomicUsizeorAtomicBoolare lock-free and often faster. - If you only need read‑only shared data,
Arc<T>alone is enough - noMutexneeded. - If your critical section involves heavy computation or I/O,
tokio::sync::Mutexor other concurrency primitives might be a better fit.
But for any shared data that must be mutated and the mutation is quick (like updating a counter, inserting into a map, or flipping a flag), Arc<Mutex<T>> is the standard, proven pattern in Axum.
Summary
Mutex gives you safe interior mutability in a shared context. Combined with Arc, it lets Axum handlers share mutable state without data races. The key mental model is: every time you want to read or write the protected data, you first lock the mutex to obtain a guard, do your work, and then drop the guard (automatically at scope end). The main trap to avoid is holding a std::sync::Mutex guard across an .await point, which the compiler rejects because the guard is not Send.
Now that you understand how to mutate shared state with Mutex, the next logical step is exploring RwLock, which provides a more flexible locking strategy when many readers need access at once. But before moving on, practice with the examples here: build the counter, then extend it to a HashMap, and observe how multiple concurrent requests stay consistent.