The layer Method in Axum

How the layer method attaches Tower middleware to a Router, a MethodRouter, or a single handler, how ordering and scope work, and how to handle middleware that can fail

What the layer method does

The layer method is the call that attaches middleware to a part of your Axum application. Middleware is code that runs around a handler. A handler is the async function that answers a request and produces a response. Middleware gets a chance to look at the request before the handler runs, and to look at the response after the handler finishes. Logging, timeouts, compression, and adding headers are all jobs that middleware does.

Axum does not have a middleware system of its own. It borrows the one from Tower. Tower is a Rust library for building reusable pieces that wrap services, and tower-http is a companion library full of ready-made HTTP middleware. A layer is one such reusable piece. A layer is a value that knows how to wrap a service and return a new service with extra behaviour. The layer method is the connection point between your routes and that world. You hand it a layer, and it wraps the routes you point it at.

Think of a layer as a sleeve you slide over a pipe. The water still flows through the same pipe, but the sleeve can warm it, filter it, or shut it off. The handler is the pipe. The layer is the sleeve. The layer method is how you slide the sleeve on.

There are three places you can call layer, and they differ only in how much of your application the sleeve covers. You can call it on a whole Router, on a MethodRouter, or on one handler. A Router holds all the routes of your application or of one group of routes. A MethodRouter holds the handlers for one path, such as /items, across the HTTP methods on that path, such as GET and POST. A handler is a single async function. The rest of this page walks through each place in turn, then through ordering, then through the mistakes that catch beginners.

A first example with Router layer

Start with the smallest program that shows layer doing something visible. It adds a timeout to every route in a router. A timeout is a time limit. If the handler finishes inside the limit, the response passes through as normal. If the handler takes too long, the timeout middleware answers with a 408 Request Timeout response instead of waiting forever.

src/main.rs
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower_http::timeout::TimeoutLayer;

async fn slow_handler() -> &'static str {
    tokio::time::sleep(Duration::from_secs(3)).await;
    "This response took a while."
}

async fn fast_handler() -> &'static str {
    "This response was quick."
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/slow", get(slow_handler))
        .route("/fast", get(fast_handler))
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(2),
        ));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The program builds a router with two routes and then calls .layer(...) on the router. Both routes were added before the layer call, so both are wrapped. The layer itself comes from the tower-http crate, so the project needs that crate as well as axum and tokio.

Cargo.toml
[package]
name = "layer-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = "0.5"
tower-http = { version = "0.7", features = ["timeout"] }

Run the program with cargo run and open the two paths in a browser or with curl. A request to /fast returns 200 OK with the text This response was quick. A request to /slow takes about two seconds and then returns 408 Request Timeout, because the handler needs three seconds and the limit is two. The handler itself never learns that a timeout exists. It keeps sleeping, but its answer is thrown away and the client gets the timeout response instead. That separation is the whole point of middleware. The timing rule lives in one place, and the handlers stay plain.

Two timeout layers with similar names:

Tower and tower-http each have a layer called TimeoutLayer, and they behave differently. The tower-http one used above is infallible, which means it can never produce an error. It builds the 408 response itself. The tower one produces an error instead of a response, and that error has to be converted into a response by other means.

You are on the right track:

If /fast returns its text and /slow returns a 408 after about two seconds, the layer is attached correctly. If both routes return their text with no timeout, check that the .layer(...) call comes after the .route(...) calls, and check that the timeout feature is enabled in Cargo.toml, because a missing feature makes the import fail at compile time rather than silently doing nothing.

The three places you can call layer

The same layer method behaves differently depending on what you call it on. The word for this is scope, and scope means how much of your application the middleware touches. Picking the right scope matters more than picking the middleware itself, because a timeout on the wrong scope either protects routes that do not need it or misses the route that does. The three scopes, from widest to narrowest, are the router, the method router, and the handler.

Router layer applies to every route already in the router

Calling layer on a Router wraps every route that was already added to that router before the call. It also wraps the fallback, which is the handler that answers when no route matches, if a fallback was already set. The example below adds a tracing layer to a router with two routes. Tracing is a way of recording what a request did, using the tracing crate, and TraceLayer is the tower-http layer that records one span per request.

