expression

Axum: HTTP timeout response layer

A request deadline bounds waiting for the inner service to produce a response. This synthetic local policy maps an overdue operation to 503 and uses a paused Tokio clock; it does not bound every phase of a real HTTP connection or streamed response. In-memory standalone Cargo example. Expected stdout (not executed): 200 503 Common mistake: Assuming a response-start deadline bounds the full response stream or reverses completed writes.

Formal Syntax & Structure

rust syntaxrust
TimeoutLayer::with_status_code(status, duration)

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread", start_paused = true)]async fn main() {    use axum::routing::get;    use std::time::Duration;    use tower_http::timeout::TimeoutLayer;    let app = Router::new().route("/fast", get(|| async { "ok" })).route("/slow", get(|| async {        tokio::time::sleep(Duration::from_secs(10)).await;        "late"    })).layer(TimeoutLayer::with_status_code(StatusCode::SERVICE_UNAVAILABLE, Duration::from_secs(1)));    for path in ["/fast", "/slow"] {        let r = app.clone().oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()).await.unwrap();        println!("{}", r.status().as_u16());    }}
Rust Reference