Tower Service and Layer Idea

Understand the Tower Service and Layer abstractions that power Axum middleware, with beginner-friendly explanations and practical examples.

Tower is a library that gives Rust developers a standard way to build and combine network services. It provides two central abstractions - the Service trait and the Layer trait - that together form the foundation of Axum's middleware system. If you have ever wondered how Axum adds timeouts, logging, compression, or authentication to your endpoints without forcing you into a custom plugin API, this page explains the core idea. By the end of this page, you will know what a Service is, what a Layer does, how they compose, and why this design makes Axum so flexible. You will also see small code examples that illustrate the concepts, even though you will not build a full web server here.

Why Tower exists

Before Tower, different Rust networking libraries each defined their own way of handling requests and building middleware. A library for HTTP servers had one middleware system, a library for gRPC had another, and a custom TCP server had a third. Developers had to learn a new abstraction every time they switched tools. Tower solves this by defining one generic, protocol-agnostic contract that any network service can follow. A service that receives a request and returns a response can be described by the same Service trait, whether it is handling HTTP, gRPC, raw TCP, or anything else. Middleware can then be written once and reused across different protocols. That is why Axum does not invent its own middleware API. Axum says: "I will use Tower's Service trait." This immediately gives Axum access to a whole ecosystem of middleware that works with other libraries like Hyper and Tonic. It also means you can share middleware between an Axum web server and a Tonic gRPC server, which is a huge advantage in real projects.

The big idea:

Tower is not a web framework and not a middleware library by itself. It is a set of abstractions - interfaces, if you will - that let services and middleware talk to each other in a uniform way. Axum builds on top of those abstractions.

The Service trait - an async function from request to response

The most important thing in Tower is the Service trait. In plain words, a service is something that takes a request and asynchronously returns a result that is either a response or an error. It is like an async function, but wrapped in a trait so that it can have extra structure. Here is a simplified look at the trait as defined in the tower-service crate (which Tower re-exports):

use std::future::Future;

pub trait Service<Request> {
    type Response;
    type Error;
    type Future: Future<Output = Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>>;

    fn call(&mut self, req: Request) -> Self::Future;
}

Let's unpack this line by line.

  • Service<Request> - the trait is generic over the request type. A service that handles HTTP requests would have Request equal to http::Request<Body>; a service that handles database commands would have a different Request type.
  • type Response - the type of successful response the service produces.
  • type Error - the type of error that can happen while processing.
  • type Future - the asynchronous computation that the call method returns. It must produce a Result<Response, Error>.
  • poll_ready - used by the runtime (like Tokio) to check whether the service is ready to accept another request. For simple services this often just returns Poll::Ready(Ok(())), meaning "I am always ready".
  • call - performs the actual work. It takes the request and returns a future that will eventually resolve to either a response or an error. A beginner should think of a Service as a box that accepts a request and eventually produces a result. The box may be simple, like a function that converts a string to uppercase, or complex, like a full HTTP handler that queries a database.

A minimal Service implementation

Even before you use Axum, you can implement a Service manually to see the pattern. Suppose we want a service that takes an integer and returns that integer multiplied by two.

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tower::Service;

// A service that doubles an integer.
struct DoubleService;

impl Service<i32> for DoubleService {
    type Response = i32;
    type Error = std::convert::Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: i32) -> Self::Future {
        let doubled = req * 2;
        Box::pin(async move { Ok(doubled) })
    }
}

In this code, the DoubleService implements Service<i32>. The associated Response type is also i32. The Error type is Infallible, which is a special type meaning "this can never fail". The Future type is a boxed future because we don't want to define a custom named future type. The poll_ready always returns ready. The call method returns a future that immediately produces the doubled value.

If this compiles, you have understood the Service idea:

You don't need to write such services yourself in Axum, because Axum's Router already implements Service. But seeing a raw implementation removes the magic: a Service is just a struct with an async call method and a poll_ready method.

How a Service is used by a runtime

A runtime like Tokio does not call call directly in a loop. Instead, it asks the service if it is ready with poll_ready, and if so, invokes call and polls the returned future. This separation allows services to signal backpressure - for example, a service that is overloaded can return Poll::Pending from poll_ready until it has capacity again. For most services you will encounter in Axum, poll_ready is always Ready.

The Layer trait - a factory for wrapping services

A Service alone is not enough to build middleware. The problem is this: middleware often needs to wrap another service. For example, a logging middleware wants to log the request, then call the inner service, then log the response. A timeout middleware wants to start a timer, call the inner service, and cancel if it takes too long. We could write a new Service implementation for each such wrapper, but we also need a way to create those wrappers from a configuration. That is where the Layer trait comes in. A Layer is a factory that takes an inner service and returns a new service that wraps it. It is a way to add behavior to a service without changing the inner service itself. Here is the simplified definition:

