Axum AppState Struct - Grouping Shared Application Data
Learn how to define a custom AppState struct in Axum to organize and share application-level data across handlers, with simple examples and common mistakes.
When you build a web application, you often need to keep pieces of data that many different request handlers will use. Maybe a database connection pool, a configuration object, a counter, or a list of connected users. Instead of passing each piece around separately, Axum lets you bundle them together in one custom struct. That struct is usually called AppState, and it becomes the single container that holds everything your application needs to share.
This page focuses on that struct itself: what it is, why you create it, what kinds of fields you might put inside it, and how to define it correctly. You will see examples that start with the smallest possible version and then grow to include multiple types of data.
What Is Application State?
Before we talk about the struct, let's define what "state" means in this context. A web server receives many requests, and each request normally starts with a fresh set of local variables inside its handler function. But sometimes you need information that survives across requests and is visible to all handlers. That shared information is called application state.
For example:
- A pool of connections to a database, so you don't open a new connection for every request.
- A configuration object loaded from a file at startup.
- A counter that tracks how many total requests have been made.
- A cache of frequently used data.
Axum provides a mechanism to store this shared information and pass it to your handler functions automatically. The first step is to create a Rust struct that represents all of that shared information. That struct is your AppState.
What Is a Struct?:
In Rust, a struct is a custom data type that groups related values together. You give each value a name and a type. For example, a struct Person { name: String, age: u32 } defines a type where every Person has a name and an age. You create a value of that type by writing Person { name: "Alice".to_string(), age: 30 }.
Why Bundle State into a Single Struct?
You could imagine sharing state without a struct. For instance, if you only need one number, you could just wrap it in Arc<AtomicUsize> and pass that around. But real applications usually need many pieces of shared data. Without a struct, you would end up with several separate variables, and passing all of them to every handler becomes messy.
A struct gives you three main advantages:
- Organization - All the shared data lives in one place. When you want to know what the app can access, you look at one type definition.
- Type safety - Rust checks that you only access fields that actually exist. You won't accidentally try to extract the wrong type of state.
- Clarity - A handler that receives
State<AppState>is clear about what it can use. Compare that to a handler with five separate extractor arguments.
Think of the AppState struct as a backpack. Each field is a pocket. You put different tools in different pockets, but you carry the whole backpack as one object.
A First Minimal AppState Struct
Let's start with the simplest possible struct. Suppose you want to share a single string that contains the application's name. You can define:
struct AppState {
app_name: String,
}
That's it. A struct with one field. Now you need to create an instance of this struct and hand it to your Axum router. Axum clones the state for every request that extracts it, so the state type must implement Clone. Cloning a whole struct on every request can be expensive if the struct holds large data, and the usual way to make cloning cheap is to wrap the state in an Arc, which stands for "atomic reference count." Cloning an Arc only copies a pointer and bumps a reference count, so the data itself is never duplicated.
Here is a complete tiny example that uses this struct:
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
app_name: String,
}
#[tokio::main]
async fn main() {
let shared_state = Arc::new(AppState {
app_name: "My Axum App".to_string(),
});
let app = Router::new()
.route("/", get(show_app_name))
.with_state(shared_state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn show_app_name(State(state): State<Arc<AppState>>) -> String {
format!("Welcome to {}", state.app_name)
}
Let's walk through what's happening.
First, we define AppState with a single field app_name of type String. We add #[derive(Clone)] on the struct, which tells Rust to automatically generate a method that creates a copy of the whole struct. Strictly speaking, that derive is not needed in this example: the state type passed to the router is Arc<AppState>, and Arc is Clone on its own, so Axum clones the Arc, never the struct. The derive is kept here because it is harmless and because the same struct then also works if you later pass it directly without the Arc wrapper.
In main, we create shared_state by putting our AppState inside an Arc. Then we build a router with one route and attach the state using .with_state(shared_state). Finally, we start the server.
The handler show_app_name takes an argument State(state): State<Arc<AppState>>. The State part tells Axum, "please give me the shared state." Inside the parentheses, we name the variable state, and its type is Arc<AppState>. Because Arc dereferences to the inner struct, we can write state.app_name directly.
If you see this output, it works:
Run the program, then open http://localhost:3000/ in a browser. You should see the text Welcome to My Axum App. That confirms your state is being shared correctly.
Adding More Fields to AppState
In practice, you will rarely have just one string. A typical AppState contains several pieces of data, each with a different type and purpose. Let's expand the struct to include:
- A configuration value (like a port or a feature flag).
- A shared counter for tracking visits.
- A database connection pool placeholder (we won't actually connect to a database, just show the field).
We'll use Arc<Mutex<...>> for data that needs to be mutated, and Arc<...> for data that is already safe to share. When you pass the struct to the router, you will usually wrap it in another Arc as well, so the fields should be cheap to clone. If a field itself is an Arc, cloning the struct is just cloning the Arc (cheap). If a field is a String, cloning the struct will deep-clone the string. That's why we often wrap expensive fields in Arc inside the struct too.
Here's a more realistic AppState:
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
#[derive(Clone)]
struct AppState {
config: Arc<AppConfig>,
visit_count: Arc<Mutex<u64>>,
cache: Arc<Mutex<HashMap<String, String>>>,
}
#[derive(Clone)]
struct AppConfig {
max_items_per_page: u32,
enable_debug: bool,
}
In this example:
configis anArc<AppConfig>.AppConfigis just a simple struct with two primitive fields. BecauseAppConfigderivesClone, andArcclones cheaply, this is fine.visit_countisArc<Mutex<u64>>. AMutexallows safe mutation from multiple threads, and theArclets us share the same mutex across clones.cacheisArc<Mutex<HashMap<String, String>>>. This could be used to store temporary data keyed by string.
Notice that AppState still derives Clone. When AppState is cloned, each field is cloned. Since all fields are wrapped in Arc, cloning is cheap - it just increments a reference count.
Clone can be expensive if you are not careful:
If you put a large String or Vec directly in AppState and derive Clone, every request will make a full copy of that data. For read‑only configuration data that never changes, that might be acceptable if the data is small. But for anything large or frequently cloned, wrap it in Arc inside the struct.
Defining AppState with Different Field Styles
There is no single "right" way to define an AppState struct. The fields you choose depend on what your application actually needs. Let's look at a few common patterns.
Read‑Only Configuration Fields
If a field never changes after startup, you can store it directly in the struct without synchronization. For example, a port number or a static token. You might still wrap it in Arc to keep clones cheap, or if it is a small copy type like u32, you can leave it as is.
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
server_port: u16,
api_token: Arc<String>,
}
Here, server_port is a u16 (a small integer) and copying it is trivial. api_token is an Arc<String> so cloning the struct is cheap.
Mutable Shared Counters
For counters that need to be updated by handlers, you need interior mutability. The common choices are AtomicUsize for lock‑free counters or Mutex<u64> when you want a mutex lock. If you have not yet read about atomics or mutexes in Axum, the key idea is that these types allow multiple parts of the program to safely read and modify the same value.
use std::sync::atomic::AtomicUsize;
#[derive(Clone)]
struct AppState {
request_count: Arc<AtomicUsize>,
}
You can then call fetch_add(1, Ordering::Relaxed) inside a handler to increment the counter.
Collections That Need Locking
For a Vec or HashMap that handlers will modify, you usually wrap it in Arc<Mutex<...>> (or Arc<RwLock<...>>).
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
#[derive(Clone)]
struct AppState {
user_sessions: Arc<Mutex<HashMap<String, String>>>,
}
Because Mutex provides safe access from multiple threads, this works when Axum runs handlers on different tasks.
Optional Fields with Option
Sometimes a piece of state might not be available at startup. You can use Option<T> to represent "maybe there, maybe not." For example, a cache that is populated lazily.
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
#[derive(Clone)]
struct AppState {
feature_cache: Arc<Mutex<Option<HashMap<String, bool>>>>,
}
Now handlers can check whether the cache has been initialized.
Grouping Related Fields into Sub‑Structs
When your state grows large, it's a good idea to split it into smaller logical groups. For instance, you might have DatabaseState, CacheState, and ConfigState as separate structs, then put them all inside AppState.
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
#[derive(Clone)]
struct AppState {
db: DatabaseState,
cache: CacheState,
config: ConfigState,
}
#[derive(Clone)]
struct DatabaseState {
// Replace this placeholder with your real database pool type,
// for example the pool type from the database library you use.
pool: Arc<DbPool>,
}
#[derive(Clone)]
struct CacheState {
data: Arc<Mutex<HashMap<String, String>>>,
}
#[derive(Clone)]
struct ConfigState {
admin_email: String,
}
This keeps each concern separate while still having a single top‑level state object.
Naming is up to you:
The struct does not have to be named AppState. You can call it SharedState, ServerState, or anything else. However, AppState is a common convention in Axum examples and tutorials, so using it makes your code easier to recognize for other developers.
How Axum Uses Your AppState Struct
When you call .with_state(shared_state) on the router, Axum stores that value. Then, for every incoming request, Axum clones the state and makes it available to handlers through the State extractor. The important part is that your struct must implement Clone (or be wrapped in Arc, which is cloneable). If you forget to make it cloneable, you will see a compile error.
Let's look at a slightly larger example that uses multiple fields and shows a handler reading from them.
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
app_name: String,
visit_count: Arc<Mutex<u32>>,
admin_email: Arc<String>,
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState {
app_name: "My Axum App".to_string(),
visit_count: Arc::new(Mutex::new(0)),
admin_email: Arc::new("admin@example.com".to_string()),
});
let app = Router::new()
.route("/", get(show_info))
.route("/admin-email", get(show_admin_email))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn show_info(State(state): State<Arc<AppState>>) -> String {
format!(
"App name: {}, visits so far: {}",
state.app_name,
*state.visit_count.lock().unwrap()
)
}
async fn show_admin_email(State(state): State<Arc<AppState>>) -> String {
format!("Admin email: {}", state.admin_email)
}
Here the first handler reads the visit_count from the Mutex, and the second reads the admin_email. Both handlers receive the same state object (actually a clone of the Arc, but pointing to the same underlying data). The visit_count is wrapped in Mutex because we intend to modify it later; for now, we just read it.
A Plain Clone Struct Works Too, Without Arc:
If you write #[derive(Clone)] struct AppState { ... } and then pass AppState directly to .with_state() without wrapping it in Arc, it compiles fine, as long as the struct implements Clone + Send + Sync + 'static. Arc<T> satisfies these bounds automatically if T does, and it makes cloning cheap, but it is not required. The trade-off is that a plain struct is deep-cloned on every request, while an Arc clone only bumps a reference count. So use Arc when the struct holds data that is expensive to copy or must be shared, and pass the struct directly when it is small and cheaply cloneable.
Mental Model: The Toolbox Analogy
Think of your AppState struct as a toolbox that you place in a central workshop. Every worker (handler) can walk over, open the toolbox, and take out the tool they need. They don't each carry their own copy of every tool; they all share the same toolbox. The Arc wrapper is like a label that says "this toolbox is shared, don't throw it away until everyone is done." The Mutex around a field is like a lock on a specific drawer: only one worker can open that drawer at a time.
This mental model helps you decide what belongs in AppState and how to protect each field. If a field is read‑only, no lock is needed. If a field might be changed by many workers simultaneously, it needs a lock or an atomic type.
Common Mistakes with AppState Structs
Several errors trip up beginners when they first define their own AppState.
Not Deriving Clone
Axum clones the state for every request, so the state type itself must implement Clone. There are two patterns, and the Clone requirement lands differently in each one.
When you pass Arc<AppState> to .with_state(), the state type is Arc<AppState>. Arc<T> implements Clone for any T, because cloning an Arc only copies the pointer, never the data inside it. So in this pattern the struct itself does not need to implement Clone at all. A plain struct AppState {} with no derive, wrapped in Arc::new and passed to .with_state(), compiles fine, because the Clone bound is checked on Arc<AppState>, not on AppState.
When you pass AppState directly to .with_state(), without wrapping it in Arc, the state type is AppState itself, so the struct must derive Clone and every field must be cheap to clone. That works when each field is a copy type like u32 or itself an Arc, because then cloning the struct is cheap. If a field holds a large String or Vec directly, every request deep-copies that data.
Most beginners use the Arc approach because it is safe and simple, and it stays correct when a non-cheap field is added later. The common mistake is the reverse: passing a plain struct without deriving Clone, which fails at the .with_state() call with the trait bound AppState: Clone is not satisfied.
Do you need Clone on AppState?:
If you are passing Arc<AppState>, the struct itself does not need to implement Clone. The Arc wrapper handles cheap cloning. However, if you plan to pass AppState directly to .with_state() (without Arc), then you must derive Clone and ensure every field is cheap to clone. In most tutorials and real projects, the Arc approach is preferred because it gives you more flexibility for fields that are not cheap to clone.
Storing Non‑Thread‑Safe Types Directly
Axum runs handlers on multiple threads, so every type stored in AppState must be safe to share across threads, meaning Send and Sync. The type to avoid is Rc, the single-threaded reference-counted pointer: Rc<T> is neither Send nor Sync, so any struct containing it fails the state bounds at compile time. Use Arc instead of Rc everywhere in shared state.
A std::sync::Mutex<T> is Sync when T is Send, so a mutex field is fine as long as the data inside it can move between threads. The same holds for RwLock<T> and for atomic types like AtomicUsize, which are designed for sharing. If the compiler rejects your state type, check each field for Rc, Cell, RefCell, or a raw pointer, and replace it with the thread-safe equivalent.
Forgetting to Initialize All Fields
When you create an instance of AppState, every field must be provided. Missing one will cause a compile error. This is good because it prevents uninitialized state.
Trying to Mutate Without Synchronization
If a field is a plain u32 or String and you try to modify it in a handler, you will get a compile error because Arc<AppState> gives you shared (read‑only) access. To mutate, you need an interior mutability pattern like AtomicUsize or Mutex. This is a common source of confusion.
Cannot assign to state field without lock:
If you write state.counter += 1; inside a handler and counter is a plain u32 in AppState, the compiler will complain that state is not declared as mutable. And even if you make the binding mutable, the increment would only change the handler's own per-request clone and be lost as soon as the handler returns. The fix is to make counter an AtomicU32 or wrap it in Mutex<u32> and use lock / atomic operations.
A Complete Example with Mutation Using AtomicUsize
To show a realistic AppState struct that actually changes, let's include an AtomicUsize for a request counter. This demonstrates how the struct can hold data that handlers modify safely.
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
struct AppState {
request_count: AtomicUsize,
app_name: String,
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState {
request_count: AtomicUsize::new(0),
app_name: "Counter App".to_string(),
});
let app = Router::new()
.route("/", get(handler))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn handler(State(state): State<Arc<AppState>>) -> String {
let count = state.request_count.fetch_add(1, Ordering::Relaxed) + 1;
format!("{} has been visited {} times", state.app_name, count)
}
In this example:
AppStatecontainsrequest_count: AtomicUsizeandapp_name: String.- We do not derive
CloneonAppStatebecause we wrap the whole thing inArc. TheArcgives us cheap clones. - Inside the handler, we call
fetch_add(1, Ordering::Relaxed)on the atomic. This atomically increments the value and returns the previous value. We add 1 to get the current visit number. - The
app_nameis read directly because it is immutable.
This pattern is common for simple counters. Later, you might use a Mutex if you need to protect a more complex data structure.
Testing the counter:
Run the server and refresh the page several times. Each refresh will show an increasing number: "Counter App has been visited 1 times", then "2 times", and so on. This proves that the state is shared and mutation works.
Organizing AppState for Large Applications
As your application grows, the AppState struct can become unwieldy if you just keep adding fields. A good practice is to group related fields into sub‑structs and then include those sub‑structs as fields of AppState. This is sometimes called "composition."
Here's an example:
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
#[derive(Clone)]
struct DatabaseState {
// Replace this placeholder with your real database pool type,
// for example the pool type from the database library you use.
pool: Arc<DbPool>,
}
#[derive(Clone)]
struct CacheState {
entries: Arc<Mutex<HashMap<String, String>>>,
}
#[derive(Clone)]
struct AppState {
db: DatabaseState,
cache: CacheState,
config: AppConfig,
}
Then, inside a handler, you access state.db.pool or state.cache.entries. This keeps each concern in its own type and makes the top‑level state a neat index.
You might also consider deriving Clone on each sub‑struct instead of on AppState directly, but if you wrap AppState in Arc, you don't need Clone on anything at the top level. However, if you want the option to pass AppState directly without Arc, you would need Clone on all parts. Most teams stick with Arc<AppState> and avoid deriving Clone on the struct.
Choosing Between Arc and Direct Clone
As shown above, you can either pass Arc<AppState> to .with_state() or pass AppState directly if it implements Clone and all fields are cheap. Let's compare these two approaches with concrete code.
Approach A: Arc<AppState> (Recommended)
// src/main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
struct AppState {
data: String, // could be large
}
async fn handler(State(state): State<Arc<AppState>>) -> String {
state.data.clone()
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState {
data: "some large string".to_string(),
});
let app = Router::new()
.route("/", get(handler))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here, cloning the state (which Axum does for each request) only clones the Arc, not the String. This is very cheap.
Approach B: AppState Directly with #[derive(Clone)]
// src/main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
data: Arc<String>, // each field is cheap to clone
}
async fn handler(State(state): State<AppState>) -> String {
(*state.data).clone()
}
#[tokio::main]
async fn main() {
let state = AppState {
data: Arc::new("some large string".to_string()),
};
let app = Router::new()
.route("/", get(handler))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In this version, AppState itself derives Clone, and each field is either a copy type or wrapped in Arc, so cloning the struct is cheap. You don't need an outer Arc; Axum will call .clone() on the AppState directly for each request, but because the fields are cheap, that clone is cheap.
Which should you choose?:
Most examples and real‑world code use Arc<AppState> because it removes the requirement that every field be cheap to clone. It also makes the shared nature explicit. The second approach is fine if you know all fields are cheap, but it's easier to accidentally add a non‑cheap field later and cause performance problems. So stick with Arc<AppState> unless you have a specific reason not to.
Step‑by‑Step: Building an AppState from Scratch
If you are creating your first Axum application with shared state, here is a logical sequence to follow. This is a genuine ordered process, so a stepper is appropriate.
Step 1: Identify the shared data
List every piece of data that more than one handler will need. Example: a database pool, a configuration object, a counter, and a cache.
Step 2: Define the AppState struct
Write a Rust struct with a field for each item. For mutable data, decide whether to use Atomic* types or Mutex / RwLock. Wrap fields that need sharing in Arc if you plan to clone the struct.
Step 3: Create an instance and wrap it in Arc
In your main function, create Arc::new(AppState { ... }). This becomes the shared state.
Step 4: Attach the state to the router
Build your Router and call .with_state(state). This tells Axum to make the state available to handlers.
Step 5: Extract the state in handlers
In each handler, add an argument like State(state): State<Arc<AppState>>. Then use state.field_name to access the data. For mutable fields, use lock or atomic methods.
This sequence is the standard flow for using an AppState struct.
Summary
The decision to make when you design an AppState comes down to two questions, and the answers pick the pattern for you. First, will every field be cheap to clone on its own? If yes, pass the struct directly with #[derive(Clone)] and skip the outer Arc. If any field is large or cannot be cloned cheaply, wrap the whole struct in Arc<AppState> and let the Arc carry the cloning cost. Second, can each field be shared between threads as it stands? Read-only values and copy types pass as they are, while anything handlers must change needs interior mutability, an atomic type for a plain number or a Mutex or RwLock for a larger value, so the change is visible to the next request instead of dying with one request's private clone.
That second question is the one that unlocks everything else in state design. Once the struct holds shared handles instead of private copies, the same container works for configuration, counters, caches, and connection pools, and the only thing left to learn is how the router accepts the struct and how handlers pull pieces out of it.