Sync Requirement on Handlers in Axum

Learn why Axum handlers must be thread-safe, what Send and Sync mean in Rust, how the requirement changed in Axum 0.8, and how to fix common compilation errors when your handler captures non-thread-safe types.

When you write an HTTP handler in Axum, you're writing a function that will run inside Tokio's multi-threaded asynchronous runtime. This means your handler's code can be paused, moved between operating system threads, and then resumed on a completely different thread. For that to be safe, Rust needs to guarantee that your handler and everything it holds onto are safe to move and share across threads. That guarantee comes from two special Rust traits called Send and Sync.

This page explains what those traits mean, why Axum cares about them, what changed in Axum 0.8 regarding the Sync requirement specifically, and how to fix the compilation errors you'll hit when you accidentally use a non-thread-safe type inside a handler.

What Send and Sync Mean in Plain Language

Rust's type system has two marker traits that describe whether a type is safe to use across threads. They are enforced by the compiler, not by runtime checks, so they catch thread-safety bugs before your program ever starts.

Send means: "This value can be safely moved from one thread to another." When you pass a String from one thread to another, the thread that receives it takes full ownership. No other thread can touch that exact same String at the same time. That's safe, so String is Send.

Sync means: "This value can be safely accessed by multiple threads at the same time through shared references." If two threads both hold a read-only reference to the same u64 integer, they can both read it without causing a data race. That's safe, so u64 is Sync.

Send is about moving, Sync is about sharing:

A type can be Send but not Sync, or Sync but not Send. For example, Mutex<T> from std::sync is both Send and Sync as long as T is Send. A raw pointer *const T is neither Send nor Sync because Rust can't guarantee the pointed-to data is managed safely. Every beginner should learn these two words early because they appear constantly in error messages when working with async Rust.

For an async handler in Axum, the critical requirement is:

  1. The future returned by the handler must be Send. An async function returns a future, and that future is what actually runs on Tokio's worker threads. Any data that lives across an .await point inside that future must be Send, because Tokio can move the future to a different thread at that .await point.
  2. The handler itself (the function or closure) must be Clone + Send + Sync + 'static. This is the Handler trait's own bound, and Axum 0.8 made the Sync part explicit for handlers added to a Router - it was not relaxed, as we'll cover shortly.

Think of it this way: your handler is a recipe, and the future is the cook following that recipe. The recipe (handler) needs to be readable by anyone in the kitchen without causing chaos. The cook (future) needs to be able to walk around the kitchen (move between threads) while carrying all the ingredients (data).

Why Axum Requires Thread-Safe Handlers

Axum is built on top of Tokio. When you start an Axum server, Tokio creates a pool of worker threads - typically one per CPU core on your machine. Incoming HTTP requests are distributed across these threads using a work-stealing scheduler. One request might start executing on thread 1, pause at an .await point (like waiting for a database query to complete), and then resume on thread 3.

If your handler held something that isn't Send across that .await point - like an Rc<T> (a reference-counted pointer that's not atomic) or a RefCell<T> (runtime borrow checking that doesn't use locks) - then moving the future to a different thread would be unsound. Thread 1 might still be using that Rc's reference count while thread 3 also tries to modify it. That's a data race, and data races cause undefined behavior in Rust.

Rust prevents this entire category of bug at compile time. If your handler captures or holds something that's not Send, the compiler refuses to build your program, and the error message points you directly to the offending type.

The Change in Axum 0.8

Before Axum 0.8, the Handler trait - the trait that every handler function implements - required three bounds: Clone, Send, and Sync. The Clone bound existed because the Router needed to make copies of handlers internally when you registered them with .route(). The Sync bound existed because the Router itself might be shared across threads through Arc<Router>.

Axum 0.8 did not relax this - it tightened it. The 0.8.0 changelog lists as a breaking change: "Require Sync for all handlers and services added to Router and MethodRouter (#2473)". The Handler trait in Axum 0.8.9 is still declared as pub trait Handler<T, S>: Clone + Send + Sync + Sized + 'static. You cannot use a closure as a handler if it captures non-Clone data (like a tokio::sync::oneshot::Sender it actually uses) or non-Sync data (like a std::cell::Cell) - both fail to compile. This is a new constraint in 0.8, not a relaxation.

Axum 0.8 is a breaking release:

If you're following tutorials written for Axum 0.7 or earlier, some code patterns will look slightly different. In 0.8 the Sync requirement became explicit for handlers added to a Router, so code that relied on non-Sync handlers may now fail to compile. Existing code that already compiled should keep compiling.

Here's a concrete before-and-after comparison of the trait bounds:

In Axum 0.7:

// Not real code from the compiler, just an illustration
pub trait Handler<T, S = ()>: Clone + Send + Sync + Sized + 'static {
    // ...
}

