Updating State Safely in Handlers

Learn how to safely modify shared application state from Axum handlers using the lock-mutate-unlock pattern, avoid holding locks across await points, and handle lock poisoning.

When you build a web server with Axum, handlers often need to change shared data - a counter that goes up with each visit, a list of items that grows when users submit forms, or a status flag that flips when something happens. But if two requests arrive at the same time and both try to change that data, you can end up with lost updates or corrupted values. This page shows you how to update state safely so that every change happens correctly, no matter how many requests are in flight.

We'll focus on the lock-mutate-unlock pattern. This is the most common way to protect shared state in Rust web applications. You'll learn what a lock is, how to use it inside a handler, and the mistakes that trip up beginners.

The Problem - Why Naive Updates Break

Imagine you have a shared counter stored as an Arc<Mutex<i32>>. A tempting way to write the handler is to read the value, release the lock, and then lock again to write the new value back:

use axum::{extract::State, routing::get, Router};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<i32>>,
}
async fn increment(State(state): State<AppState>) -> String {
    // Read the value, then drop the guard: the lock is released here.
    let current = *state.counter.lock().unwrap();
    // Another request can slip in between this line and the next lock.
    let mut count = state.counter.lock().unwrap();
    *count = current + 1;
    format!("Counter: {}", *count)
}

