What you will build#
A server that, when told to stop, finishes the request it is handling before exiting. The program below proves that with a slow request and a stop signal sent while it runs.
Before you start#
- An axum server (see the thread on a minimal server).
Steps#
1. Write the shutdown signal#
The future below completes on Ctrl+C everywhere. On Unix it also completes on SIGTERM, the signal that service managers and containers send to ask a program to stop. On Windows only the Ctrl+C branch exists; the SIGTERM lines are #[cfg(unix)] and were not compiled here.
2. Pass it to the server#
with_graceful_shutdown takes any future. In a real program pass shutdown_signal(); the demo below passes a channel so that it can trigger the stop itself.
use axum::{routing::get, Router};
use std::time::Duration;
use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}, sync::oneshot};
/// Completes when the process is asked to stop: Ctrl+C everywhere, SIGTERM on Unix.
#[allow(dead_code)]
async fn shutdown_signal() {
let ctrl_c = async { tokio::signal::ctrl_c().await.expect("cannot listen for Ctrl+C") };
#[cfg(unix)]
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("cannot listen for SIGTERM").recv().await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! { _ = ctrl_c => {}, _ = terminate => {} }
}
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_millis(300)).await;
"finished the slow request"
}
async fn get_text(addr: std::net::SocketAddr) -> String {
let mut s = TcpStream::connect(addr).await.unwrap();
s.write_all(b"GET /slow HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").await.unwrap();
let mut out = String::new();
s.read_to_string(&mut out).await.unwrap();
out.lines().next().unwrap().to_string() + " / " + out.lines().last().unwrap()
}
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (stop, stopped) = oneshot::channel::<()>();
// In a real program this future is `shutdown_signal()`; a channel lets this demo trigger it.
let server = tokio::spawn(async move {
axum::serve(listener, Router::new().route("/slow", get(slow)))
.with_graceful_shutdown(async { let _ = stopped.await; })
.await
.unwrap();
});
let client = tokio::spawn(get_text(addr));
tokio::time::sleep(Duration::from_millis(100)).await; // the request is now in flight
stop.send(()).unwrap(); // ask the server to stop
println!("in-flight request: {}", client.await.unwrap());
server.await.unwrap();
println!("server task ended");
println!("new connection after shutdown: {}", TcpStream::connect(addr).await.is_err());
}3. Run it#
in-flight request: HTTP/1.1 200 OK / finished the slow request
server task ended
new connection after shutdown: trueThe request that was in flight when the stop was requested got its full answer (200 OK, finished the slow request). The server task then ended, and a new connection afterwards was refused.
Check that it works#
Start your real server with shutdown_signal(), send a slow request, press Ctrl+C in the terminal and watch the request finish before the program exits.
Troubleshooting#
| Symptom | Cause | Fix |
|---|---|---|
| work in background tasks is cut off | graceful shutdown covers requests only | signal your background tasks too (see the thread on periodic jobs) and await them |
Going further#
- Flush logs and close the database pool after
servereturns. - Put a time limit on the whole shutdown, so a stuck request cannot keep the process alive for ever.
Related questions#
Does a graceful shutdown help during a deployment?#
It lets the old process finish its requests while a new one takes over; the new process must be started by whatever manages your deployment.
Sources#
- axum,
serveandwith_graceful_shutdown: https://docs.rs/axum/0.8.9/axum/serve/struct.Serve.html (read 2026-12-05) - tokio,
signal: https://docs.rs/tokio/1.54.1/tokio/signal/index.html (read 2026-12-05)