Sharing Application State with Arc
Learn how to use std::sync::Arc to share immutable data across Axum handlers and spawned tasks, with complete examples and plain-language explanations.
When a web server handles many requests at once, those requests often need to use the same piece of data. Maybe it's a configuration object, a read-only lookup table, or a pool of reusable connections. This page teaches you the most common way to share that data safely in Axum: wrapping it in Arc from the Rust standard library.
Arc stands for "Atomically Reference Counted." It gives you shared ownership of a value, which means multiple parts of your program can hold a pointer to the same value without needing to copy the value itself. Axum serves each connection from a Tokio task, and different connections may run on different operating system threads. Arc is designed exactly for this situation: safe, cheap, thread-safe sharing of data that doesn't need to change while the server runs.
Why Sharing State Needs Arc
Imagine you have a Config struct that holds your application's port number, database URL, and a list of feature flags. You create this struct once when the server starts. Then you have many handler functions - maybe a dozen - that all need to read those values to do their jobs.
Without any sharing mechanism, each handler would need its own copy of the Config. If the struct is small, that's not terrible, but if it contains large data like a HashMap with thousands of entries, copying it for every request would waste memory and CPU time. Even worse, if you need to share the same piece of data across multiple threads simultaneously, you can't just pass around raw references because the Rust compiler can't guarantee the data will outlive every thread that uses it.
Arc solves both problems. It stores the data on the heap and keeps a counter of how many owners exist. When you clone an Arc, you're not copying the underlying data; you're just creating a new pointer to the same heap allocation and incrementing the counter. The data is dropped only when the last Arc pointing to it is dropped. This means every handler can get its own cheap clone of the Arc, all pointing to the same Config value.
What Exactly Is an Arc?
Arc<T> is a smart pointer that owns a T placed on the heap. When you call Arc::new(value), the value is moved onto the heap, and Arc keeps a pointer to it plus a reference count. Calling clone() on an Arc creates a new smart pointer that points to the same heap data and increments the reference count. When any Arc clone is dropped, the count goes down. When the count reaches zero, the heap data is deallocated.
The "atomic" part means that the reference count is updated using atomic operations. These are special CPU instructions that can be performed safely from multiple threads at the same time without data races. That's why Arc<T> is safe to share across threads: many threads can clone and drop their own Arc copies concurrently, and the reference count remains correct.
For Arc<T> to be used across threads, T must be Send and Sync. Send means the type can be moved to another thread. Sync means the type can be referenced from multiple threads at the same time. Most plain data types like numbers, strings, structs made of those, and read-only collections are Send and Sync, so they work fine inside an Arc.
Reference Counting in One Sentence:
Think of Arc as a library book that many people can borrow at the same time. The library keeps a count of how many people currently have the book. When someone returns it, the count goes down. When the count hits zero, the book is removed from the shelf.
Your First Shared State with Arc
Let's build a minimal Axum application that shares a read-only configuration object across two handlers. We'll start by defining the data we want to share, wrap it in an Arc, register it with the router using with_state, and then extract it inside handlers using Axum's State extractor.
Here is the complete code. We'll go through it piece by piece afterward.
# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
// src/main.rs
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::Arc;
// The configuration we want to share.
#[derive(Debug)]
struct AppConfig {
app_name: String,
max_connections: u32,
}
async fn show_config(
State(config): State<Arc<AppConfig>>,
) -> String {
format!(
"App: {}, max connections: {}",
config.app_name, config.max_connections
)
}
async fn show_name(
State(config): State<Arc<AppConfig>>,
) -> String {
format!("This server runs {}", config.app_name)
}
#[tokio::main]
async fn main() {
// Create the shared configuration once.
let config = AppConfig {
app_name: "My Axum Server".to_string(),
max_connections: 100,
};
// Wrap it in an Arc so it can be shared cheaply.
let shared_config = Arc::new(config);
// Build the router and attach the shared state.
let app = Router::new()
.route("/config", get(show_config))
.route("/name", get(show_name))
.with_state(shared_config);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
Let's examine what's happening.
First, we define AppConfig with two fields. Because it's just two simple types (String and u32), it automatically implements Send and Sync, so we can put it inside an Arc and share it between threads.
In main, we create an AppConfig value. Then we call Arc::new(config) to move that value onto the heap and get an Arc<AppConfig>. The original config variable is no longer usable because its value was moved. If we needed to use config after wrapping it, we would have to clone it first (which would be a deep copy of the String and integer, not cheap, but fine for small structs). In this case, we don't need it after wrapping, so moving is fine.
The router is built with .route() calls, then .with_state(shared_config). This tells Axum to store the Arc<AppConfig> inside the router. The router now owns that Arc, but because Arc allows cloning, Axum can hand a cheap clone of the Arc to each handler that asks for it.
Our handler functions take a State<Arc<AppConfig>> parameter. The State extractor tells Axum: "Please give me access to the state stored in the router." The type inside State must match exactly what we passed to with_state - in this case, Arc<AppConfig>. Axum passes a clone of the Arc to the handler. That clone is extremely cheap: it just increments the reference count by one, no copying of the AppConfig data.
Inside the handler, we can access fields through the Arc using the dot operator, just like we would with a regular reference. config.app_name works because Arc implements Deref, which lets us treat the Arc<AppConfig> as if it were &AppConfig.
When the handler returns and its parameter config goes out of scope, the Arc clone is dropped, and the reference count goes down. The original Arc inside the router remains alive, so the data isn't freed.
You can test this by running the server and visiting http://localhost:3000/config and http://localhost:3000/name in your browser or with curl. Both endpoints will display the same shared values.
Everything Compiles and Runs:
If your code compiles and you see the expected output for both routes, you have successfully shared state using Arc. The key indicator is that both handlers see the same app_name without any cloning of the AppConfig struct itself.
Reading Shared Data from Multiple Handlers
In the previous example, we had two handlers that each extracted the state independently. That works because State<Arc<AppConfig>> gives each handler its own clone of the Arc, all pointing to the same AppConfig. You can have any number of handlers - ten, fifty, a hundred - and they will all share the same data without any duplication.
Let's expand the example to show a more realistic scenario: a shared read-only lookup table, like a list of valid user roles mapped to their permission levels. This data is created at startup and never changes. We will read the role from the query string, so the handler uses the Query extractor with a small struct.
This example needs serde for the query struct, so add it to the dependencies:
# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
// src/main.rs
use axum::{
extract::{Query, State},
routing::get,
Router,
};
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Arc;
type RolePermissions = HashMap<String, Vec<String>>;
#[derive(Deserialize)]
struct RoleQuery {
role: String,
}
fn load_roles() -> RolePermissions {
let mut map = HashMap::new();
map.insert(
"admin".to_string(),
vec!["read".to_string(), "write".to_string(), "delete".to_string()],
);
map.insert(
"user".to_string(),
vec!["read".to_string()],
);
map
}
async fn get_role_permissions(
State(roles): State<Arc<RolePermissions>>,
Query(query): Query<RoleQuery>,
) -> String {
match roles.get(&query.role) {
Some(perms) => format!("Permissions for {}: {:?}", query.role, perms),
None => format!("Role {} not found", query.role),
}
}
#[tokio::main]
async fn main() {
let roles = load_roles();
let shared_roles = Arc::new(roles);
let app = Router::new()
.route("/permissions", get(get_role_permissions))
.with_state(shared_roles);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
The handler takes both State<Arc<RolePermissions>> and Query<RoleQuery>. Axum runs the extractors in order; the State extractor gives us a clone of the Arc, and Query parses the query string into a RoleQuery struct. Inside the handler, we call roles.get(&query.role) to look up the role in the shared HashMap. Since the map is read-only and HashMap is Sync when its key and value types are Sync, this is safe.
A bare String reads the body, not the query:
A handler parameter of plain type String is a valid Axum extractor, but it reads the request body, not the query string. Writing role: String here would compile, yet the role from the URL would never reach the handler that way. Use Query with a struct whenever the value comes from the query string.
Notice that we didn't need to clone the HashMap or use any locks. The Arc<HashMap<String, Vec<String>>> can be read concurrently from many threads because HashMap allows multiple readers as long as nobody is writing. Since we never write to it after initialization, this is perfectly safe.
You can test this by running the server and sending requests like:
curl "http://localhost:3000/permissions?role=admin"
curl "http://localhost:3000/permissions?role=user"
curl "http://localhost:3000/permissions?role=guest"
The first two return the permission lists, and the third returns "Role guest not found". All requests read from the same shared map without any copying.
Cloning Arc to Move into Spawned Tasks
Sometimes a handler needs to do some work in the background after sending a response, or it needs to spawn a separate async task that also uses the shared state. Because the handler's state parameter goes out of scope when the handler returns, you can't simply move it into a spawned task unless you clone it first. Cloning an Arc is cheap, so this is the standard pattern.
Here's an example where a handler logs a request and then spawns a background task that updates a separate log file or database using the shared configuration. For simplicity, we'll just have the background task print something after a short delay.
// src/main.rs
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::Arc;
use std::time::Duration;
#[derive(Debug)]
struct AppConfig {
app_name: String,
log_level: String,
}
async fn handle_request(
State(config): State<Arc<AppConfig>>,
) -> String {
// Clone the Arc so we can move it into a spawned task.
let config_for_task = Arc::clone(&config);
// Spawn a background task that uses the shared config.
tokio::spawn(async move {
// Simulate some work.
tokio::time::sleep(Duration::from_millis(100)).await;
println!(
"Background task for {}: log level {}",
config_for_task.app_name, config_for_task.log_level
);
});
// Return an immediate response; the task continues in the background.
format!("Request handled by {}", config.app_name)
}
#[tokio::main]
async fn main() {
let config = AppConfig {
app_name: "Async Server".to_string(),
log_level: "debug".to_string(),
};
let shared_config = Arc::new(config);
let app = Router::new()
.route("/", get(handle_request))
.with_state(shared_config);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
Inside handle_request, we have State(config): State<Arc<AppConfig>>. This config is a local Arc clone that was created by Axum for this handler call. We then call Arc::clone(&config) to create a second clone. The first clone stays in the handler and is used to read config.app_name for the response. The second clone is moved into the async move block passed to tokio::spawn. Because we used move, the closure takes ownership of config_for_task, and since it's an Arc, that ownership is just a reference count increment - no deep copy of AppConfig.
The spawned task runs independently after the handler returns. It can safely read from the shared AppConfig even though the original handler's config clone has been dropped, because the Arc inside the router still keeps the data alive, and the background task has its own clone. When the background task finishes and its clone drops, the reference count goes down. If the router is eventually dropped and no other clones exist, the AppConfig is finally freed.
Clone Before You Move (Only When You Still Need It):
A common beginner mistake is to move the original State parameter directly into a spawned task and then try to use it again afterwards. For example, this will fail to compile:
async fn handler(State(config): State<Arc<AppConfig>>) -> String {
tokio::spawn(async move {
println!("{}", config.app_name);
});
// error: use of moved value: `config`
format!("Served by {}", config.app_name)
}
The error occurs because the config variable was moved into the spawned task, but the handler still needs it afterwards for the return value. Moving the State value into a spawned task is perfectly fine when the handler does not need it again afterwards. The fix, when you do need it in both places, is to explicitly clone it before moving. Remember: Arc clones are cheap, so always clone before moving into a separate task if the handler still needs its own copy.
Arc and Interior Mutability: A Preview
So far, we've shared data that never changes after startup. But what if you need to share a counter that increments, or a cache that gets updated? Arc<T> by itself does not allow mutation of T. If you try to write config.app_name = "New Name".to_string() through an Arc, the compiler will stop you because Arc only provides shared references, and shared references cannot be used to mutate data.
To share mutable data safely across threads, you need to combine Arc with a type that provides interior mutability, a way to mutate a value through a shared reference. Rust provides several such types: Mutex, RwLock, AtomicUsize, etc. For now, the key takeaway is that Arc itself is only for sharing ownership of a value; if that value must change, you need to wrap it in an interior mutability type before putting it inside the Arc.
A typical pattern is Arc<Mutex<MyState>>. The Arc lets you share the Mutex across threads cheaply, and the Mutex allows safe mutation by locking.
Common Mistakes and Misunderstandings
Let's address the most frequent errors beginners make when using Arc with Axum state.
1. Forgetting to wrap in Arc
If you pass a plain AppConfig to with_state, then your handlers must extract State<AppConfig>. That works, because Axum clones the AppConfig for each handler, but every clone deep-copies the whole struct, and you cannot cheaply move a handle to the same shared value into spawned tasks. Using Arc is the standard for shared state because it gives you cheap clones and clear ownership semantics.
2. Trying to mutate an Arc directly
As mentioned, Arc doesn't allow mutation through a shared reference. If you need to change the data, you must use Arc<Mutex<T>> or similar. Don't try to use unsafe or RefCell (which is not thread-safe) to hack around this; you'll introduce data races and undefined behavior.
3. Using Rc instead of Arc
Rc is the single-threaded reference-counted pointer. It's cheaper because it doesn't use atomic operations, but it cannot be shared across threads. Axum handlers run in an async runtime that may execute them on different threads, so Rc is not allowed inside the state you pass to with_state. The compiler will reject it because Rc is not Send or Sync. Always use Arc for shared state in Axum.
4. Cloning the inner data instead of the Arc
Sometimes beginners write something like Arc::new(config.clone()) in a handler, thinking they need a separate copy. That defeats the purpose of Arc. To get another handle to the same shared data, clone the Arc itself, not the inner value: Arc::clone(&shared_arc) or shared_arc.clone() (which does the same thing). This is cheap and shares the same heap allocation.
5. Forgetting to derive Send and Sync?
You don't need to derive them; most types automatically are Send and Sync if all their fields are. But if your state contains a type that is not Send or Sync (like Rc, raw pointers, or some non-thread-safe structures), then Arc<ThatType> will also not be Send or Sync, and Axum will reject it at compile time with a trait bound error. Read the error message carefully; it will point to the problematic type.
Compile Error: State Must Be Cloneable and Send + Sync:
If you see an error like:
the trait bound `AppConfig: Clone` is not satisfied
or
the trait bound `AppConfig: Send` is not satisfied
It usually means you forgot to wrap your state in Arc, or you're trying to use a non-thread-safe type. Arc<T> is always Clone and is Send/Sync when T is Send/Sync. So wrapping in Arc solves the Clone bound, but not the Send/Sync bound if T itself is not thread-safe.
Summary
Using Arc to share application state in Axum is a foundational pattern. It lets you create data once at startup, wrap it in an Arc, attach it to the router with with_state, and then cheaply share it across any number of handlers and spawned tasks. Because Arc provides atomic reference counting, multiple threads can clone and drop their copies concurrently without data races, and the underlying data is freed only when the last reference is gone.
The key insight is that Arc gives you shared ownership but not shared mutability. For read-only data, like configuration, lookup tables, or precomputed structures, Arc alone is perfect. When you need to modify shared data, you combine Arc with interior mutability primitives like Mutex or RwLock.
If you're writing a handler that needs to spawn a background task, always clone the Arc before moving it into the task. Cloning an Arc is extremely cheap, and it guarantees the data remains valid for as long as the task needs it.
As you continue learning Axum, remember: state that is only read should be shared with Arc. State that is read and written should be shared with Arc<Mutex<T>> or Arc<RwLock<T>>. That mental model will guide you whenever you choose a sharing pattern.