Timeout Middleware

Provides middleware support for timeout handling.

Use Cases

In web services, certain requests may take too long to process due to various reasons (such as slow database queries, delayed external service responses, etc.). To prevent these long-running requests from consuming server resources and affecting the processing of other requests, a timeout middleware can be used to set a maximum processing time limit for requests. If this time limit is exceeded, the request will be automatically terminated, and a timeout error will be returned.

Example Code

main.rs
Cargo.toml
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:8698").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: a fast-responding fast and a slow that delays for 6 seconds before responding. A timeout limit of 5 seconds is set for all requests using Timeout::new(Duration::from_secs(5)). When accessing the /slow path, the request will time out because the processing time exceeds the 5-second limit. In contrast, when accessing the /fast path, the request will be processed normally and return a result.