In Axum 0.8:

// This matches the real declaration in axum 0.8.9, handler/mod.rs
pub trait Handler<T, S>: Clone + Send + Sync + Sized + 'static {
    // ...
}

The trait bounds themselves did not change - what changed in 0.8 is that the Sync bound is now also enforced for handlers and services when they are added to a Router or MethodRouter.

The important takeaway: the future your handler returns must still be Send. That requirement never went away and never will, because it's fundamental to how Tokio's multi-threaded scheduler works. And the handler itself must be Clone + Send + Sync + 'static - that did not go away either.

What This Means in Practice

For most simple handlers, you'll never notice any difference. A plain async fn with no captured state is automatically both Send and Sync because it holds nothing. Let's start with the simplest possible example and build up.

Starter Example: A Plain Handler

use axum::{routing::get, Router};
use tokio::net::TcpListener;
async fn hello_world() -> &'static str {
    "Hello, world!"
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello_world));
    let listener = TcpListener::bind("127.0.0.1:3000")
        .await
        .expect("failed to bind listener");
    axum::serve(listener, app)
        .await
        .expect("server failed");
}

This compiles without any thought about Send or Sync because there's nothing to be worried about. hello_world is a zero-sized function item - it holds no state at all. Its future is trivially Send because there are no .await points inside the function, and it captures nothing.

When Capturing State Causes Problems

Now let's add some shared state. Imagine you want to keep a counter that tracks how many times the handler has been called. A beginner might try something like this:

use axum::{routing::get, Router};
use std::cell::Cell;
async fn count_visits(counter: Cell<u64>) -> String {
    let current = counter.get();
    counter.set(current + 1);
    format!("Visit number: {}", current)
}
#[tokio::main]
async fn main() {
    let counter = Cell::new(0u64);
    let app = Router::new()
        .route("/", get(move || count_visits(counter)));
    // ...
}

This will fail to compile, for two separate reasons. First, the closure gives the Cell away. Calling count_visits(counter) moves counter out of the closure, so the closure can only run once. A handler must be callable for every request that arrives, and it must be Clone, so a closure that consumes its captured value on the first call cannot be a handler at all.

Second, even if you fix that part by cloning the Cell on each call - move || count_visits(counter.clone()) - it still fails to compile. Cell<T> allows mutation through a shared reference with no locking, which is only safe on one thread. Two threads could call counter.set() at the same moment with nothing to stop them, so Rust makes Cell<T> not Sync, and the handler must be Sync.

The fix depends on what you're trying to do:

Option 1: Use std::sync::Mutex

Mutex provides mutual exclusion - only one thread can access the protected data at a time. It's both Send and Sync.

use axum::{routing::get, Router};
use std::sync::{Arc, Mutex};
async fn count_visits(counter: Arc<Mutex<u64>>) -> String {
    let mut current = counter.lock().expect("mutex poisoned");
    *current += 1;
    format!("Visit number: {}", *current)
}
#[tokio::main]
async fn main() {
    let counter = Arc::new(Mutex::new(0u64));
    let app = Router::new()
        .route("/", get({
            let counter = Arc::clone(&counter);
            move || count_visits(Arc::clone(&counter))
        }));
    // ...
}

The Arc (atomic reference count) wraps the Mutex so multiple threads can share ownership of the same lock. Arc<Mutex<u64>> is both Send and Sync.

Option 2: Use tokio::sync::Mutex