src/main.rs
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;

async fn home() -> &'static str {
    "Home page"
}

async fn about() -> &'static str {
    "About page"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/about", get(about))
        .layer(TraceLayer::new_for_http());

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Both routes were added before .layer(...), so both get the tracing middleware. A request to either path is recorded by the tracing layer before it reaches the handler, and the response is recorded on the way back out. This scope fits a policy that belongs to a whole group of routes. Every route in an API group should have a timeout, every route in an admin group should require a login check, and every route in a public group should be traced. One layer call on the router expresses that policy once, instead of repeating it on every route.

Cargo.toml
[package]
name = "layer-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = "0.5"
tower-http = { version = "0.7", features = ["trace"] }
tracing-subscriber = "0.3"

The Cargo.toml above adds tracing-subscriber, because TraceLayer records its spans through the tracing system and nothing prints without a subscriber that listens for those spans. Add tracing_subscriber::fmt().init(); as the first line of main if you want to see the spans in the terminal. Without it the program still runs, and the layer still wraps the routes, but the recorded spans have nowhere to go.

MethodRouter layer applies to one path across its methods

A MethodRouter is the value you get from writing get(handler) or post(handler). It matches one path, and it holds the handlers for the HTTP methods registered on that path. Calling layer on a method router wraps every method handler attached to that path at the time of the call. The example below puts a timeout on the /items path, where a GET lists items and a POST creates one.

src/main.rs
use axum::{
    http::StatusCode,
    routing::{get, post},
    Router,
};
use std::time::Duration;
use tower_http::timeout::TimeoutLayer;

async fn list_items() -> &'static str {
    "List of items"
}

async fn create_item() -> &'static str {
    "Item created"
}

#[tokio::main]
async fn main() {
    let items_route = get(list_items)
        .post(create_item)
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(5),
        ));

    let app = Router::new().route("/items", items_route);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The timeout applies to both the GET /items handler and the POST /items handler, because the layer is attached to the method router that contains both. A request to either method gets the same five second limit. If a new method were added to the same method router after the layer call, that new handler would not get the layer, for the same reason a route added after a router level layer call misses out. The layer wraps what exists at the moment it is called.

This scope fits a policy that belongs to one endpoint rather than a whole group. An upload endpoint might need a larger body limit than the rest of the application, or a search endpoint might need a shorter timeout than the rest, and both its GET and POST handlers should share that rule. The Cargo.toml for this example is the same as the first example on this page, with the timeout feature of tower-http enabled.

Handler layer applies to one handler only

The Handler trait itself has a layer method. A trait in Rust is a set of methods that a type promises to provide, and every async function that can act as an Axum handler implements the Handler trait. Calling .layer(...) on a handler function wraps that one function before it is turned into a route. The result is a handler that carries its middleware with it wherever it goes.

src/main.rs
use axum::{
    handler::Handler,
    http::{HeaderName, HeaderValue},
    routing::get,
    Router,
};
use tower_http::set_header::SetResponseHeaderLayer;

async fn expensive_report() -> &'static str {
    "Report generated"
}

async fn home() -> &'static str {
    "Home page"
}

