expression

Axum: ServiceBuilder ordering

ServiceBuilder combines layers so request processing follows their declaration order. The return path runs in reverse. This is a different ordering convention from repeated Router::layer calls. In-memory standalone Cargo example. Expected stdout (not executed): A in B in handler B out A out Common mistake: Assuming ServiceBuilder has the same order as repeated Router::layer.

Formal Syntax & Structure

rust syntaxrust
ServiceBuilder::new().layer(a).layer(b)

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{routing::get, middleware::{self, Next}, response::Response};    async fn a(req: axum::extract::Request, next: Next) -> Response {        println!("A in"); let r = next.run(req).await; println!("A out"); r    }    async fn b(req: axum::extract::Request, next: Next) -> Response {        println!("B in"); let r = next.run(req).await; println!("B out"); r    }    let app = Router::new().route("/", get(|| async { println!("handler"); "ok" })).layer(tower::ServiceBuilder::new().layer(middleware::from_fn(a)).layer(middleware::from_fn(b)));    let _ = app.oneshot(Request::new(Body::empty())).await.unwrap();}
Rust Reference