Tokio provides its own Mutex that's designed to be used with .await. The lock acquisition is an async operation, which means you don't block the entire thread while waiting.

use axum::{routing::get, Router};
use std::sync::Arc;
use tokio::sync::Mutex;
async fn count_visits(counter: Arc<Mutex<u64>>) -> String {
    let mut current = counter.lock().await;
    *current += 1;
    format!("Visit number: {}", *current)
}
#[tokio::main]
async fn main() {
    let counter = Arc::new(Mutex::new(0u64));
    let app = Router::new()
        .route("/", get({
            let counter = Arc::clone(&counter);
            move || count_visits(Arc::clone(&counter))
        }));
    // ...
}

std::sync::Mutex vs tokio::sync::Mutex:

Use std::sync::Mutex when the critical section is very short and doesn't contain any .await points. Use tokio::sync::Mutex when you need to hold the lock across .await points or when the critical section is relatively long and you don't want to block a Tokio worker thread. For simple counters like this, std::sync::Mutex is usually faster.

The Problem with Rc and RefCell

Rc<T> is a non-atomic reference-counted pointer. It's cheap because it doesn't use atomic operations, but it's not Send or Sync. If you try to share an Rc across threads, two threads could decrement the reference count simultaneously, leading to a double-free or use-after-free.

RefCell<T> allows mutable access through a shared reference, similar to Cell<T>, but it's also not Sync for the same reason.

Here's an example that won't compile:

use axum::{routing::get, Router};
use std::cell::RefCell;
use std::rc::Rc;
async fn read_data(data: Rc<RefCell<String>>) -> String {
    data.borrow().clone()
}
#[tokio::main]
async fn main() {
    let shared = Rc::new(RefCell::new("Hello".to_string()));
    let app = Router::new()
        .route("/", get({
            let shared = Rc::clone(&shared);
            move || read_data(Rc::clone(&shared))
        }));
    // ...
}

The compiler error will say something like:

error[E0277]: `Rc<RefCell<String>>` cannot be sent between threads safely
   --> src/main.rs:...
    |
    |     let app = Router::new()
    |         .route("/", get({
    |             let shared = Rc::clone(&shared);
    |             move || read_data(Rc::clone(&shared))
    |         }));
    |         ------- ^ `Rc<RefCell<String>>` cannot be sent between threads safely
    |
    = help: the trait `Send` is not implemented for `Rc<RefCell<String>>`

That is the detailed form of the error. Without extra help the compiler only says the closure does not implement Handler, without naming the type. The section on reading compiler errors later on this page shows how #[axum::debug_handler] produces the detailed form.

The fix is to replace Rc with Arc and RefCell with Mutex or RwLock:

use axum::{routing::get, Router};
use std::sync::{Arc, RwLock};
async fn read_data(data: Arc<RwLock<String>>) -> String {
    data.read().expect("lock poisoned").clone()
}
#[tokio::main]
async fn main() {
    let shared = Arc::new(RwLock::new("Hello".to_string()));
    let app = Router::new()
        .route("/", get({
            let shared = Arc::clone(&shared);
            move || read_data(Arc::clone(&shared))
        }));
    // ...
}

RwLock allows multiple threads to read simultaneously (via .read()) but only one thread to write (via .write()). For read-heavy workloads, this is better than Mutex, which allows only one thread at a time regardless of read or write.

The Difference Between Send on the Future and Sync on the Handler

There are two separate requirements, and beginners often confuse them:

The future must be Send. This applies to every async handler. The future is the object that actually runs when the request is processed. Tokio can pause it at an .await and resume it on a different thread. Any data that's alive at that .await point must be Send.

The handler (the function/closure) must be Clone + Send + Sync + 'static. This is the Handler trait's own bound, and it applies to the function object itself, before it is even called. Axum 0.8 made the Sync part explicit for handlers and services added to a Router or MethodRouter - it did not remove it.

In short: the future must be Send, and the handler itself must be Clone + Send + Sync + 'static. Neither requirement went away in 0.8.

What this means for you:

In Axum 0.8, a closure used as a handler must still satisfy all four bounds. Capturing a String or an Arc<Mutex<T>> is fine (both are Clone + Send + Sync). Capturing a std::cell::Cell fails because Cell is not Sync, and capturing a tokio::sync::oneshot::Sender fails because Sender is not Clone - even though Sender is both Send and Sync.

A Practical Example Showing What Fails

Let's build a small example that demonstrates the bounds in practice.

Imagine a handler that captures a tokio::sync::oneshot::Sender. This type is used to send a single message across threads. Is Sender Send? Yes. Is Sender Sync? Yes, too - but is it Clone? No: there is only ever one sender, so it cannot be cloned. A closure that moves Sender into its future cannot be Clone, so it cannot be a handler:

// This does NOT compile in Axum 0.8
use axum::{routing::get, Router};
use tokio::sync::oneshot;
#[tokio::main]
async fn main() {
    let (tx, _rx) = oneshot::channel::<String>();
    let app = Router::new()
        .route("/", get(move || async move {
            // Sender is Send and Sync, but NOT Clone
            tx.send("Hello from handler".to_string()).ok();
            "sent"
        }));
    // This fails because the closure captures `tx`,
    // which is not Clone, and the handler must be Clone.
}

The fix is to stop capturing the sender in the handler. A Sender can only send once and cannot be cloned, so sharing it through a plain Arc does not help - send takes the sender by value. Wrap it so it can be taken exactly once, for example in an Arc<Mutex<Option<oneshot::Sender<String>>>> held in shared state, and have the handler take it out and send on it. The same applies to a std::cell::Cell, which is Clone and Send but not Sync - a closure capturing it also fails to compile, because the handler must be Sync.

How the Future's Send Bound Works

Let's look more carefully at what happens inside an async handler when you hold non-Send data across an .await point. This is where most beginners hit walls.

Here's a handler that tries to use Rc<T> across an .await:

use axum::{routing::get, Router};
use std::rc::Rc;
use tokio::time::{sleep, Duration};
async fn broken_handler() -> String {
    let data = Rc::new("hello".to_string());
    // This await creates a suspension point.
    // The future might resume on a different thread.
    sleep(Duration::from_millis(100)).await;
    // Rc is still alive here, but it's not Send.
    // The future as a whole is therefore not Send.
    data.to_string()
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(broken_handler));
    // This fails to compile: the future is not Send
}

The compiler error will point to the Rc and say something like:

error: future cannot be sent between threads safely
  --> src/main.rs:...
   |
   | async fn broken_handler() -> String {
   |                    ^^^^^^ future returned by `broken_handler` is not `Send`
   |
   = help: within `impl Future<Output = String>`, the trait `Send` is not implemented for `Rc<String>`
note: future is not `Send` as this value is used across an await
  --> src/main.rs:...
   |
   |     let data = Rc::new("hello".to_string());
   |         ---- has type `Rc<String>` which is not `Send`
   |     sleep(Duration::from_millis(100)).await;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ await occurs here, with `data` maybe used later

The key phrase is "future is not Send as this value is used across an await." That tells you exactly what to fix.

The fix is to use Arc instead of Rc:

use axum::{routing::get, Router};
use std::sync::Arc;
use tokio::time::{sleep, Duration};
async fn fixed_handler() -> String {
    let data = Arc::new("hello".to_string());
    sleep(Duration::from_millis(100)).await;
    data.to_string()
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(fixed_handler));
    // This compiles: Arc<String> is Send and Sync
    // ...
}

Arc<String> is Send and Sync because it uses atomic reference counting, which is safe across threads. The future can now be moved between threads at the .await point.

Multiple Approaches to Fixing Non-Send Futures

When you hit a "future is not Send" error, you have several ways to resolve it depending on the situation.

Approach 1: Replace Non-Send Types with Thread-Safe Equivalents

This is the most straightforward approach. The table below shows common non-Send/non-Sync types and their thread-safe replacements.

