Substate extraction

Learn how to extract smaller pieces from a large application state in Axum using the FromRef trait and the State extractor.

An application state struct often holds several fields: a database pool, a configuration object, a cache, and more. This page focuses on a specific benefit of that setup: the ability to extract only a part of the state in a handler, rather than the whole state. That part is called a substate.

When you have a state struct with several fields, a handler often needs just one of them. Instead of receiving State<AppState> and then reaching into the fields manually, Axum lets you ask for State<SubstateType> directly. The framework automatically converts from the full state to the requested substate using the FromRef trait.

The Problem Substate Extraction Solves

Imagine your application has a shared AppState that contains a database pool, a configuration object, and a cache. A handler that only needs the configuration should not have to know about the database pool or the cache. That would create unnecessary coupling: the handler would depend on the entire state type even though it uses only a small part of it.

Substate extraction solves this by letting each handler declare exactly which part of the state it needs. The router still stores the full AppState, but the handler signature can ask for State<Config> instead of State<AppState>. Axum then uses the FromRef implementation to produce the smaller state from the larger one.

This has a few practical advantages:

  • Handlers become self-documenting. You can see immediately what data they use.
  • Handlers are easier to test because you can construct only the substate they need, not the whole state.
  • The dependency between a handler and the global state is reduced, which makes refactoring easier.

FromRef Recap:

The FromRef trait is what makes this possible. It defines how to get a substate from a reference to a larger state. When you derive FromRef on a struct, Axum generates an implementation for each field that returns a clone of that field. You must enable the macros feature in your Cargo.toml for the derive to work.

A Basic Example of Substate Extraction

Let's start with the smallest possible example. We have an AppState with two fields: a String for the application name, and a u32 for a version number. A handler will only need the application name, so it will extract State<String> instead of State<AppState>.

First, make sure your Cargo.toml includes axum with the macros feature:

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

Now the full application:

use axum::{
    extract::{FromRef, State},
    routing::get,
    Router,
};
#[derive(Clone, FromRef)]
struct AppState {
    app_name: String,
    version: u32,
}
async fn show_app_name(State(app_name): State<String>) -> String {
    format!("The application name is: {app_name}")
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        app_name: "My Axum App".to_string(),
        version: 1,
    };
    let app = Router::new()
        .route("/name", get(show_app_name))
        .with_state(app_state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Let's understand what is happening here.

AppState derives Clone and FromRef. The FromRef derive generates an implementation like this:

impl FromRef<AppState> for String {
    fn from_ref(input: &AppState) -> Self {
        input.app_name.clone()
    }
}

Even though String is not a field name in AppState (it's a type), the derive macro looks at the field types and generates an implementation for each unique field type. In this case, there is one field of type String, so it creates FromRef<AppState> for String. If there were two String fields, it would be ambiguous, which we'll discuss later.

The handler show_app_name takes State(app_name): State<String>. Because the router was built with .with_state(app_state), the state stored in the router is an AppState. But the handler's extractor asks for State<String>. Axum sees that String implements FromRef<AppState>, so it can convert the stored AppState into a String by calling from_ref, which clones the app_name field, and hands the resulting String to the handler as State<String>.

When you run this and visit http://127.0.0.1:3000/name, you will see The application name is: My Axum App.

Compile-time check:

The conversion between the router's state type and the handler's requested state type is checked at compile time. If you forget to implement FromRef for the substate, the code will not compile. This is one of the strengths of Axum's state system.

Extracting Different Substate Types in Different Handlers

Now let's make a more realistic example with a Config struct and a DbPool struct. We want one handler to use only Config, another to use only DbPool, and a third to use the whole AppState.

use axum::{
    extract::{FromRef, State},
    routing::get,
    Router,
};
#[derive(Clone)]
struct Config {
    host: String,
    port: u16,
}
#[derive(Clone)]
struct DbPool {
    connection_string: String,
}
#[derive(Clone, FromRef)]
struct AppState {
    config: Config,
    db_pool: DbPool,
}
async fn config_handler(State(config): State<Config>) -> String {
    format!("Server will listen on {}:{}", config.host, config.port)
}
async fn db_handler(State(db): State<DbPool>) -> String {
    format!("Using database at {}", db.connection_string)
}
async fn full_state_handler(State(state): State<AppState>) -> String {
    format!(
        "Config host: {}, DB connection: {}",
        state.config.host, state.db_pool.connection_string
    )
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        config: Config {
            host: "127.0.0.1".to_string(),
            port: 8080,
        },
        db_pool: DbPool {
            connection_string: "postgres://localhost/mydb".to_string(),
        },
    };
    let app = Router::new()
        .route("/config", get(config_handler))
        .route("/db", get(db_handler))
        .route("/full", get(full_state_handler))
        .with_state(app_state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here, AppState contains two fields of distinct types, Config and DbPool. The FromRef derive generates two implementations:

impl FromRef<AppState> for Config {
    fn from_ref(input: &AppState) -> Self {
        input.config.clone()
    }
}
impl FromRef<AppState> for DbPool {
    fn from_ref(input: &AppState) -> Self {
        input.db_pool.clone()
    }
}

Each handler requests the substate it needs:

  • config_handler receives State<Config>.
  • db_handler receives State<DbPool>.
  • full_state_handler receives State<AppState>, which works because AppState itself trivially implements FromRef<AppState> (Axum provides a blanket implementation for the same type).

This design keeps handlers focused. The config_handler doesn't know that a database exists. The db_handler doesn't know about configuration. That separation is the main benefit of substate extraction.

How Substate Extraction Works Under the Hood

To understand why substate extraction works, it helps to look at the types involved.

The router is created with .with_state(app_state), which provides the state the router was missing. The router stores the AppState value itself, not wrapped in an Arc.

When a request arrives, Axum needs to construct the state that the handler expects. The handler signature says State<Config>. Axum's extractor for State<T> is generic over T, but it requires that T: FromRef<S> where S is the router's state type. If that bound is satisfied, it can call T::from_ref(&s) where s is the stored AppState. That call produces a Config by value (because from_ref returns Self, not a reference). Then Axum passes that Config to the handler inside the State wrapper.

That's why the substate type must implement Clone. The conversion clones the field out of the original state. If the field isn't Clone, it can't be returned by value.

Substate must be Clone:

Every type that you want to use as a substate must implement Clone. This is because FromRef::from_ref returns Self by value, so Axum must clone the relevant field from the original state. If you forget to derive Clone on a field's type, you will get a compile error telling you that the type does not implement Clone.

Extracting Nested Substate

Sometimes your state is nested: the AppState contains a struct, which itself contains another struct. You can extract a deeply nested substate, but the derive on AppState only reaches one level deep, so a deeper field needs its own manual FromRef implementation.

Consider this hierarchy:

#[derive(Clone)]
struct AppConfig {
    database: DatabaseConfig,
    server: ServerConfig,
}
#[derive(Clone)]
struct DatabaseConfig {
    url: String,
}
#[derive(Clone)]
struct ServerConfig {
    bind_address: String,
}
#[derive(Clone, FromRef)]
struct AppState {
    config: AppConfig,
}

If a handler wants only the DatabaseConfig, you might be tempted to write State<DatabaseConfig> directly. But that won't work unless DatabaseConfig implements FromRef<AppState>. The derive on AppState only generates FromRef<AppState> for AppConfig, not for DatabaseConfig.

To make nested extraction possible, you need to implement FromRef for DatabaseConfig manually, or restructure your state so the nested value becomes a direct field of AppState. One simple way is to manually implement FromRef<AppState> for DatabaseConfig:

impl FromRef<AppState> for DatabaseConfig {
    fn from_ref(input: &AppState) -> Self {
        input.config.database.clone()
    }
}

Then a handler can use State<DatabaseConfig>.

Here is a complete example:

use axum::{
    extract::{FromRef, State},
    routing::get,
    Router,
};
#[derive(Clone)]
struct DatabaseConfig {
    url: String,
}
#[derive(Clone)]
struct ServerConfig {
    bind_address: String,
}
#[derive(Clone)]
struct AppConfig {
    database: DatabaseConfig,
    server: ServerConfig,
}
#[derive(Clone, FromRef)]
struct AppState {
    config: AppConfig,
}
// Manual FromRef implementation for nested type
impl FromRef<AppState> for DatabaseConfig {
    fn from_ref(input: &AppState) -> Self {
        input.config.database.clone()
    }
}
async fn database_info(State(db): State<DatabaseConfig>) -> String {
    format!("Database URL: {}", db.url)
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        config: AppConfig {
            database: DatabaseConfig {
                url: "postgres://localhost/mydb".to_string(),
            },
            server: ServerConfig {
                bind_address: "127.0.0.1:3000".to_string(),
            },
        },
    };
    let app = Router::new()
        .route("/db", get(database_info))
        .with_state(app_state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This approach gives you fine control over how the substate is created. In many cases, it's simpler to extract the whole AppConfig and then access config.database inside the handler, but if you have many handlers that only need DatabaseConfig, the manual FromRef impl reduces boilerplate.

Multiple Fields of the Same Type

A common pitfall occurs when your AppState has two fields of the same type. For example:

#[derive(Clone, FromRef)]
struct AppState {
    primary_db: DbPool,
    secondary_db: DbPool,
}

Here DbPool appears twice. The FromRef derive macro will generate two implementations of FromRef<AppState> for DbPool, one cloning primary_db and one cloning secondary_db. That causes a conflict because a type can only have one implementation of a trait for a given set of type parameters. The Rust compiler will reject this with an error about conflicting implementations.

There are two ways to solve this:

  1. Use newtype wrappers for each field to make the types distinct.
  2. Implement FromRef manually and decide which field to use, but then the ambiguity remains: which one should State<DbPool> refer to? In that case, you would likely not want to extract DbPool directly; instead, you'd extract a wrapper or the whole state.

The newtype approach is the cleanest. Define two distinct structs:

#[derive(Clone)]
struct PrimaryDb(DbPool);
#[derive(Clone)]
struct SecondaryDb(DbPool);

Then your AppState has fields of these distinct types. You can then implement FromRef<AppState> for PrimaryDb and SecondaryDb by deriving on AppState with fields of those types, or manually.

Example:

#[derive(Clone)]
struct DbPool {
    connection_string: String,
}
#[derive(Clone)]
struct PrimaryDb(DbPool);
#[derive(Clone)]
struct SecondaryDb(DbPool);
#[derive(Clone, FromRef)]
struct AppState {
    primary_db: PrimaryDb,
    secondary_db: SecondaryDb,
}
async fn primary_handler(State(db): State<PrimaryDb>) -> String {
    format!("Primary DB: {}", db.0.connection_string)
}

Now each field has a unique type, and the derive macro generates separate FromRef implementations without conflict.

Ambiguous FromRef implementations:

If your AppState contains two fields of the same type, deriving FromRef will result in conflicting trait implementations and your code will not compile. Use newtype wrappers to differentiate them, or implement FromRef manually and decide which field to expose.

Manual FromRef for Custom Logic

The derive macro is convenient, but sometimes you want to transform the state before handing it to a handler. For example, you might want to extract a computed value that isn't stored directly as a field.

Suppose your AppState stores a raw Vec<i32>, but a handler expects a Stats struct containing the sum and average. You can manually implement FromRef<AppState> for Stats to perform the computation.

use axum::{
    extract::{FromRef, State},
    routing::get,
    Router,
};
#[derive(Clone)]
struct AppState {
    numbers: Vec<i32>,
}
#[derive(Clone)]
struct Stats {
    sum: i32,
    average: f64,
}
impl FromRef<AppState> for Stats {
    fn from_ref(input: &AppState) -> Self {
        let sum: i32 = input.numbers.iter().sum();
        let average = if input.numbers.is_empty() {
            0.0
        } else {
            sum as f64 / input.numbers.len() as f64
        };
        Stats { sum, average }
    }
}
async fn stats_handler(State(stats): State<Stats>) -> String {
    format!("Sum: {}, Average: {:.2}", stats.sum, stats.average)
}
#[tokio::main]
async fn main() {
    let app_state = AppState {
        numbers: vec![10, 20, 30, 40, 50],
    };
    let app = Router::new()
        .route("/stats", get(stats_handler))
        .with_state(app_state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here, Stats does not exist as a field in AppState. The from_ref implementation computes it on the fly from the numbers field. This shows that substate extraction is not limited to direct field access; you can implement any logic you need. Keep in mind that from_ref runs on every request that extracts the substate, so a computed substate should stay cheap. Summing a short list is fine, but a slow computation here would slow down every request that uses the handler.

A Complete Walkthrough: Setting Up Substate Extraction

Let's walk through the entire process from scratch, step by step, to reinforce the flow.

1

Step 1: Define the substate types

Start by defining the types that your handlers will use. Each type that will be extracted must implement Clone. In this example, we'll have a Database and a Cache type.

#[derive(Clone)]
struct Database {
    url: String,
}
#[derive(Clone)]
struct Cache {
    capacity: usize,
}
2

Step 2: Define the full AppState and derive FromRef

Now define the AppState struct that contains both substates. Derive Clone and FromRef on it. This requires the macros feature to be enabled.

use axum::extract::FromRef;
#[derive(Clone, FromRef)]
struct AppState {
    database: Database,
    cache: Cache,
}
3

Step 3: Write handlers that use State<Substate>

Each handler can now declare the specific substate it needs as an argument.

use axum::extract::State;
async fn db_handler(State(db): State<Database>) -> String {
    format!("Database URL: {}", db.url)
}
async fn cache_handler(State(cache): State<Cache>) -> String {
    format!("Cache capacity: {}", cache.capacity)
}
4

Step 4: Build the router with the full state

Finally, create the Router, add the routes, and call .with_state(app_state) with the full AppState. The router now holds an AppState, and the handlers can receive substates because of the FromRef implementations.

use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app_state = AppState {
        database: Database {
            url: "postgres://localhost/mydb".to_string(),
        },
        cache: Cache { capacity: 1024 },
    };
    let app = Router::new()
        .route("/db", get(db_handler))
        .route("/cache", get(cache_handler))
        .with_state(app_state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

After completing these steps, you have a working application where handlers receive only the substate they need. The router still holds the entire AppState, but the extraction happens automatically.

What Can Go Wrong

Several issues can trip you up when working with substate extraction.

Forgetting to enable the macros feature. The FromRef derive macro is only available if you add the macros feature to your axum dependency in Cargo.toml.

Forgetting to derive Clone on substate types. The conversion from the full state to a substate requires cloning the field. If a type doesn't implement Clone, you'll get a compile error.

Trying to extract a type that doesn't implement FromRef for your state. Only types for which an FromRef implementation exists (whether derived or manual) can be extracted. If you try to extract State<SomeRandomType> without an FromRef impl, the compiler will complain.

Having two fields of the same type. As we saw, this creates conflicting FromRef implementations. Use newtype wrappers to disambiguate.

Assuming the substate is a reference to the original. The substate is a clone of the data, not a reference to the original. Mutating the substate inside a handler will not affect the original state. If you need to mutate shared data, you should use Arc<Mutex<...>> or similar interior mutability, but that is a separate topic.

Mutation is not shared:

When you extract a substate with State<Substate>, you get a clone of that substate. Any changes you make to it will not be visible to other requests or to the rest of the application. If you need to mutate shared data, store it behind an Arc<Mutex<T>> inside the state and extract that field as a substate, then mutate through the lock.

Summary

Substate extraction is a pattern that lets handlers request only the piece of application state they need, rather than the entire state struct. It relies on the FromRef trait, which Axum uses to convert from the router's state type to the handler's requested substate type. By deriving FromRef on your AppState, you can automatically implement conversion for each distinct field type. You can also implement FromRef manually for more control, such as when you need to compute a value or handle nested types.

The key benefit is reduced coupling between handlers and the global state. Handlers become easier to understand, test, and refactor. When you design your application state, think about which substates your handlers will need and structure your state accordingly. If you run into ambiguous types, newtype wrappers are your friend.

Once you are comfortable with substate extraction, you will find that it naturally leads to better-organized Axum applications: each handler declares its dependencies clearly, and the router keeps the full state in one place.