#[tokio::main]
async fn main() {
    let layered_report = expensive_report.layer(SetResponseHeaderLayer::overriding(
        HeaderName::from_static("x-report"),
        HeaderValue::from_static("v1"),
    ));

    let app = Router::new()
        .route("/", get(home))
        .route("/report", get(layered_report));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Only the /report handler carries the extra header layer. A request to /report gets a response with an x-report: v1 header added, while a request to / gets a plain response with no such header. The layer used here, SetResponseHeaderLayer, sets one header on every response that passes through it, and the overriding form replaces the header if the handler already set it. This is the narrowest scope available, and it fits the case where exactly one handler needs special treatment that the rest of the router does not.

One detail in the code deserves attention. The Handler trait has to be imported with use axum::handler::Handler; before .layer(...) works on a plain function. Without that import the compiler reports that no method named layer exists, even though the function is a valid handler. The import is what brings the trait method into scope. The Cargo.toml for this example enables the set-header feature of tower-http.

The same middleware works at every scope:

TimeoutLayer, TraceLayer, and SetResponseHeaderLayer all work at all three levels. The middleware does not care which layer method you used. The scope decides how much of your application the middleware touches, and nothing else changes about how the middleware itself behaves.

How ordering works when you chain layer calls

Ordering is the part of layer that surprises beginners most often. When you call layer more than once in a chain, the middleware does not run in the order you wrote the calls. It runs like an onion. Each new layer wraps everything that came before it, so the last layer you added becomes the outermost layer. It sees the request first and the response last. The first layer you added sits closest to the handler, so it sees the request last and the response first.

A plain text picture of a chain with two layers, first added before second, looks like this.

request comes in
  second sees the request
    first sees the request
      handler runs and builds a response
    first sees the response
  second sees the response
response goes out

The following program makes that order visible. It builds two small pieces of middleware with from_fn, which turns an async function into a layer. Each one prints a line when the request passes through it and another line when the response comes back. The handler prints nothing, so every line in the terminal comes from the middleware.

src/main.rs
use axum::{
    extract::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

async fn first(request: Request, next: Next) -> Response {
    println!("first sees the request");
    let response = next.run(request).await;
    println!("first sees the response");
    response
}

async fn second(request: Request, next: Next) -> Response {
    println!("second sees the request");
    let response = next.run(request).await;
    println!("second sees the response");
    response
}

async fn hello() -> &'static str {
    "hello"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(hello))
        .layer(middleware::from_fn(first))
        .layer(middleware::from_fn(second));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Run it and request / once. The terminal prints four lines, in this exact order.

second sees the request
first sees the request
first sees the response
second sees the response

The second middleware was added last, so it is outermost and meets the request first. The first middleware was added first, so it sits next to the handler and meets the response first on the way back out. The Cargo.toml for this example needs only axum and tokio, because from_fn is part of Axum itself and no tower-http layer is used.

Your chain order is not your execution order:

If you write .layer(A).layer(B), a request meets B first, then A, then the handler. The response leaves the handler through A and then B. This is the opposite of what many people expect when reading the code from top to bottom, and it is the most common source of ordering confusion on this page. When the order matters, run the program and read the printed lines instead of guessing from the chain.

The onion picture also explains why ordering matters in real applications. A logging layer placed outside an auth layer records every request, including ones the auth layer refuses. An auth layer placed outside a logging layer means refused requests never reach the logger. Neither order is wrong in general. The right order depends on which behaviour you want, and the onion model is how you predict it before running anything.

Two ways to apply multiple layers

Chaining .layer(...) calls works, but the official Axum documentation recommends tower::ServiceBuilder when you have more than one or two layers. ServiceBuilder is a helper from Tower that collects layers into a single combined layer. It flips the ordering so the first layer you list is the first one to receive the request, which matches the way most people read code from top to bottom.

Here is the same pair of layers written both ways, so the difference is easy to see. The first version chains two layer calls on the router.

src/main.rs
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower_http::{timeout::TimeoutLayer, trace::TraceLayer};

async fn handler() -> &'static str {
    "Hello"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(5),
        ))
        .layer(TraceLayer::new_for_http());

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

In the chained version, TraceLayer was added last, so it is outermost and sees the request first. TimeoutLayer was added first, so it sits closer to the handler and sees the response first. Now the same two layers inside a ServiceBuilder.

src/main.rs
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::{timeout::TimeoutLayer, trace::TraceLayer};

async fn handler() -> &'static str {
    "Hello"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(TimeoutLayer::with_status_code(
                    StatusCode::REQUEST_TIMEOUT,
                    Duration::from_secs(5),
                )),
        );

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Inside the builder, TraceLayer is listed first and it runs first on the request. TimeoutLayer is listed second and runs second. The response travels back in the reverse order, through the timeout layer first and then the tracing layer. Both versions build the same stack in the end, and both are valid. The builder version is easier to read when the stack grows, because the order on the screen matches the order of execution. Pick one style for a project and stay with it, so nobody on the team has to mentally reverse the order every time they read the code.

