Per-request vs Shared Data in Axum

Understand the difference between data created for each HTTP request and data shared across requests, and why AppState exists

When you build a web server, every single HTTP request that arrives is its own little world. It has its own URL, its own headers, its own body - and once the server sends back a response, that world disappears. But some data needs to live longer than a single request. A database connection pool should not be recreated from scratch every time someone visits your site. A hit counter has to remember its previous value. This page explains the fundamental split between these two kinds of data - the per-request kind and the shared kind - and why Axum's AppState exists to hold the shared kind.

What Per-request Data Is

Per-request data is information that arrives inside an incoming HTTP request and exists only for the duration of handling that one request. When a client sends a GET request to /users/42?active=true, the number 42, the query flag active=true, any custom headers, and the request body are all per-request data. The next request to /users/99 will have completely different per-request data.

In Axum, per-request data is extracted using extractors. An extractor is a type that implements a trait Axum recognizes, and it pulls a specific piece of information out of the request. The most common extractors you will use for per-request data are Path, Query, Json, Form, and HeaderMap. Each one reads a different part of the request.

Think of per-request data like a paper form someone hands you at a counter. You read the form, do what it asks, and then the form is gone. The next person brings a completely different form. None of the information from the first form carries over to the second person.

What Shared Data Is

Shared data is information that exists independently of any single request. It is created once when the server starts, lives for the entire lifetime of the server, and can be accessed by every handler that needs it. Examples include configuration values, a database connection pool, an in-memory cache, or a counter that tracks how many visitors the server has received.

In Axum, shared data lives inside an application state struct - the AppState you create and attach to your Router using .with_state(). Handlers access this shared data through the State extractor. Because the same underlying data is shared across many requests, it is typically wrapped in Arc (for read-only sharing) or in Arc<Mutex<T>> or Arc<RwLock<T>> (for mutable sharing).

A good mental model for shared data is a whiteboard on the wall. Everyone who walks into the room can read from it and write on it. The whiteboard stays on the wall whether or not anyone is currently using it. When you erase something and write a new value, the next person who looks at the whiteboard sees the updated value. Shared data in Axum works the same way - it persists across requests.

The Lifetime Difference That Defines Both

The core distinction between per-request and shared data comes down to lifetime - how long the data lives.

Per-request data is born when a request arrives and dies when the handler returns. The value you extract from a Path or Json extractor exists only inside that one handler function call. Once the function returns a response, the data is dropped from memory (unless you deliberately store it somewhere shared).

Shared data is born when you construct the AppState in your main function, before the server even starts accepting connections. It lives until the server process ends. Every handler that receives a State<AppState> extractor gets a clone of the AppState. That clone is cheap when the fields are Arcs, because cloning an Arc only increments a reference count, but plain fields like a String or a Vec are deep-copied on every request.

The following tiny example makes this visible. Notice how a per-request local variable resets to 1 on every request, while a shared counter keeps climbing.

use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    shared_counter: Arc<AtomicUsize>,
}
async fn show_difference(State(state): State<AppState>) -> String {
    // Per-request data - created fresh every time this handler runs
    let request_local = 1;
    // Shared data - persists across requests
    let count = state.shared_counter.fetch_add(1, Ordering::SeqCst) + 1;
    format!(
        "request_local is always {}, shared_counter is now {}",
        request_local, count
    )
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        shared_counter: Arc::new(AtomicUsize::new(0)),
    };
    let app = Router::new()
        .route("/show", get(show_difference))
        .with_state(app_state);
    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();
}

Run this server and send three requests to http://localhost:3000/show. You will see output like this:

request_local is always 1, shared_counter is now 1
request_local is always 1, shared_counter is now 2
request_local is always 1, shared_counter is now 3

The request_local variable is created inside the handler function body, so it is brand new on every request. It is always 1. The shared_counter, however, lives inside the AppState that was created once in main. Every request reads the same AtomicUsize, increments it, and sees the updated value. That is the difference in one paragraph and three requests.

A Useful Mental Shortcut:

If the data came from the request itself - URL, query string, body, headers - it is per-request. If you created the data before the server started accepting connections and want it to survive between requests, it is shared.

Why AppState Exists

AppState exists because handlers are plain Rust functions, and plain Rust functions have no natural way to access data that outlives a single function call. Without shared state, every handler would start from a blank slate on every request. If you needed a database connection, you would have to open a new one for every request - slow and wasteful. If you needed a hit counter, you would have nowhere to store the previous count, so it could never increment.

