Send Sync static bounds for Axum state
Understand why Axum state types must implement Send, Sync, and a static lifetime, what each bound means, and how to fix common errors when your state does not satisfy them.
When you attach state to an Axum router using with_state, you are handing that value to a system that will share it across many concurrent requests. Axum is built on top of the Tokio async runtime, which runs tasks on a pool of worker threads. That means your state can be accessed from multiple threads at the same time. To make this safe, Rust requires the state type to have three specific capabilities. These are called trait bounds:
Send- the value can be moved from one thread to another safely.Sync- the value can be referenced from multiple threads at the same time safely.'static- the value does not contain any references that might become invalid while the server is running.
These bounds are not Axum being picky. They are Rust's way of guaranteeing that your program will not have data races or dangling references when it runs across multiple threads. On this page we will explain each bound in plain language, show what happens when your state does not satisfy them, and give you several realistic examples of fixing those situations.
Why shared state needs Send and Sync
Think of an Axum server as a restaurant with several waiters. The kitchen has a shared whiteboard where waiters write down orders. The whiteboard is like your application state: every waiter (thread) can look at it and sometimes write on it. For that to work without chaos, the whiteboard must be safe to carry around the restaurant (Send) and safe for multiple people to read and write on at the same time (Sync). If the whiteboard were something that could only be used by one person at a time, the restaurant would break.
Rust does not allow you to accidentally create a dangerous shared whiteboard. The compiler checks whether your state type is Send and Sync. If it is not, and you try to put it into with_state, the compiler stops you with an error. That error is your friend: it prevents a whole class of bugs that would otherwise appear only under heavy traffic.
The 'static bound is about time, not about threads. It says: your state must own all of its data. It cannot borrow a string or a number from outside and expect that outside value to still exist when a request arrives five minutes later.
Understanding each bound one by one
Let us look at the three bounds separately, because they each solve a different problem.
Send - moving between threads
A type is Send if it is safe to transfer ownership of a value of that type to another thread. Most ordinary Rust types are Send: numbers, strings, Vec, HashMap, Option, Result, structs made of Send fields, and so on. A type is not Send if it carries something that is tied to the thread where it was created.
A common non-Send type in single-threaded Rust programs is Rc<T>, the reference-counted pointer. Rc is fast because it does not use atomic operations, but that speed comes from the fact that it assumes it will only ever be used on one thread. If you moved an Rc to another thread and two threads tried to clone or drop it at the same time, the reference count would become corrupted.
The same goes for RefCell<T> in one respect: it enforces borrowing rules at runtime with a counter, but that counter is not thread-safe, so RefCell is never Sync. A bare RefCell<u32> is still Send, because moving it to another thread does not touch the counter from two threads at once. But Axum state must be both Send and Sync, so a state containing RefCell still fails, on the Sync bound. Rc fails the Send bound outright, so if your state contains Rc, the whole state type is not Send.
Sync - shared references across threads
A type is Sync if it is safe to share a reference to it across multiple threads. In Rust, sharing a reference means multiple threads can read the value at the same time, or some threads can read while one writes under certain conditions. The type itself must guarantee that its internal data will not be corrupted by concurrent access.
u32 is Sync. String is Sync. Vec<u32> is Sync. But RefCell<u32> is not Sync, because RefCell's borrow counter is not thread-safe. Even if you wrapped RefCell in an Arc, the Arc is Send and Sync only if its inner value is both Send and Sync. RefCell fails Sync, so Arc<RefCell<T>> is neither Send nor Sync, even though a bare RefCell<u32> is Send.
For a type to be usable as Axum state, it must be both Send and Sync. The compiler checks this automatically when you call with_state.
'static - owning your data
The 'static lifetime does not mean the value lives forever. It means the type does not contain any non-'static references. In other words, it owns all its data.
If you write:
let name = String::from("Alice");
let state = AppState { user_name: &name };
The state borrows name. If name goes out of scope before the server finishes running, the reference becomes dangling. Rust prevents that by requiring 'static. An owned String is 'static because it contains no references. A &str that points to a string literal is also 'static because string literals live for the entire program.
So when you define your state struct, avoid fields that are references. Use owned types like String, Vec, HashMap, or Arc. If you need to share a large piece of data, put it inside an Arc and clone the Arc; the Arc owns the data.
A basic example that satisfies all bounds
Create a project with Axum and Tokio, and add serde now as well, because the last example on this page reads JSON bodies:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
Let's start with a simple state that works out of the box. We will create a small Axum server with a counter stored in an AtomicU32. AtomicU32 is a type from the standard library that can be safely modified from multiple threads. It is Send and Sync.
// main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
counter: Arc<AtomicU32>,
}
async fn index(State(state): State<AppState>) -> String {
let current = state.counter.fetch_add(1, Ordering::Relaxed);
format!("Current count: {}", current)
}
#[tokio::main]
async fn main() {
let state = AppState {
counter: Arc::new(AtomicU32::new(0)),
};
let app = Router::new()
.route("/", get(index))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here AppState contains an Arc<AtomicU32>. AtomicU32 is Send and Sync, and Arc<T> is Send and Sync when T is Send and Sync. The AppState struct itself derives Clone because Axum requires state to be Clone. The compiler is happy.
When you run this server and visit http://127.0.0.1:3000 in a browser, every request increments the counter. Because AtomicU32 is lock-free and thread-safe, you can handle many requests at once without data races.
If your state compiles and runs:
If you see the counter increment correctly even when you open multiple tabs and refresh quickly, your state has correctly satisfied Send, Sync, and 'static. That is the sign you have designed shared state in a Rust-friendly way.
What happens when a bound is missing
To understand the bounds, it helps to see the compiler error when they are not met. Let's change our state to use Rc<RefCell<u32>> instead of Arc<AtomicU32>. Rc is not Send, and RefCell is not Sync, so this state will fail.
// broken_state.rs
use axum::{extract::State, routing::get, Router};
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone)]
struct AppState {
counter: Rc<RefCell<u32>>,
}
async fn index(State(state): State<AppState>) -> String {
let mut count = state.counter.borrow_mut();
*count += 1;
format!("Current count: {}", count)
}
#[tokio::main]
async fn main() {
let state = AppState {
counter: Rc::new(RefCell::new(0)),
};
let app = Router::new()
.route("/", get(index))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
When you try to compile this, you will see an error message that includes something like:
error[E0277]: `Rc<RefCell<u32>>` cannot be sent between threads safely
--> src/main.rs:...
|
| let app = Router::new().route("/", get(index)).with_state(state);
| ^^^^^^^^^^^^^ `Rc<RefCell<u32>>` cannot be sent between threads safely
|
= help: the trait `Send` is not implemented for `Rc<RefCell<u32>>`
And a similar one for Sync. This is the compiler telling you exactly which bound is broken and why. Rc is not Send, and RefCell is not Sync. To fix it, replace them with thread-safe alternatives: Arc and Mutex or RwLock.
Do not ignore these errors by using unsafe code:
Some beginners are tempted to write unsafe impl Send for MyState to silence the compiler. That is almost always wrong. The trait bounds exist because the type genuinely cannot be safely shared across threads. Writing an unsafe impl without understanding the type's internals can cause data corruption that is extremely hard to debug.
Fixing non-Send and non-Sync state with Arc and Mutex
The standard fix is to wrap the state in an Arc combined with a lock. The Arc provides thread-safe reference counting and allows the inner value to be shared. The lock (Mutex or RwLock) provides interior mutability with synchronization. Let's rewrite the broken example correctly.
// fixed_state.rs
use axum::{extract::State, routing::get, Router};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
counter: Arc<Mutex<u32>>,
}
async fn index(State(state): State<AppState>) -> String {
let mut count = state.counter.lock().unwrap();
*count += 1;
format!("Current count: {}", count)
}
#[tokio::main]
async fn main() {
let state = AppState {
counter: Arc::new(Mutex::new(0)),
};
let app = Router::new()
.route("/", get(index))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now Mutex<u32> is Sync (and Send if the inner u32 is Send, which it is). Arc<Mutex<u32>> is therefore Send and Sync. The lock().unwrap() call blocks the current thread until it gets exclusive access, then we can mutate the counter safely.
In an async handler, blocking on a std::sync::Mutex is usually fine for very short critical sections, but you cannot hold the lock across an .await point in an Axum handler: the guard is not Send, so the compiler rejects the handler. For handlers that need to await while holding state, use tokio::sync::Mutex instead. It is worth remembering that the choice of lock also affects what the compiler allows.
Do not hold a std::sync::Mutex across an await:
If your handler does something like let guard = state.lock().unwrap(); and then calls .await while still holding the guard, the code will not compile in Axum: std::sync::MutexGuard is not Send, so the handler future is not Send and does not implement Handler. The compiler stops you before any runtime blocking can happen. Keep the critical section as short as possible, or use an async-aware lock.
The 'static bound and how to satisfy it
The 'static bound often confuses beginners because they think it means the value must live forever. It actually means the type cannot contain any references with a shorter lifetime. For example, this state struct will fail:
struct AppState<'a> {
greeting: &'a str,
}
If you try to use AppState<'_> as state, the compiler will complain that the state must be 'static. The fix is to own the data:
struct AppState {
greeting: String,
}
Now AppState owns its String, and the compiler sees that String is 'static (it contains no references) even though the String itself may be dropped at some point. The 'static bound is about the type, not a specific value's lifetime.
Here is a complete example that shows the error and the fix. First, the broken version:
// non_static_state.rs
use axum::{extract::State, routing::get, Router};
struct AppState<'a> {
greeting: &'a str,
}
async fn index(State(state): State<AppState<'_>>) -> String {
state.greeting.to_string()
}
#[tokio::main]
async fn main() {
let greeting = String::from("Hello");
let state = AppState { greeting: &greeting };
let app = Router::new()
.route("/", get(index))
.with_state(state);
// ... serve
}
The error will be something like:
error[E0277]: the trait bound `for<'a> fn(State<AppState<'a>>) -> impl Future<Output = String> {index}: Handler<_, _>` is not satisfied
--> src/main.rs:...
|
| let app = Router::new().route("/", get(index)).with_state(state);
| --- ^^^^^ the trait `Handler<_, _>` is not implemented for fn item `for<'a> fn(State<AppState<'a>>) -> impl Future<Output = String> {index}`
|
= note: the trait `Handler<_, _>` is not implemented for fn item `for<'a> fn(State<AppState<'a>>) -> impl Future<Output = String> {index}`
error[E0277]: the trait bound `AppState<'_>: Clone` is not satisfied
--> src/main.rs:...
|
| let app = Router::new().route("/", get(index)).with_state(state);
| ^^^^^^^^^^^^^ the trait `Clone` is not implemented for `AppState<'_>`
The compiler tells you the state must be 'static and Clone: the handler cannot be a Handler because its state type carries a borrowed lifetime, and the struct as written does not even implement Clone. The fix is to own the string (and derive Clone):
// static_state_fixed.rs
use axum::{extract::State, routing::get, Router};
#[derive(Clone)]
struct AppState {
greeting: String,
}
async fn index(State(state): State<AppState>) -> String {
state.greeting.clone()
}
#[tokio::main]
async fn main() {
let state = AppState {
greeting: String::from("Hello"),
};
let app = Router::new()
.route("/", get(index))
.with_state(state);
// ... serve
}
Now AppState is 'static because String is 'static. In real applications, state almost always owns its data, possibly behind an Arc or a database connection pool.
Common state types and their bounds
Let's review some types you are likely to use in Axum state and whether they satisfy Send + Sync + 'static.
| Type | Send | Sync | 'static | Notes |
|---|---|---|---|---|
u32, String, Vec<T>, HashMap<K,V> | Yes if T, K, V are Send | Yes if T, K, V are Sync | Yes if no references | Most standard owned types work. |
Rc<T> | No | No | Yes if T: 'static | Single-threaded reference counting. |
RefCell<T> | Yes if T: Send | No | Yes if T: 'static | Runtime borrow checking, not thread-safe. |
Arc<T> | Yes if T: Send + Sync | Yes if T: Send + Sync | Yes if T: 'static | Thread-safe reference counting. |
Mutex<T> | Yes if T: Send | Yes if T: Send | Yes if T: 'static | Blocks on lock; short critical sections okay. |
RwLock<T> | Yes if T: Send | Yes if T: Send + Sync | Yes if T: 'static | Multiple readers, one writer. |
AtomicU32, AtomicBool, etc. | Yes | Yes | Yes | Lock-free primitive types. |
Database connection pools (e.g., sqlx::PgPool) | Yes | Yes | Yes | Designed for sharing across threads. |
&str referencing a local | Yes | Yes | No | Borrows data; cannot be state because it is not 'static. |
&'static str | Yes | Yes | Yes | String literal lives forever, so it's okay. |
This table gives you a quick reference. If your state contains any of the "No" entries, you must change the design.
A more realistic example: sharing a configuration struct
Imagine you want to store application configuration loaded from a file. The configuration contains an owner name, a port, and a list of allowed origins. A naive struct might contain borrowed string slices, but we know better: we own everything.
// config_state.rs
use axum::{extract::State, routing::get, Router};
use std::collections::HashSet;
#[derive(Clone)]
struct AppConfig {
owner: String,
port: u16,
allowed_origins: HashSet<String>,
}
async fn config_info(State(config): State<AppConfig>) -> String {
format!(
"Owner: {}, Port: {}, Allowed origins: {:?}",
config.owner, config.port, config.allowed_origins
)
}
#[tokio::main]
async fn main() {
let config = AppConfig {
owner: "Alice".to_string(),
port: 8080,
allowed_origins: HashSet::from([
"https://example.com".to_string(),
"http://localhost:3000".to_string(),
]),
};
let app = Router::new()
.route("/info", get(config_info))
.with_state(config);
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
AppConfig is Send and Sync because all its fields are. It is 'static because it owns all its data. No locks are needed because the configuration never changes after startup. This is a common pattern: immutable state shared read-only across all requests.
What about types from external crates?
Many crates you use for database connections, HTTP clients, or caches provide types that are already Send + Sync + 'static. For example, sqlx::PgPool, redis::Client, or reqwest::Client are all designed for use in async multi-threaded environments. When you wrap them in your state struct, the struct will automatically satisfy the bounds, assuming your own fields do.
However, some older libraries might provide types that are not thread-safe. Always check the crate's documentation. If a type is not Send or Sync, look for an alternative that is, or wrap it appropriately with synchronization primitives, but only if that makes sense for the type's internal design.
Debugging trait bound errors step by step
When the compiler tells you a bound is not satisfied, the error may point to a large type, especially if your state contains nested generics. Here is a structured approach to fix it:
- Read the error message carefully. It will tell you whether
Send,Sync, or'staticis missing. - Identify which field causes the problem. The error will often name the specific type that fails, such as
Rc<RefCell<u32>>. - Determine why that type is not
SendorSync. If it isRcorRefCell, replace withArcand a lock. If it is a borrowed reference, change to an owned type. - Modify your state struct accordingly. Often adding
Arc<...>around the offending field is enough. - If the offending type is from a third-party crate, search for a thread-safe alternative or consider wrapping it in a
Mutexonly if the type itself isSendbut notSync. For example, a type that isSendbut notSynccan be shared withArc<Mutex<T>>because theMutexprovidesSyncifT: Send. - Recompile and repeat until clean.
Let's see an example where a type is Send but not Sync. Suppose you have a Cell<u32> (from std::cell). Cell is Send if the inner u32 is Send (it is), but Cell is not Sync because it allows mutation through shared references without synchronization. If you put Cell<u32> in state, the Sync bound fails. You can fix it by wrapping it in a Mutex:
// cell_state_fixed.rs
use axum::{extract::State, routing::get, Router};
use std::cell::Cell;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
counter: Arc<Mutex<Cell<u32>>>,
}
async fn index(State(state): State<AppState>) -> String {
let counter_cell = state.counter.lock().unwrap();
let current = counter_cell.get();
counter_cell.set(current + 1);
format!("Current count: {}", current)
}
#[tokio::main]
async fn main() {
let state = AppState {
counter: Arc::new(Mutex::new(Cell::new(0))),
};
let app = Router::new()
.route("/", get(index))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now Mutex<Cell<u32>> is Sync because Mutex<T> is Sync when T: Send, and Cell<u32> is Send. The lock ensures that only one thread can access the Cell at a time.
Why does wrapping in Mutex make it Sync?:
Mutex<T> provides thread-safe interior mutability. Internally, it uses atomic operations and OS-level locks to guarantee exclusive access. The compiler trusts that Mutex properly synchronizes access, so it marks Mutex<T> as Sync even if T itself is not Sync. This is exactly how we make thread-unsafe types usable in a multi-threaded context.
Understanding Send vs Sync with a simple mental model
It is common to mix up Send and Sync. Here is a mental model that helps:
Sendasks: "Can I give this value to someone else and never see it again?" If yes, it isSend. Think of owning a book: you can hand it to a friend, and now they own it. That transfer is safe if the book has no secret thread-specific bookmarks.Syncasks: "Can many people read this value at the same time through a shared reference?" If yes, it isSync. Think of a public notice board: many people can look at it simultaneously without causing problems.
A type can be Send but not Sync. A good example is Cell<T>: you can move it to another thread (Send), but you cannot share a reference to it across threads because then two threads could call set at the same time, which is unsafe.
A type can also be Sync but not Send, though that combination is rare in practice and you will not meet it in ordinary state types. The case that matters for Axum is the first one: a type can be Send but not Sync, like Cell, and the fix is to add synchronization around it. In practice, most non-Send types are also non-Sync.
For Axum state, the type must be both. Usually, using Arc plus appropriate interior mutability covers both requirements.
What about 'static with Arc and references to static data?
If your state contains a reference to data that lives forever (like a &'static str), that is allowed. For example:
// static_str_state.rs
use axum::{extract::State, routing::get, Router};
#[derive(Clone)]
struct AppState {
app_name: &'static str,
}
async fn index(State(state): State<AppState>) -> String {
format!("Welcome to {}", state.app_name)
}
#[tokio::main]
async fn main() {
let state = AppState { app_name: "My App" };
let app = Router::new()
.route("/", get(index))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here &'static str is 'static by definition, and it is also Send and Sync because it is just a pointer and length with no interior mutability. So this works.
But what if you want to store a reference to something that is shared via Arc but not 'static? For example, you have an Arc<str> that you obtained at runtime. The Arc<str> itself is 'static because it owns the string data (even though the original String may be dropped). You can store Arc<str> in state without problems.
Common pitfalls and how to avoid them
Pitfall 1: Using Rc and RefCell out of habit
If you are coming from single-threaded Rust, you might reach for Rc and RefCell automatically. In Axum, they will not work. Always use Arc and a lock (Mutex, RwLock, or atomic types). This is the most common beginner mistake.
Pitfall 2: Holding locks across .await
We already mentioned this, but it bears repeating. In an Axum handler, holding a std::sync::MutexGuard across an .await does not compile at all, because the guard is not Send. The compiler stops you before any blocking can happen, so there is no runtime slowdown to worry about in that case, only a compile error to fix. If you must hold a lock across an await, use tokio::sync::Mutex, whose guard is Send and can be held across suspension points. Even then, keep the locked section short, because every other task that needs the same lock still has to wait.
Pitfall 3: Thinking 'static means the value never gets dropped
'static is a lifetime, not a storage duration. A String is 'static even though it will be freed when the state is dropped. The bound ensures that no references inside the state can become dangling, not that the value itself lives forever.
Pitfall 4: Ignoring Send/Sync errors by wrapping everything in Mutex
Sometimes wrapping a non-Send type in Mutex does not fix Send. Mutex<T> is only Send if T: Send. So if your inner type is not Send (like Rc), Mutex<Rc<T>> is still not Send. You need to replace Rc with Arc first. Remember: Arc fixes Send, Mutex fixes Sync (when T: Send).
Pitfall 5: Using raw pointers without unsafe
Raw pointers (*const T, *mut T) are not Send or Sync by default because the compiler cannot guarantee safety. If you need to store a raw pointer in state, you must wrap it in a type that manually implements Send and Sync and ensure the pointee is valid for the lifetime of the server. This is advanced and rarely needed. Avoid raw pointers in Axum state.
Avoid raw pointers unless you fully understand memory ordering and lifetimes:
Using raw pointers in shared state is a common source of undefined behavior. Even if you wrap them in unsafe impl Send and unsafe impl Sync, you are responsible for ensuring the pointed-to data remains valid and that access is properly synchronized. For beginners, prefer safe types like Arc, Mutex, and atomics.
A complete working example with multiple state fields
Let's put everything together. We will build a small API that stores a counter and a list of names. The counter uses AtomicU32 for lock-free increments. The names are stored in a Mutex<Vec<String>>. The state is cloneable and satisfies all bounds.
// complete_state.rs
use axum::{extract::State, routing::{get, post}, Json, Router};
use serde::Deserialize;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
counter: Arc<AtomicU32>,
names: Arc<Mutex<Vec<String>>>,
}
#[derive(Deserialize)]
struct AddName {
name: String,
}
async fn get_count(State(state): State<AppState>) -> String {
let count = state.counter.load(Ordering::Relaxed);
format!("Current count: {}", count)
}
async fn increment(State(state): State<AppState>) -> String {
let old = state.counter.fetch_add(1, Ordering::Relaxed);
format!("Old count was {}, new count is {}", old, old + 1)
}
async fn list_names(State(state): State<AppState>) -> Json<Vec<String>> {
let names = state.names.lock().unwrap();
Json(names.clone())
}
async fn add_name(State(state): State<AppState>, Json(input): Json<AddName>) -> String {
let mut names = state.names.lock().unwrap();
names.push(input.name);
format!("Name added, total names: {}", names.len())
}
#[tokio::main]
async fn main() {
let state = AppState {
counter: Arc::new(AtomicU32::new(0)),
names: Arc::new(Mutex::new(Vec::new())),
};
let app = Router::new()
.route("/count", get(get_count))
.route("/increment", post(increment))
.route("/names", get(list_names).post(add_name))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
This example demonstrates:
- Immutable counter using an atomic for high-concurrency increments.
- Mutable list protected by a
Mutexfor safe push and read. Arcused for both fields so the state can be cheaply cloned.- The entire
AppStateautomatically implementsSend + Sync + 'static.
You can test it with curl:
curl http://127.0.0.1:3000/count
# Output: Current count: 0
curl -X POST http://127.0.0.1:3000/increment
# Output: Old count was 0, new count is 1
curl -X POST http://127.0.0.1:3000/names -H "Content-Type: application/json" -d '{"name":"Alice"}'
# Output: Name added, total names: 1
curl http://127.0.0.1:3000/names
# Output: ["Alice"]
This is a solid foundation for many Axum applications. The state is safe, fast enough for many use cases, and easy to understand.
When you need Arc<Mutex<...>> vs Arc<Atomic...>
Choosing between a lock and an atomic depends on what you are doing:
- Atomic types (e.g.,
AtomicU32,AtomicBool,AtomicUsize) are lock-free and ideal for simple counters, flags, or small values that can be updated with a single instruction. They are faster than locks and do not require holding a guard. - Mutex or RwLock are needed when the data is more complex (like a
VecorHashMap) and updates require multiple steps or read-modify-write sequences.RwLockallows many readers concurrently, which is good if reads are much more frequent than writes.
For a beginner, start with Mutex for anything that is not a simple number. It is straightforward and correct. Optimize later with atomics or RwLock only after profiling.
How the Clone requirement interacts with these bounds
Axum also requires your state type to implement Clone. That is because the state is stored inside the router and cloned for each request or when the router is cloned. If your state contains Arc, Clone is cheap because it only increments the reference count. If your state contains large owned data like String, cloning can be expensive. Therefore, wrap large data in Arc to make cloning cheap.
The Clone bound is separate from Send, Sync, and 'static, but it is also required. Your state must satisfy all four bounds: Clone + Send + Sync + 'static.
Testing your state for trait bounds
Sometimes you want to check that your state type satisfies the bounds without running the server. You can write a small test function that uses compile-time assertions. Rust does not have a built-in static_assert for traits, but you can use a generic function that requires the trait. This check does not need Axum at all; it only asks the compiler about the type:
fn assert_send_sync_static<T: Send + Sync + 'static>() {}
#[derive(Clone)]
struct AppState {
counter: std::sync::Arc<std::sync::atomic::AtomicU32>,
}
fn main() {
assert_send_sync_static::<AppState>();
}
If AppState does not satisfy the bounds, the compiler will fail at the call site with a clear error. This can be useful during development to isolate the problem before integrating with Axum.
Summary and next steps
The Send, Sync, and 'static bounds on Axum state are not arbitrary restrictions. They are the compiler's way of ensuring that your shared data can be safely used across the many threads of the Tokio runtime. Understanding these bounds helps you design state that is both correct and performant.
The single most important takeaway is: avoid Rc, RefCell, and borrowed references in state. Use Arc for shared ownership, Mutex/RwLock/atomics for interior mutability, and own all your data. If you follow that rule, you will rarely encounter trait bound errors.
This page focused on the why and how of these bounds. With this foundation, you can now confidently design application state that scales across concurrent requests. From here, you might explore lock-free counters in more detail (AtomicUsize patterns) or move on to how to safely mutate complex state in handlers without blocking the async runtime.