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:
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));
}
}/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.
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)