Explicit Dependency Surface in Axum

Learn how Axum makes every dependency visible in function signatures and router construction, so you always know what a handler needs to run

When you write a handler in Axum, you write a plain Rust function. The function's parameters tell you exactly what it depends on. If it needs a database connection, you see that in the signature. If it needs a path parameter, you see that too. Nothing is hidden behind global variables, macro magic, or framework internals.

That is what "explicit dependency surface" means. The phrase sounds technical, but the idea is simple: a piece of code should clearly show everything it needs from the outside world. Axum is built around this principle. In this lesson, you will see what that looks like in practice, why it matters, and how to use it when you build an Axum application.

What a Dependency Surface Is

Think of a function as a machine. It takes inputs, does some work, and produces an output. The dependencies of that machine are everything it needs to do its work that it does not create itself. That includes:

  • Data coming from the HTTP request (the URL, query string, JSON body, headers)
  • Shared application state (a database pool, a configuration object, a cache client)
  • Services the handler calls (a user repository, a payment processor)
  • Middleware that runs before or after the handler (logging, authentication)

The surface is the boundary where those dependencies meet your code. When that boundary is explicit, you can see every dependency by reading the code. When it is implicit, some dependencies are invisible; they are pulled from somewhere else at runtime, and you only find out about them by digging into the framework or the global state.

A handler in Axum makes its dependencies explicit in two places:

  1. The function signature - every extractor and piece of state is a parameter.
  2. The router setup - middleware layers and shared state are attached to the router using method calls.

There is no hidden dependency injection container, no reflection, no attribute macros that secretly wire things together. Axum trusts you to write out what you need, and it checks at compile time that everything is provided.

Why Explicit Dependencies Make Code Easier to Work With

When dependencies are hidden, you pay a price every time you read, test, or change code. You cannot tell what a function does without looking inside it, and you cannot test it in isolation without setting up a whole environment.

Axum's explicit approach gives you three practical benefits:

  1. Readability - you can understand what a handler needs by looking at its first few lines, without jumping to other files or searching for global state.
  2. Testability - because dependencies are passed as arguments, you can replace a real database pool with a mock in a unit test, without changing the handler code.
  3. Safe refactoring - when you add or remove a dependency, the Rust compiler tells you every caller that needs to change. You cannot silently forget to provide a required service.

These benefits compound as an application grows. A handler that depends on a database, a cache, and an external API becomes a self-describing unit. You know exactly what it touches.

A Sign of Good Design:

If a handler's parameter list reads like a checklist of what the endpoint needs, you are on the right track. That is the explicit dependency surface working for you.

Axum's Building Blocks for Explicit Dependencies

Axum gives you several tools for declaring dependencies. Each one makes a different kind of dependency visible in a different place. This section focuses on how they contribute to explicitness.

Extractors declare request dependencies

An extractor is a type that pulls information out of the incoming HTTP request and hands it to your handler. Path, Query, Json, and State are all extractors. When you write Path(user_id): Path<u32> as a parameter, you are explicitly declaring: "this handler needs a path parameter named user_id of type u32."

That declaration is visible to anyone reading the code. Note the limit of the check, though: the compiler does not check the path-parameter name in the handler against the name in the route string. Path<u32> deserialises positionally, so a handler whose parameter name does not match the route still compiles, and a request to that route is rejected at runtime (a 400 Bad Request when the segment cannot be deserialised). What the compiler does check is that the extractor type itself is valid and that the state type matches.

use axum::{
    extract::{Path, State},
    routing::get,
    Router,
};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    api_key: String,
}
async fn get_user(
    Path(user_id): Path<u32>,
    State(state): State<Arc<AppState>>,
) -> String {
    format!("User {} fetched with API key {}", user_id, state.api_key)
}
#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        api_key: "secret".to_string(),
    });
    let app = Router::new()
        .route("/users/{user_id}", get(get_user))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The handler get_user has two dependencies: a path parameter and shared state. Both are explicit. There is no way to call this handler without providing both, and the compiler enforces that.

Shared state is attached to the router

In the example above, with_state(state) attaches an Arc<AppState> to the router. Handlers that need it declare State<Arc<AppState>> in their signature. This is explicit because:

  • The router must be given the state before it can run.
  • The handler must ask for the state in its parameters.
  • The types must match exactly.

