Contents
When people talk about Rust HTTP middleware, Tower comes up fast.
Tower is protocol-agnostic middleware plumbing; Service and Layer are how you stack Logger, timeout, and handler layers.
A bare handler
Start from hyper’s hello-world handler:
1 | use http_body_util::Full; |
service_fn turns the async fn into something that implements Service—what the server actually calls. That’s the hook middleware wraps.
After hyper v1, this
Serviceis not literally tower’s trait, but the shape matches. We’ll contrast the interfaces later.
To add logging and a five-second timeout around the handler:

1 | let svc = hyper::service::service_fn(handler); |
Service trait
Each middleware is another link in a chain: handle side effects, then delegate inward.
Tower’s Service:
1 | pub trait Service<Request> { |
poll_ready gates call. call returns a Future so slow work doesn’t block the caller’s ability to accept other requests.
Why Future instead of async fn in the trait? Historical—async in traits wasn’t stable yet. Since Rust 1.75 you could write:
1 | trait Service<Request> { |
A Logger middleware
1 | use tower::Service; |
Wire it manually:
1 | let svc = Logger::new(svc); |
Then timeout:
1 | let svc = Timeout::new(svc, std::time::Duration::from_secs(5)); |
That’s awkward—last wrapped runs first—and not chain-friendly. Layer fixes ordering and ergonomics.
Layer trait
1 | pub trait Layer<S> { |
Implement it for Logger:
1 | impl<S> Layer<S> for Logger<S> { |
Then build in call order:
1 | tower::ServiceBuilder::new() |
layer_fn adapts closures into Layer. Middleware runs in the same order you .layer() it.
hyper’s Service trait
Hyper used to depend on tower’s Service. Before v1 stabilized, it switched to its own trait:
- tower wasn’t stable yet
- hyper wanted a thinner surface: drop
poll_ready, and take&selfincall(shared state viaArc<Mutex<_>>if you need mutation)
1 | pub trait Service<Request> { |
Reusing tower middleware (e.g. Timeout) against hyper often needs an adapter:
1 | let svc = TowerToHyperService::new(svc); |
Frameworks built on hyper—Axum, Actix Web, and others—also integrate tower, so middleware written once tends to travel.
Tower’s Service/Layer split looks obvious in hindsight; getting Future-returning call right took real design work. Tokio’s write-up is worth it: Inventing the Service trait.
For a live build-through: David Pedersen’s Tower deep dive (search “Tower deep dive” on Bilibili if YouTube is blocked).
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
