rust
45 lines · 8 steps
Graceful shutdown in an Axum server
Wire an Axum server to drain connections cleanly when it receives Ctrl+C or SIGTERM.
Explained by
highlit
1use std::time::Duration;
2
3use axum::{routing::get, Router};
4use tokio::net::TcpListener;
5use tokio::signal;
6
7async fn shutdown_signal() {
8 let ctrl_c = async {
9 signal::ctrl_c()
10 .await
11 .expect("failed to install Ctrl+C handler");
12 };
13
14 #[cfg(unix)]
15 let terminate = async {
16 signal::unix::signal(signal::unix::SignalKind::terminate())
17 .expect("failed to install SIGTERM handler")
18 .recv()
19 .await;
20 };
21
22 #[cfg(not(unix))]
23 let terminate = std::future::pending::<()>();
24
25 tokio::select! {
26 _ = ctrl_c => {},
27 _ = terminate => {},
28 }
29
30 tracing::info!("shutdown signal received, draining connections");
31}
32
33pub async fn serve() -> anyhow::Result<()> {
34 let app = Router::new().route("/health", get(|| async { "ok" }));
35
36 let listener = TcpListener::bind("0.0.0.0:3000").await?;
37 tracing::info!("listening on {}", listener.local_addr()?);
38
39 axum::serve(listener, app)
40 .with_graceful_shutdown(shutdown_signal())
41 .await?;
42
43 tokio::time::sleep(Duration::from_millis(250)).await;
44 Ok(())
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Graceful shutdown means racing two signal futures and stopping the server when either fires.
- 2Platform differences like SIGTERM are handled with cfg attributes so the code compiles everywhere.
- 3with_graceful_shutdown lets Axum finish in-flight requests instead of dropping connections abruptly.
Related explainers
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/graceful-shutdown-in-an-axum-server-explained-rust-7bad/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.