Non-thread-safe typeThread-safe replacementNotes
Rc<T>Arc<T>Arc uses atomic reference counting with slightly higher overhead
RefCell<T>Mutex<T> or RwLock<T>Both from std::sync
Cell<T>Mutex<T> or AtomicU64 / AtomicI64 etc.Atomic types only work for primitives
*const T / *mut TArc<T> or Box<T>Raw pointers are never Send or Sync
use axum::{routing::get, Router};
use std::sync::{Arc, Mutex};
use tokio::time::{sleep, Duration};
async fn counter_handler(counter: Arc<Mutex<u64>>) -> String {
    {
        let mut count = counter.lock().expect("poisoned");
        *count += 1;
    }
    // Simulate some async work
    sleep(Duration::from_millis(10)).await;
    let count = counter.lock().expect("poisoned");
    format!("Total visits: {}", *count)
}
#[tokio::main]
async fn main() {
    let counter = Arc::new(Mutex::new(0u64));
    let app = Router::new()
        .route("/", get({
            let counter = Arc::clone(&counter);
            move || counter_handler(Arc::clone(&counter))
        }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .expect("failed to bind");
    axum::serve(listener, app).await.expect("server failed");
}

Approach 2: Restructure the Code to Avoid Holding Non-Send Data Across .await

Sometimes you can reorganize your logic so that non-Send data is dropped before you hit an .await point. This is often possible when the non-Send data is only needed for a short computation.

use axum::{routing::get, Router};
use std::rc::Rc;
use tokio::time::{sleep, Duration};
async fn restructured_handler() -> String {
    // Use Rc in a short, synchronous block
    let computed = {
        let data = Rc::new("temporary data".to_string());
        // Compute something with the Rc, then drop it
        let result = data.len() * 2;
        result.to_string()
    };
    // Rc is gone by now, so this future is Send
    sleep(Duration::from_millis(10)).await;
    computed
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(restructured_handler));
    // This compiles because Rc is not alive across the await
    // ...
}

This is a valid approach when the non-Send data is only needed for a short, synchronous computation. The key insight is that Rc is fine as long as it's created and destroyed within a single synchronous block and never lives across an .await.

Approach 3: Use tokio::task::block_in_place (Rarely Needed)

For CPU-bound synchronous work that needs to use non-Send types, you can use block_in_place to tell Tokio not to move the future while that code runs.

use axum::{routing::get, Router};
use std::rc::Rc;
use tokio::task::block_in_place;
async fn blocking_handler() -> String {
    let result = block_in_place(|| {
        // This synchronous block can use Rc freely
        let data = Rc::new(vec![1, 2, 3, 4, 5]);
        let mut sum = 0;
        for x in data.iter() {
            sum += x;
        }
        sum.to_string()
    });
    result
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(blocking_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .expect("failed to bind listener");
    axum::serve(listener, app).await.expect("server failed");
}

block_in_place runs the closure on the current worker thread and blocks that thread until the closure returns, so the Rc never lives inside a future that could move. The handler itself stays an ordinary async function, and the route registration is unchanged. Request / and the response is 15, the sum of the numbers in the vector.

blockinplace has limited use cases:

block_in_place only works when the future is running on a multi-threaded runtime, not a current-thread runtime. It also blocks the current worker thread while the closure runs, which can reduce throughput if overused. Prefer Approach 1 or 2 for most situations.

What the Sync Requirement Means for Router Composition

The Sync bound on handlers has implications for how you compose Routers. If you build a Router inside a function and return it, the router needs to contain handlers that are Clone + Send + Sync + 'static. A closure that captures nothing satisfies this trivially:

use axum::{routing::get, Router};
fn build_router() -> Router {
    Router::new()
        .route("/", get(|| async { "hello" }))
        // This closure captures nothing, so it is Clone + Send + Sync.
}
#[tokio::main]
async fn main() {
    let app = build_router();
    // ...
}

But a closure that captures a non-Clone or non-Sync value still fails in Axum 0.8 - for example, capturing a tokio::sync::oneshot::Sender (which is Send and Sync, but not Clone) does not compile:

use axum::{routing::get, Router};
use tokio::sync::oneshot;
fn build_router() -> Router {
    let (tx, _rx) = oneshot::channel::<String>();
    Router::new()
        .route("/", get(move || async move {
            // tx is Send and Sync, but NOT Clone.
            // This does NOT compile in Axum 0.8: the closure
            // cannot be Clone, so it cannot be a Handler.
            tx.send("done".to_string()).ok();
            "response"
        }))
}
#[tokio::main]
async fn main() {
    let app = build_router();
    // ...
}

The practical impact is that when you build routers inside functions, anything the closures capture must be Clone + Send + Sync - share it through Arc or application state instead of capturing a bare non-Clone value.

Common Misconceptions

Let's clear up some frequent misunderstandings about this topic.

Misconception 1: "Async handlers automatically make everything thread-safe."

No. Writing async fn doesn't magically make non-thread-safe types safe. The Rust compiler still checks every type inside your function. The async keyword just changes how the function is compiled into a state machine - it doesn't relax the thread-safety requirements.

Misconception 2: "If it compiles, it's thread-safe."

Mostly true for Send and Sync - the compiler does enforce these traits. However, thread safety in the broader sense (avoiding deadlocks, lock contention, logical race conditions) is still your responsibility. The Send and Sync traits prevent memory unsafety, but they don't prevent every possible concurrency bug.

Misconception 3: "The Sync requirement in Axum 0.8 means I need to mark my handler with #[sync] or something."

No. Sync is a trait that the compiler automatically determines based on the types in your code. You never explicitly mark something as Sync - you either use types that implement it or you don't.

Misconception 4: "Since 0.8, I can now use RefCell in handlers."

No. Axum 0.8 did not remove the Sync requirement - it made it explicit for handlers added to a Router. And separately, the future your handler returns must still be Send. If you hold a RefCell across an .await point, the future won't be Send, and compilation will still fail.

Misconception 5: "I should always use tokio::sync::Mutex instead of std::sync::Mutex."

Not always. tokio::sync::Mutex is designed for situations where you need to hold the lock across .await points. For short critical sections that don't contain .await, std::sync::Mutex is simpler and often faster because it doesn't require an async operation to acquire the lock.

A Complete Working Example

Let's tie everything together with a complete, runnable example that demonstrates several handlers with different thread-safety considerations. This example uses Axum 0.8.

use axum::{
    extract::{Path, State},
    routing::get,
    Router,
};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::{future::Future, pin::Pin};
use tokio::net::TcpListener;
// A shared counter using an atomic, which is inherently thread-safe.
// Atomics are both Send and Sync and can be mutated without locks
// for simple increment operations.
#[derive(Clone)]
struct AppState {
    visits: Arc<AtomicU64>,
    // This Mutex protects a String that might be updated occasionally
    message: Arc<Mutex<String>>,
}
// Handler 1: Reads from atomic (no lock needed)
async fn get_visits(State(state): State<AppState>) -> String {
    let count = state.visits.load(Ordering::Relaxed);
    format!("Total visits: {}", count)
}
// Handler 2: Increments the atomic and returns the new value
async fn increment_visits(State(state): State<AppState>) -> String {
    let new_count = state.visits.fetch_add(1, Ordering::Relaxed) + 1;
    format!("New visit count: {}", new_count)
}
// Handler 3: Reads the message (uses a lock but no await inside the lock)
async fn get_message(State(state): State<AppState>) -> String {
    let message = state.message.lock().expect("poisoned");
    message.clone()
}
// Handler 4: Shows a handler that captures data directly.
// The closure captures a `String`, which is `Clone + Send + Sync`, so it
// satisfies the `Handler` bounds. (A closure capturing a non-`Sync` or
// non-`Clone` value would not compile as a handler in Axum 0.8.)
// Note the argument is `Path<String>`: a bare `String` argument would be
// read from the request body, not from the `{name}` path segment.
fn make_greeting_handler(
    name: String,
) -> impl Fn(Path<String>) -> Pin<Box<dyn Future<Output = String> + Send>> + Clone + Send + Sync + 'static {
    move |Path(path_param): Path<String>| {
        let name = name.clone();
        Box::pin(async move { format!("Hello, {}! You requested: {}", name, path_param) })
    }
}
#[tokio::main]
async fn main() {
    let state = AppState {
        visits: Arc::new(AtomicU64::new(0)),
        message: Arc::new(Mutex::new("Server running".to_string())),
    };
    let app = Router::new()
        .route("/visits", get(get_visits))
        .route("/visits/increment", get(increment_visits))
        .route("/message", get(get_message))
        .route("/greet/{name}", get(make_greeting_handler("Friend".to_string())))
        .with_state(state);
    let listener = TcpListener::bind("127.0.0.1:3000")
        .await
        .expect("failed to bind listener");
    println!("Server listening on http://127.0.0.1:3000");
    axum::serve(listener, app)
        .await
        .expect("server failed");
}

This example shows four different thread-safety patterns:

  • AtomicU64 provides lock-free atomic increments for simple counters. It's both Send and Sync.
  • Arc<Mutex<String>> provides shared mutable access to a string. The lock is acquired only for reading, and it's released before any .await point.
  • AppState is Clone (derived), which makes it easy to share across handlers.
  • The closure in make_greeting_handler captures a String (which is Send and Sync), which is exactly why it satisfies the Handler bounds - a closure capturing a non-Sync or non-Clone value would fail to compile in Axum 0.8.

Don't hold std::sync::Mutex across await points:

If you're using std::sync::Mutex and you acquire the lock, make sure you release it before hitting an .await point. Holding the guard across an .await does not compile at all, because std::sync::MutexGuard is not Send. Use tokio::sync::Mutex if you need to hold the lock across .await.

How to Read Compiler Errors

When you violate the Send/Sync requirements, Rust's compiler produces detailed error messages. Learning to read them is half the battle. Here's a typical error and how to interpret it. Without any extra help, registering the broken handler gives a short message:

error[E0277]: the trait bound `fn() -> impl Future<Output = String> {broken_handler}: Handler<_, _>` is not satisfied
   --> src/main.rs:14:42
    |
 14 |         .route("/", get(broken_handler))
    |                         ^^^^^^^^^^^^^^ the trait `Handler<_, _>` is not implemented for fn item `fn() -> impl Future<Output = String> {broken_handler}`
    |
    = note: Consider using `#[axum::debug_handler]` to improve the error message
note: required by a bound in `axum::routing::get`

That short message only tells you the handler does not satisfy the Handler trait. It does not say which bound failed. Adding #[axum::debug_handler] above the handler function gives the detailed version, which names the exact type and the exact reason:

error: future cannot be sent between threads safely
 --> src/main.rs:6:1
  |
6 | #[axum::debug_handler]
  | ^^^^^^^^^^^^^^^^^^^^^^ future returned by `broken_handler` is not `Send`
  |
  = help: within `impl Future<Output = String>`, the trait `Send` is not implemented for `Rc<String>`
note: future is not `Send` as this value is used across an await
 --> src/main.rs:9:39
  |
8 |     let data = Rc::new("hello".to_string());
  |         ---- has type `Rc<String>` which is not `Send`
9 |     sleep(Duration::from_millis(100)).await;
  |                                       ^^^^^ await occurs here, with `data` maybe used later

debug_handler is a macro from Axum, so it needs the macros feature enabled in your Cargo.toml:

[dependencies]
axum = { version = "0.8", features = ["macros"] }

The key parts of the detailed error:

  • The type in question: Rc<String>
  • The requirement: Send is not implemented
  • Where it's used: inside impl Future<Output = String> (the future returned by the handler)
  • The exact spot: the value is used across an await, at the sleep line

Armed with this understanding, you know to look for the Rc in your handler and replace it with Arc or restructure your code. When you hit a Handler is not implemented error that does not name a type, reach for debug_handler first - it turns a one-line complaint into a pointer at the exact value that breaks the bound.

A Note on MutexGuard and .await

One subtle mistake that trips up even intermediate Rust developers: holding a MutexGuard (the guard returned by .lock()) across an .await point.

use axum::{routing::get, Router};
use std::sync::{Arc, Mutex};
use tokio::time::{sleep, Duration};
async fn bad_guard_handler(counter: Arc<Mutex<u64>>) -> String {
    let mut guard = counter.lock().expect("poisoned");
    *guard += 1;
    // BAD: guard is still alive across this await
    sleep(Duration::from_millis(100)).await;
    format!("Count: {}", *guard)
}

This does not compile. A std::sync::MutexGuard is not Send, so a future that holds one across an .await point cannot be moved to another thread, and the handler's future must be Send. The compiler reports that the future cannot be sent between threads safely and names MutexGuard as the type that is not Send. That is the compiler protecting you, not a false alarm.

The fix is to drop the guard before the .await:

use axum::{routing::get, Router};
use std::sync::{Arc, Mutex};
use tokio::time::{sleep, Duration};
async fn good_guard_handler(counter: Arc<Mutex<u64>>) -> String {
    let current_count = {
        let mut guard = counter.lock().expect("poisoned");
        *guard += 1;
        *guard // guard dropped here at end of block
    };
    sleep(Duration::from_millis(100)).await;
    format!("Count: {}", current_count)
}

The inner block ends before the sleep, so the guard is dropped and the lock is released while the handler waits. The future no longer holds anything that is not Send across the .await, and the code compiles.

The second fix is to use tokio::sync::Mutex instead. Its guard type is Send, because Tokio's mutex is built for async code and its guard is allowed to travel with the future between threads:

use axum::{routing::get, Router};
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::time::{sleep, Duration};
async fn tokio_guard_handler(counter: Arc<Mutex<u64>>) -> String {
    let mut guard = counter.lock().await;
    *guard += 1;
    // This compiles: tokio's MutexGuard is Send.
    sleep(Duration::from_millis(100)).await;
    format!("Count: {}", *guard)
}

This compiles, but it still holds the lock for the whole sleep. Other tasks waiting on the same mutex have to wait until this handler finishes, even though no thread is blocked. Prefer the first fix - release the lock before the .await - and reach for tokio::sync::Mutex only when the lock genuinely has to span an .await point.

std MutexGuard across await is a compile error, not a warning:

If you hold a std::sync::MutexGuard across an .await, the handler's future is not Send and the program does not compile. Do not try to work around it. Drop the guard before the .await, or switch to tokio::sync::Mutex, whose guard is Send and is designed for this exact situation.

Working with Third-Party Non-Send Types

Sometimes you'll use a library that returns or requires non-Send types. For example, some database drivers or GUI frameworks might provide types that are !Send (not Send). In those cases, you have a few options:

  1. Wrap the non-Send type inside something that is Send. This only works if the non-Send type is actually safe to use across threads, which is usually not the case (that's why it's non-Send).
  2. Do not expect a Mutex to make a non-Send type Send. Mutex<T> is Send only when T itself is Send, so wrapping a non-Send type in a Mutex still does not compile. A Mutex helps when the inner type is already Send but needs shared mutable access, not when the type itself cannot move between threads.
  3. Use tokio::task::spawn_blocking to run the work on a dedicated thread. This is useful when you need to use a non-Send type but can run it in a blocking context.
  4. Refactor to avoid holding the non-Send type in the handler at all. Often the best approach is to restructure your code so that non-Send types are created and destroyed within a synchronous block, and only thread-safe data is passed around.

Summary

The Sync requirement on handlers is fundamentally about thread safety in Rust's type system. Axum handlers run on Tokio's multi-threaded runtime, which means they must be safe to move between threads and, historically, safe to share across threads.

In Axum 0.8, the Sync bound became an explicit requirement for handlers and services added to a Router or MethodRouter (axum 0.8.0 changelog, #2473). Handlers must be Clone + Send + Sync + 'static, and the futures they return must be Send. Closures that capture non-Sync types (like std::cell::Cell) or non-Clone types (like a oneshot::Sender) cannot be used directly as handlers.

The most important practical takeaway is: any data that lives across an .await point in your handler must be Send. If you get a "future cannot be sent between threads safely" error, look for the non-Send type in the error message, replace it with a thread-safe alternative (Arc for Rc, Mutex for RefCell, AtomicU64 for Cell<u64>), or restructure your code so the non-Send type doesn't live across the .await.

Once you understand Send and Sync in the context of async Rust, the rest of Axum's handler requirements fall into place naturally.