Layer trait in Axum middleware
Learn what the Tower Layer trait is, how it builds Services, and how to write configurable middleware layers in Axum with working examples
A service does the work. It receives a request and returns a response. But a service does not build itself. Somebody has to take the handler service, wrap it in a logging service, wrap that in an authentication service, and hand the finished chain to the server. That somebody is a layer.
A layer is a factory for services. You give it an inner service, and it gives you back a new service that wraps the inner one with extra behavior. You have already seen this idea in action without naming it. Every time you write .layer(...) on a router, you are handing Axum a layer, and Axum calls that layer to build the service that will handle requests. This page teaches the Layer trait from the ground up, so you can read any middleware, understand how it plugs in, and write your own layers when the ready-made ones do not fit.
What a Layer is and what problem it solves
Imagine you have a handler that returns a user profile. You want to add logging around it, so every request gets recorded. You could edit the handler and add logging code inside it. That works for one handler. Now imagine you have forty handlers, and you want the same logging on all of them. Editing forty handlers is slow, and the logging code would be duplicated in forty places. If you later change the log format, you have to edit forty files again.
A layer solves this by separating the wrapping from the work. The handler stays focused on returning the profile. The logging layer knows only how to wrap any service with logging. You apply the layer once to the whole router, and every route gets the behavior. The same layer can wrap a different handler tomorrow with no changes. That separation is the whole point. A service is one unit of request handling. A layer is a reusable recipe for wrapping a service with new behavior.
A useful mental picture is a gift-wrapping station. The service is the gift. The layer is the station. You hand the station any gift, and it hands you back the same gift wrapped in paper. The gift inside is unchanged. The wrapping is new. A different station wraps with different paper. The station never opens the gift, and it never needs to know what is inside. It only needs to know how to wrap.
Service is the worker, Layer is the factory:
A Service does the actual work of handling a request. A Layer decides how to build a service that does extra work around another service. You never call Layer::layer yourself in application code. Axum calls it for you when the router is built, and, for routes added with .route(), again for every request, as the section on the layer lifecycle later on this page shows. All per-request logic still lives inside Service::call. The layer method only constructs the service.
The trait definition, line by line
The Layer trait lives in the tower crate, next to Service. Here is its definition.
pub trait Layer<S> {
type Service;
fn layer(&self, inner: S) -> Self::Service;
}
The definition is short, and every part of it matters. Layer<S> is generic over S, the type of the inner service being wrapped. A layer does not wrap one specific service. It wraps any service of type S, which is what makes a layer reusable across many different handlers.
type Service is an associated type. It names the type of the service that this layer produces. When you implement the trait, you say what that produced service type is, usually a struct you define yourself that holds the inner service in a field.
fn layer(&self, inner: S) -> Self::Service is the single method. It takes a reference to the layer itself and the inner service, and it returns the new wrapping service. Note that it takes &self, not self. The layer is borrowed, not consumed, so the same layer value can build many services. That is why layers are usually Clone. Axum clones the layer while constructing the router, and the layer must be able to build a fresh service whenever it is asked.
The produced service must itself implement the Service trait. That is the contract. A layer takes a service and returns a service. Because the result is itself a service, layers can be stacked. One layer wraps the result of another, and the chain grows as long as you need it to.
Your first Layer, a pass-through that does nothing
The smallest possible layer is one that does nothing at all. It wraps the inner service and passes every request through unchanged. Writing it once teaches you the full skeleton, because every real layer has exactly the same shape with different behavior inside call.
Add the dependencies to Cargo.toml. These are the current versions, axum 0.8.9 with tokio 1.54.1 and tower 0.5.3.
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower = { version = "=0.5.3", features = ["util"] }
futures-util = "0.3"
Now put this complete program in src/main.rs.
use axum::{extract::Request, response::Response, routing::get, Router};
use futures_util::future::BoxFuture;
use std::task::{Context, Poll};
use tower::{Layer, Service};
// 1. Define the layer struct. It must be Clone.
#[derive(Clone)]
struct NoopLayer;
// 2. Implement Layer for the layer struct.
impl<S> Layer<S> for NoopLayer {
type Service = NoopService<S>;
fn layer(&self, inner: S) -> Self::Service {
NoopService { inner }
}
}
// 3. Define the service produced by the layer.
#[derive(Clone)]
struct NoopService<S> {
inner: S,
}
// 4. Implement Service for the produced service.
impl<S> Service<Request> for NoopService<S>
where
S: Service<Request, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let future = self.inner.call(request);
Box::pin(async move {
let response = future.await?;
Ok(response)
})
}
}
#[tokio::main]
async fn main() {
async fn handler() -> &'static str {
"Hello from the handler"
}
let app = Router::new()
.route("/", get(handler))
.layer(NoopLayer);
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 it with cargo run and visit http://localhost:3000. You will see the same response as without the layer, Hello from the handler. That is expected. The layer does nothing. But look at the structure, because it is the complete pattern for every custom middleware you will ever write. The NoopLayer implements Layer<S> for any inner service S, and its layer method returns a NoopService<S>. That service implements Service<Request> and delegates everything to the inner service. poll_ready delegates to the inner service's poll_ready. call passes the request to the inner service and returns whatever response comes back.
A beginner might wonder why so many types and trait bounds are needed for a layer that does nothing. The reason is that Rust needs to know at compile time that the wrapped service can handle a Request and produce a Response. Making NoopLayer generic over S lets Axum use it with any inner service that meets the bounds. The where clause on NoopService ensures that S can handle a request and that its future is Send, safe to move across threads, and 'static, holding no borrowed data that could disappear. The Response and Error types of the produced service are taken from the inner service, type Response = S::Response and type Error = S::Error, so the wrapper is transparent. Whatever the inner service returns, the wrapper returns.
You have built a working middleware layer:
Even though it does nothing, this is the complete pattern for every custom middleware you will ever write by hand. Run the program, confirm the handler response appears unchanged, and you have verified the skeleton. The only thing that changes later is what happens inside the call method.
Adding real behavior, a logging layer
Now change the call method to print something before and after the inner service runs. This is the classic middleware logging example, and it shows how little needs to change to turn the skeleton into something useful.
Replace the call method in NoopService with this version. The rest of the file stays the same.
fn call(&mut self, request: Request) -> Self::Future {
println!("Request started: {} {}", request.method(), request.uri());
let future = self.inner.call(request);
Box::pin(async move {
let response = future.await?;
println!("Request finished with status: {}", response.status());
Ok(response)
})
}
Run the server and make a request to http://localhost:3000. In the terminal you will see two lines.
Request started: GET /
Request finished with status: 200 OK
The first line prints before the inner future is awaited, so it appears before the handler runs. The second line prints after the await, so it appears after the handler has produced its response. That sandwich shape is the whole mechanism. Anything you print or record before the await is request-side work. Anything after the await is response-side work. In a real application you would typically use the tracing crate instead of println!, but the idea is identical.
Applying a layer at different scopes
Axum gives you several places where you can attach a layer, and the place you choose decides which routes the middleware affects. There are four forms you will use.
Router::layer applies to all routes already added to that router. Router::route_layer also applies to all routes currently in the router, but it only runs when a request actually matches one of those routes, so unmatched requests skip it and fall through to the fallback or a 404. MethodRouter::layer applies to one method router, which is the value returned by get(...) or post(...) inside a single .route(...) call. Handler::layer applies to a single handler function directly, before it is passed to get(...).
The program below builds four routers that show all four forms side by side, all using the same logging layer from the previous section. Read it as a comparison, not as an application you would run. Each router is built but never served.
use axum::{extract::Request, handler::Handler, response::Response, routing::get, Router};
use futures_util::future::BoxFuture;
use std::task::{Context, Poll};
use tower::{Layer, Service};
#[derive(Clone)]
struct LoggingLayer;
impl<S> Layer<S> for LoggingLayer {
type Service = LoggingService<S>;
fn layer(&self, inner: S) -> Self::Service {
LoggingService { inner }
}
}
#[derive(Clone)]
struct LoggingService<S> {
inner: S,
}
impl<S> Service<Request> for LoggingService<S>
where
S: Service<Request, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
println!("Request started");
let future = self.inner.call(request);
Box::pin(async move {
let response = future.await?;
println!("Request finished");
Ok(response)
})
}
}
#[tokio::main]
async fn main() {
async fn handler() -> &'static str {
"Hello from handler"
}
async fn admin() -> &'static str {
"Hello admin"
}
// A layer on the whole router, covering every route added before it.
let app: Router = Router::new()
.route("/", get(handler))
.route("/admin", get(admin))
.layer(LoggingLayer);
// A layer on one method router only, covering /admin and nothing else.
let app_with_method_layer: Router = Router::new()
.route("/", get(handler))
.route("/admin", get(admin).layer(LoggingLayer));
// A layer attached directly to one handler function.
let app_with_handler_layer: Router = Router::new()
.route("/", get(handler.layer(LoggingLayer)))
.route("/admin", get(admin));
// A route layer on the whole router. It wraps every route added before
// it, but it only runs when a request matches one of those routes.
let app_with_route_layer: Router = Router::new()
.route("/", get(handler))
.route("/admin", get(admin))
.route_layer(LoggingLayer);
let _ = (
app,
app_with_method_layer,
app_with_handler_layer,
app_with_route_layer,
);
}
The : Router annotations on the four routers pin the router state type. Without them, a router that is never served cannot have its state type inferred, and the compiler will complain. In a real application you serve the router, so the type is inferred from the serve call and the annotation is unnecessary.
Which scope you choose depends on what you need. If the middleware is logging or request timing, you usually want it on the whole router. If it is an expensive check that only one route needs, use MethodRouter::layer on that route or Handler::layer on that handler. Do not reach for Router::route_layer when you want one route, because it wraps every route added so far, not just one. The Layer trait itself does not change between these scopes. Only the place where you attach it changes.
The difference between Router::layer and Router::route_layer shows up on unmatched requests. Serve the app_with_route_layer router and request /, and the logging layer runs, printing its two lines before the handler answers. Request /missing instead, and nothing prints at all. The layer never runs, because no route matched, and the router answers 404 Not Found on its own. A plain Router::layer would have run for the unmatched request too, since it wraps the whole router including the fallback. That is the practical difference: route_layer protects matched routes only, and leaves unmatched requests alone.
Router::route_layer wraps every route added so far:
Router::route_layer is often misread as scoping a layer to one route. It does not. It wraps every route currently in the router, and the layer runs only if the request matches a route. To protect only /admin, attach the layer to that route with get(admin).layer(...) or to that handler with admin.layer(...), as shown above.
Making a layer configurable
Real middleware often needs configuration. A header-adding layer needs to know which header to add. A logging layer might need a prefix. Since a Layer is just a struct, you can store fields in it, and the layer method copies those fields into the service it builds. Here is a layer that adds a custom header to every response, configured with a name and a value.
use axum::{extract::Request, http::HeaderValue, response::Response, routing::get, Router};
use futures_util::future::BoxFuture;
use std::task::{Context, Poll};
use tower::{Layer, Service};
#[derive(Clone)]
struct AddHeaderLayer {
header_name: &'static str,
header_value: HeaderValue,
}
impl<S> Layer<S> for AddHeaderLayer {
type Service = AddHeaderService<S>;
fn layer(&self, inner: S) -> Self::Service {
AddHeaderService {
inner,
header_name: self.header_name,
header_value: self.header_value.clone(),
}
}
}
#[derive(Clone)]
struct AddHeaderService<S> {
inner: S,
header_name: &'static str,
header_value: HeaderValue,
}
impl<S> Service<Request> for AddHeaderService<S>
where
S: Service<Request, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Response, S::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let future = self.inner.call(request);
let header_name = self.header_name;
let header_value = self.header_value.clone();
Box::pin(async move {
let mut response = future.await?;
response.headers_mut().insert(header_name, header_value);
Ok(response)
})
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello" }))
.layer(AddHeaderLayer {
header_name: "x-custom-header",
header_value: HeaderValue::from_static("hello-from-layer"),
});
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Make a request with curl and you will see the header in the response.
HTTP/1.1 200 OK
x-custom-header: hello-from-layer
content-type: text/plain; charset=utf-8
content-length: 5
Two details in this example deserve attention. First, the layer method clones the HeaderValue from the layer into the service. The layer is borrowed, and the service must own its data, so anything the service needs has to be copied or cloned at build time. Second, the call method copies the header name and value into local variables before creating the async block. The boxed future is 'static, so the async block cannot borrow from self. Anything the block needs must be owned before the block is created. This copy-before-the-block pattern appears in almost every middleware you will write, and forgetting it is one of the most common compile errors beginners hit.
Borrowing from self inside a boxed future will not compile:
Because the future returned from call is a BoxFuture<'static, _>, the async block cannot borrow any data from self or from the request. If you try to use self.header_value inside the async block, the compiler will complain that the borrowed value does not live long enough. Always extract the values you need into local variables before creating the async block, as the example above does.
When layer runs, and where shared state must live
A natural assumption is that layer() runs once, when the router is built, and that the service it builds then handles every request. For routes added with .route() in axum 0.8.9, that assumption is wrong. Axum applies Router::layer lazily. It builds a fresh service for every request. You can see this with a small probe, a layer that prints a line every time layer() runs and counts the calls in a shared counter.
use axum::{body::Body, extract::Request, response::Response, routing::get, Router};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
task::{Context, Poll},
};
use tower::{Layer, Service, ServiceExt};
#[derive(Clone)]
struct CountingLayer {
calls: Arc<AtomicUsize>,
}
impl<S> Layer<S> for CountingLayer {
type Service = CountingService<S>;
fn layer(&self, inner: S) -> Self::Service {
let n = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
println!("layer() called, total so far: {n}");
CountingService { inner }
}
}
#[derive(Clone)]
struct CountingService<S> {
inner: S,
}
impl<S> Service<Request> for CountingService<S>
where
S: Service<Request, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Response, S::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let future = self.inner.call(request);
Box::pin(async move { future.await })
}
}
#[tokio::main]
async fn main() {
let calls = Arc::new(AtomicUsize::new(0));
let app: Router = Router::new()
.route("/", get(|| async { "hi" }))
.layer(CountingLayer {
calls: calls.clone(),
});
println!(
"after build: layer() calls = {}",
calls.load(Ordering::SeqCst)
);
for i in 1..=2 {
let request = Request::builder().uri("/").body(Body::empty()).unwrap();
let response = app.clone().oneshot(request).await.unwrap();
println!(
"request {i}: status {}, layer() calls = {}",
response.status(),
calls.load(Ordering::SeqCst)
);
}
}
An Arc<AtomicUsize> is a thread-safe shared counter. Arc stands for atomically reference counted, which means many owners can share the same value across threads. AtomicUsize is an integer that can be incremented safely from multiple threads at once. The layer holds the Arc, so every service it builds shares the same counter even though the services themselves are fresh each time.
Running this program prints output like the following. The exact number of build-time calls can vary with the router internals, but the pattern is stable. Several calls happen while the router is built, and then exactly one more call happens per request.
layer() called, total so far: 1
layer() called, total so far: 2
layer() called, total so far: 3
layer() called, total so far: 4
after build: layer() calls = 4
layer() called, total so far: 5
request 1: status 200 OK, layer() calls = 5
layer() called, total so far: 6
request 2: status 200 OK, layer() calls = 6
Two consequences follow, and both matter when you design a layer. First, all per-request logic still belongs inside Service::call. The layer() method only constructs the service, so do not put request handling in it. Anything layer() does runs at build time and again per request, which is the wrong place for logic that should run exactly once per request. Second, state held on the service itself does not survive from one request to the next. A counter stored as a plain field on the service struct resets with every request, because each request gets a brand-new service. State that must be shared across requests belongs in the layer struct itself, behind an Arc, because the layer is what gets cloned and reused.
Here is that second consequence as a working pattern. The layer holds an Arc<AtomicUsize>, and each service it builds gets a clone of the same Arc. Every request increments the shared counter, so the count persists across requests even though the service is rebuilt each time.
use axum::{extract::Request, http::HeaderValue, response::Response, routing::get, Router};
use futures_util::future::BoxFuture;
use std::{
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
task::{Context, Poll},
};
use tower::{Layer, Service};
#[derive(Clone)]
struct SharedCounterLayer {
count: Arc<AtomicUsize>,
}
impl<S> Layer<S> for SharedCounterLayer {
type Service = SharedCounterService<S>;
fn layer(&self, inner: S) -> Self::Service {
SharedCounterService {
inner,
count: self.count.clone(),
}
}
}
#[derive(Clone)]
struct SharedCounterService<S> {
inner: S,
count: Arc<AtomicUsize>,
}
impl<S> Service<Request> for SharedCounterService<S>
where
S: Service<Request, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Response, S::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let count = self.count.fetch_add(1, Ordering::SeqCst) + 1;
let future = self.inner.call(request);
Box::pin(async move {
let mut response = future.await?;
let value = HeaderValue::from_str(&count.to_string())
.unwrap_or_else(|_| HeaderValue::from_static("0"));
response.headers_mut().insert("x-request-count", value);
Ok(response)
})
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello" }))
.layer(SharedCounterLayer {
count: Arc::new(AtomicUsize::new(0)),
});
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Send three requests to this server and the x-request-count header will read 1, then 2, then 3. The service is rebuilt for each request, but the counter lives in the Arc shared by all of them, so the count keeps growing. This is the pattern to use whenever middleware needs to remember something across requests, such as a request counter, a rate-limit bucket, or a shared cache handle. Keep the shared data in the layer behind an Arc, clone the Arc into each service, and never store cross-request state as a plain field on the service.
A plain field on the service does not survive across requests:
If you store a counter as a plain usize field on the service struct, it will read 1 on every request for .route() routes, because axum builds a fresh service per request. That looks like the counter is broken, but the counter is fine. The service is new each time. Move the state into the layer behind an Arc, as in the example above, and clone the Arc into each service the layer builds.
A shortcut for simple layers, layer_fn
Writing two structs and two trait implementations is a lot of boilerplate for a layer that does one small thing. Tower provides a shortcut called layer_fn for exactly that case. You give it a closure, which is a small anonymous function, that takes the inner service and returns the wrapping service. Tower builds a layer from that closure, so you skip the Layer struct and its implementation entirely. You still write the service struct and its Service implementation, because that is where the behavior lives.
use axum::{extract::Request, response::Response, routing::get, Router};
use futures_util::future::BoxFuture;
use std::task::{Context, Poll};
use tower::{layer::layer_fn, Service};
#[derive(Clone)]
struct LoggingService<S> {
inner: S,
}
impl<S> Service<Request> for LoggingService<S>
where
S: Service<Request, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
println!("Request started");
let future = self.inner.call(request);
Box::pin(async move {
let response = future.await?;
println!("Request finished");
Ok(response)
})
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello" }))
.layer(layer_fn(|inner| LoggingService { inner }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
The .layer(layer_fn(|inner| LoggingService { inner })) line replaces the whole LoggingLayer struct. The closure receives the inner service and wraps it. Use layer_fn when the layer carries no configuration and exists only to construct one service type. Write a named layer struct when the layer needs fields, such as the header name and value in the configurable example, or when the layer will be reused and named in more than one place. Both forms produce the same behavior at runtime.
Putting it all together, a timing layer
Here is one more complete example that combines everything on this page. It is a layer that measures how long the inner service takes and adds that duration as a response header. Timing is a common production pattern, and it exercises the full skeleton. Configuration, delegation, work before and after the await, and a response change.
use axum::{extract::Request, http::HeaderValue, response::Response, routing::get, Router};
use futures_util::future::BoxFuture;
use std::{
task::{Context, Poll},
time::Instant,
};
use tower::{Layer, Service};
#[derive(Clone)]
struct TimingLayer;
impl<S> Layer<S> for TimingLayer {
type Service = TimingService<S>;
fn layer(&self, inner: S) -> Self::Service {
TimingService { inner }
}
}
#[derive(Clone)]
struct TimingService<S> {
inner: S,
}
impl<S> Service<Request> for TimingService<S>
where
S: Service<Request, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Response, S::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let start = Instant::now();
let future = self.inner.call(request);
Box::pin(async move {
let mut response = future.await?;
let elapsed = start.elapsed();
let header_value = HeaderValue::from_str(&format!("{}us", elapsed.as_micros()))
.unwrap_or_else(|_| HeaderValue::from_static("unknown"));
response
.headers_mut()
.insert("x-request-duration", header_value);
Ok(response)
})
}
}
#[tokio::main]
async fn main() {
async fn slow_handler() -> String {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
"Finished".to_string()
}
let app = Router::new().route("/", get(slow_handler)).layer(TimingLayer);
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 Instant::now() call captures the start time before the inner service runs. The start value is moved into the async block, where start.elapsed() computes the duration after the response arrives. The header value is built from the duration in microseconds, with a fallback of "unknown" if the formatted string somehow fails to parse as a header value. HeaderValue::from_str can fail if the string contains characters that are not allowed in a header, so the fallback keeps the code from panicking.
When you hit the endpoint, the response will include a header like x-request-duration: 50213us. The exact number varies, but it will always be at least the 50 milliseconds the handler sleeps. The header measures the whole inner service, which is the handler plus any layers inside this one. That is what makes the position of a timing layer matter. A timing layer placed outside another layer measures that layer too. A timing layer placed inside measures only what is deeper than it.
Stacking layers and the order they run in
When you stack layers with repeated .layer() calls, the last call becomes the outermost wrapper and runs first on the request. Axum applies layers from bottom to top, so the order you write them in is the reverse of the order they execute in. If you write .layer(a).layer(b), a request reaches b first, then a, then the handler, and the response travels back through a first and then b. This catches beginners out, because it is the opposite of reading order.
The recommended way to compose several layers is tower::ServiceBuilder, which runs layers in the order they are listed, top to bottom. With ServiceBuilder, the first layer listed is the outermost and sees the request first, which matches reading order. The rule to remember here is simple. One layer is easy. Two or more layers belong in a ServiceBuilder unless you are deliberately using the onion order of repeated .layer() calls.
Common mistakes and misconceptions
Forgetting to implement Clone is the first mistake. A layer must be Clone because Axum clones it while constructing the router. If you forget #[derive(Clone)] on your layer struct, you will get a compile error when you call .layer(...). The produced service should also be Clone, because axum requires the built service to be Clone and clones it while assembling the route for each request. Most of the time you can just derive Clone on both structs.
Not forwarding poll_ready is the second. The poll_ready method is how tower checks whether a service is ready to accept a new request. In almost all middleware, you should simply delegate to the inner service's poll_ready. If you override it incorrectly, you might cause your service to never be ready, or to accept requests when it should not. In the examples above, poll_ready always calls self.inner.poll_ready(cx) and returns its result unchanged.
Returning an error from middleware is the third. Axum expects every request to eventually produce a Response. If your middleware returns an Err from call, the connection will be closed without sending a response. To avoid this, convert any internal errors into a Response, for example a 500 Internal Server Error, and return Ok(response). Keep the error type Infallible and handle failures inside call.
Misunderstanding the order of layers is the fourth. When you stack layers with multiple .layer() calls, the outermost layer is the last one you added. If you expect them to run in the order you wrote them, you will be surprised. Use ServiceBuilder when the order matters and you want it to match reading order.
Assuming layer() runs once is the fifth, and it is the subtlest. For .route() routes in axum 0.8.9, layer() runs at build time and again for every request, producing a fresh service each time. Do not put per-request work in layer(), and do not store cross-request state as a plain field on the service. Put per-request work in call, and put shared state in the layer behind an Arc.
Manual futures are possible but rarely needed:
The examples on this page use BoxFuture because it is easy to write and understand. Some middleware authors avoid the heap allocation that Box::pin introduces and instead implement their own Future type. That gives full control and can help performance on very hot paths, but it requires implementing the Future trait by hand, which is an advanced Rust topic. For the large majority of use cases, BoxFuture is fine and much easier to get right.
Summary
The Layer trait is the factory pattern of the tower ecosystem. It takes an inner service and returns a new service that adds behavior, and because the result is itself a service, layers stack without limit. Writing a custom layer means defining two structs, one for the layer and one for the produced service, and implementing Layer and Service respectively. The call method is where all per-request middleware logic lives. You can make layers configurable by adding fields to the layer struct and cloning those fields into the service, and you can skip the layer struct entirely with layer_fn when no configuration is needed.
The decision framework for this page has three branches. If you need to wrap services with reusable behavior, write a layer. If the behavior needs to be remembered across requests, keep the shared data in the layer behind an Arc and clone the Arc into each service, because axum rebuilds the service per request for .route() routes. If you only need the behavior in one place and the boilerplate feels heavy, use layer_fn for a bare layer, or reach for the async-function helpers that hide Layer and Service entirely. Either way, the layer you write and the layers shipped in ready-made crates are the same shape, and now you can read both.