pub trait Layer<S> {
    type Service;

    fn layer(&self, inner: S) -> Self::Service;
}
  • Layer<S> is generic over the inner service type S.
  • type Service is the type of the new, wrapped service.
  • layer(&self, inner: S) -> Self::Service takes ownership of the inner service and returns the wrapped service. A beginner mental model: a Layer is like a blueprint for decorating a service. You hand it a service, and it hands you back a new service with extra powers. The original service is still inside, but now there are additional steps before or after the original call.

A minimal Layer implementation

Let's create a LoggingLayer that wraps any service, prints a message before and after calling the inner service, and then returns the same response. We need a wrapper service that holds the inner service and also implements Service. We'll make it generic over the inner service.

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tower::{Layer, Service};

// A Layer that adds logging around any inner service.
#[derive(Clone)]
struct LoggingLayer;

impl<S> Layer<S> for LoggingLayer {
    type Service = LoggingService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        LoggingService { inner }
    }
}

// The service produced by LoggingLayer.
#[derive(Clone)]
struct LoggingService<S> {
    inner: S,
}

impl<S, Req> Service<Req> for LoggingService<S>
where
    S: Service<Req> + Clone,
    S::Future: 'static,
    S::Error: 'static,
    Req: 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Req) -> Self::Future {
        println!("Request received");
        let mut inner = self.inner.clone();
        let fut = inner.call(req);
        Box::pin(async move {
            let response = fut.await;
            println!("Response ready");
            response
        })
    }
}

This example shows how a Layer produces a LoggingService that wraps an inner service. The call method prints before delegating and prints after the inner future completes. This is the essence of middleware: code that runs before and after the inner service.

Cloning the inner service:

In this example we clone the inner service before calling it because call takes &mut self, and the clone is what lets us move the inner service into the async block. That is why the impl block requires S: Service<Req> + Clone - without the Clone bound, self.inner.clone() does not compile. Many services are cheap to clone (they might hold an Arc internally), so this is common. But if your service is not Clone, you would need a different design, such as using &mut self directly in an async block. Real middleware often uses Buffer or Arc to handle this.

Composing Layers - the middle of the onion

A single Layer is useful, but the real power comes when you stack many Layers. Each Layer wraps the previous service, producing a new service. The result is like an onion: the outermost layer handles the request first, then passes it inward, and each layer adds its own behavior on the way in and on the way out. You can compose layers manually by calling .layer() repeatedly:

use std::time::Duration;
use tower::timeout::TimeoutLayer;

let base_service = MyAppService::new();

let with_logging = LoggingLayer.layer(base_service);
let with_timeout = TimeoutLayer::new(Duration::from_secs(5)).layer(with_logging);
let with_trace = TraceLayer::new_for_http().layer(with_timeout);

In this snippet, TraceLayer is the outermost service. When a request arrives, TraceLayer runs first, then passes to the timeout wrapper, then to the logging wrapper, and finally to the original app service. The response travels back through the same layers in reverse order.

How to picture the stack:

Imagine a stack of nested boxes. The outermost box sees the request first and the response last. The innermost box is your actual handler logic. Each box can modify the request on the way in, modify the response on the way out, or short-circuit (e.g., return an error without calling the inner service).

Why Axum uses Tower instead of a custom middleware system

Axum's Router is itself a Service. When you call axum::serve(listener, app), Axum converts the Router into a Service and gives it to Hyper to run. Because Router implements Service, you can apply any Tower Layer to it with the .layer() method. That method itself is Axum's own - Router::layer is defined by Axum, not by Tower - but the layers you pass to it are Tower layers, which is what makes the whole ecosystem interchangeable. This design has several practical benefits:

  • One middleware system for many libraries: A middleware written for Tower works with Axum, Hyper, Tonic, and any other Tower-based library. You learn Tower once, and you can use it everywhere.
  • Huge existing ecosystem: The tower-http crate provides dozens of ready-made middleware layers for HTTP: compression, CORS, tracing, request ID, timeouts, and more. Axum gets all of them for free.
  • Composability: Layers can be combined in any order, and each layer is independent. You can create a custom layer for your business logic and mix it with existing ones.
  • Backpressure and resource management: The poll_ready mechanism allows services to limit concurrency or apply backpressure in a standard way. This is important for high-performance systems.

Don't confuse Axum middleware with Tower layers:

Axum does have a middleware module that provides helpers like from_fn, but these are built on top of Tower's Service and Layer. The fundamental abstraction is still Tower. When someone says "Axum middleware," they usually mean "a Tower layer applied to an Axum service." Understanding this distinction prevents confusion later when you see both middleware::from_fn and tower::Layer.

A concrete Axum example with layers

