FAQ - Help and questions

How do I add a request timeout to an axum server?

#axum#timeout#tower-http#reliabilitypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

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.

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

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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:

src/main.rsrust
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.

Cargo.tomltoml
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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet