Tower middleware for composable HTTP service layers
Marcus Chen
Jan 2026
1 tab
use axum::{Router, routing::get};
use tower::ServiceBuilder;
use tower_http::{trace::TraceLayer, timeout::TimeoutLayer};
use std::time::Duration;
async fn handler() -> &'static str {
"Hello"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::new(Duration::from_secs(10)))
);
}
1 file · rust
Explain with highlit
Tower is a library of modular middleware (called "layers") for async services. Axum is built on Tower, so you can use any Tower middleware: TimeoutLayer, CompressionLayer, TraceLayer, etc. Layers wrap services, adding behavior like logging, metrics, or retries. The ServiceBuilder API chains layers in the order they're applied. I use tower-http for common HTTP concerns and write custom layers for domain-specific logic (auth, rate limiting). The beauty is that layers are decoupled from the framework: you can test them in isolation and reuse them across different servers. This composability is a key strength of the Rust async ecosystem.