While we are not building a full Axum app yet, you can already see how Tower layers appear in Axum code. Suppose you have a basic Axum router and want to add timeout and tracing. The code would look like this:

use axum::{http::StatusCode, routing::get, Router};
use tower_http::{timeout::TimeoutLayer, trace::TraceLayer};
use std::time::Duration;

async fn handler() -> &'static str {
    "Hello, world!"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(10),
        ))
        .layer(TraceLayer::new_for_http());

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here, .layer(TimeoutLayer::with_status_code(...)) wraps the router with a timeout service. Then .layer(TraceLayer::new_for_http()) wraps that with tracing. Because Router implements Service, it can be wrapped by any Tower layer. The order matters: the last .layer() call becomes the outermost layer, so TraceLayer sees the request first, then TimeoutLayer, then the router. If you run this, every request to / will be traced (logged) and will time out if it takes longer than 10 seconds. A request that times out gets a 408 Request Timeout response.

Use the tower-http timeout layer, not tower's:

Tower also has its own tower::timeout::TimeoutLayer, and it looks interchangeable - it is not, for Axum. Tower's version reports a timeout as an error, and Router::layer only accepts layers whose error type can be converted into Infallible, so the code will not compile. The tower_http::timeout::TimeoutLayer used above answers a timeout with a 408 Request Timeout response instead, which is why it works with a router. When a layer reports errors instead of responses, it needs a HandleErrorLayer wrapped around it to turn those errors into responses. The rule to remember is simple: with Axum, prefer the tower-http version of a layer whenever one exists.

Common misconceptions and mistakes beginners make

Understanding Tower's abstractions takes time. Here are the most frequent errors.

Mistake 1: Thinking a Service is the same as a handler function

A handler in Axum (an async function with extractors) is converted into a Service by Axum internally. But a Service is a trait, not a function. It has state, can be cloned, and can manage readiness. When you write get(handler), Axum wraps the handler in a service. But the handler itself is not a service until Axum makes it one.

Mistake 2: Confusing Layer and Service

A Layer is a factory, not a service. You cannot call .call() on a layer. You must call .layer(inner_service) to get a service. A common beginner error is trying to pass a Layer where a Service is expected, or vice versa.

Mistake 3: Ignoring poll_ready

Most tutorials skip poll_ready, but it is part of the contract. When you write your own service, you must implement it. For a simple service that is always ready, return Poll::Ready(Ok(())). If you forget, your code will not compile. If you return Pending without waking the task, your service may hang.

Mistake 4: Not understanding layer ordering

The order in which you apply .layer() calls matters a lot. The last layer you apply is the outermost. For example, if you apply a TimeoutLayer and then a TraceLayer, the trace layer is outermost. That means tracing starts before the timeout, and the timeout only applies to the inner service. If you reverse them, the timeout is outermost, and tracing is only active while the timeout is waiting. Sometimes this subtle difference changes behavior.

Mistake 5: Assuming all Tower layers are compatible with Axum's Router

Most Tower layers work fine, but some layers expect a specific request type. For instance, tower::buffer::BufferLayer works with any service, but tower_http::cors::CorsLayer expects an HTTP request type. Since Router's request type is axum::http::Request<axum::body::Body>, HTTP-specific layers are fine. But if you try to apply a non-HTTP layer (like a TCP-oriented one) to a Router, you will get a type error. This is actually a feature: the type system prevents mismatched layers.

The most consequential beginner mistake:

The single most common error is mixing up Router::layer, Router::route_layer, and per-route .layer(). Router::layer wraps the whole router (including unmatched requests). Router::route_layer wraps only requests that already matched a route on that router. Neither is "one specific route." For a single endpoint, put .layer(...) on the method router: get(handler).layer(...). Also apply layers after the routes you want wrapped - routes added later are not covered.

How beginners should think about Tower

Here is a simple mental model that works well for most cases.

  • A Service is like a vending machine. You put in a coin (request), and eventually a snack (response) comes out. Some vending machines are simple, some are complex, but they all follow the same basic contract: coin in, snack out.
  • A Layer is like a vending machine upgrade kit. You take an existing vending machine, install the kit, and now the machine has a camera, a screen, or a payment validator. The kit doesn't replace the machine; it wraps around it and adds new behavior.
  • Composition is like stacking upgrade kits. Install a screen kit, then a camera kit, and the outermost kit handles the interaction first. Another analogy: a pipeline. A request flows through a series of stages, and each stage can modify the request, stop it, or add something to the response. The Service is the whole pipeline, and the Layers are the stages.

Multiple ways to apply layers in Axum

There are several ways to add Tower layers to an Axum application, each suited to different situations.

Applying a layer to the entire Router

Use .layer() on the Router instance. This wraps the whole router as a Tower service, so the middleware sees every request that reaches that router - including ones that do not match any route. Add the routes you care about first, then call .layer(...). Routes added after that .layer(...) call are not wrapped by it.