If you forget to call .with_state(), or if the handler expects a different state type, the compiler reports an error. There is no runtime "state not found" exception that only appears when you hit the endpoint.

Middleware layers are declared on the router

Middleware in Axum is not hidden inside a configuration file. You add it with methods like .layer(...) or .route_layer(...). The order in which you chain layers is visible in the router construction code.

use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
async fn root() -> &'static str {
    "Hello"
}
fn build_app() -> Router {
    Router::new()
        .route("/", get(root))
        .layer(TraceLayer::new_for_http())
}

The TraceLayer is a dependency of the whole application: it provides logging for every request. Because it is added with .layer(), you can see at a glance that the app has tracing middleware. You do not need to search for a hidden middleware registry.

A Starter Example with a Database Dependency

Let us look at a slightly more realistic example. Suppose you have a handler that needs to query a database. In many frameworks, you might use a global connection pool variable that the handler reaches into. In Axum, you pass the pool explicitly through state.

First, define a simple mock database pool. In a real project you would use a library like sqlx, but for this lesson we will keep it minimal.

use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::Arc;
#[derive(Clone)]
struct Database {
    // In reality, this would hold a connection pool.
    connection_string: String,
}
impl Database {
    fn fetch_user(&self, id: u32) -> Option<String> {
        // Pretend this queries a database.
        if id == 1 {
            Some("Alice".to_string())
        } else {
            None
        }
    }
}
#[derive(Clone)]
struct AppState {
    db: Database,
}
async fn get_user(
    State(state): State<Arc<AppState>>,
    axum::extract::Path(user_id): axum::extract::Path<u32>,
) -> String {
    match state.db.fetch_user(user_id) {
        Some(name) => format!("User found: {}", name),
        None => "User not found".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        db: Database {
            connection_string: "postgres://localhost/mydb".to_string(),
        },
    });
    let app = Router::new()
        .route("/users/{user_id}", get(get_user))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Look at the get_user handler. Its signature says: "I need State<Arc<AppState>> and Path<u32>." The AppState contains a Database. So the handler depends on a database, and that dependency is visible immediately. You can test this handler by creating a mock Database and passing it inside a test AppState - no changes to the handler required.

Explicitness Does Not Mean Repetition:

You might think writing State<Arc<AppState>> every time is noisy. In practice, you can define a type alias like type AppState = Arc<MyState> and then use State<AppState>. The key point is that the dependency remains visible, not hidden.

Three Ways to Pass Dependencies Explicitly

Axum offers multiple ways to make a dependency available to a handler. Each way is explicit, but the trade-offs differ. The most common methods are:

  1. State extractor - type-safe, checked at compile time.
  2. Closure captures - you directly pass the dependency when defining the route.
  3. Extension extractor - more dynamic, checked at runtime.

For a single handler, you will choose one of these. The following tabs show the same handler using each approach. Read through them and notice how the dependency is made visible in each case.

use axum::{
    extract::State,
    routing::get,
    Router,
};
use std::sync::Arc;
#[derive(Clone)]
struct Database;
impl Database {
    fn new() -> Self {
        Self
    }
}
#[derive(Clone)]
struct AppState {
    db: Database,
}
async fn get_user(State(state): State<Arc<AppState>>) -> String {
    // use state.db
    let _ = state;
    String::new()
}
fn build_app() -> Router {
    Router::new()
        .route("/user", get(get_user))
        .with_state(Arc::new(AppState { db: Database::new() }))
}

The handler declares State<Arc<AppState>> directly. The router provides the state with .with_state(). The compiler ensures the types match, and the state is cheap to clone because it is wrapped in Arc.

Each method has its place. The State extractor is the recommended default because it gives compile-time guarantees. Closure captures are useful when you need to pass a dependency that is not part of the global application state, perhaps a per-router value. Extensions are useful for middleware that needs to attach request-scoped data later in the request lifecycle.

Extension Errors Appear at Runtime:

If you use Extension and forget to add the layer, your handler will compile fine but every request will return a 500 Internal Server Error. That error is harder to catch than the compile-time error you get with State. Use State whenever possible.

Making Service Dependencies Explicit with Traits