Before Axum's state mechanism, Rust web developers sometimes reached for global variables. Rust makes global mutable state deliberately awkward because it is a source of data races and undefined behavior. Axum's AppState provides a safe, compiler-checked alternative: you create the state once, attach it to the router, and the router guarantees that every handler requesting State<AppState> gets a clone of the same underlying data. The borrow checker and the type system do the hard work of making sure the data is shared safely.

A practical way to understand why AppState exists is to imagine building a visitor counter without it. You write a handler:

async fn counter() -> String {
    let mut count = 0;
    count += 1;
    format!("Visitor #{count}")
}

This compiles and runs, but every request returns Visitor #1. The count variable is recreated on every call. To make it persist, you need to move the counter out of the handler and into something that lives longer than any single request. That "something" is AppState.

A First Real Example - Per-request and Shared Data Together

Most real handlers use both kinds of data at the same time. Per-request data tells the handler what to do. Shared data tells the handler what resources it has available to do it.

Consider a greeting endpoint that takes a name from the URL path (per-request) and also counts total visitors using a shared counter:

use axum::{
    extract::{Path, State},
    routing::get,
    Router,
};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    visit_count: Arc<AtomicUsize>,
}
async fn greet(
    State(state): State<AppState>,
    Path(name): Path<String>,
) -> String {
    let count = state.visit_count.fetch_add(1, Ordering::SeqCst) + 1;
    format!("Hello, {name}! You are visitor #{count}")
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        visit_count: Arc::new(AtomicUsize::new(0)),
    };
    let app = Router::new()
        .route("/hello/{name}", get(greet))
        .with_state(app_state);
    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();
}

Send requests to /hello/alice, then /hello/bob, then /hello/carol. You will see:

Hello, alice! You are visitor #1
Hello, bob! You are visitor #2
Hello, carol! You are visitor #3

The name value is different for every request because it comes from the URL path. The visit_count is the same underlying AtomicUsize for all requests, so it increments each time. This is the pattern you will use constantly in real Axum applications: a State extractor for shared resources, and one or more other extractors for per-request details.

If You See Incrementing Numbers:

When your counter goes from #1 to #2 to #3 across separate curl commands or browser refreshes, you have correctly set up shared state. The numbers persisting across requests is exactly the behavior you want.

How Axum Delivers Per-request Data

Axum delivers per-request data through extractors that implement the FromRequest trait. Each extractor knows how to read a specific part of the incoming request and convert it into a Rust type you can work with. The extractor runs inside the handler call, after the request has been parsed by the HTTP layer.

The most commonly used per-request extractors are:

  • Path<T> - reads path parameters from the URL, like {id} in /users/{id}
  • Query<T> - reads query string parameters, like ?page=2&limit=10
  • Json<T> - reads and deserializes a JSON request body
  • Form<T> - reads and deserializes form-encoded request bodies
  • HeaderMap - reads HTTP headers
  • String - reads the raw request body as a UTF-8 string

Each of these extractors produces data that is unique to the request. If two requests arrive at the same time, each gets its own copy of the extracted values. There is no risk of one request overwriting another request's per-request data, because each handler invocation gets its own fresh values.

How Axum Delivers Shared Data

Shared data travels through a different channel. When you call .with_state(app_state) on your Router, Axum stores the state inside the router. When a request arrives and Axum invokes a handler that has a State<AppState> parameter, Axum clones the stored state and hands that clone to the handler.

Because AppState must be cloneable, you almost always derive Clone on it and wrap its inner fields in Arc. When the fields are Arcs, the clone is cheap: it only increments a reference count, and all clones point to the same underlying data in memory. Plain owned fields, by contrast, are deep-copied on every clone.

The key point is that the State extractor does not read anything from the incoming request. It ignores the URL, the headers, and the body. It only looks at the state that was attached to the router. That is why State works even on requests that have no useful per-request data at all.

State Is Not Per-request Data:

A common beginner mistake is to think of State as just another extractor that reads from the request. It does not. State gives you access to data that was created before any request arrived. If you need request-specific values, you must use a per-request extractor like Path or Json.

Comparing Per-request and Shared Data Side by Side

The following table summarizes the differences. Read it slowly - each row contrasts the two kinds of data on one specific dimension.

DimensionPer-request DataShared Data
Created whenEach time a request arrivesOnce at server startup
Destroyed whenWhen the handler returnsWhen the server process ends
Stored inThe HTTP request itselfThe AppState struct
Accessed viaPath, Query, Json, Form, headersState<AppState> extractor
UniquenessDifferent for every requestSame underlying data for all requests
MutabilityRead-only (you can copy and modify locally)Can be mutable if wrapped in Mutex or RwLock
ExamplesURL parameters, request body, headersDatabase pool, config, cache, counters
Concurrency concernNone - each request has its own copyNeeds Arc + lock if mutated