let app = Router::new()
    .route("/", get(handler))
    .layer(TraceLayer::new_for_http());

Applying a layer to matched routes only (route_layer)

Use Router::route_layer(...) when you want middleware on every route already registered on that router, but not on unmatched requests (those skip the layer). Like .layer(), it only covers routes that exist at the moment you call it.

use axum::http::StatusCode;
use std::time::Duration;
use tower_http::timeout::TimeoutLayer;

let app = Router::new()
    .route("/", get(handler))
    .route("/other", get(other_handler))
    .route_layer(TimeoutLayer::with_status_code(
        StatusCode::REQUEST_TIMEOUT,
        Duration::from_secs(5),
    ));

Both / and /other get the timeout; a request to an unknown path does not run that layer.

Applying a layer to one specific route

For a single endpoint, call .layer(...) on the method router (get / post / …), not route_layer:

use axum::http::StatusCode;
use std::time::Duration;
use tower_http::timeout::TimeoutLayer;

let app = Router::new()
    .route("/", get(handler).layer(TimeoutLayer::with_status_code(
        StatusCode::REQUEST_TIMEOUT,
        Duration::from_secs(5),
    )))
    .route("/other", get(other_handler));

Here, only the / route gets the timeout; /other does not.

Applying layers with ServiceBuilder

The tower::ServiceBuilder provides a convenient way to chain multiple layers and services. It is especially useful when you have several layers that share configuration.

use axum::http::StatusCode;
use std::time::Duration;
use tower::ServiceBuilder;
use tower_http::{timeout::TimeoutLayer, trace::TraceLayer, compression::CompressionLayer};

let middleware_stack = ServiceBuilder::new()
    .layer(TraceLayer::new_for_http())
    .layer(CompressionLayer::new())
    .layer(TimeoutLayer::with_status_code(
        StatusCode::REQUEST_TIMEOUT,
        Duration::from_secs(30),
    ));

let app = Router::new()
    .route("/", get(handler))
    .layer(middleware_stack);

ServiceBuilder implements Layer, so you can pass it to .layer(). Ordering inside the builder is outer → inner: the first .layer(...) you add is the outermost (sees the request first), and the last is closest to your handler. That is the opposite of stacking several separate Router::layer(...) calls, where the last call becomes outermost.

Why use ServiceBuilder?:

ServiceBuilder can also add services that are not layers, such as concurrency_limit and buffer. It keeps the middleware configuration in one place, making your code cleaner.

How Axum's Router is a Service

Axum's Router type implements the Service trait. Its request type is axum::http::Request<axum::body::Body>, its response type is axum::response::Response, and its error type is std::convert::Infallible (meaning routing errors are converted to HTTP responses internally). When you call axum::serve, it takes ownership of the router, converts it into a Service, and passes it to Hyper. Hyper then calls poll_ready and call on the router for each incoming connection. This is how Axum plugs into the broader Rust async ecosystem without reinventing HTTP. Because Router is a service, you can also use it as a building block in other Tower services. For example, you could embed an Axum router inside a larger service that combines gRPC and HTTP endpoints using Tower's ServiceBuilder. This flexibility is one of Axum's greatest strengths.

Tower's relationship to Hyper and Tokio

To complete the picture, remember the stack:

  • Tokio is the async runtime. It schedules tasks and drives I/O.
  • Hyper is the HTTP implementation. It knows how to parse HTTP/1 and HTTP/2, manage connections, and talk to sockets.
  • Tower defines the Service and Layer abstractions that Hyper uses to interface with application logic.
  • Axum builds on Hyper and Tower by providing routing, extractors, and response handling on top. This stack is cleanly layered. Axum does not need to know how TCP works; Tokio handles that. Axum does not need to parse HTTP; Hyper does that. Axum only needs to implement Service so Hyper can call it. That is why Axum can be a thin, ergonomic library while still being high-performance and compatible with the entire Tower ecosystem.

Summary

Tower's Service and Layer traits are the foundation of Axum's middleware system. A Service is an asynchronous function from request to response, with a readiness check. A Layer is a factory that wraps one service to produce a new service with additional behavior. By composing layers, you can build a pipeline of middleware that runs before and after your core application logic. The key insight is that Axum deliberately avoids a custom middleware API. Instead, it adopts Tower's standard abstractions, which means Axum automatically benefits from the entire Tower and tower-http ecosystem. When you see .layer(...) in Axum code, you are seeing Tower at work. If you understand the basic idea - a service receives requests, and a layer decorates a service - you are ready to move forward. The next time you encounter a middleware like TraceLayer or TimeoutLayer, you will know that it is just a Layer that wraps your router in a new service. That understanding will make Axum's design feel obvious rather than magical.