Explicitness becomes even more valuable when you have handlers that depend on business logic services, not just data. Suppose you have a user service that fetches users from a database. You want the handler to depend on an abstraction (a trait) so you can swap implementations for testing.

Axum lets you pass any type as state, including trait objects and structs that implement a trait. The handler still declares its dependency explicitly.

This example uses the async-trait crate: a trait with an async fn method cannot be turned into a trait object with plain Rust, because the future the method returns has no nameable type. Add the crate first with cargo add async-trait.

First, define a trait for the service.

use async_trait::async_trait;
use std::sync::Arc;
#[async_trait]
pub trait UserService: Send + Sync {
    async fn get_user(&self, id: u32) -> Option<User>;
}
pub struct User {
    pub id: u32,
    pub name: String,
}

Now create a real implementation.

pub struct DatabaseUserService {
    // database connection pool here
}
#[async_trait]
impl UserService for DatabaseUserService {
    async fn get_user(&self, id: u32) -> Option<User> {
        // real database query
        Some(User {
            id,
            name: "Alice".to_string(),
        })
    }
}

Then define the application state to hold a boxed or Arc trait object.

#[derive(Clone)]
pub struct AppState {
    pub user_service: Arc<dyn UserService>,
}

Finally, the handler depends on State<AppState> and calls the service through the trait.

use axum::{extract::State, routing::get, Router};
async fn get_user(
    State(state): State<AppState>,
    axum::extract::Path(user_id): axum::extract::Path<u32>,
) -> String {
    match state.user_service.get_user(user_id).await {
        Some(user) => format!("User: {}", user.name),
        None => "Not found".to_string(),
    }
}
fn build_router(service: Arc<dyn UserService>) -> Router {
    let app_state = AppState { user_service: service };
    Router::new()
        .route("/users/{id}", get(get_user))
        .with_state(app_state)
}

Now you can build the router with the real service in production, or with a mock service in tests.

fn main() {
    // Production
    let real_service = Arc::new(DatabaseUserService {});
    let app = build_router(real_service);
    let _ = app;
    // Test
    struct MockUserService;
    #[async_trait]
    impl UserService for MockUserService {
        async fn get_user(&self, _id: u32) -> Option<User> {
            Some(User { id: 1, name: "Test User".to_string() })
        }
    }
    let mock_service = Arc::new(MockUserService);
    let app_for_tests = build_router(mock_service);
    let _ = app_for_tests;
}

The handler did not change between production and test. The dependency on UserService is explicit in the AppState type, and the concrete implementation is swapped at the router construction site. This is the essence of explicit dependency management.

Common Misconceptions About Explicit Dependencies

Beginners sometimes push back on the idea of explicit dependencies because it feels like more typing. Let us address the most common misunderstandings.

"Global state is simpler"

A global variable holding a database pool is tempting because you can access it from anywhere without passing parameters. But then the dependency is hidden. A handler that uses a global pool does not show that dependency in its signature. To test that handler in isolation, you have to set up the global variable before running the test, and you risk tests interfering with each other if the global is mutable. Axum's explicit state avoids these problems.

"Explicit means verbose"

Explicit code often has a few more characters, but it is not verbose in the sense of unnecessary repetition. The type aliases and with_state calls are placed once per router. Inside handlers, the State<AppState> parameter is a clear contract. The time you save later by not debugging hidden state issues far outweighs the extra keystrokes.

"Extensions are just as good as State"

As shown earlier, Extension has weaker type safety and fails at runtime. Use it only when you need to attach data later in the request pipeline (for example, from middleware that authenticates a user and stores the user ID). For application-wide shared state, State is the right tool.

Do Not Mix State and Extensions for the Same Dependency:

If you pass the same dependency sometimes via State and sometimes via Extension, you create two ways to access it. That is a form of hidden coupling because a handler might use one method while the router provides the other, and you only find out at runtime (for Extension) or compile time (for State). Pick one mechanism per dependency and stick with it.

How Explicit Dependencies Shape a Growing Application

In a small example with one handler, explicit dependencies might not seem important. But as an Axum application grows, the explicitness becomes the backbone of maintainability.

