# How do I add a request timeout to an axum server?
Source: https://ruststudio.org/community/t/278/how-do-i-add-a-request-timeout-to-an-axum-server
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot; tower-http 0.6.11
Category: Help and questions | Kind: FAQ | Tags: axum, timeout, tower-http, reliability | Views: 0

## Short answer
Add tower-http TimeoutLayer with a duration and a status code. A request whose handler is still running when the time is up is answered with that status, 408 Request Timeout in the example, so a stuck database call cannot keep a client waiting forever.

## Answer
## Answer
`TimeoutLayer::with_status_code(status, duration)` wraps the routes it is added to. A handler that is quick answers normally; a slow one is cut off:

```rust title=src/main.rs
use axum::{body::{to_bytes, Body}, http::{Request, StatusCode}, routing::get, Router};
use std::time::Duration;
use tower::ServiceExt;
use tower_http::timeout::TimeoutLayer;

async fn quick() -> &'static str { "quick" }
async fn slow() -> &'static str {
    tokio::time::sleep(Duration::from_millis(300)).await;
    "slow"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/quick", get(quick))
        .route("/slow", get(slow))
        .layer(TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, Duration::from_millis(100)));
    for uri in ["/quick", "/slow"] {
        let res = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
        let status = res.status();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{uri} -> {status} {:?}", String::from_utf8_lossy(&body));
    }
}
```

```text
/quick -> 200 OK "quick"
/slow -> 408 Request Timeout ""
```

The handler slept 300 ms against a 100 ms limit, and the client got `408 Request Timeout`.

`TimeoutLayer::new(duration)` also exists in tower-http 0.6.11 but the compiler reports it as deprecated in favour of `with_status_code`, because it does not let you choose the status.

```toml title=Cargo.toml
tower-http = { version = "0.6.11", features = ["timeout"] }
```

## Common mistakes
- Setting one timeout for everything. A report or an upload may need much longer than a page; layer the long routes separately.
- Treating the timeout as a way to stop the work. It answers the client; see the thread on background tasks for work that must continue regardless.

## Related questions
### Should I time out database calls separately?
The pool options of your database library have their own acquire timeout (see the sqlx pool thread). The request timeout is the outer limit.

## Sources
- tower-http, `TimeoutLayer`: https://docs.rs/tower-http/0.6.11/tower_http/timeout/struct.TimeoutLayer.html (read 2026-12-05)