Cargo.toml
[package]
name = "layer-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = "0.5"
tower-http = { version = "0.7", features = ["timeout", "trace"] }

The Cargo.toml above is shared by both versions. The timeout feature of tower-http provides its TimeoutLayer, and the trace feature provides TraceLayer. If either feature is missing, the corresponding import fails to compile, which is a useful signal, because it tells you exactly which piece is absent instead of failing quietly at runtime.

A quick ordering check:

If your middleware does not seem to run in the order you expect, add a temporary println! inside each middleware, as in the ordering example above. The order of the printed lines shows exactly how the layers are nested, and that beats staring at the chain and guessing.

The most common mistake, routes added after layer

The layer method only wraps routes that already exist when it is called. If you add routes after calling layer, those later routes will not have the middleware. This is the single most common mistake with layer, and it is dangerous precisely because nothing goes wrong visibly. The application compiles and runs, and the later routes answer requests normally. They simply skip the middleware, which can mean a route runs without logging, without a timeout, or without an auth check, and nobody notices until much later.

src/main.rs
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;

async fn first() -> &'static str {
    "First"
}

async fn second() -> &'static str {
    "Second"
}

#[tokio::main]
async fn main() {
    // This is wrong. The second route is not wrapped in TraceLayer.
    let app = Router::new()
        .route("/first", get(first))
        .layer(TraceLayer::new_for_http())
        .route("/second", get(second));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

In this program, /first is traced and /second is not, because /second was added after the layer call. The fix is to move every route call before the layer call, so the layer sees the finished set of routes.

src/main.rs
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;

async fn first() -> &'static str {
    "First"
}

async fn second() -> &'static str {
    "Second"
}

#[tokio::main]
async fn main() {
    // This is correct. Both routes are added before the layer.
    let app = Router::new()
        .route("/first", get(first))
        .route("/second", get(second))
        .layer(TraceLayer::new_for_http());

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The same rule applies to the other scopes. A method added to a method router after its layer call misses the layer, and a handler wrapped after it is registered is a different handler from the one the router holds. The practical habit is simple. Finish the routes first, then add the layers last, at the end of the chain. When a router grows and a new route is added weeks later, add it above the layer call, not below it.

Routes added after layer are invisible to the middleware:

There is no warning or error when this happens. The application compiles and runs, and the later routes work normally. They simply skip the middleware. Always finish adding routes before calling layer on a router or a method router, and check the order again whenever a new route is added to an existing router.

What layer runs on, and what it cannot change

A layer added with Router::layer runs after routing has already happened. Routing is the step where Axum looks at the request path and method and decides which handler should answer. The middleware therefore cannot change which route matches. A layer that rewrites the request path cannot change the routing decision from inside Router::layer, because by the time it runs, the route has already been chosen. The rewrite still changes the URI the handler sees, just not which handler runs. A layer that needs to see the request before routing must wrap the whole router from the outside instead, which is a different construction from the one this page teaches.

The same after-routing position has a second consequence that surprises people. A layer on a router runs even when no route matches. A request to an unknown path still passes through the router level layers before Axum answers with 404 Not Found. That is usually what you want for logging, because a log that misses every mistyped URL is a log with a hole in it. It is not what you want for an auth check that should only guard real routes, and that is why a different method exists for the matched-only case. The point here is only that Router::layer is broad by design. It wraps the whole router, including its fallback and its unmatched paths.

A third fact about layer in Axum 0.8 concerns timing. For normal routes added with route, the layer is applied again for each request, so a fresh service is built per request. A service is the Tower object that actually handles one request, and the layer is the recipe for building it. Because the service is rebuilt each time, anything stored inside the service itself does not survive from one request to the next. State that must be shared between requests has to live behind an Arc held by the layer, so each fresh service shares the same underlying data. An Arc is a reference counted pointer that lets several owners share one value, and it is the standard tool for sharing state across requests in Rust. A plain counter field on a layer struct would not keep counting across requests, because each request works with a fresh clone of the layer, while a counter behind an Arc keeps counting.

Layers are also cloned. Axum clones the layer when it builds those per-request services, so a layer should be cheap to clone. That is another reason to keep shared data behind an Arc and keep the layer struct itself small. A layer that holds a large owned value would copy that value on every request, while a layer that holds an Arc to it copies only the pointer.

Do not keep request-counting state in the service:

If a custom layer keeps a counter or a cache in the service it builds, that counter resets on every request in Axum 0.8, because the service is rebuilt per request. Put shared state in the layer itself, behind an Arc, so every rebuilt service points at the same data. This is the same reason the standard layers keep their shared pieces, such as a semaphore or a counter, behind an Arc inside the layer.

Middleware that can fail needs error handling

Some middleware can produce an error instead of a response. Axum requires every request to end with a response, because the HTTP server underneath, hyper, closes a connection without answering if it receives an error. Middleware is one way errors can enter an application, so those errors have to be turned into responses before they reach hyper. The tool for that is HandleErrorLayer, which lives at axum::error_handling::HandleErrorLayer. It wraps a fallible layer and converts its errors into responses using a function you supply.

The classic example uses the tower TimeoutLayer, which is the fallible one. When its time limit passes, it produces an error of type BoxError, which is a boxed error that can hold any error type. The example below catches that error and turns it into a 408 Request Timeout response.

src/main.rs
use axum::{
    error_handling::HandleErrorLayer,
    http::StatusCode,
    routing::get,
    BoxError, Router,
};
use std::time::Duration;
use tower::{timeout::TimeoutLayer, ServiceBuilder};

async fn slow() -> &'static str {
    tokio::time::sleep(Duration::from_secs(3)).await;
    "Finished in time"
}