Imagine you have 50 handlers. Some need the database, some need a Redis cache, some need an external email service, and some need all three. With Axum's state pattern, you can group related dependencies into a single AppState struct, and each handler takes State<AppState>. You can see which handlers use the state by looking at their signatures. If you later split the application into separate modules, each module's router can be given a subset of the state using FromRef (which we touched on earlier), preserving explicitness across module boundaries.

The alternative - a hidden service locator or global registry - makes it impossible to know what a handler touches without reading every line. That becomes a maintenance nightmare.

What axum::serve and the Real Dependency Surface Look Like

So far this page has talked about dependencies in your own code. The framework itself has an explicit dependency surface too, and it is worth naming it correctly, because beginners often guess it wrong.

axum::serve is not a thin wrapper around hyper's serve_connection and TokioIo. It is a small helper that builds a Serve future around a tokio::net::TcpListener you create yourself: you bind the listener with Tokio, hand it to axum::serve(listener, app), and the returned Serve future accepts connections, wraps each accepted stream for hyper-util's connection builders, and drives your router. Internally it uses hyper-util's TokioIo and TokioExecutor adapters - those live in the hyper-util crate, not in hyper itself - but you never call them directly when you use axum::serve. It is intentionally simple: the only configuration knobs are .with_graceful_shutdown(...), .with_executor(...), and .connection_lifetime_limits(...). (TCP_NODELAY is already set on accepted connections; use ListenerExt::tap_io to change it.) If you need custom connection handling, use hyper or hyper-util directly.

Axum also does not re-export hyper, tokio, or tower as public modules. What it does re-export is the http crate (as axum::http) and pieces of http-body-util through axum::body. The listener in every example on this page is a tokio::net::TcpListener, imported from Tokio itself - you add tokio as your own dependency, with axum = "0.8" (latest 0.8.9, 14 April 2026, MSRV Rust 1.80) and tokio = "1" (latest 1.54.1) in Cargo.toml.

The real dependency surface of an Axum application is the workspace of crates around axum itself:

  • axum - routing, handlers, extractors, axum::serve, the Json/Form extractors.
  • axum-core - the shared foundation (IntoResponse, FromRequest, the body type) that axum and axum-extra both build on.
  • axum-extra - optional extras that are not in axum itself, such as TypedHeader, CookieJar, TypedPath, and the multi-value Query extractor.
  • axum-macros - the small set of macros Axum does have, notably #[debug_handler] (for readable handler errors) and #[derive(FromRef)].
  • tokio - the async runtime; hyper (latest 1.12.0) - the HTTP engine underneath; tower / tower-http (latest 0.7.1) - the Service/Layer middleware ecosystem.

Feature flags you will actually meet

Axum keeps optional pieces behind Cargo feature flags, so a plain axum = "0.8" does not compile everything:

FeatureDefault?What it enables
http1YesHTTP/1.1 support in axum::serve
http2NoHTTP/2 support in axum::serve
jsonYesThe Json extractor and response type
formYesThe Form extractor
queryYesThe Query extractor
matched-pathYesThe MatchedPath extractor
original-uriYesThe OriginalUri extractor
tokioYesaxum::serve, SSE, and ConnectInfo
multipartNoThe Multipart extractor
wsNoWebSocket support (axum::extract::ws) - without it, a WebSocket handler does not compile
tracingYesTracing instrumentation inside Axum itself
tower-logNoEnables tower's log feature, so TraceLayer can emit log records
macrosNoEnables the axum-macros crate: #[debug_handler] and #[derive(FromRef)]

If a snippet on another page fails to compile with "unresolved import" or "not found in axum", check this table first: the item you need is often behind an opt-in feature, or lives in axum-extra rather than in axum itself.

Summary and What Comes Next

Explicit dependency surface is not a single feature; it is a design philosophy that runs through every part of Axum. Handlers declare what they need in their parameters. Routers declare what they provide in their construction. The compiler checks that declarations match provisions. This creates a tight feedback loop: when you change a dependency, you immediately see every place that needs updating.

The single most important insight from this lesson is: in Axum, if a handler needs something, it says so out loud. That transparency is what makes Axum code approachable, testable, and safe to refactor as your application grows.

This topic leads naturally into understanding how Axum handles errors, because explicit dependencies also make error paths more predictable. When a handler cannot get what it needs, the failure happens early and visibly, not as a mysterious null pointer deep in application logic.