expression
Axum: request graceful server shutdown
The shutdown future completes to initiate graceful server shutdown. This opt-in fixture binds an ephemeral local port, supplies an already-ready signal, and verifies that the idle server returns within a generous deadline. It does not prove that active requests drain or background jobs finish. Production code must coordinate those separately and set a shutdown deadline. Opt-in loopback Cargo example; no external connections. Expected stdout (not executed): idle server stopped Common mistake: Assuming graceful shutdown terminates every independent task or every long-lived stream automatically.
Formal Syntax & Structure
rust syntaxrust
axum::serve(listener, app).with_graceful_shutdown(signal).awaitWorking Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::routing::get; use std::time::Duration; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let app = Router::new().route("/health", get(|| async { "ok" })); let result = tokio::time::timeout(Duration::from_secs(5), async { axum::serve(listener, app).with_graceful_shutdown(async {}).await }).await; assert!(result.unwrap().is_ok()); println!("idle server stopped");}