Manual Service Implementation for Middleware in Axum
Learn how to write a tower Service by hand as middleware - short-circuiting, response inspection, readiness gating, and the exact bounds axum requires
What a manual middleware service is
A middleware service is a wrapper. It holds another service inside it, called the inner service, and it sits between the client and the handler. Every request passes through the wrapper first. The wrapper can look at the request, decide whether the inner service should run at all, wait for the inner service to finish, and then look at the response before it goes back to the client.
The word service here means something specific. A service is a value that takes a request and returns a future, and that future eventually produces a response. A future is a value that represents work that is not finished yet. When Rust runs a future to completion, the work happens and the response appears. The tower crate defines this idea as the Service trait, and axum builds all of its middleware on top of it. A trait is a set of methods a type promises to provide. The Service trait promises two methods, poll_ready and call, and three associated types, Response, Error, and Future. An associated type is a type that a trait leaves for each implementation to choose.
Most middleware never needs a hand-written service. A small async function passed to the from_fn helper covers logging, auth checks, header stamping, and most other everyday jobs with far less code. A manual service earns its keep in four situations, and those four are the subject of this page. The first is observing a request and a response while counting or stamping, with the count shared across requests. The second is short-circuiting with shared state that a closure captures awkwardly. The third is inspecting or changing the response body. The fourth is gating on readiness, which only poll_ready can express. The service also controls its own future type, through the boxed future in the shape section below, but that is a property of every service on this page, not a separate pattern. If none of those four applies, the function-based helper is the better tool, and this page says so plainly so the reader does not reach for the heavier tool by habit.
Think of the wrapper as a checkpoint on a road. The handler is the town at the end of the road. A checkpoint can count the cars, turn some cars back, inspect the cargo on the way out, or close the road until the town is ready. It cannot do any of that unless it is built as a service, because axum only lets services sit on that road.
The smallest working service
Before the four patterns, here is the smallest service that does anything at all. It adds one fixed header to every response and otherwise passes the request straight through to the handler. It is small enough to hold in one view, and every later example on this page is the same shape with more work added inside.
use axum::{
extract::Request,
http::{HeaderName, HeaderValue},
response::Response,
routing::get,
Router,
};
use futures_util::future::BoxFuture;
use std::{convert::Infallible, task::{Context, Poll}};
use tower::{Layer, Service};
#[derive(Clone)]
struct AddHeaderService<S> {
inner: S,
name: &'static str,
value: &'static str,
}
impl<S> Service<Request> for AddHeaderService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let (name, value) = (self.name, self.value);
let future = self.inner.call(request);
Box::pin(async move {
let mut response = future.await?;
response.headers_mut().insert(
name.parse::<HeaderName>().unwrap(),
value.parse::<HeaderValue>().unwrap(),
);
Ok(response)
})
}
}
#[derive(Clone)]
struct AddHeaderLayer {
name: &'static str,
value: &'static str,
}
impl<S> Layer<S> for AddHeaderLayer {
type Service = AddHeaderService<S>;
fn layer(&self, inner: S) -> Self::Service {
AddHeaderService {
inner,
name: self.name,
value: self.value,
}
}
}
async fn hello() -> &'static str {
"hello"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.layer(AddHeaderLayer {
name: "x-powered-by",
value: "hand-rolled",
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
[package]
name = "manual-service"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower = "=0.5.3"
futures-util = "0.3"
A layer is the other half of the pair. A layer is a factory that takes an inner service and returns a wrapped service. The AddHeaderLayer above holds the header name and value, and its layer method builds an AddHeaderService around whatever inner service axum hands it. The router calls the layer, the layer builds the service, and the service does the work on each request. The layer constructs, the service executes.
Run the program with cargo run, then request the root path. The response body is hello, and the response carries the header x-powered-by: hand-rolled. The header is the proof the wrapper ran. Without the layer, the same request returns the same body with no such header. The name and value fields are plain &'static str values, which means string data that lives for the whole run of the program. They are copied into each fresh service, so they are configuration, not shared state. Shared state looks different, and the next section shows how.
A service always wraps something:
A manual service is never used on its own. It always wraps an inner service, and the inner service is usually the router's own route handler stack. If a service has no inner service to call, it is not middleware. It is a handler written the hard way, and a plain handler function would serve better.
The shape axum requires
The small example above already contains every piece axum demands. This section takes those pieces apart one by one, because the compiler errors in this area name these pieces directly, and a reader who knows what each piece means can fix the error instead of guessing.
The three associated types come first. type Response = Response says the service produces a full axum response. Response here is axum::response::Response, the response type handlers produce. type Error = Infallible says the service cannot fail. Infallible is a type that can never be constructed, so a function returning Result<T, Infallible> can never return the error case. type Future = BoxFuture<'static, Result<Response, Infallible>> says the future returned by call is a boxed future. A boxed future is a future stored behind a pointer on the heap, which lets the service return one fixed type no matter what the async block inside does. BoxFuture comes from the futures-util crate. The 'static part means the future must not borrow anything short-lived. It must own everything it uses, which is why the async block is written async move. The word Pin appears in the full name of the boxed type, and it means the future is pinned in memory so it cannot be moved while it is running. A beginner does not need to manage pinning by hand. Using Box::pin handles it.
The where clause carries the bounds on the inner service. S: Service<Request, Response = Response, Error = Infallible> says the inner service must itself produce an axum response and never fail. S: Send + 'static says the inner service can be moved between threads and does not borrow short-lived data. Send is a marker that means a value is safe to send to another thread. S::Future: Send + 'static says the same about the future the inner service returns. Axum serves requests on a multi-threaded runtime, so a middleware future that cannot cross threads cannot be served. These bounds are the reason the compiler rejects a service whose inner future holds a non-Send value, such as a standard library mutex guard held across an await point.
The poll_ready method is the readiness check. poll_ready asks the service whether it is ready to accept a request, and it answers with Poll::Ready or Poll::Pending. Poll is an enum with two variants. Ready means the answer is available now. Pending means not yet, and the task will be woken when the answer changes. The example forwards the check to the inner service with self.inner.poll_ready(cx). Forwarding matters because the inner service may have its own limits, such as a concurrency limit that is full. If the wrapper never asks, the inner limit becomes invisible and requests are accepted that the inner service cannot handle. Forward poll_ready in every pattern except an explicit readiness gate, which is the fourth pattern below.
The call method does the work. It takes the request, hands it to the inner service with self.inner.call(request), and returns a boxed future. The future waits for the inner response with future.await, stamps the header, and returns the response. The ? after future.await propagates an error if one occurs. Since the error type is Infallible, that error can never actually happen, but the ? is still needed because the types demand it.
One more bound sits on the service struct itself. Axum requires the produced service to be Clone, which means it can be duplicated cheaply. The struct derives Clone, and every field must be Clone too. A bare Mutex field or a channel receiver is not Clone, so it breaks the bound. Shared state goes behind an Arc instead. An Arc is a reference-counted pointer that lets many owners share one value, and cloning an Arc is cheap because it shares the value instead of copying it.
Borrowing inside the boxed future does not compile:
The future must be 'static, so the async block must own everything it uses. Borrowing self or the request inside the async block is the usual cause of the error. The fix is to move the needed values out before Box::pin, exactly as the example moves name and value into local variables first. The compiler error mentions a lifetime, but the repair is always the same. Move the values, then pin.
Pattern one - observe and pass through
The first pattern is the counting service. It does something on the way in, calls the inner service, and does something on the way out. Here it counts requests and stamps each response with the running total. The service and its layer look like this.
use axum::{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};
#[derive(Clone)]
struct CountingService<S> {
inner: S,
counter: Arc<AtomicUsize>,
}
impl<S> Service<Request> for CountingService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let n = self.counter.fetch_add(1, Ordering::SeqCst) + 1;
let future = self.inner.call(request);
Box::pin(async move {
let mut response = future.await?;
response
.headers_mut()
.insert("x-request-count", n.to_string().parse().unwrap());
Ok(response)
})
}
}
#[derive(Clone)]
struct CountingLayer {
counter: Arc<AtomicUsize>,
}
impl CountingLayer {
fn new() -> (Self, Arc<AtomicUsize>) {
let counter = Arc::new(AtomicUsize::new(0));
(Self {
counter: counter.clone(),
}, counter)
}
}
impl<S> Layer<S> for CountingLayer {
type Service = CountingService<S>;
fn layer(&self, inner: S) -> Self::Service {
CountingService {
inner,
counter: self.counter.clone(),
}
}
}
An AtomicUsize is a counter that many threads can increment safely without a lock. fetch_add(1, Ordering::SeqCst) adds one and returns the old value, so adding one to the result gives the request number. Ordering::SeqCst is the strictest memory ordering, and it is the safe default while learning. The counter lives inside an Arc, and the layer holds that Arc. Every service the layer builds receives a clone of the same Arc, so every service increments the same counter.
That sharing is load-bearing. In axum 0.8, a fresh middleware service is built for every request on a normal route, so a plain number stored in the service struct would reset to zero on every request. The Arc survives the rebuild because the layer holds it and hands a clone to each fresh service. Three requests to a router carrying this layer return x-request-count: 1, then 2, then 3. That sequence is the proof the sharing works. The constructor returns both the layer and a handle to the counter, so the rest of the program can read the same count. A test can send three requests and assert the header each time, then assert the handle reads 3.
The split to remember is simple. Configuration lives in the service as plain copied values, like the header name and value in the earlier example. Shared mutable state lives behind an Arc, held by the layer and cloned into each service. That split is the rule for every service on this page.
The count 1, 2, 3 means the sharing works:
If three requests return x-request-count: 1, then 2, then 3, the Arc sharing is correct. If every request returns 1, the counter is a plain field in the service struct instead of an Arc held by the layer. That single symptom diagnoses the single most common mistake on this page.
Pattern two - short-circuit
A short-circuit service returns a response without calling the inner service at all. The handler never runs, the inner service never sees the request, and the client still gets a well-formed response. Maintenance mode is the cleanest example. A flag shared through an Arc decides whether requests reach the handler.
use axum::{
body::Body, extract::Request, http::StatusCode, response::Response,
};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
task::{Context, Poll},
};
use tower::{Layer, Service};
#[derive(Clone)]
struct MaintenanceService<S> {
inner: S,
maintenance: Arc<AtomicBool>,
}
impl<S> Service<Request> for MaintenanceService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
if self.maintenance.load(Ordering::SeqCst) {
return Box::pin(async move {
Ok(Response::builder()
.status(StatusCode::SERVICE_UNAVAILABLE)
.body(Body::from("maintenance"))
.unwrap())
});
}
let future = self.inner.call(request);
Box::pin(async move { future.await })
}
}
#[derive(Clone)]
struct MaintenanceLayer {
maintenance: Arc<AtomicBool>,
}
impl<S> Layer<S> for MaintenanceLayer {
type Service = MaintenanceService<S>;
fn layer(&self, inner: S) -> Self::Service {
MaintenanceService {
inner,
maintenance: self.maintenance.clone(),
}
}
}
An AtomicBool is a flag that many threads can read and write safely. While the flag is on, every request gets status 503 with the body maintenance. While the flag is off, requests pass through to the handler and get status 200. The flag is an Arc<AtomicBool>, so the application can flip maintenance mode on and off at runtime, from an admin endpoint, a signal handler, or a config reload, and the change takes effect on the next request because every rebuilt service clones the same Arc.
The same shape sits behind auth failures and feature flags. Check a condition, and either return early or call through. The function-based helper does the same thing in fewer lines, so the manual form earns its keep only when the condition needs shared state with richer behaviour than a closure captures cleanly, or when the service is part of a larger hand-built stack. A beginner should reach for the helper first and move to this pattern when the helper starts to feel cramped.
Short-circuit means the handler never runs:
Returning early is not the same as returning an error. The client receives a normal response with a 503 status, and nothing downstream runs. Logging, tracing, or metrics middleware placed inside this service will not see the request at all, because the request never reaches them. Put any middleware that must observe every request outside the short-circuiting layer.
Pattern three - inspect the response
The counting service already inspects the response in a small way. It changes a header after the inner future resolves. The full form of the pattern reads the response before returning it. Two versions of the idea cover most real uses. The cheap version reads only the status code and headers. The expensive version reads the body.
The cheap version logs the status of every response into shared state. Its call method waits for the inner response, records the status, and returns the response untouched.
use axum::{extract::Request, response::Response};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use tower::{Layer, Service};
#[derive(Clone)]
struct StatusLogService<S> {
inner: S,
seen: Arc<Mutex<Vec<u16>>>,
}
impl<S> Service<Request> for StatusLogService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request) -> Self::Future {
let seen = self.seen.clone();
let future = self.inner.call(request);
Box::pin(async move {
let response = future.await?;
seen.lock().unwrap().push(response.status().as_u16());
Ok(response)
})
}
}
#[derive(Clone)]
struct StatusLogLayer {
seen: Arc<Mutex<Vec<u16>>>,
}
impl<S> Layer<S> for StatusLogLayer {
type Service = StatusLogService<S>;
fn layer(&self, inner: S) -> Self::Service {
StatusLogService {
inner,
seen: self.seen.clone(),
}
}
}
A Mutex is a lock that lets one thread at a time touch the value inside it. The shared list holds the status codes the service has seen. After one request to a handler that returns 200, the list holds [200]. Status and header inspection costs nothing extra, because the response is already in memory at that point. Everything after future.await runs on the response path, so a slow inspection delays every response. Keep it cheap.
The expensive version reads the body. A response body is a stream, not a buffer, which means its bytes arrive piece by piece and reading them consumes them. A service that inspects the body must collect it and rebuild a new response from the collected bytes, or it will return an empty body to the client. The example below appends a marker to a text body, which shows the whole collect-and-rebuild dance in one place.
use axum::{body::Body, extract::Request, response::Response};
use futures_util::future::BoxFuture;
use std::{convert::Infallible, task::{Context, Poll}};
use tower::{Layer, Service};
#[derive(Clone)]
struct SuffixService<S> {
inner: S,
}
impl<S> Service<Request> for SuffixService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
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?;
let (mut parts, body) = response.into_parts();
let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let mut text = String::from_utf8(bytes.to_vec()).unwrap();
text.push_str(" [checked]");
parts.headers.insert(
"content-length",
text.len().to_string().parse().unwrap(),
);
Ok(Response::from_parts(parts, Body::from(text)))
})
}
}
#[derive(Clone)]
struct SuffixLayer;
impl<S> Layer<S> for SuffixLayer {
type Service = SuffixService<S>;
fn layer(&self, inner: S) -> Self::Service {
SuffixService { inner }
}
}
into_parts splits a response into its head, which holds the status and headers, and its body. axum::body::to_bytes collects the whole body stream into one block of bytes, waiting for every piece. Response::from_parts joins a head and a new body back into a response. The content-length header is updated because the body grew by ten characters. A handler returning hello now returns hello [checked]. Collecting the body also removes streaming, so a large download would be buffered in memory instead of flowing to the client piece by piece. Only inspect bodies when there is a genuine reason, such as an audit log or a response transformer, and prefer status-and-headers inspection everywhere else.
Reading a body without rebuilding it empties the response:
The body stream is consumed on read. A service that collects the body and then returns the original response sends an empty body to the client, with no error and no warning. Always build a new response from the collected bytes, and always fix the content-length header when the body changes size.
Pattern four - gate on readiness
poll_ready is the one method the function-based helper cannot express, and it is the reason manual services exist for load shedding. A service can refuse to become ready by returning Poll::Pending until a condition holds. A downstream dependency might be unhealthy, a warm-up might not have finished, or a circuit breaker might be open. While the service reports pending, the caller waits instead of sending the request into a service that cannot handle it.
A correct gate must arrange for the waiting task to be woken when the condition flips, or the request waits forever. The waker is stored in shared state and woken by whoever flips the flag. A waker is a small handle the runtime uses to wake a task that is waiting. The example below holds the flag and the waker in Arc values so the layer, the service, and the code that flips the flag all share them.
use axum::{extract::Request, response::Response};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
task::{Context, Poll, Waker},
};
use tower::{Layer, Service};
#[derive(Clone)]
struct GateService<S> {
inner: S,
ready: Arc<AtomicBool>,
waker: Arc<Mutex<Option<Waker>>>,
}
impl<S> Service<Request> for GateService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
if !self.ready.load(Ordering::SeqCst) {
*self.waker.lock().unwrap() = Some(cx.waker().clone());
return Poll::Pending;
}
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 })
}
}
#[derive(Clone)]
struct GateLayer {
ready: Arc<AtomicBool>,
waker: Arc<Mutex<Option<Waker>>>,
}
impl GateLayer {
fn new() -> (Self, Arc<AtomicBool>, Arc<Mutex<Option<Waker>>>) {
let ready = Arc::new(AtomicBool::new(false));
let waker = Arc::new(Mutex::new(None));
(
Self {
ready: ready.clone(),
waker: waker.clone(),
},
ready,
waker,
)
}
}
impl<S> Layer<S> for GateLayer {
type Service = GateService<S>;
fn layer(&self, inner: S) -> Self::Service {
GateService {
inner,
ready: self.ready.clone(),
waker: self.waker.clone(),
}
}
}
The constructor returns the layer plus handles to the flag and the waker, so the rest of the program can open the gate. Whoever flips the flag wakes the stored waker, and the waiting request is polled again and proceeds. The flipping code looks like this.
ready.store(true, Ordering::SeqCst);
if let Some(wk) = waker.lock().unwrap().take() {
wk.wake();
}
A request sent while the gate is closed waits in poll_ready. Flipping the flag and waking the stored waker lets it through with a 200. In a runtime check, the request waited about 150 milliseconds, which was the delay before the flag flipped, and then completed normally. The wiring below is the complete program that produces that check: the gate starts closed, a background task opens it after 150 milliseconds, and one request is sent while it is still closed.
use axum::{extract::Request, routing::get, Router};
use std::{
sync::{atomic::Ordering, Arc},
time::{Duration, Instant},
};
use tower::ServiceExt;
async fn hello() -> &'static str {
"hello"
}
#[tokio::main]
async fn main() {
let (layer, ready, waker) = GateLayer::new();
let app = Router::new().route("/", get(hello)).layer(layer);
tokio::spawn({
let ready = ready.clone();
let waker = waker.clone();
async move {
tokio::time::sleep(Duration::from_millis(150)).await;
ready.store(true, Ordering::SeqCst);
if let Some(wk) = waker.lock().unwrap().take() {
wk.wake();
}
}
});
let start = Instant::now();
let res = app
.oneshot(
Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
println!(
"gate opened after {} ms, status {}",
start.elapsed().as_millis(),
res.status()
);
}
The program prints gate opened after 150 ms, status 200 OK, with the exact millisecond count varying slightly by run. The request is sent before the background task opens the gate, so it waits in poll_ready until the wake arrives, and only then runs the handler. oneshot is a tower test helper that sends one request through the router in memory, without starting a server. The shape is the point. poll_ready is where readiness lives, call is where work happens, and a manual service is the only way to write the first. A ready-made load-shedding layer exists in tower, so write a gate of this kind only when its behaviour does not fit.
A gate that never wakes is a hang:
Returning Poll::Pending without storing the waker means nobody can wake the waiting task, and the request waits forever with no error. Every path that returns pending must store cx.waker().clone(), and every path that opens the gate must wake the stored waker. Test a gate by sending a request while it is closed and confirming it completes after the flag flips.
Error handling - returning a response instead of an error
The services above all use Error = Infallible. They cannot fail, because every error path is converted inside call. A short-circuit returns a response instead of an error, and the inner service cannot fail by the bound. That is the convenient choice in axum, and it is why no error-handling layer is needed around them.
The alternative is Error = BoxError. A BoxError is a boxed error that can hold any error type, which means the service can fail in ways the caller must handle. The error must then be handled by an outer HandleErrorLayer that converts it into a response. HandleErrorLayer lives in axum::error_handling. There is no equivalent in tower-http, so importing it from tower-http does not compile. The example below is a service that fails when a shared flag is on, wrapped so the failure becomes a 502 response.
use axum::{
error_handling::HandleErrorLayer, extract::Request, http::StatusCode,
response::Response, routing::get, BoxError, Router,
};
use futures_util::future::BoxFuture;
use std::{
convert::Infallible,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
task::{Context, Poll},
};
use tower::{Layer, Service, ServiceBuilder};
#[derive(Clone)]
struct FailSometimesService<S> {
inner: S,
fail: Arc<AtomicBool>,
}
impl<S> Service<Request> for FailSometimesService<S>
where
S: Service<Request, Response = Response, Error = Infallible> + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = BoxError;
type Future = BoxFuture<'static, Result<Response, BoxError>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
match self.inner.poll_ready(cx) {
Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
Poll::Ready(Err(e)) => match e {},
Poll::Pending => Poll::Pending,
}
}
fn call(&mut self, request: Request) -> Self::Future {
if self.fail.load(Ordering::SeqCst) {
return Box::pin(async move {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"upstream failed",
)) as BoxError)
});
}
let future = self.inner.call(request);
Box::pin(async move {
match future.await {
Ok(response) => Ok(response),
Err(e) => match e {},
}
})
}
}
#[derive(Clone)]
struct FailSometimesLayer {
fail: Arc<AtomicBool>,
}
impl<S> Layer<S> for FailSometimesLayer {
type Service = FailSometimesService<S>;
fn layer(&self, inner: S) -> Self::Service {
FailSometimesService {
inner,
fail: self.fail.clone(),
}
}
}
async fn hello() -> &'static str {
"hello"
}
#[tokio::main]
async fn main() {
let fail = Arc::new(AtomicBool::new(true));
let app = Router::new().route("/", get(hello)).layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|err: BoxError| async move {
(StatusCode::BAD_GATEWAY, format!("handled: {err}"))
}))
.layer(FailSometimesLayer { fail: fail.clone() }),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Two details in this listing deserve attention. The match e {} arms handle the Infallible error from the inner service. An empty match on Infallible is exhaustive because the type has no values, so it tells the compiler the error case is impossible without any runtime code. The ServiceBuilder lists the HandleErrorLayer first, which makes it the outermost layer, so it sees the error before anything else. With the flag on, a request returns status 502 with a body that starts handled: upstream failed. With the flag off, the same request returns 200. A router layer whose service can fail does not compile on its own, because axum requires the error to convert into Infallible. The HandleErrorLayer is what makes the fallible form legal.
Choose BoxError only when the middleware failure is genuinely an error that the caller should decide how to render, such as a timeout or a failed upstream call. For everything else, Infallible with an early response is simpler, and it keeps the error-handling surface out of the router.
Common mistakes
Forgetting Clone is the first mistake. Axum requires the service to be Clone, and the derive fails if any field is not Clone. Wrap shared state in an Arc and keep configuration in Clone types.
Not forwarding poll_ready is the second. The inner service backpressure disappears, and requests are accepted that cannot be served. Forward it in every pattern except an explicit readiness gate, and even there, forward it once the gate opens.
State in the service struct instead of an Arc is the third. A plain counter or flag in the service resets on every request in axum 0.8, because the service is rebuilt per request. Shared state lives in the layer, behind an Arc, and the service holds a clone.
BoxFuture lifetime errors are the fourth. The future must be 'static, so the async block must own everything it uses. Move the inner future and any values into the block. A borrow of self or of the request inside the async block is the usual cause, and the fix is to move the needed values out before Box::pin.
Reading a response body without rebuilding it is the fifth. The body stream is consumed on read. Collect it and build a new response, or do not read it at all.
Writing a manual service where the function-based helper would do is the sixth. The manual form is more code, more bounds, and more ways to get the bounds wrong. Use it for the four patterns above, and use the helper for everything else.
Summary
The decision framework for this page has three questions. The first question is whether the job needs something the function-based helper cannot express. Observing a request and stamping the response while counting, short-circuiting with shared state, body inspection, and readiness gating are the four cases where the manual form earns its keep. The second question is where the state lives. Configuration goes in the service by value, shared state goes in the layer behind an Arc, and nothing shared goes in the service struct itself, because the service is rebuilt per request and only the Arc survives. The third question is how failure is reported. Return a response and keep Error = Infallible whenever the middleware itself decides what the client sees, and reach for Error = BoxError with an outer HandleErrorLayer only when the caller should decide. A service that answers those three questions the same way every time is a service a reader can trust, and the layer that builds it is the subject of the companion lesson on manual layers.