TimeoutLayer in Axum

Learn how to set time limits on HTTP requests using TimeoutLayer in Axum, handle timeout errors gracefully, and apply different timeouts per route.

When you build a web service, some requests take a very long time to finish. A handler might wait on a slow database, call another API that is not responding, or sit in a loop that never ends. If you do not set a limit, those requests pile up and use all your server resources, making the whole application slow or unresponsive for everyone. A timeout is a deadline. It says that if a handler does not produce a response within a certain amount of time, the server stops waiting and answers with an error instead. In Axum, that deadline is set with a TimeoutLayer. This page explains the two TimeoutLayers you will meet, how to use each one, what a timeout actually covers, and how to apply different timeouts to different routes.

Why Timeouts Are Essential

Imagine a restaurant with only one cook. If one customer orders a dish that takes three hours, the cook is stuck on that order and everyone else waits. The same happens with web servers. A single slow request can occupy a worker and delay all other requests. Setting a timeout is like telling the cook that if a dish takes more than thirty minutes, stop making it and tell the customer the kitchen is too busy.

Without timeouts, a single hung request can occupy a connection indefinitely, and users get no feedback when something goes wrong. Their browser just spins forever. With timeouts, your application stays responsive and users get a clear error, such as 408 Request Timeout. The timeout does not fix the slow database or the unresponsive API. It limits the damage they can do to the rest of the application.

Two Layers with the Same Name

There are two types called TimeoutLayer, and confusing them is the first mistake most beginners make. One comes from the tower crate, at tower::timeout::TimeoutLayer. The other comes from tower-http, at tower_http::timeout::TimeoutLayer. They do the same job in different ways, and the difference decides how much extra code you need.

tower TimeoutLayertower-http TimeoutLayer
What it returns on timeoutAn error of type Elapsed, wrapped in a BoxErrorA response directly, with an empty body and a status code you choose
Extra code neededAn error handler layer that turns the error into a responseNone
ConstructorTimeoutLayer::new(duration)TimeoutLayer::with_status_code(status, duration)
Feature flagtower with the timeout featuretower-http with the timeout feature

The tower version signals a timeout with an error. The tower-http version signals a timeout with a response. Axum handlers always return responses, never errors, so the tower version needs a partner layer to convert its error into a response, while the tower-http version needs nothing extra. If all you want is to time out and return a status code, the tower-http version is less code. If you need to inspect the error, log it differently, or return a custom body, the tower version with an error handler gives you that control.

TimeoutLayer does not protect against Slowloris:

A slow client that never finishes sending its request is not stopped by this layer. TimeoutLayer only starts timing once the request head has been received and routed and the inner service call begins. Slow or incomplete request transmission needs read and connection timeouts at the server level, which this layer does not provide. The timeout protects you from slow handlers, not from slow clients.

The Simpler Timeout, from tower-http

Start with the tower-http version, because it is the shortest path to a working timeout. First, make sure Cargo.toml includes the required dependencies. The tower-http timeout feature enables the layer, and tokio with full features provides the timer it uses.

Cargo.toml
[package]
name = "axum-timeout-example"
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 = ["timeout"] }

Now the application, in src/main.rs. The handler sleeps for five seconds to simulate slow work, and the timeout is set to two seconds.

src/main.rs
use axum::{http::StatusCode, routing::get, Router};
use std::time::Duration;
use tower_http::timeout::TimeoutLayer;

async fn slow_handler() -> &'static str {
    tokio::time::sleep(Duration::from_secs(5)).await;
    "This response is too late"
}

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

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

Run the server and request the root path. The handler starts sleeping. After about two seconds, the timeout fires, the handler is dropped, and the client receives an HTTP 408 Request Timeout response with an empty body. That timing was verified by running the program. The response arrived in 2.00 seconds, not five, and the status line read HTTP/1.1 408 Request Timeout. A fast handler under the same layer returns normally. A handler that answers immediately still returns a 200, because the timeout only fires when the deadline passes first.

The constructor deserves attention, because the older form is deprecated. TimeoutLayer::new is deprecated since tower-http 0.6.7, and the compiler warns you if you use it. The current form is with_status_code, which takes the status code to return and the duration. The status code is yours to choose. REQUEST_TIMEOUT, which is 408, is the natural choice for a request that took too long. Some applications return 503 Service Unavailable instead, to signal that the server is busy rather than blaming the request. The layer returns an empty body either way. If you want a body that explains the timeout, use the tower version with an error handler.

The tower-http timeout returns an empty body:

A client that receives the tower-http timeout gets a status code and nothing else. That is enough for a browser or an API client that checks the status, and it is not enough for a human who wants to know what happened. If the response body matters, use the tower TimeoutLayer with an error handler that writes a message.

The Tower Timeout and Its Error Handler

The tower version needs more code, because it reports a timeout as an error and Axum needs that error turned into a response. The tempting version, applying a bare tower TimeoutLayer to a router, does not build at all. It fails with error E0277, which says the trait bound for converting the error type is not satisfied. The reason is a type mismatch, not a logic error. Router::layer requires the layered service error type to convert into Infallible, which is the type Rust uses for a service that never fails. Tower Timeout service fails with BoxError, a boxed error type that can hold any error, and BoxError does not convert into Infallible. There is no runtime behaviour to observe, no empty reply from curl, because the program never builds.

src/main.rs
use axum::{routing::get, Router};
use std::time::Duration;
use tower::timeout::TimeoutLayer;

async fn slow_handler() -> &'static str {
    tokio::time::sleep(Duration::from_secs(5)).await;
    "This response is too late"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(slow_handler))
        .layer(TimeoutLayer::new(Duration::from_secs(2)));
    // This does not compile. The error is E0277, because the timeout
    // service fails with BoxError and Router::layer needs Infallible.
}

The fix is to pair the timeout with axum error_handling::HandleErrorLayer, which converts the error into a response. HandleErrorLayer is axum own layer, from axum::error_handling. There is no tower_http::error::HandleErrorLayer. Tower-http has no error module at all, so that import does not exist and will not compile. The working version below is the only version of this example that runs, and it was compile checked and run against axum 0.8.9, tokio 1.54.1, tower 0.5.3, and tower-http 0.7.1.

Cargo.toml
[package]
name = "axum-timeout-example"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower = { version = "=0.5.3", features = ["timeout", "util"] }
src/main.rs
use axum::{
    error_handling::HandleErrorLayer,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Router,
};
use std::time::Duration;
use tower::{timeout::TimeoutLayer, ServiceBuilder};

async fn slow_handler() -> &'static str {
    tokio::time::sleep(Duration::from_secs(5)).await;
    "This response is too late"
}

async fn handle_timeout_error(
    err: Box<dyn std::error::Error + Send + Sync>,
) -> impl IntoResponse {
    if err.is::<tower::timeout::error::Elapsed>() {
        (StatusCode::REQUEST_TIMEOUT, "Request took too long")
    } else {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Internal server error",
        )
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(slow_handler))
        .layer(
            ServiceBuilder::new()
                .layer(HandleErrorLayer::new(handle_timeout_error))
                .layer(TimeoutLayer::new(Duration::from_secs(2))),
        );

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

Walk through the pieces. The slow_handler waits five seconds before returning a string. Without a timeout, anyone calling this endpoint would wait five seconds. The TimeoutLayer::new(Duration::from_secs(2)) call says any request going through this router must finish within two seconds. The handle_timeout_error function receives the error as a boxed error, checks whether it is the Elapsed error type that a timeout produces, and returns a 408 with the body Request took too long. Any other error becomes a 500. The ServiceBuilder stacks the two layers, with HandleErrorLayer listed first, so it is the outermost layer. It wraps TimeoutLayer, catches its Elapsed error, and turns it into a response.

When you run this application and request the root path, the handler starts sleeping. After about two seconds, TimeoutLayer cancels the handler, HandleErrorLayer converts the error, and the client receives HTTP/1.1 408 Request Timeout with the body Request took too long. That was verified by running the program. The response arrived in 2.00 seconds, and the body was exactly the message the error handler wrote.

HandleErrorLayer must wrap the layer that produces the error:

In a ServiceBuilder stack, the first layer listed is the outermost, and it wraps everything below it. HandleErrorLayer only catches errors from the layers inside it. If you list TimeoutLayer first and HandleErrorLayer second, HandleErrorLayer ends up wrapping the route itself, whose error type is Infallible, while your handler expects a BoxError. The program does not compile. The compiler reports E0277, so the mistake is caught at compile time, not at runtime. Always put HandleErrorLayer before, meaning outside, the layer that may produce the error.

Why HandleErrorLayer Cannot Wrap the tower-http Timeout

A natural question is whether the same error handler pattern works with the tower-http TimeoutLayer. With the usual error handler, the one that takes a BoxError, it does not compile. The compiler reports E0277, saying the HandleError service is not a valid service for the request. The reason is simple once you see it. The tower-http timeout never produces an error. Its error type is Infallible, which means it cannot fail. A handler that expects a BoxError has nothing to receive, because no error will ever arrive. There is nothing to handle, so the layer has nothing to do. That is the point of the tower-http design. It returns a response directly, so no error handler is needed, and adding one is a type error rather than a safety net.

