The tower-http Layer Ecosystem in Axum

Understand how Axum uses tower-http layers for tracing, compression, CORS, and timeouts, with beginner-friendly examples and practical guidance.

The tower-http Layer Ecosystem in Axum

Axum does not have its own private middleware system. Instead, it plugs directly into the Tower ecosystem, and tower-http is a crate full of ready-made HTTP middleware built on that same foundation. This page shows what tower-http gives you, why it matters for Axum applications, and how to use its layers in your own projects. You'll start with a tiny example, then add tracing, compression, CORS, and timeouts one by one, always with complete code you can run yourself.

What tower-http Provides

When you build a web server, most of the work is not the "hello world" route. Real services need to log every request, compress large responses, decide which websites may call your API from a browser, and stop slow requests from hanging forever. Writing all of that by hand for every project would be tedious and error-prone.

tower-http solves this by packaging these common needs as reusable layers. A layer is a wrapper that sits around your request handler and can do something before the handler runs, after it runs, or both. You already know the idea of a layer from Tower middleware. Here we focus on the specific implementations that tower-http provides: TraceLayer for logging, CompressionLayer for compressing responses, CorsLayer for cross-origin rules, TimeoutLayer for time limits, and several others.

The important mental model: each layer is independent. You can pick one, stack several, or write your own and mix it in. Axum's Router has methods like .layer(...) and .route_layer(...) that accept any Tower layer. Because tower-http layers are built on the same tower::Layer trait, they work with Axum out of the box, with no special adapter code.

Versions used on this page: tower-http 0.7:

Every example on this page uses tower-http 0.7.1 (released 31 August 2026), with axum 0.8.9 and tokio 1.54.1. Tower-http 0.7 is a new minor line after 0.6, so treat the upgrade as potentially breaking and check the changelog before moving an existing project. Two things from the 0.7 line matter most on this page: TimeoutLayer::new is deprecated (since 0.6.7) in favour of TimeoutLayer::with_status_code, and the timeout module also offers body-deadline layers - RequestBodyTimeoutLayer / RequestBodyDeadlineLayer for request bodies and ResponseBodyTimeoutLayer / ResponseBodyDeadlineLayer for response bodies - for when the whole-request timeout is not the right tool. Tower-http also has a full feature that enables every layer at once, which is handy for learning but compiles far more than a real project needs.

A First tower-http Layer - TraceLayer

Let's begin with a complete, minimal Axum application that uses one tower-http layer: TraceLayer. This layer automatically creates a span (a context container) for every incoming HTTP request. Any logging you do inside a handler will then automatically include the method, path, and other request details.

First, create a new Rust project:

cargo new axum-towerhttp-demo
cd axum-towerhttp-demo

Open Cargo.toml and add the dependencies:

Cargo.toml
[package]
name = "axum-towerhttp-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
tower-http = { version = "0.7.1", features = ["trace"] }
tracing = "0.1.41"
tracing-subscriber = "0.3.19"

Then replace src/main.rs with this:

src/main.rs
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
use tracing::info;
#[tokio::main]
async fn main() {
    // Set up a logger that prints to the terminal
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    let app = Router::new()
        .route("/", get(hello))
        // Add TraceLayer to every route
        .layer(TraceLayer::new_for_http());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    info!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
    info!("Inside the hello handler");
    "Hello, tower-http!"
}

Run the server with cargo run. In another terminal, send a request:

curl http://127.0.0.1:3000/

Back in the server terminal, you will see something like this (simplified):

INFO Server running on http://127.0.0.1:3000
INFO request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_request: started processing request
INFO request{method=GET uri=/ version=HTTP/1.1}: axum_towerhttp_demo: Inside the hello handler
INFO request{method=GET uri=/ version=HTTP/1.1}: tower_http::trace::on_response: finished processing request

Observe that your own info! line is now prefixed with request{method=GET uri=/ ...}. That context comes from the span created by TraceLayer. Without the layer, your log line would just say "Inside the hello handler" with no way to know which request triggered it. This is why TraceLayer is often the very first layer people add to a new Axum service.

Everything is working:

If you see log lines that include request{method=... uri=...} around your handler log, the TraceLayer is correctly wrapping every request and attaching context. This confirms that tower-http is loaded and active.

Adding tower-http to a Project

The previous example already added tower-http to Cargo.toml. For completeness, here is the exact ordered procedure when you start from a plain Axum project without tower-http.

1

Step 1: Add the tower-http dependency

Open Cargo.toml and add tower-http under [dependencies], along with the feature flags you need. For example, to use tracing and compression:

Cargo.toml
[dependencies]
tower-http = { version = "0.7.1", features = ["trace", "compression-gzip"] }

Every layer has a corresponding feature flag. The flag name usually matches the layer name, such as trace, cors, timeout, or compression-gzip.

2

Step 2: Import the layer in your Rust file

In main.rs (or wherever you define your router), bring the layer into scope:

src/main.rs
use tower_http::trace::TraceLayer;
use tower_http::compression::CompressionLayer;
3

Step 3: Apply the layer to your Router

Call .layer(...) on your Router for a global layer, or .layer(...) on a single route's method router (for example get(handler).layer(...)) for a layer that only covers that route. (Router::route_layer is not per-route - it applies to all routes added so far, and only runs when a request matches a route.)

src/main.rs
let app = Router::new()
    .route("/", get(hello))
    .layer(TraceLayer::new_for_http())
    .layer(CompressionLayer::new());

Why feature flags exist:

tower-http is designed to be small and modular. If you only use tracing, you don't want to compile CORS and compression code. Each feature flag pulls in only the code for that specific middleware. Forgetting to enable a feature is one of the most common beginner mistakes because the layer won't exist at compile time.

Understanding Layer Stacking and Order

When you stack multiple layers with repeated .layer(...) calls, the order matters in a non-obvious way. Let's make it clear with a concrete example.

Suppose you write:

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

The last .layer(...) added is the outermost layer, meaning it runs first for an incoming request. Here, TraceLayer is outermost: it starts a span, then calls the next layer (the timeout), which then calls your handler. When the handler returns, the timeout layer returns the response, and finally the trace layer finishes the span and logs the response.

If you reverse the order:

.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::with_status_code(
    StatusCode::REQUEST_TIMEOUT,
    std::time::Duration::from_secs(5),
))

Now TimeoutLayer is outermost. It starts a timer first. If the entire request (including tracing overhead) takes too long, the timeout may fire before the trace span is even created. In practice, you usually want TraceLayer on the outside so you can see timeouts and other inner behavior in your logs.

Layer order changes runtime behavior:

The layer added last is the first to run. If you mix layers with side effects like tracing, authentication, and timeouts, test your stack order carefully. A timeout placed outside a compression layer might behave differently than one placed inside. Always reason from the outermost layer inward.

CompressionLayer - Making Responses Smaller

When a client (like a web browser) sends a request, it can advertise which compression formats it understands via the Accept-Encoding header, for example gzip, deflate, br. If your server sends back a large JSON or HTML response, compressing it with gzip can reduce the bytes transferred by a large amount.

CompressionLayer reads the request's Accept-Encoding header and automatically compresses the response body if the client supports it. It also sets the Content-Encoding header on the response so the client knows how to decompress.

Let's extend the previous example to include compression. Update Cargo.toml to add the compression feature:

Cargo.toml
[dependencies]
tower-http = { version = "0.7.1", features = ["trace", "compression-gzip"] }

Modify main.rs to add a route that returns a large string and add CompressionLayer:

src/main.rs
use axum::{routing::get, Router};
use tower_http::compression::CompressionLayer;
use tower_http::trace::TraceLayer;
use tracing::info;
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    let app = Router::new()
        .route("/", get(hello))
        .route("/big", get(big_response))
        // TraceLayer is added first, so it is innermost, closest to the handler
        .layer(TraceLayer::new_for_http())
        // CompressionLayer is added last, so it is outermost and runs first
        .layer(CompressionLayer::new());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    info!("Server running with compression");
    axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
    "Hello, tower-http!"
}
async fn big_response() -> String {
    // Create a 2 KB string with repeating text
    "A".repeat(2048)
}