async fn fast() -> &'static str {
    "Finished quickly"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/slow", get(slow))
        .route("/fast", get(fast))
        .layer(
            ServiceBuilder::new()
                .layer(HandleErrorLayer::new(|_error: BoxError| async {
                    StatusCode::REQUEST_TIMEOUT
                }))
                .layer(TimeoutLayer::new(Duration::from_secs(1))),
        );

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Run it and request both paths. /fast returns 200 OK at once. /slow returns 408 Request Timeout after about one second, because the tower timeout fires, produces its error, and the HandleErrorLayer outside it converts that error into the 408 response. The placement matters. Inside the ServiceBuilder, HandleErrorLayer is listed first, so it is outermost and wraps the timeout layer. An error handler can only catch errors from layers inside it, so listing it after the timeout layer would leave the error uncaught.

Cargo.toml
[package]
name = "layer-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["timeout"] }

The Cargo.toml needs the timeout feature of tower here, because the tower TimeoutLayer is the one being used. The closure given to HandleErrorLayer::new receives the error and returns anything that can be turned into a response. A bare StatusCode works, and so would a fuller response with a body explaining the timeout. The underscore in front of _error marks the error as intentionally unused, which keeps the compiler from warning about an unused variable.

Two facts about this example are easy to get wrong, so they are worth stating plainly. First, this pattern only works because the HandleErrorLayer and the timeout are combined into one layer by the ServiceBuilder before being handed to Router::layer. The combined service never produces an error, because the error handler converts every error into a response, and that is what Router::layer accepts. Second, the tower-http TimeoutLayer from the first example on this page must not be paired with a HandleErrorLayer in this way. It is infallible and returns a 408 itself, so there is no error for a handler to convert, and the types do not fit together.

A fallible layer directly on Router layer does not compile:

Applying the tower TimeoutLayer straight to Router::layer, with no HandleErrorLayer around it, fails at compile time with error E0277, because its BoxError cannot be converted into the infallible error type that Router::layer requires. That compile error is the compiler protecting you. It means the failure mode of an unhandled middleware error cannot happen through Router::layer at all. It can only happen when a fallible layer is placed outside the router, which is exactly the situation the ServiceBuilder example above handles.