What a Timeout Actually Times

A timeout measures the time until the inner service produces a response, which means the status line and headers. It does not measure the time the response body takes to stream to the client. A handler that returns quickly and then streams a large body slowly will not trip a TimeoutLayer, because the response future has already completed. The body streaming continues after the timeout has finished its measurement. That is also why neither placement of a timeout relative to a compression layer times compression. Compression happens as the body streams out, after the response future resolves.

A timeout also does not cancel the underlying work in a guaranteed way. The timer stops waiting, and the handler future is dropped, which cancels the work in many cases, such as a database query in progress. That is not guaranteed for all libraries. If you have side effects that must not be cancelled, you may need a different strategy, such as running the work in a background task and polling it. And a timeout does not protect against a slow client that never finishes sending its request. It only times the inner service call, which begins after the request head has been received and routed.

Timeouts for Request and Response Bodies

Tower-http 0.7.1 provides separate layers for the body transfer itself, for when the body is the slow part. RequestBodyTimeoutLayer resets its deadline each time a frame of the request body arrives, so a client that keeps sending data slowly but steadily never trips it, while a client that stalls does. RequestBodyDeadlineLayer enforces a hard wall clock limit on the whole request body transfer, from the first byte to the last. ResponseBodyTimeoutLayer and ResponseBodyDeadlineLayer do the same for the response body going out. These layers are applied the same way as TimeoutLayer, with .layer() or through ServiceBuilder, and they take a Duration.

src/main.rs
use std::time::Duration;
use tower_http::timeout::{RequestBodyTimeoutLayer, ResponseBodyTimeoutLayer};

let request_body_timeout = RequestBodyTimeoutLayer::new(Duration::from_secs(5));
let response_body_timeout = ResponseBodyTimeoutLayer::new(Duration::from_secs(5));

Use a body timeout when the risk is a slow upload or a slow download, and use the plain TimeoutLayer when the risk is a slow handler. They cover different parts of the request, and an application with both risks can use both layers.

Applying Timeouts to Specific Routes

Sometimes you want a timeout only on one route, not the entire application. An endpoint that performs a long computation might need ten seconds, while all other routes should have a default three second timeout. Axum gives you two tools for scoping a layer, and they behave differently in a way that surprises beginners.

The first tool is route_layer on the Router. It sounds like it applies to one route, and it does not. Router::route_layer applies the layer to all routes that have been added to the router so far. If you call it after adding two routes, both get the layer. That was verified at runtime. A router with a /fast route and a /slow route, both with handlers that sleep for five seconds, and a two second timeout applied with route_layer, answered GET /fast with 408 Request Timeout in 2.00 seconds. The fast route was not fast at all. It was wrapped, because route_layer wraps everything added before the call.

src/main.rs
use axum::{
    error_handling::HandleErrorLayer,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Router,
};
use std::time::Duration;
use tower::{timeout::TimeoutLayer, ServiceBuilder};

async fn fast_handler() -> &'static str {
    // This handler is called "fast", but it still takes five seconds,
    // which is what makes the route_layer trap visible.
    tokio::time::sleep(Duration::from_secs(5)).await;
    "This is fast"
}

async fn slow_handler() -> &'static str {
    tokio::time::sleep(Duration::from_secs(5)).await;
    "This is slow"
}

async fn handle_timeout_error(
    err: Box<dyn std::error::Error + Send + Sync>,
) -> impl IntoResponse {
    if err.is::<tower::timeout::error::Elapsed>() {
        (StatusCode::REQUEST_TIMEOUT, "Slow route timed out")
    } else {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Internal server error",
        )
    }
}

