tower ServiceBuilder in Axum
How to compose middleware with tower ServiceBuilder in Axum, including its methods, feature flags, tower-http one-liners and the two compile bounds a builder must satisfy
A stack of two layers is easy to read. A stack of eight is not, because chained .layer() calls run in the opposite order to the order they are written. ServiceBuilder fixes that. It is a builder for composing layers into one layer: you list the layers in the order they should run, top to bottom, and the builder hands you a single layer to pass to one .layer() call. The builder itself implements the Layer trait, so anywhere a layer is accepted, a builder is accepted too.
This page teaches the builder itself. It lists every method on the builder, the feature flag each method needs, the one-line helpers tower-http adds, and the two compile bounds axum places on any builder handed to a router. It does not teach any single layer in depth. The timeout, the concurrency limit and the rate limit each have their own subject, and they appear here only as examples of builder methods.
The smallest builder
A builder starts with ServiceBuilder::new(), takes one .layer(...) call per layer, and is passed to Router::layer as a single argument. The example below builds an app with three layers: request tracing, a five-second timeout, and a limit of one hundred requests in flight at once. The timeout uses tower-http's form, which answers with a status code directly.
use axum::{routing::get, Router};
use std::time::Duration;
use tower::{limit::ConcurrencyLimitLayer, ServiceBuilder};
use tower_http::{timeout::TimeoutLayer, trace::TraceLayer};
async fn hello() -> &'static str {
"hello"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::with_status_code(
axum::http::StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(5),
))
.layer(ConcurrencyLimitLayer::new(100)),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
[package]
name = "builder-tour"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower = { version = "=0.5.3", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["full"] }
Run it with cargo run and request http://localhost:3000/ in a browser or with curl. The handler answers hello with a 200 status. Nothing in the response betrays the three layers, which is the point: the builder changes how the stack is written, not what the client sees. The tracing layer writes request logs, the timeout guards slow handlers, and the concurrency limit caps simultaneous work, all without touching the handler code. The server above only needs the limit, trace and timeout features, but the page uses one Cargo.toml for every example, with tower's full feature enabled so each method in the tour is available.
The rest of this page tests builders without starting a server. The probe program below sends requests in memory with oneshot, which runs the whole stack and returns the response. It lives in the same file as the server above would, in src/main.rs, with the serving lines replaced by probe functions, and it shares the Cargo.toml above. The helpers are shared by every probe.
use axum::{
error_handling::HandleErrorLayer,
extract::Request,
http::StatusCode,
middleware::{self, Next},
response::Response,
routing::get,
BoxError, Router,
};
use std::{
sync::{Arc, Mutex},
time::Duration,
};
use tower::{ServiceBuilder, ServiceExt};
use tower_http::{request_id::MakeRequestUuid, ServiceBuilderExt};
type Order = Arc<Mutex<Vec<&'static str>>>;
async fn hello() -> &'static str {
"hello"
}
// Sends one request to the app without starting a server.
async fn send(app: Router, uri: &str) -> Response {
let req = Request::builder()
.uri(uri)
.body(axum::body::Body::empty())
.unwrap();
app.oneshot(req).await.unwrap()
}
#[tokio::main]
async fn main() {
ordering_probe().await;
conditional_layer().await;
full_stack().await;
request_id_pair().await;
whole_app_service().await;
timeout_bounds().await;
}
Ordering, first listed runs first
The single most important fact about the builder is its ordering rule, and it is the opposite of chained .layer() calls. In a builder, the first listed layer runs first on the request path. In a chain, the last call runs first. The probe below records the order through both forms with the same recorder middleware used to measure order across scopes: a from_fn middleware that pushes its name into a shared list before passing the request onward.
async fn ordering_probe() {
let order: Order = Arc::new(Mutex::new(Vec::new()));
let tag = |order: Order, name: &'static str| {
middleware::from_fn(move |req: Request, next: Next| {
let order = order.clone();
async move {
order.lock().unwrap().push(name);
next.run(req).await
}
})
};
// A builder: first listed runs first.
let app = Router::new().route("/", get(hello)).layer(
ServiceBuilder::new()
.layer(tag(order.clone(), "first"))
.layer(tag(order.clone(), "second"))
.layer(tag(order.clone(), "third")),
);
send(app, "/").await;
println!("builder: {:?}", order.lock().unwrap());
// Chained calls: last call runs first.
let order2: Order = Arc::new(Mutex::new(Vec::new()));
let app2 = Router::new()
.route("/", get(hello))
.layer(tag(order2.clone(), "first"))
.layer(tag(order2.clone(), "second"));
send(app2, "/").await;
println!("chained: {:?}", order2.lock().unwrap());
}
The output is:
builder: ["first", "second", "third"]
chained: ["second", "first"]
The builder reads top to bottom, outside in. The chain reads bottom to top. That is the whole reason the builder exists: a long stack written as a builder reads the way the request flows through it. When you convert a chain to a builder, or a builder to a chain, reverse the order, then run the recorder once to confirm. A builder passed to .layer() counts as one layer in the chain around it, so the chain rule still applies to the builder as a unit.
The builder is a Layer, not a router method:
ServiceBuilder::new() returns a builder, and the builder itself implements Layer. That is why you pass it to .layer(...) as a single argument. You can also pass a builder to route_layer, to a method router layer, and to a handler layer, anywhere a Layer is accepted.
The method tour, adding layers
The builder has many methods, and they are easier to learn grouped by purpose than alphabetically. This section walks through them group by group: adding layers, tower's built-in middleware, transforming requests and responses, and finishing the builder. Every method named here exists on ServiceBuilder in tower 0.5.3, and the feature flag for each one is stated with it. The flags are collected into one table in the section after the tour.
layer, option_layer, layer_fn
.layer(layer) adds any layer and is the workhorse of the builder. Most stacks are a sequence of .layer(...) calls, one per middleware. It needs no feature flag at all: a ServiceBuilder with only .layer(...) calls compiles against tower with no features enabled.
.option_layer(layer) adds a layer only when the Option holds one, and adds nothing when it holds None. It needs the util feature. This is how a layer becomes conditional on configuration without an if around the whole builder:
async fn conditional_layer() {
let verbose = true;
async fn verbose_log(req: Request, next: Next) -> Response {
println!("verbose: {} {}", req.method(), req.uri());
next.run(req).await
}
let app = Router::new().route("/", get(hello)).layer(
ServiceBuilder::new()
.option_layer(verbose.then(|| middleware::from_fn(verbose_log))),
);
let res = send(app, "/").await;
println!("conditional layer: {}", res.status());
}
When verbose is true, the logging middleware runs and prints verbose: GET / before the handler answers. When it is false, verbose.then(...) produces None, the builder adds nothing in that slot, and the request passes straight to the handler. The then call is a method on bool that returns Some of the value when the bool is true and None when it is false.
Two details about option_layer catch beginners. First, the layer type must be concrete. None::<TraceLayer> does not compile, because TraceLayer is generic over its span maker and other parameters, so the compiler cannot tell which TraceLayer is meant. Write None::<tower_http::timeout::TimeoutLayer>, a concrete type, instead. Second, the two branches of the option must agree on the request, response and error types, because the builder wraps the layer in an Either that picks one branch or the other. A layer that changes the response body type, such as TraceLayer, cannot go in an option_layer around a router: the Some branch would produce one body type and the None branch another, and the program does not compile. A layer that leaves the body type alone, such as a from_fn middleware, works. A fallible layer fails for the same reason on the error type: the Some branch would produce a BoxError and the None branch would not, so a fallible layer in an option_layer needs its error handled outside the option.
option_layer needs a layer that changes neither the body type nor the error type:
TraceLayer in an option_layer does not compile, because it wraps the response body and the two branches of the option would disagree about the body type. A from_fn middleware works because it returns an ordinary response with an infallible error. When the conditional layer is a body-changing or fallible one, use a plain .layer(...) call, or handle the error outside the option.
.layer_fn(f) builds a layer from a closure that takes a service and returns a service, with no layer struct. It needs no feature flag. It is the shortcut form of writing a Layer implementation by hand: layer_fn(|inner| MyService { inner }) wraps the inner service in your own service type directly. Use it when the service needs no configuration beyond the inner service itself. An identity closure, layer_fn(|svc| svc), changes nothing and only proves the point: the builder accepts any function from a service to a service as a layer.
The method tour, tower built-ins
These methods add tower's own middleware without naming a layer type. Each one is shorthand for a .layer(SomeLayer::...) call, and each needs its own feature flag.
.timeout(duration) needs the timeout feature. It fails requests that take longer than the duration, producing a BoxError. That error is the reason tower's timeout always travels with an outer HandleErrorLayer in axum, as the bounds section below shows. Do not confuse it with tower-http's timeout, which returns a response directly.
.concurrency_limit(max) needs the limit feature. At most max requests are in flight at once, and further requests wait for a slot. A request counts as in flight from the moment it arrives until its response future completes, including the time spent in the layers inside the limit. One behaviour deserves a plain sentence here: axum's routing always reports itself ready, so a permit-based limiter cannot gate requests the way it does in plain tower, and a limit placed on a router does not hold back concurrent requests. The limit still counts as a layer in the stack, but do not rely on it to serialize work inside an axum router.
.rate_limit(num, per) needs the limit feature. At most num requests pass per per duration, and excess requests are delayed rather than refused. The limiter is not Clone, so a builder containing it is rejected by Router::layer until a .buffer(...) call wraps it, and the buffer's BoxError needs an outer error handler too. Both fixes are shown in full in the bounds section below.
.buffer(bound) needs the buffer feature. It hands requests to a background worker through a channel of capacity bound, which makes the wrapped service Clone even when the inner service is not. That is the standard workaround for the rate limit clone problem, and it is also useful whenever a service must be cloned but cannot be. The bound is the number of requests that may wait in the channel on top of the requests already forwarded inward.
.load_shed() needs the load-shed feature. When the inner service is not ready, it refuses the request at once with an error instead of waiting for capacity. Waiting is the default behaviour of most middleware: a caller that finds no capacity waits until some appears. Load shedding turns that wait into an immediate error, which keeps a queue from growing without bound under load. The error it produces is a BoxError, so in axum it needs an outer error handler like the timeout does.
.retry(policy) needs the retry feature. It retries a failed request according to a retry policy, which is a type that implements tower's Policy trait. A policy has two methods: retry, which looks at the request and the result and returns Some future that delays the next attempt when the request should be tried again, and clone_request, which clones the request before the first attempt so a copy is available for a retry. There is no built-in policy that retries everything; you write a small policy type for the failures you care about, such as retrying only on a particular error and only a fixed number of times.
The program below runs the built-ins against a plain tower service in a second file, src/bin/builtins.rs, in the same package, so it shares the page's Cargo.toml. The service is a function that echoes strings, built with service_fn, and the builder wraps it. That keeps the focus on the builder methods instead of on axum routing.
use std::time::Duration;
use tower::{retry::Policy, BoxError, ServiceBuilder, ServiceExt};
#[derive(Clone)]
struct NeverRetry;
impl<Req, Res, E> Policy<Req, Res, E> for NeverRetry
where
Req: Clone,
{
type Future = std::future::Ready<()>;
fn retry(&mut self, _req: &mut Req, _result: &mut Result<Res, E>) -> Option<Self::Future> {
None
}
fn clone_request(&mut self, req: &Req) -> Option<Req> {
Some(req.clone())
}
}
#[tokio::main]
async fn main() {
let svc = ServiceBuilder::new()
.buffer(10)
.concurrency_limit(5)
.rate_limit(5, Duration::from_secs(1))
.load_shed()
.retry(NeverRetry)
.timeout(Duration::from_secs(5))
.service_fn(|req: String| async move { Ok::<_, BoxError>(req) });
let out = svc.oneshot("hello".to_string()).await.unwrap();
println!("builtins: {out}");
}
The program prints:
builtins: hello
The request passes through the buffer, the concurrency limit, the rate limit, the load shedder, the retry policy and the timeout, and comes back unchanged. The NeverRetry policy never retries, so the retry layer is transparent here. A real policy would return Some from retry for the failures worth another attempt, and the future it returns would sleep before the next try. Note the order in the listing: the buffer is outermost and runs first, and the timeout is innermost, closest to the service. Swapping the buffer and the concurrency limit would change how many requests can be in flight in total, because the buffer adds waiting room on top of the requests already forwarded inward.
The method tour, transforming requests, responses and errors
These methods change the request, the response or the error in flight, without a separate layer type. They all need the util feature. They are synchronous where they look synchronous: the closure runs inline as the request or response passes, with no await inside it. For anything async, use a layer or a from_fn middleware instead.
The examples below run against a plain tower service in a second file, src/bin/transforms.rs, in the same package, so they share the page's Cargo.toml. The service is a function that echoes strings, built with service_fn, and the builder wraps it. That keeps the focus on the transform methods instead of on axum routing.
.map_request(f) runs a synchronous function over the request before the inner service sees it. The function takes the request by value and returns a new request, which is usually the same request with a header added or a field changed. The closure must be Clone, because axum applies the layer per request and clones the layer each time.
.map_response(f) runs a synchronous function over the response after the inner service produces it. It is the place for small response edits such as adding a header.
.map_err(f) runs a function over the error when the inner service fails, changing the error type. It is useful in a pure tower stack for converting one error type into another. It cannot fix axum's error bound on its own, as the bounds section shows, because axum needs the error to convert into Infallible and no function can produce an Infallible value out of a real error.
.map_future(f) transforms the future the inner service returns, rather than the request or the response. The function receives the response future and returns a new future, which lets you add logging or timing around the wait for the response without touching the request or the response values.
.then(f) runs an async function after the inner service, whether it succeeded or failed. The function receives the whole Result<Response, Error> and returns a new one. .and_then(f) runs an async function only after success: it receives the response and returns a new result, so it can chain another async step onto a successful response. The difference between the two is only what happens on failure: then always runs, and_then runs only on success.
.map_result(f) maps the whole result, success or failure, through a synchronous function. It is the synchronous twin of then.
.filter(predicate) needs the filter feature. It conditionally rejects requests based on a predicate, which is a closure that returns a Result: Ok(request) forwards the request inward, and Err(error) rejects it. The predicate takes the request by value, not by reference, and its error must convert into a BoxError. A closure returning a plain bool does not work. The filter's own error is a BoxError, so in axum it needs an outer error handler. .filter_async(predicate) is the async form, and its predicate returns a future of a Result.
use tower::{BoxError, ServiceBuilder, ServiceExt};
#[tokio::main]
async fn main() {
let svc = ServiceBuilder::new()
.map_request(|req: String| req.to_uppercase())
.map_response(|res: String| format!("got: {res}"))
.map_err(|e: BoxError| e)
.map_result(|r: Result<String, BoxError>| r.map(|s| format!("{s}!")))
.then(|r: Result<String, BoxError>| async move { r })
.and_then(|s: String| async move { Ok::<_, BoxError>(format!("{s}?")) })
.map_future(|fut| async move {
let r: Result<String, BoxError> = fut.await;
r
})
.service_fn(|req: String| async move { Ok::<_, BoxError>(req) });
let out = svc.oneshot("hello".to_string()).await.unwrap();
println!("transforms: {out}");
let svc = ServiceBuilder::new()
.filter_async(|req: String| async move {
if req == "blocked" {
Err::<String, BoxError>("blocked".into())
} else {
Ok(req)
}
})
.service_fn(|req: String| async move { Ok::<_, BoxError>(req) });
let out = svc.oneshot("hello".to_string()).await.unwrap();
println!("filter_async pass: {out}");
}
The output is:
transforms: got: HELLO?!
filter_async pass: hello
Follow the first line through the stack. The request "hello" is uppercased by map_request on the way in. The service echoes "HELLO". On the way back, and_then appends "?", map_result appends "!", and map_response prepends "got: ", giving "got: HELLO?!". The listing order decides the response order: the transforms listed last run first on the response path, because the response travels back in reverse. The second program shows the async filter passing a normal request through untouched.
A filter predicate returns a Result, not a bool:
.filter(|req| req.uri().path() != "/blocked") does not compile. The predicate must return Ok(req) to forward the request or Err(error) to reject it, and it takes the request by value. The error type must convert into a BoxError, and the filter itself fails with a BoxError, so in axum it needs an outer error handler.
The method tour, finishing the builder
Four groups of methods finish a builder: attaching the inner service, unwrapping the layer, erasing the type, and checking the bounds at compile time.
.service(s) attaches the inner service and produces a finished, callable service. It needs no feature flag. .service_fn(f) does the same for an async function, and needs the util feature. You rarely need either in axum, because Router::layer does the attaching for you: the router is the inner service. The place they do appear is wrapping a whole application from the outside, which the worked example at the end of this section shows.
.into_inner() unwraps the composed layer back out of the builder, and needs no feature flag. It is useful when a function returns a builder and the caller wants the layer itself, for example to store it or to pass it somewhere a builder would not fit.
.boxed(), .boxed_clone() and .boxed_clone_sync() need the util feature. They erase the builder's exact type into a boxed service, which is useful when a stack's type is too long to name, for example when a function must return one of several different stacks. boxed produces a service that is not Clone, boxed_clone produces one that is, and boxed_clone_sync adds Sync as well. The boxed form goes before the layers it should erase, so the layers listed after it are inside the box.
.check_clone(), .check_service_clone() and .check_service() need no feature flag. They are compile-time assertions that cost nothing at runtime. check_clone asserts the builder itself can be cloned, which catches a non-cloneable layer early. check_service_clone asserts the service the builder produces for a given inner service type can be cloned. check_service asserts the produced service has the given request, response and error types. They do not change the builder; they only fail the build with a clear error when the assertion is false, instead of letting the failure surface later at the .layer(...) call with a longer type in the message.
The whole-app form of .service(...) deserves one example, because it is the one place axum programmers meet it. A router is itself a service, so a builder can wrap an entire application from the outside:
async fn whole_app_service() {
let inner = Router::new().route("/", get(hello));
let app = ServiceBuilder::new()
.layer(tower_http::trace::TraceLayer::new_for_http())
.service(inner);
let req = Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
println!("whole app service: {}", res.status());
}
The request passes through the tracing layer and then the whole router. This form is the way to put backpressure-sensitive middleware around an entire application, because the middleware then sits outside the router instead of inside it. The same builder passed to Router::layer would sit inside the routing step instead. One caution travels with this form: errors still need handling, because the builder is no longer inside axum's error handling, so a fallible layer here needs its error handler in the builder itself.
Feature flags
The builder itself needs no features, but almost every method does. Tower ships with no default features, so a Cargo.toml that only names tower gets ServiceBuilder::new(), .layer(), .layer_fn(), .into_inner(), .service() and the check_* methods, and nothing else. Each method below lists the flag that unlocks it, taken from the tower 0.5.3 source.
| Method | Feature |
|---|---|
layer, layer_fn, into_inner, service, check_clone, check_service_clone, check_service | none |
option_layer, map_request, map_response, map_err, map_future, then, and_then, map_result, service_fn, boxed, boxed_clone, boxed_clone_sync | util |
timeout | timeout |
concurrency_limit, rate_limit | limit |
buffer | buffer |
load_shed | load-shed |
retry | retry |
filter, filter_async | filter |
A typical axum stack needs tower = { version = "0.5", features = ["limit", "timeout", "util"] }: limit for the concurrency limit and the rate limit, timeout for tower's timeout, util for option_layer and the map_* methods. A stack that only ever calls .layer(...) needs no tower features at all. The full feature enables everything, which is convenient in a scratch project and wasteful in a real one, because it pulls in retry, load shedding, filtering and balancing support the stack never calls. Enable only what the stack uses, and the compiler will tell you when a method is missing its flag: the error names the method and the feature that gates it.
A missing feature is a method-not-found error, not a dependency error:
When a builder method is called without its feature enabled, the compiler reports that the method does not exist on ServiceBuilder. The fix is the feature flag in the table above, not a different method name and not a version change.
One builder, many layers
Here is a single builder combining the built-ins, a conditional layer, a layer_fn, and the map_* transforms: the kind of stack that would be unreadable as chained .layer() calls. The error handler is listed first, so it is outermost and catches the error from tower's timeout below it. The tracing layer is a plain .layer(...) call, and the conditional logging layer is a from_fn middleware inside an option_layer, which is safe because that middleware changes neither the body type nor the error type.
async fn full_stack() {
async fn echo(req: Request) -> Response {
let v = req
.headers()
.get("x-added")
.and_then(|h| h.to_str().ok())
.unwrap_or("missing")
.to_string();
Response::new(axum::body::Body::from(v))
}
async fn verbose_log(req: Request, next: Next) -> Response {
println!("verbose: {} {}", req.method(), req.uri());
next.run(req).await
}
let verbose = true;
let app = Router::new()
.route("/", get(echo))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_: BoxError| async {
StatusCode::REQUEST_TIMEOUT
}))
.timeout(Duration::from_secs(5))
.concurrency_limit(100)
.layer(tower_http::trace::TraceLayer::new_for_http())
.option_layer(verbose.then(|| middleware::from_fn(verbose_log)))
.layer_fn(|svc| svc)
.map_request(|mut req: Request| {
req.headers_mut().insert("x-added", "yes".parse().unwrap());
req
})
.map_response(|mut res: Response| {
res.headers_mut().insert("x-mapped", "yes".parse().unwrap());
res
}),
);
let res = send(app, "/").await;
let status = res.status();
let mapped = res
.headers()
.get("x-mapped")
.and_then(|h| h.to_str().ok())
.unwrap_or("missing")
.to_string();
let body = axum::body::to_bytes(res.into_body(), usize::MAX)
.await
.unwrap();
println!(
"full stack: {} handler saw x-added={} x-mapped={}",
status,
String::from_utf8_lossy(&body),
mapped
);
}
The output is:
verbose: GET /
full stack: 200 OK handler saw x-added=yes x-mapped=yes
The verbose log line prints first, because the conditional logging layer runs on the request path before the handler. The handler receives the request carrying x-added: yes, which map_request added, and answers with that value as the body. The response leaves carrying x-mapped: yes, which map_response added. The timeout and the concurrency limit do not appear in the output: a five-second timeout on a fast handler never fires, and a limit of one hundred never binds on a single request. The layer_fn(|svc| svc) in the middle changes nothing; it stands in the slot where a real service-wrapping function would go, such as one that wraps the inner service in a custom type. Read the listing top to bottom and the request flows the same way: error handler, timeout, concurrency limit, tracing, conditional logging, the identity wrap, request mapping, handler, then response mapping on the way back.
The full stack works when the handler sees the mapped header:
If your run prints handler saw x-added=yes and x-mapped=yes, every layer in the builder is in place and in order. The two headers are the proof: one proves the request transform ran before the handler, and the other proves the response transform ran after it.
ServiceBuilderExt, the tower-http one-liners
Tower-http adds an extension trait, tower_http::ServiceBuilderExt, which adds one-line methods for its most common layers. The trait itself needs tower-http's util feature, and each method needs the feature of the layer it adds. Each method is shorthand for a .layer(SomeLayer::...) call: same behaviour, less typing. Import the trait before using the methods, or the compiler will report that the method does not exist on the builder.
The methods, grouped by what they do, are: propagate_header for copying a header from request to response; add_extension for inserting a value into request extensions; map_request_body and map_response_body for changing body types; compression and decompression for content encoding; trace_for_http and trace_for_grpc for tracing; follow_redirects for client-side redirects; sensitive_headers, sensitive_request_headers and sensitive_response_headers for marking headers sensitive; override_request_header, append_request_header and insert_request_header_if_not_present, with the same three for responses, for setting headers; set_request_id and propagate_request_id, with x-request-id shortcuts set_x_request_id and propagate_x_request_id; catch_panic for turning panics into 500 responses; request_body_limit for rejecting oversized bodies; and trim_trailing_slash and append_trailing_slash for normalizing paths.
The request-id pair is the worked example, because it is the one where the one-liners save the most ceremony. set_x_request_id generates an id for requests that lack one, and propagate_x_request_id copies it to the response:
async fn request_id_pair() {
let app = Router::new().route("/", get(hello)).layer(
ServiceBuilder::new()
.set_x_request_id(MakeRequestUuid)
.propagate_x_request_id(),
);
let res = send(app, "/").await;
let id = res
.headers()
.get("x-request-id")
.and_then(|h| h.to_str().ok())
.unwrap_or("missing")
.to_string();
println!("request id: {} len={}", id, id.len());
}
The output is:
request id: 8a11c553-01eb-4bf7-a95b-b35aec298746 len=36
Every response now carries an x-request-id header with a fresh UUID, a 36-character string. The two calls are exactly SetRequestIdLayer::x_request_id(MakeRequestUuid) and PropagateRequestIdLayer::x_request_id(). If you need the explicit form, for a custom header name or a custom id generator, use the layers directly. One ordering rule carries over unchanged: the setter must run before the propagator, so set_x_request_id is listed first. Listed the other way around, the propagator reads the header before the id exists, and the generated id is silently dropped from the response.
The two axum compile bounds
A builder passed to Router::layer must satisfy two bounds, and the compiler errors they produce are the most common stumbling block with ServiceBuilder. Both come from axum's Router::layer signature: the service the layer produces must be Clone + Send + Sync, and its error type must convert into Infallible. Infallible is Rust's empty error type: a type with no values, used to mean "this cannot fail". A service whose error is Infallible can never fail, so axum always gets a response.
The service must be Clone
Tower's RateLimit service is not Clone: it holds a sleep timer and mutable budget state that cannot be shared by cloning. A builder containing .rate_limit(...) is rejected with this error:
let app = Router::new()
.route("/", get(hello))
.layer(ServiceBuilder::new().rate_limit(5, Duration::from_secs(1)));
error[E0277]: the trait bound `RateLimit<Route>: Clone` is not satisfied
The fix is .buffer(...) before the rate limit, which wraps the non-cloneable service in a cloneable channel-based one. But the buffer alone is not enough, because the buffer's own error type is a BoxError, and that trips the second bound. The form that compiles needs both fixes: an outer error handler for the buffer's error, and the buffer for the cloneability.
let app: Router = Router::new()
.route("/", get(hello))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_: BoxError| async {
StatusCode::TOO_MANY_REQUESTS
}))
.buffer(10)
.rate_limit(5, Duration::from_secs(1)),
);
This form compiles and builds inside a Tokio runtime. The error handler converts the buffer's error into a 429 Too Many Requests response, and the buffer makes the service cloneable. Note the order inside the builder: the handler is listed first so it is outermost, and the buffer sits between the handler and the limiter. One more behaviour is worth a plain sentence: even in this compiling form, the limiter delays excess requests rather than refusing them, and it counts requests globally rather than per client.
The error must convert into Infallible
Tower's built-ins produce BoxError errors, which axum cannot turn into a response on its own. A builder containing tower's .timeout(...) with no error handler is rejected:
let app = Router::new()
.route("/", get(hello))
.layer(ServiceBuilder::new().timeout(Duration::from_secs(5)));
error[E0277]: the trait bound `!: From<Box<(dyn std::error::Error + Send + Sync + 'static)>>` is not satisfied
The fix is a HandleErrorLayer listed first, outermost, in the builder, converting the error into a status code. The full-stack example above shows the shape, and the timeout probe below shows it working: a handler that sleeps for three seconds is cut off after 200 milliseconds with a 408.
async fn timeout_bounds() {
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_secs(3)).await;
"slow"
}
// Tower timeout with its HandleErrorLayer listed first, outermost.
let app = Router::new().route("/slow", get(slow)).layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_: BoxError| async {
StatusCode::REQUEST_TIMEOUT
}))
.timeout(Duration::from_millis(200)),
);
let start = std::time::Instant::now();
let res = send(app, "/slow").await;
println!(
"tower timeout: {} after {} ms",
res.status(),
start.elapsed().as_millis()
);
// Tower-http timeout returns a 408 itself, with no error handler.
let app = Router::new().route("/slow", get(slow)).layer(
ServiceBuilder::new().layer(
tower_http::timeout::TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
Duration::from_millis(200),
),
),
);
let start = std::time::Instant::now();
let res = send(app, "/slow").await;
println!(
"tower-http timeout: {} after {} ms",
res.status(),
start.elapsed().as_millis()
);
}
The output is:
tower timeout: 408 Request Timeout after 201 ms
tower-http timeout: 408 Request Timeout after 201 ms
The asymmetry matters: tower-http's timeout returns a response directly, so it needs no error handler, and wrapping it in one does not compile. Tower's timeout produces an error, so it needs the handler outside it. Check the import path when the two are confused: tower::timeout::TimeoutLayer against tower_http::timeout::TimeoutLayer. Also note that map_err cannot rescue a fallible layer here. Mapping the error to another error type still leaves an error that is not Infallible, and only Infallible converts into Infallible. The conversion into a response has to happen in a HandleErrorLayer, not in a mapping.
Read a builder failure as a bound failure, not a type mistake:
When a builder fails to compile, the error names the trait that is missing: Clone, or the conversion into Infallible. The fix is a wrapper, a buffer for cloneability and an outermost HandleErrorLayer for the error type, not a different layer. Adding the missing wrapper in the wrong position fails again, so check the listing order too.
Common mistakes
- Mixing builder and chained
.layer()calls without thinking. A builder passed to.layer(...)is one layer in the chain, and the chain's reverse-order rule applies to it as a unit. If the builder must run before a chained layer, the builder goes in the later.layer(...)call. option_layer(None)with a generic layer type.None::<TraceLayer>fails becauseTraceLayeris generic. Use a concrete type such asNone::<tower_http::timeout::TimeoutLayer>.- Putting a body-changing layer in
option_layer.TraceLayerin anoption_layerdoes not compile, because the two branches would disagree about the response body type. Use a plain.layer(...)call for those layers. - Putting
HandleErrorLayerinside the fallible layer. In a builder, the error handler must be listed first, outermost. Listed after the timeout, it never sees the timeout's error, and the builder does not compile. - Using tower's timeout where tower-http's was meant, or the reverse. They have opposite error behaviour. Tower's needs
HandleErrorLayer, and tower-http's forbids it. Check the import path. - Writing a filter predicate that returns a bool. The predicate must return a
Result, withOk(req)to forward andErr(error)to reject, and it takes the request by value. - Enabling
fulland forgetting the flags. In a real project, pin the features you use. A stack that only calls.layer(...)needs no tower features at all, and addingfullpulls in retry, load shedding and filter support you never call. - Calling
map_errto fix the axum error bound. It changes the error type but cannot produce anInfallible. Only an outerHandleErrorLayerconverts a real error into a response.
Summary
A builder is a Layer built from layers, listed in execution order: first listed runs first, the reverse of chained .layer() calls. Its methods fall into four groups: adding layers, tower built-ins, transforms, and finishing. Adding layers is layer, option_layer and layer_fn. The built-ins are timeout, concurrency_limit, rate_limit, buffer, load_shed and retry. The transforms are map_request, map_response, map_err, map_future, then, and_then, map_result, filter and filter_async. Finishing is service, service_fn, into_inner, the boxed forms and the check_* assertions. Each group has its feature flags, and tower ships with none enabled. Tower-http's ServiceBuilderExt adds one-liners for its common layers, including the request-id pair.
The decision framework to carry away has two questions. First, how long is the stack: one or two layers read fine as chained calls, and three or more read better as a builder, because the builder lists layers in execution order. Second, what does the compiler say: a builder that fails to compile is almost always failing one of the two bounds, and the fix is a wrapper in the right position, a buffer for a service that cannot be cloned, or an outermost error handler for a layer that can fail. When the bounds pass and the recorder prints the layers in the order they were listed, the builder is doing its job: the stack reads the way the request flows.