This compiles and runs, but it loses updates. Here is what happens if two requests arrive at the exact same time:

  1. Request A reads the current value (say 5) and releases the lock.
  2. Request B also reads the current value (still 5, because A hasn't written yet).
  3. Request A locks again, writes 6, and releases the lock.
  4. Request B locks again, writes 6, and releases the lock.

Both requests think they incremented the counter, but the final value is 6 instead of 7. One increment got lost. That is a race condition: the outcome depends on the unpredictable order in which the two tasks run. In a real server with many concurrent connections, this happens all the time.

The fix is to make the read-check-write sequence atomic, which means no other task can interfere between the read and the write. Hold one lock for the whole sequence: lock once, read and change the value while you hold the guard, and only then release it. The Mutex (mutual exclusion) provides exactly that. When you call lock(), you gain exclusive access to the data. No other task can lock it until you release the lock. That's the "mutual exclusion" part.

The Lock-Mutate-Unlock Pattern

The pattern has three simple steps:

  1. Lock the data - acquire the guard that gives you exclusive access.
  2. Mutate the data - change it while no one else can see it.
  3. Unlock - release the lock, usually by letting the guard go out of scope.

In Rust, the MutexGuard returned by lock() automatically releases the lock when it is dropped. So you don't need an explicit "unlock" call - the guard's Drop implementation does it for you. This is why the code above works: count is a MutexGuard<i32>, and when the function returns, count is dropped, unlocking the mutex.

Let's break down the basic handler step by step:

async fn increment(State(state): State<AppState>) -> String {
    // Step 1: Lock
    let mut count = state.counter.lock().unwrap();
    // Step 2: Mutate
    *count += 1;
    // Step 3: Unlock happens automatically when `count` is dropped at the end of the scope
    format!("Counter: {}", *count)
}

The count variable is a MutexGuard. To change the underlying integer, you dereference it with *count because the guard acts like a reference to the inner value. Then you return a string that reads the updated value. When the function ends, count goes out of scope, and the lock is released. The next request can now lock and see the updated number.

What is a Mutex?:

A mutex (short for mutual exclusion) is a synchronization primitive that lets only one thread or task access a piece of data at a time. In Rust, std::sync::Mutex wraps a value and provides a lock() method. That method blocks the current thread until the lock is available, then returns a MutexGuard that gives you read/write access. When the guard is dropped, the lock is released automatically.

A Complete Counter Example

The examples on this page use Axum and Tokio, and the list example later reads query parameters into a struct with serde, so add all three to your Cargo.toml now:

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

Let's build a tiny but complete Axum application that uses this pattern. The server will have one route, /, that increments a shared counter each time it is called.

src/main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<i32>>,
}
async fn increment(State(state): State<AppState>) -> String {
    let mut count = state.counter.lock().unwrap();
    *count += 1;
    format!("Counter: {}", *count)
}
#[tokio::main]
async fn main() {
    // Create the initial state with counter = 0
    let state = AppState {
        counter: Arc::new(Mutex::new(0)),
    };
    // Build the router and attach the state
    let app = Router::new()
        .route("/", get(increment))
        .with_state(state);
    // Start the server
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here's what happens when you run this program and visit http://127.0.0.1:3000/:

  1. The first request locks the mutex, sees 0, increments it to 1, releases the lock, and returns "Counter: 1".
  2. The second request locks again, sees 1, increments it to 2, and returns "Counter: 2".
  3. And so on.

Try opening the page in two browser tabs and refreshing them rapidly. You'll see the counter increase one by one without ever skipping or repeating numbers. The mutex guarantees that.

It's Working:

If you refresh the page multiple times and see the counter go 1, 2, 3, 4... without any jumps or repeats, your lock-mutate-unlock pattern is working correctly. The state is protected from race conditions.

Using RwLock for Read-Heavy State

A Mutex allows only one reader or writer at a time, even if many tasks only want to read the data without changing it. If your state is read often but written rarely, you can use RwLock (read-write lock). An RwLock allows many readers simultaneously, but only one writer. When a writer wants to modify the data, it must wait until all readers have finished.

Let's create a simple in-memory list of strings. Visitors can see the list (read) and add an item (write). We'll use an RwLock<Vec<String>>.

src/main.rs
use axum::{
    extract::{Query, State},
    routing::{get, post},
    Router,
};
use serde::Deserialize;
use std::sync::{Arc, RwLock};
#[derive(Clone)]
struct AppState {
    items: Arc<RwLock<Vec<String>>>,
}
#[derive(Deserialize)]
struct AddParams {
    item: String,
}
async fn list_items(State(state): State<AppState>) -> String {
    // Acquire a read lock - many readers can do this at once
    let items = state.items.read().unwrap();
    format!("Items: {:?}", *items)
}
async fn add_item(
    State(state): State<AppState>,
    Query(params): Query<AddParams>,
) -> String {
    // Acquire a write lock - only one writer at a time
    let mut items = state.items.write().unwrap();
    items.push(params.item);
    format!("Added. Total items: {}", items.len())
}
#[tokio::main]
async fn main() {
    let state = AppState {
        items: Arc::new(RwLock::new(Vec::new())),
    };
    let app = Router::new()
        .route("/", get(list_items))
        .route("/add", post(add_item))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

To test this, run the server and use curl or your browser:

  • GET http://127.0.0.1:3000/ returns an empty list: Items: []
  • POST http://127.0.0.1:3000/add?item=apple adds "apple" and returns Added. Total items: 1
  • GET again returns Items: ["apple"]

The read() method returns a RwLockReadGuard, which allows shared read access. The write() method returns a RwLockWriteGuard, which gives exclusive write access. Just like Mutex, the lock is released when the guard is dropped.

Why use RwLock instead of Mutex?:

If your handlers mostly read data and rarely change it, RwLock can improve concurrency. Many requests can read at the same time without blocking each other. Only when a write happens does it temporarily block all readers and writers. For a counter that is updated on every request, Mutex is simpler and just as good. For a configuration object that is read many times but updated occasionally, RwLock is a better fit.

Keeping Lock Scopes Short - The Await Trap

One of the biggest beginner mistakes is holding a lock across an .await point. In Rust, when you use an async runtime like Tokio, your handler can pause at .await and let other tasks run. If you are holding a std::sync::MutexGuard (the guard from std::sync::Mutex) while you await, the compiler will reject the code because the guard is not Send: Axum handlers must return Send futures, regardless of whether the runtime is multi-threaded or single-threaded. That compile error is the protection. If the same pattern somehow compiled (for example, outside of Axum), holding the lock while suspended means every other task that tries to lock the same mutex will block until your task resumes and finishes. That can cause severe performance issues and even deadlocks.

Here's a bad example:

use axum::extract::State;
use std::sync::{Arc, Mutex};
async fn bad_handler(State(counter): State<Arc<Mutex<i32>>>) -> String {
    let mut num = counter.lock().unwrap(); // lock acquired
    // ... do some async work while holding the lock
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    *num += 1;
    format!("Counter: {}", *num)
}

This code will not compile in an Axum handler, on any runtime flavour, because MutexGuard is not Send and cannot be held across an await point. The compiler rejects the handler before the server ever runs. The one-second sleep shows why the rule exists: had this code compiled, the lock would have been held for a full second, preventing any other request from incrementing the counter during that time.

The correct approach is to keep the lock scope as small as possible. Do the locking, mutate the data, and release the lock before any .await that doesn't need the lock.

async fn good_handler(State(counter): State<Arc<Mutex<i32>>>) -> String {
    let new_value;
    {
        let mut num = counter.lock().unwrap();
        *num += 1;
        new_value = *num;
    } // lock released here
    // Now it's safe to await without holding the lock
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    format!("Counter: {}", new_value)
}

In this version, we use an inner block { } to limit the lifetime of the guard. After that block, num is dropped and the lock is released. Then we can safely call .await.

Never Hold a Lock Across Await:

Holding a std::sync::MutexGuard across an .await point in an Axum handler does not compile, because the guard is not Send. Always keep the lock scope tight: acquire, mutate, and drop the lock before any suspension point.

If you truly need to hold a lock across an async operation, you can use tokio::sync::Mutex instead of std::sync::Mutex. tokio::sync::Mutex is designed for async code and allows its guard to be held across await points. However, even with tokio::sync::Mutex, you should still minimize the time you hold the lock, because it serializes access just like the standard mutex. The main difference is that tokio::sync::Mutex::lock() is async and yields to the runtime instead of blocking a thread.

Using std::sync::Mutex for short sections without await

Use std::sync::Mutex when the critical section is short and does not contain any .await. It is faster because it does not require async overhead. The lock call is synchronous and blocks the current thread until the lock is acquired.

use axum::extract::State;
use std::sync::{Arc, Mutex};
async fn handler(State(counter): State<Arc<Mutex<i32>>>) -> String {
    let mut num = counter.lock().unwrap();
    *num += 1;
    format!("{}", *num)
}

Using tokio::sync::Mutex when the lock must span an await

Use tokio::sync::Mutex when you must hold the lock across an .await or when you want the lock acquisition itself to be async (non-blocking). The lock() method returns a future, so you need to .await it.

use axum::extract::State;
use std::sync::Arc;
use tokio::sync::Mutex;
async fn handler(State(counter): State<Arc<Mutex<i32>>>) -> String {
    let mut num = counter.lock().await;
    *num += 1;
    format!("{}", *num)
}

Pick one lock type per piece of state: the standard mutex for short sections with no await, the Tokio mutex when the lock must survive a suspension point. Mixing the two on the same value does not work, because they are different types with different guards.

For most simple state updates that happen entirely inside a handler without intermediate async work, std::sync::Mutex is the right choice.

Handling Lock Poisoning

If a thread panics while holding a Mutex or RwLock, the lock becomes poisoned. This is a safety mechanism in Rust: a panic might leave the protected data in an inconsistent state, so the next attempt to lock will return an Err instead of panicking silently and potentially using corrupted data.

In the examples above, we used .unwrap() after lock(). That means if the lock is poisoned, the program will panic. For a robust server, you should decide what to do when a lock is poisoned. Usually, you want to recover the guard and continue, but you must be aware that the data might be partially modified.

Here's an example of recovering from a poisoned lock:

use std::sync::{Arc, Mutex};
async fn update(State(counter): State<Arc<Mutex<i32>>>) -> String {
    let mut num = counter.lock().unwrap_or_else(|poisoned| {
        // The lock is poisoned. We can still get the inner data.
        println!("Lock was poisoned, recovering...");
        poisoned.into_inner()
    });
    *num += 1;
    format!("{}", *num)
}

PoisonError::into_inner() returns the MutexGuard even though the lock is poisoned. This lets you access the data and continue. But remember: the data might be in a weird state because a panic interrupted a previous mutation. In practice, no panic can happen in the middle of a plain integer increment, so recovering is safe for a simple counter. For more complex data structures, you may need to validate or reset the data after recovering.

Don't Ignore Poisoning:

Lock poisoning is not a rare edge case: any panic inside a lock will trigger it. If you blindly use .unwrap(), a poisoned lock will panic inside the handler, and that request will fail (the panic unwinds the task handling the connection, so the client gets an empty reply). It does not crash the whole server process, but the request still fails. Always think about whether your application should recover or fail fast. For simple atomic updates like a counter, recovering with unwrap_or_else is usually fine. For complex state, you may want to log an error and return a 500 response instead.

You can also avoid panicking while holding a lock altogether by doing any fallible or complex logic before locking, and keeping the lock section to only the minimal state mutation. For example, validate input before locking, then lock and store the result.

Common Mistakes and How to Fix Them

Let's look at the errors that beginners most often make when updating state safely.

1. Forgetting to Dereference the Guard

The lock guard is not the value itself; it's a wrapper that gives you access to the value. Many newcomers write:

let mut count = state.counter.lock().unwrap();
count += 1; // ERROR! `MutexGuard<i32>` does not have an `add_assign` implementation

They get a compile error because count is a MutexGuard, not an i32. The fix is to dereference with *:

*count += 1;

2. Holding the Lock Too Long

Even without .await, if you perform heavy computation, file I/O, or database queries while holding the lock, you serialize all other requests that need the same state. Keep the critical section (the part between lock and unlock) as short as possible.

// Bad: holding lock during expensive operation
let mut data = state.data.lock().unwrap();
let result = expensive_calculation(&*data);
*data = result; // lock held for entire calculation
// Good: do calculation first, lock only for assignment
let result = expensive_calculation(); // no lock needed
let mut data = state.data.lock().unwrap();
*data = result;

3. Using std::sync::Mutex with tokio::spawn and Holding Across Await

A std::sync::MutexGuard is not Send. If you try to hold it while awaiting in an Axum handler, the compiler rejects the handler outright. Use tokio::sync::Mutex if you absolutely must hold a lock across await, but better yet, restructure your code to avoid that.

4. Not Handling Poisoning

Always assume the lock could be poisoned. Decide on a strategy: recover, log, or fail with a proper response. Never leave a bare .unwrap() in production code unless you are certain that no panic can occur inside the lock (which is rare).

5. Confusing RwLock Read and Write Guards

read() returns a guard that only allows immutable access. write() returns a guard that allows mutable access. If you try to modify data through a read() guard, you'll get a compile error. Make sure you use write() when you need to change the data.

let mut items = state.items.read().unwrap();
items.push("new"); // ERROR: cannot borrow as mutable

Stepping Through a Safe Update - A Full Walkthrough

Let's put everything together with a step-by-step guide to building a safe state update for a hit counter. This assumes you have a basic Axum project set up.

1

Step 1: Define your state struct with a protected field

Create a struct that will hold your shared state. Use Arc to make it shareable across threads, and wrap the mutable part in a Mutex.

use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    hits: Arc<Mutex<u64>>,
}
2

Step 2: Initialize the state in main

In your main function, create an instance with the mutex containing the initial value.

let state = AppState {
    hits: Arc::new(Mutex::new(0)),
};
3

Step 3: Attach the state to the router

Use .with_state(state) when building the router. This makes the state available to all handlers.

let app = Router::new()
    .route("/", get(handler))
    .with_state(state);
4

Step 4: Write the handler using lock-mutate-unlock

Inside your handler, extract the state, lock the mutex, mutate the value, and let the guard drop.

async fn handler(State(state): State<AppState>) -> String {
    let mut hits = state.hits.lock().unwrap();
    *hits += 1;
    format!("Total hits: {}", *hits)
}
5

Step 5: Test for correctness under concurrency

Run the server and send many requests in parallel (using wrk, ab, or a simple loop with curl &). Verify that the final count equals the number of requests. The mutex ensures no updates are lost.

All Set:

If you followed these steps and your counter reaches the correct total after hundreds of parallel requests, you have successfully implemented safe state updates. This pattern will serve you well for any kind of shared data in Axum.

Summary

Updating shared state safely in Axum handlers comes down to one idea: make sure only one task can modify the data at a time. The lock-mutate-unlock pattern with Mutex or RwLock gives you that guarantee. Locking wraps the critical section in a guard that automatically releases when it goes out of scope, so you don't have to remember to unlock manually.

The key decisions you need to make are:

  • Mutex vs RwLock: Use Mutex for simple, frequently written state like counters. Use RwLock when reads vastly outnumber writes.
  • std vs tokio mutex: Use std::sync::Mutex for short critical sections without .await; use tokio::sync::Mutex if you must hold the lock across suspension points.
  • Poisoning: Decide how to recover if a panic occurs while holding a lock. unwrap_or_else is a common recovery pattern.

With this pattern in your toolbox, you can safely store and update any kind of shared data in your Axum application - counters, lists, configuration flags, or even complex structs. The next logical step is to explore how to combine this with other features like database connections or background tasks, but the principle remains the same: protect shared mutable state with a lock, and keep that lock scope as small as possible.