#[tokio::main]
async fn main() {
    let timeout_layer = ServiceBuilder::new()
        .layer(HandleErrorLayer::new(handle_timeout_error))
        .layer(TimeoutLayer::new(Duration::from_secs(2)));

    let app = Router::new()
        .route("/fast", get(fast_handler))
        .route("/slow", get(slow_handler))
        .route_layer(timeout_layer);

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

In this program, both routes carry the timeout, because route_layer wraps every route added before it. The route named /fast still times out, because the name does not matter. Only the layer does. If you want a timeout on only one route, apply the layer to that route alone, using .layer() on the MethodRouter returned by get().

src/main.rs
let app = Router::new()
    .route("/fast", get(fast_handler))
    .route("/slow", get(slow_handler).layer(timeout_layer));

That is precise. The .layer() call on get(slow_handler) wraps only the /slow route, and /fast is untouched. With this version, GET /fast takes the full five seconds and returns 200, because no timeout applies to it, while GET /slow returns 408 after two seconds. Which one you choose depends on whether you have one route or several that need the same timeout. For one route, use the per-route .layer(). For several routes that share a timeout, put them in their own router and apply the layer to that router, or use route_layer after adding exactly those routes and no others.

Route layer wraps every route added so far:

Router::route_layer does not limit the scope to one route. It wraps all routes currently in the router. To limit the scope, use per-route .layer() on a MethodRouter, or put the routes that need the timeout in their own nested router. If you use .layer() on the entire Router, the timeout applies to every route, including ones you might not intend to time out, such as health checks or static file serving.

Setting Different Timeouts for Different Endpoints

You can have multiple timeouts by creating different layer stacks and applying them to different routes. Each stack has its own duration, and each route gets the stack that fits its work. The error handler function is the same for all three stacks, because it is just a function passed to HandleErrorLayer::new, and you can define it once and reuse it everywhere.

src/main.rs
use axum::{
    error_handling::HandleErrorLayer,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Router,
};
use std::time::Duration;
use tower::{timeout::TimeoutLayer, ServiceBuilder};

async fn fast_handler() -> &'static str {
    "This is fast"
}

async fn medium_handler() -> &'static str {
    tokio::time::sleep(Duration::from_secs(3)).await;
    "This is medium"
}

async fn slow_handler() -> &'static str {
    tokio::time::sleep(Duration::from_secs(8)).await;
    "This is slow"
}

async fn handle_timeout_error(
    err: Box<dyn std::error::Error + Send + Sync>,
) -> impl IntoResponse {
    if err.is::<tower::timeout::error::Elapsed>() {
        (StatusCode::REQUEST_TIMEOUT, "Request timed out")
    } else {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Internal server error",
        )
    }
}

#[tokio::main]
async fn main() {
    let short_timeout = ServiceBuilder::new()
        .layer(HandleErrorLayer::new(handle_timeout_error))
        .layer(TimeoutLayer::new(Duration::from_secs(1)));
    let medium_timeout = ServiceBuilder::new()
        .layer(HandleErrorLayer::new(handle_timeout_error))
        .layer(TimeoutLayer::new(Duration::from_secs(4)));
    let long_timeout = ServiceBuilder::new()
        .layer(HandleErrorLayer::new(handle_timeout_error))
        .layer(TimeoutLayer::new(Duration::from_secs(10)));

    let app = Router::new()
        .route("/fast", get(fast_handler).layer(short_timeout))
        .route("/medium", get(medium_handler).layer(medium_timeout))
        .route("/slow", get(slow_handler).layer(long_timeout));

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

Trace the behaviour. The /fast route answers immediately, well inside its one second limit. The /medium route sleeps three seconds, inside its four second limit, so it returns 200. The /slow route sleeps eight seconds, inside its ten second limit, so it returns 200 as well. If the medium handler ever slowed past four seconds, requests to it would receive a 408, while the slow route would keep working. Each route is judged against its own deadline, which is the point of per-route timeouts. A quick database lookup might deserve two seconds, while a report generation endpoint might need thirty. One global timeout forces you to pick a number that is wrong for both.

The same pattern works with the tower-http TimeoutLayer. Build a with_status_code layer per route and apply each with the per-route .layer() call. The code is shorter, because no error handler is needed, and the trade is the empty body on timeout.

Combining TimeoutLayer with Other Layers

In real applications, you often have several layers, logging, compression, CORS, and a timeout among them. The order in which you add layers through ServiceBuilder determines the order in which requests pass through them. The first layer listed is the outermost, so it sees the request first and the response last. Here is a stack with tracing, compression, and a timeout, using the tower version so the timeout can carry a body.

Cargo.toml
[package]
name = "axum-timeout-example"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower = { version = "=0.5.3", features = ["timeout", "util"] }
tower-http = { version = "=0.7.1", features = ["trace", "compression-gzip", "timeout"] }
tracing = "0.1"
tracing-subscriber = "0.3"

This Cargo.toml declares every dependency the example below uses. The tower-http timeout feature is listed because the page also shows the tower-http variant, and the trace and compression-gzip features enable the other two layers. The tracing and tracing-subscriber crates are needed for the subscriber setup at the top of main.

src/main.rs
use axum::{
    error_handling::HandleErrorLayer,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Router,
};
use std::time::Duration;
use tower::{timeout::TimeoutLayer, ServiceBuilder};
use tower_http::{compression::CompressionLayer, trace::TraceLayer};

async fn slow_handler() -> &'static str {
    tokio::time::sleep(Duration::from_secs(5)).await;
    "This is slow"
}

