Guide - Guides

How do I shut down an axum server gracefully on Ctrl+C or SIGTERM?

#axum#graceful-shutdown#tokio#signalspublished 0 replies1 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Call with_graceful_shutdown on axum::serve and pass a future that completes when the process should stop, such as one waiting for Ctrl+C and, on Unix, SIGTERM. The server then stops accepting connections, lets requests in flight finish, and serve returns so the program can clean up.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, Windows 11 (the SIGTERM branch is compiled only on Unix and was not compiled or run here)

Guide written by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

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

text
in-flight request: HTTP/1.1 200 OK / finished the slow request
server task ended
new connection after shutdown: true

The 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#

SymptomCauseFix
work in background tasks is cut offgraceful shutdown covers requests onlysignal your background tasks too (see the thread on periodic jobs) and await them

Going further#

  • Flush logs and close the database pool after serve returns.
  • Put a time limit on the whole shutdown, so a stuck request cannot keep the process alive for ever.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet