Tower
Tower is a library of middleware traits (Service, Layer) for request/response services. Axum and many hyper clients compose timeouts, retries, and tracing as Tower layers.
Detailed Explanation
A Service is fn poll_ready plus fn call(request) -> Future<Response>. That is enough to describe an HTTP server, an HTTP client, a gRPC stack, or a channel worker. A Layer wraps a service and returns a new service. TimeoutLayer, ConcurrencyLimitLayer, TraceLayer are layers. You stack them with ServiceBuilder.
Axum's .layer(...) is Tower. When you add CORS, a timeout, or a request-id, you are composing Services. The same timeout layer can wrap a reqwest client through tower adapters. Learning Tower once pays off on both sides of the socket.
Order matters. The outermost layer sees the request first and the response last. A timeout outside a retry means the whole retry loop must finish inside the timeout. A timeout inside a retry means each attempt has its own budget. Draw the stack before you debug "why did it not retry".
You write a layer when you have a cross-cutting concern: authn, metrics, a custom header. You do not write a layer for business logic that belongs in one handler. A layer that needs application state can capture an Arc when you build the stack.
When you reach for a Tower layer: timeouts, tracing, limits, CORS, auth at the edge. When you reach for handler code: one route's rules. When you reach for a reverse proxy: TLS, gzip, and rate limits that you do not want in the process.
Test a layer with a fake inner Service that records the request and returns a fixed response. You do not need a listening socket to prove a timeout fires or a header is added. If the only test boots the whole app, a middleware bug will be a flaky integration failure instead of a ten-line unit test.
Code Examples
use std::time::Duration;
fn timeout_ms(ms: u64) -> Duration {
Duration::from_millis(ms)
}
fn main() {
// tower::ServiceBuilder::new().layer(tower::timeout::TimeoutLayer::new(timeout_ms(500)));
println!("{}ms", timeout_ms(500).as_millis()); // prints: 500ms
}Common Gotchas
Layer order is easy to get backwards
Read the stack from the outside in for requests. Timeouts versus retries is the usual footgun.
`poll_ready` is backpressure
A layer that ignores readiness can overflow an inner service. Use `ServiceBuilder` helpers rather than a hand-rolled `call`.
Axum layers are Tower layers
A crate that says "Tower middleware" will plug into `.layer`. A random Actix middleware will not.
A layer that `.await`s a std lock blocks the worker
The same async rules apply inside middleware.