Deciding Which Kind of Data to Use

Here is a practical decision framework. When you are writing a handler and realize you need a piece of information, ask yourself one question: would this value still exist if the request had never happened?

If the answer is yes - the value is a fact about your server, like its configuration or its database connection - put it in AppState and access it via State.

If the answer is no - the value only makes sense in the context of a specific incoming request, like which user ID was requested or what JSON body was sent - use a per-request extractor.

Sometimes you need both in the same handler, and that is completely normal. A handler that updates a user's profile might need:

  • State<AppState> to get the database connection pool (shared)
  • Path<u64> to get the user ID from the URL (per-request)
  • Json<UpdateProfile> to get the new profile data from the body (per-request)

All three extractors coexist in the same function signature, and Axum resolves each one from its respective source.

More Examples

The first example below reads JSON request bodies, so add serde to your Cargo.toml alongside Axum and Tokio:

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

Shared config plus per-request input

This example shows a server that limits how long a username can be. The maximum length is a shared config value. The username comes from the request body.

use axum::{
    extract::State,
    routing::post,
    Json, Router,
};
use serde::Deserialize;
#[derive(Clone)]
struct AppState {
    max_name_length: usize,
}
#[derive(Deserialize)]
struct CreateUser {
    name: String,
}
async fn create_user(
    State(state): State<AppState>,
    Json(payload): Json<CreateUser>,
) -> Result<String, String> {
    if payload.name.len() > state.max_name_length {
        return Err(format!(
            "Name too long. Maximum is {} characters.",
            state.max_name_length
        ));
    }
    Ok(format!("User '{}' created successfully", payload.name))
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        max_name_length: 10,
    };
    let app = Router::new()
        .route("/users", post(create_user))
        .with_state(app_state);
    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 max_name_length value is shared across all requests - you set it once at startup and every request sees the same value. The name value is per-request - it comes from the JSON body of each individual POST request. If you send {"name": "alice"}, the name is five characters and passes the check. If you send {"name": "christopher"}, the handler rejects it because the shared maximum is ten.

Shared mutable collection plus per-request query

Shared data does not have to be read-only. Here is a to-do list stored inside a Mutex so it can be safely mutated across requests. The per-request data comes from a query string.

use axum::{
    extract::{Query, State},
    routing::get,
    Router,
};
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
    todos: Arc<Mutex<BTreeMap<u64, String>>>,
}
async fn add_todo(
    State(state): State<AppState>,
    Query(params): Query<HashMap<String, String>>,
) -> String {
    let text = params.get("text").cloned().unwrap_or_else(|| "untitled".to_string());
    let mut todos = state.todos.lock().unwrap();
    let id = todos.len() as u64 + 1;
    todos.insert(id, text.clone());
    format!("Added todo #{id}: {text}")
}
async fn list_todos(State(state): State<AppState>) -> String {
    let todos = state.todos.lock().unwrap();
    if todos.is_empty() {
        return "No todos yet. Add one with POST /todos?text=something".to_string();
    }
    todos
        .iter()
        .map(|(id, text)| format!("#{id}: {text}"))
        .collect::<Vec<_>>()
        .join("\n")
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        todos: Arc::new(Mutex::new(BTreeMap::new())),
    };
    let app = Router::new()
        .route("/todos", get(list_todos).post(add_todo))
        .with_state(app_state);
    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();
}

Try this sequence:

  1. POST /todos?text=buy+milk → Added todo #1: buy milk
  2. POST /todos?text=write+docs → Added todo #2: write docs
  3. GET /todos → #1: buy milk\n#2: write docs

The BTreeMap persists across all three requests because it lives inside the shared AppState. The text query parameter is different for each POST request because it comes from the URL of that specific request. The map is a BTreeMap rather than a HashMap on purpose: a BTreeMap keeps its entries sorted by their id, so the list always comes out in the order the todos were added, while a HashMap would return them in an unpredictable order.

Lock the Mutex, Do Not Clone It:

When you have Arc<Mutex<BTreeMap<...>>>, you must call .lock() every time you read or write. Locking gives you temporary exclusive access to the data, then you let it go. If you try to store a reference to the locked data outside the handler, the compiler will reject it because the lock guard's lifetime is tied to the lock call. This is Rust protecting you from using shared data after the lock has been released.

The same AppState used by handlers with different per-request needs

One of the strengths of AppState is that many different handlers can share it, even if each handler also extracts different per-request data.