The general rule follows from the example. If a layer can produce an error, wrap it in a HandleErrorLayer that sits outside it, and combine the two before handing them to Router::layer. If a layer is infallible, which covers TraceLayer, SetResponseHeaderLayer, and the tower-http TimeoutLayer, no error handling is needed, because there is no error to handle.

The concurrency limit that does not limit

ConcurrencyLimitLayer looks like the answer to a common problem. It takes a number, and its name promises that at most that many requests run at the same time. In a plain Tower service, that promise holds. In an Axum application, it does not, and the reason is how Axum handles backpressure. Axum assumes the services it routes to do not care about backpressure, so a route always reports that it is ready to receive a request. A permit based limiter works by reporting that it is not ready when all permits are taken, and the router never asks it, so the permits never gate anything.

That was measured, not guessed. With a limit of one and two concurrent requests to a handler that sleeps for 300 milliseconds, both requests ran in parallel inside Axum. The total time was about 300 milliseconds, and two requests were in flight at once, whether the layer was applied with Router::layer or wrapped around the whole application. The same layer on a plain Tower service without Axum routing in between serialized the requests correctly, taking about 600 milliseconds. The layer itself is fine. The Axum router simply never gives it a chance to say no.

There is a second misunderstanding to clear up at the same time. ConcurrencyLimit can never reject a request. When no permit is free, it waits for one. It has no path that answers early with an error. Immediate rejection on overload is a different layer's job, and it works by returning an error as soon as the inner service is not ready, which is why it also needs error handling around it.

If you need a real cap on how many requests run at once inside Axum, enforce it where the work happens, not in a layer around the router. A semaphore held in shared state does the job, because the handler itself waits for a permit before doing the work. A semaphore is a counter that hands out a fixed number of permits, and a task that cannot get one waits until a permit is returned.

src/main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Semaphore;

#[derive(Clone)]
struct AppState {
    permits: Arc<Semaphore>,
}

async fn work(State(state): State<AppState>) -> &'static str {
    let _permit = state.permits.acquire_owned().await.unwrap();
    tokio::time::sleep(Duration::from_millis(300)).await;
    "done"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(work))
        .with_state(AppState {
            permits: Arc::new(Semaphore::new(1)),
        });

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The state holds a semaphore with one permit, wrapped in an Arc so every request shares the same counter. The handler takes a permit before sleeping, and the permit is returned automatically when _permit goes out of scope at the end of the handler. Two concurrent requests to this handler take about 600 milliseconds in total, because the second one waits for the first to finish and return its permit. That is the serialized behaviour the layer name seemed to promise. The Cargo.toml for this example needs only axum and tokio, because the semaphore comes from Tokio itself.

Do not rely on ConcurrencyLimitLayer inside Axum routing:

Do not use ConcurrencyLimitLayer to cap how many requests run at once in an Axum application. Axum routing does not propagate backpressure to layered services, so a permit based limiter cannot gate requests the way its name suggests. If the cap matters, enforce it inside the handler with a semaphore, as above, or in the service behind the router.

A realistic combination, different layers for different groups

Real applications rarely use one layer in isolation, and they rarely give every route the same treatment. A common shape is two groups of routes built separately, each with its own layers, and then merged into one application. Merging combines two routers into one, keeping each group's routes and layers intact. The example below builds a public group and a reports group. The public group gets only tracing. The reports group gets a timeout with error handling, because report generation is slow, and a header on the single expensive handler, because that handler's responses carry a version marker.

src/main.rs
use axum::{
    error_handling::HandleErrorLayer,
    handler::Handler,
    http::{HeaderName, HeaderValue, StatusCode},
    routing::get,
    BoxError, Router,
};
use std::time::Duration;
use tower::{timeout::TimeoutLayer, ServiceBuilder};
use tower_http::{set_header::SetResponseHeaderLayer, trace::TraceLayer};

async fn public_handler() -> &'static str {
    "Public content"
}

async fn report_handler() -> &'static str {
    tokio::time::sleep(Duration::from_millis(100)).await;
    "Report content"
}