async fn handle_timeout_error(
    err: Box<dyn std::error::Error + Send + Sync>,
) -> impl IntoResponse {
    if err.is::<tower::timeout::error::Elapsed>() {
        (StatusCode::REQUEST_TIMEOUT, "Request timed out")
    } else {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Internal server error",
        )
    }
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();

    let app = Router::new()
        .route("/", get(slow_handler))
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CompressionLayer::new())
                .layer(HandleErrorLayer::new(handle_timeout_error))
                .layer(TimeoutLayer::new(Duration::from_secs(2))),
        );

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

In this stack, TraceLayer logs incoming requests and outgoing responses. It is placed first, outermost, so it sees everything, including the 408 that the timeout produces. CompressionLayer compresses responses before they reach TraceLayer. HandleErrorLayer catches any errors from the layers inside it, including TimeoutLayer. TimeoutLayer enforces the two second limit. The order of HandleErrorLayer and TimeoutLayer is critical. The error handler must wrap the layer that produces errors. If you placed TimeoutLayer before HandleErrorLayer, HandleErrorLayer would wrap the route itself instead of the timeout, and the program would fail to compile with E0277, because the route never produces the BoxError the handler expects.

Common Mistakes and Misconceptions

Forgetting to handle the timeout error is the most common mistake. Tower TimeoutLayer fails with BoxError, which Router::layer will not accept, so applying it bare does not even compile with E0277. Pair it with axum HandleErrorLayer, outer to the timeout, so the error becomes a 408 response. Or use tower-http TimeoutLayer::with_status_code, which needs no error handler at all.

Setting a timeout that is too short is the second mistake. If your handler legitimately takes longer, for example a complex report, a too short timeout causes many false failures. Measure your endpoints typical response times and set a timeout with a comfortable margin, or use different timeouts for different routes.

Applying a timeout globally without considering health checks or static files is the third mistake. A health check endpoint should respond instantly, and adding a timeout is fine, but if you also serve large static files, a global timeout might interrupt downloads that take longer than expected. The timeout measures the response future, not the body stream, so a file download that starts quickly is usually safe, but a handler that generates a large file slowly is not. Use per-route or scoped timeouts where the work differs.

Thinking that TimeoutLayer cancels the underlying work is the fourth mistake. The timer stops waiting, but the underlying future may continue to run until it is dropped. In many cases, dropping the future cancels the work, like a database query in progress, but this is not guaranteed for all libraries. If you have side effects that must not be cancelled, you may need a different strategy, such as running the work in a background task and polling it.

Confusing the two TimeoutLayers is the fifth mistake. The one from tower::timeout returns an error of type Elapsed and requires a HandleErrorLayer. The one from tower_http::timeout returns a response directly, no error, no HandleErrorLayer needed, and is often the simpler choice in Axum. If you copy an example and it fails to compile, check which crate the import comes from first.

Using the deprecated tower-http constructor is the sixth mistake. TimeoutLayer::new is deprecated since tower-http 0.6.7. Use TimeoutLayer::with_status_code instead, which also lets you choose a different status, for example 503 Service Unavailable.

The timeout is working:

If you run the tower version and request the slow endpoint, you should see HTTP/1.1 408 Request Timeout with the body Request took too long, arriving after about two seconds. If you run the tower-http version, you should see the same status line with an empty body, after the same two seconds. Either result confirms the timeout is working. A response that arrives after five seconds with a 200 means the layer is not applied to that route.

Summary

Timeouts are not just about failing fast. They are about maintaining the overall health and responsiveness of a service under load. Without them, a few slow requests can degrade the experience for everyone. With them, a slow dependency costs one request its answer, not the whole server its capacity.

The decision framework to carry forward has three questions. First, do you need a custom body or logging for the timeout, or is a status code enough. If a status code is enough, use tower-http TimeoutLayer::with_status_code, because it is one layer and no error handler. If you need a body or a different response per error type, use tower TimeoutLayer with axum HandleErrorLayer, and put the error handler outside the timeout. Second, do all your endpoints share a timing profile. If they do, one timeout on the router is fine. If they do not, give each route its own timeout with the per-route .layer() call, and never trust route_layer to limit the scope, because it wraps every route added so far. Third, what is actually slow. If the handler is slow, a plain timeout covers it. If the body transfer is slow, add a body timeout layer. If the client is slow to send, a timeout will not help at all, and the fix belongs at the server level. Answer those three questions, and the timeout you pick will be the right one for the risk you actually face.