Now restart the server and run this curl command, which tells the server it accepts gzip:

curl -H "Accept-Encoding: gzip" -v http://127.0.0.1:3000/big

The -v flag shows response headers. You should see something like:

< HTTP/1.1 200 OK
< content-encoding: gzip
< content-length: ...
< ...
< [binary data]

Notice the content-encoding: gzip header and the much smaller content-length than the original 2048 bytes. The server compressed the 2 KB string down to a fraction of its size because the content was highly repetitive. For real JSON or HTML, the savings are less dramatic but still significant.

Compression works only if the client asks for it:

If you send the same request without the Accept-Encoding header (or with Accept-Encoding: identity), the server will not compress the response. That's the correct behavior. Compression is negotiated per-request, and CompressionLayer respects the client's preference.

CorsLayer - Allowing Browser Requests

Browsers enforce a security rule called the same-origin policy. If a JavaScript app running on http://localhost:5173 tries to fetch data from http://localhost:3000/api, the browser blocks the response unless the server explicitly allows that origin using CORS headers.

CorsLayer handles this for you. You tell it which origins are allowed, which methods, which headers, and more. Then it automatically adds the correct CORS headers to responses and also handles preflight requests (the OPTIONS request browsers send before certain requests).

First, add the cors feature to Cargo.toml:

Cargo.toml
[dependencies]
tower-http = { version = "0.7.1", features = ["trace", "cors"] }

Now create a simple API endpoint and add a permissive CorsLayer to allow all origins:

src/main.rs
use axum::{routing::get, Json, Router};
use serde_json::{json, Value};
use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::TraceLayer;
use tracing::info;
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    // Allow any origin, any method, any header for this example
    let cors = CorsLayer::new()
        .allow_origin(Any)
        .allow_methods(Any)
        .allow_headers(Any);
    let app = Router::new()
        .route("/api/data", get(data))
        .layer(cors)
        .layer(TraceLayer::new_for_http());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    info!("Server with CORS running");
    axum::serve(listener, app).await.unwrap();
}
async fn data() -> Json<Value> {
    Json(json!({ "message": "Hello from the API" }))
}

Run the server and simulate a browser request from a different origin using curl:

curl -H "Origin: http://localhost:5173" -v http://127.0.0.1:3000/api/data

You should see response headers like:

< access-control-allow-origin: *

That is the header a simple GET response carries. The other CORS settings you configured - allow_methods and allow_headers - do not appear on a simple GET response. They are sent on the preflight response: the OPTIONS request the browser sends before certain cross-origin requests. Try it:

curl -X OPTIONS -H "Origin: http://localhost:5173" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: content-type" \
  -v http://127.0.0.1:3000/api/data

Now you should see the preflight headers:

< access-control-allow-origin: *
< access-control-allow-methods: *
< access-control-allow-headers: *

If you run a frontend on http://localhost:5173 and call this API, the browser will allow the response to be read.

Do not use allow_origin(Any) with credentials:

The Any origin wildcard is convenient for development, but if your API uses cookies or authentication headers, a wildcard origin is not allowed by the browser. You must then specify exact origins with .allow_origin(["http://localhost:5173".parse().unwrap()]) and enable .allow_credentials(true). Using wildcard with credentials will cause the browser to reject the CORS setup silently.

TimeoutLayer - Preventing Stuck Requests

Sometimes a handler might wait too long for a database or external service. If no timeout exists, the client's request could hang indefinitely, tying up server resources. TimeoutLayer adds a deadline: if the inner handler takes longer than the specified duration, the request is aborted and the client gets a 408 Request Timeout response (or a similar error).

Add the timeout feature:

Cargo.toml
[dependencies]
tower-http = { version = "0.7.1", features = ["trace", "timeout"] }

Now add a handler that intentionally sleeps for 10 seconds, and set a timeout of 3 seconds:

src/main.rs
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tokio::time::sleep;
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;
use tracing::info;
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    let app = Router::new()
        .route("/slow", get(slow_handler))
        .route("/fast", get(fast_handler))
        .layer(TraceLayer::new_for_http())
        // Timeout of 3 seconds for all routes.
        // `TimeoutLayer::new` is deprecated since tower-http 0.6.7;
        // use `with_status_code` instead.
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(3),
        ));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    info!("Server with timeout running");
    axum::serve(listener, app).await.unwrap();
}
async fn slow_handler() -> String {
    info!("Slow handler started, sleeping for 10 seconds");
    sleep(Duration::from_secs(10)).await;
    info!("Slow handler finished (this will never print)");
    "Slow response".to_string()
}
async fn fast_handler() -> String {
    info!("Fast handler running");
    "Fast response".to_string()
}

Run the server and test both routes:

curl -v http://127.0.0.1:3000/slow
curl -v http://127.0.0.1:3000/fast

For /slow, after 3 seconds you'll see something like:

< HTTP/1.1 408 Request Timeout
< content-length: 0

The handler's second info! line will never appear because the timeout aborted the future. The /fast route still returns normally.

TimeoutLayer is a hard stop:

The timeout layer does not gracefully cancel the inner handler's work. It drops the future, which may leave background tasks or database connections in an inconsistent state. Always design handlers to be cancellation-safe, or use timeouts at the level of the specific blocking operation instead of the whole request when possible.

Combining Multiple Layers

Real applications rarely use just one layer. You might want tracing, compression, CORS, and timeouts all at once. Here is a complete example with all four layers, showing how the order affects the stack.

First, update Cargo.toml to include all needed features:

Cargo.toml
[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde_json = "1.0"
tower-http = { version = "0.7.1", features = ["trace", "compression-gzip", "cors", "timeout"] }
tracing = "0.1.41"
tracing-subscriber = "0.3.19"

Then replace src/main.rs with:

src/main.rs
use axum::{http::StatusCode, routing::get, Json, Router};
use serde_json::{json, Value};
use std::time::Duration;
use tower_http::{
    compression::CompressionLayer,
    cors::{Any, CorsLayer},
    timeout::TimeoutLayer,
    trace::TraceLayer,
};
use tracing::info;
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    let cors = CorsLayer::new()
        .allow_origin(Any)
        .allow_methods(Any)
        .allow_headers(Any);
    let app = Router::new()
        .route("/api/data", get(data))
        // Order from outermost to innermost (with chained `.layer()`,
        // the LAST added is outermost, so this list is the reverse
        // of the order the calls appear below):
        // 1. CompressionLayer (runs first)
        // 2. TimeoutLayer
        // 3. CorsLayer
        // 4. TraceLayer (runs last, closest to the handler)
        .layer(TraceLayer::new_for_http())
        .layer(cors)
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(5),
        ))
        .layer(CompressionLayer::new());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    info!("Server with all layers running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn data() -> Json<Value> {
    Json(json!({
        "items": [1, 2, 3, 4, 5],
        "message": "This response will be compressed if the client supports it"
    }))
}

Test the server with a request that includes both Accept-Encoding: gzip and an Origin header:

curl -H "Accept-Encoding: gzip" -H "Origin: http://localhost:5173" -v http://127.0.0.1:3000/api/data