#[tokio::main]
async fn main() {
    let public_routes = Router::new()
        .route("/public", get(public_handler))
        .layer(TraceLayer::new_for_http());

    let report_routes = Router::new()
        .route(
            "/reports",
            get(report_handler.layer(SetResponseHeaderLayer::overriding(
                HeaderName::from_static("x-report"),
                HeaderValue::from_static("v1"),
            ))),
        )
        .layer(
            ServiceBuilder::new()
                .layer(HandleErrorLayer::new(|_error: BoxError| async {
                    StatusCode::REQUEST_TIMEOUT
                }))
                .layer(TimeoutLayer::new(Duration::from_secs(10))),
        );

    let app = Router::new().merge(public_routes).merge(report_routes);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /public passes through the tracing layer and then the handler, and gets a 200 OK with the text Public content. A request to /reports passes through the timeout layer first, then the handler level header layer, then the handler itself. The handler sleeps for a tenth of a second, well inside the ten second limit, so the response is 200 OK with the text Report content and an x-report: v1 header. If the report ever took longer than ten seconds, the tower timeout would fire, the error handler would convert the error, and the client would get a 408 Request Timeout instead. The header layer sits inside the timeout layer, so a timed out response never passes through it, and no x-report header appears on the 408.

Cargo.toml
[package]
name = "layer-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["timeout"] }
tower-http = { version = "0.7", features = ["trace", "set-header"] }
tracing-subscriber = "0.3"

The Cargo.toml collects every feature the example uses. Tower supplies the timeout feature for its TimeoutLayer. Tower-http supplies trace for TraceLayer and set-header for SetResponseHeaderLayer. Nothing else is needed, and each feature maps to exactly one import in the program, so a missing feature points straight at the layer that needs it. This shape scales well. A new group of routes gets its own router, its own layers, and one more merge call, and the groups never interfere with each other.

Choosing between the three scopes

The decision is mostly about how much of your application should share the middleware, so use the narrowest scope that solves the problem. A policy that belongs to a group of routes goes on the router. A policy that belongs to one path across its methods goes on the method router. A policy that belongs to exactly one handler goes on the handler. That rule keeps middleware from leaking onto routes that do not need it, and it keeps the intent visible in the code, because the reader can see how wide each policy reaches just by looking at where layer was called.

Scopes combine freely. A router can carry a timeout for a whole group while one handler inside it carries an extra header layer of its own. The middleware stack for that handler then includes both layers, with the handler level layer sitting closer to the handler and the router level layer sitting further out. The onion ordering applies across scopes in the same way it applies within one chain. The outermost layer, whichever scope it came from, sees the request first.

Two checks catch most scope mistakes before they reach production. First, read the chain from the bottom up and ask whether every route that needs the policy sits above the layer call. Second, send one request to each route and confirm the middleware actually ran, whether that means checking a header, reading a log line, or watching for a timeout. A policy that is attached to the wrong scope fails silently, so the check has to be a real request, not a reading of the code.

Scope is a design choice, not a performance choice:

Picking a narrower scope does not make an application faster in any way a beginner needs to care about. The layers run the same code either way. Pick the scope that matches the policy, because the next person reading the code will understand the intent from the scope alone.

Summary

The layer method looks small, and that is deceptive, because three decisions hide inside every call to it. The first decision is scope, which is how much of the application the middleware touches. The second decision is order, which is where the layer sits in the onion and therefore whether it sees the request before or after its neighbours. The third decision is failure, which is whether the layer can produce an error and, if it can, what response that error becomes. Scope, order, and failure are independent. A layer can be wide and infallible, narrow and fallible, or any other combination, and each choice is made in a different place in the code.

That split is the decision framework to carry forward. When adding middleware, ask the three questions in order. Which routes need this, and no more. Where does it sit relative to the layers already there, and does the request order that produces match what you want. Can it fail, and if it can, is there an error handler outside it that turns the failure into a response. If all three answers are clear, the layer call that follows writes itself, and the habits that support it are short. Add routes before layers, prefer a builder when the stack grows past two layers, and test with a real request instead of trusting the shape of the chain. Those habits, plus the three questions, cover every use of layer this page teaches, and they are the same habits that make larger middleware stacks stay readable as an application grows.