Timeout Middleware

Middleware that provides support for request timeouts.

Use Cases

In web services, some requests might take too long to process due to various reasons (e.g., slow database queries, slow responses from external services). To prevent these long-running requests from consuming server resources and affecting the processing of other requests, you can use timeout middleware to set a maximum processing time limit for requests. If this time limit is exceeded, the request will be automatically interrupted, and a timeout error will be returned.

Example Code

main.rs
Cargo.toml
timeout/src/main.rs
use std::time::Duration;

use salvo::prelude::*;

#[handler]
async fn fast() -> &'static str {
    "hello"
}
#[handler]
async fn slow() -> &'static str {
    tokio::time::sleep(Duration::from_secs(6)).await;
    "hello"
}

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

    let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;

    let router = Router::new()
        .hoop(Timeout::new(Duration::from_secs(5)))
        .push(Router::with_path("slow").get(slow))
        .push(Router::with_path("fast").get(fast));

    Server::new(acceptor).serve(router).await;
}

In the example above, we created two handler functions: fast, which responds quickly, and slow, which delays for 6 seconds before responding. Timeout::new(Duration::from_secs(5)) sets a 5-second timeout limit for all requests. When accessing the /slow path, the request will time out because its processing time exceeds the 5-second limit. Conversely, when accessing the /fast path, the request will be processed normally and return a result.

On this page