SIGTERM, Not SIGKILL: Graceful Shutdown in Axum
Ctrl+C and docker compose stop both killed my axum server on the spot. How with_graceful_shutdown and tokio::select! let it finish what it started, the copied line that quietly disabled it, and a request that outlived the signal.
The first time I pressed Ctrl+C on my axum server, the process didn’t stop. It was stopped. The shell reported it as killed by signal 2, and any request in progress at that moment simply lost its connection. docker compose stop does the same thing with a different signal.
This post covers what those two commands actually send, what a graceful shutdown changes, how to get one in axum with about twenty lines, the line I copied that quietly disabled half of it, and a test where a request finishes after the signal has arrived. The examples come from a small demo service, and every exit status below was measured on it.
What Ctrl+C and docker compose stop send
Neither of them kills anything directly. They send a signal and let the process decide:
- Ctrl+C in a terminal sends
SIGINT. docker compose stopsendsSIGTERMto the container’s main process, waits up to 10 seconds, and only then sendsSIGKILL, which can’t be caught.
A program that doesn’t handle these signals gets the default behaviour, which is to die immediately. A minimal axum server with no shutdown handling, measured:
| Signal | Result |
|---|---|
Ctrl+C (SIGINT) | killed by signal 2 |
SIGTERM | killed by signal 15 |
Close the door, serve who’s inside, then turn off the lights
A graceful shutdown is what a shop does at closing time. Stop letting new customers in, serve the ones already inside, then turn off the lights. For a server that means:
- stop accepting new connections;
- let the requests in progress finish;
- exit with code
0, which says “stopped cleanly”, instead of being killed.
With only health checks, being killed costs nothing. It starts to matter as soon as a request writes something. Kill the process between writing a file and saving the database row that points to it, and you’re left with an orphan file that nothing references.
with_graceful_shutdown and a future that waits
axum has the whole mechanism built in. axum::serve returns a value with a with_graceful_shutdown method that takes a future: the server runs normally until that future completes, then shuts down in order. So the only thing to write is a future that completes when a signal arrives:
async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("failed to listen for Ctrl+C");
};
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to listen for SIGTERM")
.recv()
.await;
};
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
tracing::info!("shutting down");
}
tokio::select! waits on both futures and continues as soon as the first one finishes, so either signal starts the shutdown. Then, at startup:
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await?;
tracing::info!("stopped");
Note that shutdown_signal() is called here, with parentheses: with_graceful_shutdown wants the future it returns, not the function itself.
The two expect calls are a conscious exception to how I handle errors elsewhere. They only fire if the process can’t install a signal handler at all, and with_graceful_shutdown takes a future that returns nothing, so there’s no error to hand back. The axum example does the same. SIGTERM lives in tokio::signal::unix, which is fine for me: the backend runs on macOS in development and Linux in production, both Unix.
With this in place, the same demo service:
| Signal | Result |
|---|---|
Ctrl+C (SIGINT) | exit 0 |
SIGTERM | exit 0 |
The copied line that switched SIGTERM off
I wrote the first version by following the official example, and copied one line too many:
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to listen for SIGTERM")
.recv()
.await;
};
let terminate = std::future::pending::<()>();
In the example, those two definitions sit under #[cfg(unix)] and #[cfg(not(unix))]: on systems without SIGTERM, terminate becomes a future that never completes. I copied both without the attributes, so the second let shadowed the first, and select! waited on the one that never fires.
What surprised me is what happened next. I expected the server to ignore SIGTERM. It didn’t: it died on the spot, killed by signal 15. The SIGTERM handler is installed inside that first async block, and an async block does nothing until it’s awaited. Shadowed, it was never awaited, so the handler was never installed, and the signal did its default thing. Ctrl+C still shut down gracefully, so testing by hand in a terminal would have hidden the bug completely. Only SIGTERM, the signal Docker uses, was broken.
The compiler had said so: warning: unused variable: terminate. Removing the pending line, which I don’t need anyway, fixed it.
A request that outlives the signal
To see the “serve who’s inside” part, I needed a request that takes a while. The readiness endpoint provides one for free: with the database paused, it waits for the pool’s 3-second timeout before answering 503. So I paused the database, sent a readiness request, and sent SIGTERM to the service one second later:
SIGTERM sent at ~1s
in-flight request: 503 in 3.003072s
service exit code: 0
The request that was already inside got its full answer, two seconds after the signal. Only then did the process exit, and with code 0. The log shows the order:
{"level":"INFO","fields":{"message":"listening","port":18080},"target":"notes_api"}
{"level":"INFO","fields":{"message":"shutting down"},"target":"notes_api"}
{"level":"WARN","fields":{"message":"database not ready","error":"pool timed out while waiting for an open connection"},"target":"notes_api"}
{"level":"INFO","fields":{"message":"stopped"},"target":"notes_api"}
“Shutting down” comes before the request finishes, and “stopped” after it. Those lines come from the JSON logs set up in the previous post, and here they are the easiest way to check that the order is right.
Twenty lines between finished and killed
Graceful shutdown is small enough that I can’t think of a reason to skip it, and the failure without it is invisible until the day a request is cut in half. The part I’d stress is testing it with the signal production will actually send: Ctrl+C worked perfectly while SIGTERM was broken. What I haven’t done yet is put a limit on how long the shutdown may wait. Docker’s 10 seconds are a limit of sorts, but a request slower than that would still be killed in the middle, and I’d rather decide that myself than leave it to the orchestrator.