use axum::{
    extract::{Path, Query, State},
    routing::get,
    Router,
};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone)]
struct AppState {
    total_requests: Arc<AtomicUsize>,
}
async fn handler_with_path(
    State(state): State<AppState>,
    Path(user_id): Path<u64>,
) -> String {
    state.total_requests.fetch_add(1, Ordering::SeqCst);
    format!("User ID from path: {user_id}")
}
async fn handler_with_query(
    State(state): State<AppState>,
    Query(params): Query<std::collections::HashMap<String, String>>,
) -> String {
    state.total_requests.fetch_add(1, Ordering::SeqCst);
    let search = params.get("q").cloned().unwrap_or_else(|| "none".to_string());
    format!("Search query: {search}")
}
async fn request_count(State(state): State<AppState>) -> String {
    let count = state.total_requests.load(Ordering::SeqCst);
    format!("Total requests served: {count}")
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        total_requests: Arc::new(AtomicUsize::new(0)),
    };
    let app = Router::new()
        .route("/user/{user_id}", get(handler_with_path))
        .route("/search", get(handler_with_query))
        .route("/stats", get(request_count))
        .with_state(app_state);
    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();
}

Three handlers, all sharing the same AppState. handler_with_path reads a u64 from the URL path. handler_with_query reads a string from the query string. request_count reads no per-request data at all - it only uses the shared counter. Yet all three handlers increment the same shared total_requests counter. After hitting /user/5, /search?q=rust, and /user/8, a GET to /stats shows Total requests served: 3.

Common Mistakes and Misconceptions

Mistake 1 - Storing per-request data inside AppState

The most serious mistake is putting request-specific data into the shared state. Imagine you store the current user's ID in AppState:

// WRONG - do not do this
#[derive(Clone)]
struct AppState {
    current_user_id: Arc<Mutex<Option<u64>>>,
}

The problem is that all requests share the same AppState. When request A sets current_user_id to 5, then request B arrives and sets it to 9, request A's value is overwritten. Both requests see the same shared slot, so the value leaks between them. This causes data corruption and security bugs.

The correct place for a per-request user ID is a per-request extractor, like a Path<u64> or a Json body field. Shared state should only hold values that are genuinely true for the whole server.

Never Mix Request Identity Into Shared State:

If two requests can mutate the same shared value, and each request expects to see its own version of that value, you have a design error. The shared value will be overwritten by whichever request runs last. Keep request-specific data in per-request extractors.

Mistake 2 - Assuming shared data is automatically mutable

Creating an AppState with a plain integer field and trying to increment it looks like it should update a shared counter, but it does not do what you want:

#[derive(Clone)]
struct AppState {
    counter: usize,  // plain usize, not shared across clones
}
async fn increment(State(mut state): State<AppState>) -> String {
    state.counter += 1;  // compiles, but only mutates this request's clone
    format!("Counter: {}", state.counter)
}

With the mut binding this compiles, but the increment is lost as soon as the handler returns: each request receives its own fresh clone of the state, so the counter always prints 1. Without the mut keyword the same code fails to compile with error[E0594]: cannot assign to state.counter, as state is not declared as mutable.

Shared data that needs to change must be wrapped in an interior-mutability primitive like Mutex, RwLock, or an atomic type like AtomicUsize. The compiler enforces this because multiple requests could try to mutate the same value simultaneously, and unsynchronized mutation is a data race.

Mistake 3 - Forgetting that per-request data disappears after the handler returns

Sometimes beginners extract per-request data and then try to use it in another handler. This does not work. If handler A extracts a value from a Path parameter and stores it in a local variable, handler B has no access to that local variable. The only way data persists across handlers is if you explicitly place it in shared state - and then you must be careful that the data is genuinely meant to be shared.

Mistake 4 - Confusing State with other extractors

The State extractor does not read anything from the request. It does not care whether the URL contains ?state=xyz. It always returns the exact same AppState that was attached to the router. If you need request-specific data, you must add a separate extractor like Path or Query. Using State and expecting it to read from the request is a misunderstanding of what shared data means.

Summary

Per-request data and shared data are the two fundamental categories of information in an Axum server. Per-request data arrives with each HTTP request, is extracted by types like Path, Query, and Json, and dies when the handler returns. Shared data is created once at startup, lives inside AppState, is accessed with the State extractor, and persists across every request the server handles.

The reason AppState exists is simple but profound: handlers are plain functions, and plain functions have no natural way to remember anything between calls. AppState gives those functions a safe, compiler-checked way to access data that outlives any single request. Most production handlers use both kinds of data together - shared state for resources like database pools and configuration, and per-request extractors for the specific details of each incoming request. The skill is recognizing which category each piece of information belongs to, and placing it in the right one.

Once you understand this split, the next design question is how to choose between State and Extension for sharing data in Axum - both can carry shared values, but they differ in important ways.