You should see logs from TraceLayer, CORS headers in the response, and possibly a content-encoding: gzip header if the response body is large enough for compression to kick in (many small responses are not compressed because the overhead isn't worth it). The timeout of 5 seconds won't trigger for this fast handler.

All layers active:

If your logs show request context, the response includes access-control-allow-origin, and for a sufficiently large response you see content-encoding: gzip, then all four layers are correctly stacked and functioning. This is a complete, production-style middleware stack built entirely from tower-http.

Other Useful tower-http Middleware

tower-http includes more than just the four layers we've covered. Here are a few others you might encounter in real Axum projects, each with a brief purpose and feature flag:

  • SetRequestIdLayer / PropagateRequestIdLayer (request-id): generate a unique ID for each request and attach it as a header, then propagate it onto the response - useful for correlating logs across services. The supporting types are MakeRequestId (how IDs are made, e.g. MakeRequestUuid) and RequestId (the value itself). There is no type called RequestIdLayer in tower-http.
  • SetRequestHeaderLayer / SetResponseHeaderLayer (set-header): Adds a fixed header to every request or response.
  • PropagateHeaderLayer (propagate-header): Copies a header from the request to the response (e.g., propagate a request ID).
  • FollowRedirectLayer (follow-redirect): For client-side requests, automatically follows HTTP redirects.
  • AddExtensionLayer (add-extension): Wraps data in a Tower extension that handlers can extract with axum's Extension extractor.
  • RequestBodyLimitLayer (limit): Rejects request bodies over a size limit with 413 Payload Too Large. Pair it with axum's DefaultBodyLimit (which caps Bytes/String/Json/Form bodies at 2 MB by default).
  • ValidateRequestHeaderLayer (validate-request): Rejects requests missing a required header before they reach a handler - ValidateRequestHeaderLayer::accept("application/json") requires that Accept header, and ValidateRequestHeaderLayer::has_header_value("x-api-key", "secret") requires a header with an exact value (rejects with 403 Forbidden when it is missing or wrong). There is no one-line bearer/basic constructor on the server side: for Authorization checks, use AsyncRequireAuthorizationLayer::new(...) (auth feature) with your own AsyncAuthorizeRequest implementation, which rejects with 401 Unauthorized when the check fails.
  • NormalizePathLayer (normalize-path): Normalizes request paths before routing - trim_trailing_slash() turns /users/ into /users, append_trailing_slash() does the reverse. It must wrap the whole Router from the outside, because a Router::layer runs after routing and cannot change which route matches.
  • DecompressionLayer (decompression-gzip, decompression-deflate, decompression-br, decompression-zstd): Decompresses request bodies the client compressed.
  • ServeDir / ServeFile (fs): Serve static files and directories as a Tower service - mount them with Router::nest_service or fallback_service (nesting a service at / panics in axum 0.8; use fallback_service for that).

Each of these works exactly like the ones we've already used: you enable the feature in Cargo.toml, import the layer, and apply it with .layer(...) or .route_layer(...). The pattern never changes.

Common Mistakes and Fixes

Beginners often run into a small set of predictable problems when first using tower-http.

Forgetting the feature flag. You add CompressionLayer::new() to your code but forgot features = ["compression-gzip"] in Cargo.toml. The compiler will say cannot find type CompressionLayer in module tower_http::compression. Fix: check the layer's documentation for the exact feature name and add it.

Wrong layer order. You put TimeoutLayer outside TraceLayer and wonder why the log shows the request started but not the timeout. Fix: put TraceLayer on the very outside (add it last) so it wraps everything else.

Compression not applied to small responses. CompressionLayer by default skips compression for bodies smaller than a certain threshold because the compressed output might be larger than the original after headers. If you expect compression but don't see it, make the response body bigger or configure a lower threshold.

CORS preflight failing. A browser sends an OPTIONS request before a POST with custom headers. If you haven't allowed OPTIONS method or the required headers, the preflight fails. CorsLayer handles this automatically when configured correctly, but if you manually set headers you must respond to OPTIONS yourself.

Timeout too aggressive. If you set a 100ms timeout on a route that sometimes takes 200ms to query a database, you'll randomly drop valid requests. Always set timeouts based on the slowest acceptable operation, not the average.

Compile errors from missing features are the number one issue:

When the Rust compiler says a type or function from tower_http does not exist, your first thought should be "did I enable the feature in Cargo.toml?" Almost every layer has its own feature flag. Check cargo doc -p tower-http or the crate's documentation to find the correct flag.

Summary

The tower-http crate gives Axum a ready-made set of HTTP middleware that would otherwise take significant effort to write and test yourself. Instead of inventing a private logging system, you drop in TraceLayer. Instead of hand-rolling gzip encoding, you add CompressionLayer. CORS rules, request timeouts, and request IDs become one-line additions, all unified under the same Layer interface that Axum already uses.

The key insight is that Axum's design decision to build on Tower and tower-http means you are never locked into a single vendor's middleware. You can mix tower-http layers with custom layers you write yourself, layers from other Tower-based crates, and even layers designed for completely different services like Hyper or Tonic. This interoperability is a large part of what makes Axum so flexible and maintainable for real-world backend services.