Draining in-flight connections
Learn what draining means for an Axum server, how with_graceful_shutdown lets requests already in progress finish while refusing new ones, and what to do about requests that never end
Draining is what a server does when it is told to stop but still has work in progress. It closes the front door, finishes serving the requests that are already inside, and only then turns off the lights. A request that arrived a second before the stop signal still gets its full answer. A request that arrives a second after the signal is refused at once, instead of being accepted and then dropped halfway through.
Where This Fits
The graceful shutdown page introduced with_graceful_shutdown, the call that makes axum::serve return cleanly instead of being killed mid-request. This page looks inside that call. It follows one slow request through a shutdown, shows exactly what happens to new connections, to idle connections, and to requests that never finish, and shows how to put a deadline on the whole process so a single stuck request cannot hold the server open forever.
Think of a shop at closing time. The owner locks the door so nobody new comes in, serves the customers already at the counter, and then closes. Draining is that sequence, applied to network connections instead of people.
The Smallest Working Version
The smallest version needs a request slow enough to watch. A handler that sleeps for three seconds gives a window to send the stop signal while the request is still running.
// src/main.rs
use axum::{routing::get, Router};
async fn slow() -> &'static str {
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
"slow request finished"
}
async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to install SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/slow", get(slow));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
println!("Server stopped cleanly.");
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
Run the server, then try the drain yourself. Open three terminals. In the first, start the server. In the second, start a slow request. In the third, stop the server while that request is still running.
curl http://127.0.0.1:3000/slow
kill -TERM <server-process-id>
What you see is the whole lesson in one run. The slow request still prints slow request finished after its three seconds, even though the stop signal arrived during those three seconds. The server then prints Server stopped cleanly. and exits. A fresh curl after the signal gets connection refused, because the server stopped accepting new connections the moment the signal arrived.
The versions checked for this page are axum 0.8.9 and tokio 1.54.1. The shutdown_signal function is the same shape used in the model page, extended with a second branch for SIGTERM, which is the signal containers and process managers send when they stop a service. Ctrl+C sends SIGINT, and tokio::signal::ctrl_c catches that one. Without the SIGTERM branch, a container stop would kill the process outright and the drain would never happen.
Working Setup:
If the slow request returns its full answer after the signal, the server prints its stopped message, and the process exits with code 0, draining works. The request that was inside got served, the door closed for everyone else, and the program ended on its own terms.
What Happens Step by Step
Draining is four steps in a fixed order, and each step does one job. Knowing the order explains every behaviour on this page, including the ones that look like bugs.
1. The signal future completes
with_graceful_shutdown takes a future, and the server runs normally until that future completes. In the example, the future is shutdown_signal(), which waits on two signals at once with tokio::select!. The select! macro runs both waits together and continues as soon as the first one finishes, so either Ctrl+C or SIGTERM starts the shutdown. Nothing about the server changes before this moment. Requests are accepted and answered exactly as before.
2. The accept loop stops and the listener is dropped
The moment the signal future completes, Axum stops accepting new connections and drops the listener. Dropping the listener releases the port, and the operating system starts refusing new connections to it. This is why a fresh curl after the signal fails at once with connection refused, instead of hanging or being queued. A load balancer that keeps sending traffic gets a fast refusal, which lets it move that traffic to a healthy server, instead of a slow timeout.
3. In-flight requests are allowed to finish
Every connection the server already accepted is handled by its own task, and each of those tasks is told to shut its connection down gracefully. A connection that is in the middle of a request keeps running until the handler returns its response. A connection that is idle, meaning a past request finished and the socket is waiting for the next one, is closed at once, because there is nothing to wait for. The handler is never cancelled and never interrupted. The sleep in the /slow handler runs its full three seconds, and the response goes out normally.
4. serve returns and main continues
axum::serve waits until every connection task has exited, and only then does its future complete. The .await after serve finishes, the println! after it runs, and main returns. That ordering is what makes the lines after serve the right place for cleanup: closing the database pool, flushing logs, or writing a final log line. Any code placed there runs only after the last in-flight request has had its answer.
Request starts at 0.0s, sleeps 3s
|
| SIGTERM arrives at 1.0s
v
Accept loop stops, listener dropped
New curl gets connection refused
|
| slow handler keeps running
v
Response sent at 3.0s
|
v
serve returns, main prints stopped message, process exits 0
Draining Finishes Requests, It Does Not Cancel Them:
A common misunderstanding is that shutdown cancels work in progress. It does the opposite. The handler keeps running until it returns, and only then does the connection close. If a handler waits on a database query that takes ten seconds, the drain takes ten seconds. Cancelling a handler mid-query is a different tool, and it belongs inside the handler, not in the shutdown code.
The Concept Behind Draining
A server at any moment holds three kinds of connections: new ones arriving, idle ones waiting, and busy ones being served. A hard stop treats all three the same and kills them all, which means a request that was one second from its answer gets nothing, and the client sees a broken connection. Draining treats the three kinds differently, because they need different handling. New ones are refused, idle ones are closed, and busy ones are finished.
A beginner can think of the server as a kitchen taking orders. A hard stop is switching off the power with food on the stoves. Draining is stopping new orders, cooking what is already on the stoves, and then switching off. The difference is not politeness. It is correctness: a client that sent a request and got no answer cannot know whether its order went through, and for a request that writes to a database, that uncertainty is a real problem.
Why This Design
The design comes from how deployments actually replace servers. A new version is started, the old version is told to stop, and traffic moves over. If the old version drops its in-flight requests, users see errors during every deploy, even when nothing is wrong with the new version. If it drains, the deploy is invisible to anyone whose request was already running, and the only visible change is that new requests go to the new version.
The same reasoning applies to a single server on a laptop. Pressing Ctrl+C during development should not corrupt a half-written file or leave a database row half-updated. Draining gives every request a chance to finish its work and write its result before the process ends.
Listening for SIGTERM as Well as Ctrl+C
The smallest version already listens for both signals, and the reason deserves its own section because it is the most common draining failure in real deployments. On a laptop, you stop a server with Ctrl+C, which sends SIGINT. In a container, docker compose stop sends SIGTERM, and the container runtime waits a few seconds before sending SIGKILL, which cannot be caught at all. A server that only handles Ctrl+C drains fine on the laptop and is killed mid-request in the container.
The #[cfg(unix)] lines in the example handle this without breaking Windows builds, where Unix signals do not exist. On Unix, the terminate branch installs a handler for SignalKind::terminate() and waits for its first signal. On other systems, the branch is a future that never completes, so only Ctrl+C can start the shutdown. The tokio::select! macro picks whichever branch finishes first.
// src/shutdown.rs
pub async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to install SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
Putting the function in its own file keeps main short and makes the same signal handling reusable. The function is called the same way: .with_graceful_shutdown(shutdown_signal()). Note the parentheses. The method takes the future that the function returns, not the function itself, so calling it without parentheses is a type error.
Installing the Signal Handler Too Late:
The tokio::signal::unix::signal call installs the handler when the async block first runs, not when the function is defined. An async block does nothing until it is awaited, and tokio::select! starts both branches at once, so both handlers are installed when shutdown begins. The failure to avoid is building the terminate future in one place and only awaiting it much later, after the signal has already arrived and been missed. Keep the signal future inside the same select! that waits on it.
Adding a Deadline So Shutdown Cannot Hang Forever
Draining waits for every in-flight request, and a request that never ends holds the shutdown open forever. A streaming response that never closes is the classic case: the handler returned its headers long ago, the body is still open, and the connection is still busy, so the server waits. The fix is a deadline. If draining is not done within a fixed time, the server stops waiting and exits anyway.
// src/main.rs
use axum::{routing::get, Router};
use std::time::Duration;
#[tokio::main]
async fn main() {
let app = Router::new().route("/slow", get(slow));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
let server = axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal());
match tokio::time::timeout(Duration::from_secs(10), server).await {
Ok(result) => {
result.unwrap();
println!("Server stopped cleanly.");
}
Err(_) => {
eprintln!("Shutdown timed out after 10 seconds, exiting anyway.");
}
}
}
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_secs(3)).await;
"slow request finished"
}
The tokio::time::timeout wrapper runs the server future with a ten-second limit. If the server finishes first, the Ok branch runs and the shutdown was clean. If ten seconds pass first, the Err branch runs, the timeout drops the server future, and main returns, which ends the process. Dropping the future does not politely finish the handlers. It ends them. That is the trade-off a deadline makes: most requests get their clean finish, and a stuck one is cut off rather than holding the whole deploy hostage.
Picking the deadline is a judgement call, not a formula. It must be longer than the slowest request you expect to serve, and shorter than the time your platform waits before force-killing the process. Container runtimes typically allow ten seconds after SIGTERM before SIGKILL, so a deadline inside that window is the useful range. A deadline longer than the platform's kill window never runs, because the platform kills the process first.
A Deadline Shorter Than Your Slowest Request Kills Good Work:
A deadline is a trade, not a free safety net. Set it shorter than the time your slowest normal request needs, and the timeout drops requests that would have finished a second later, turning clean finishes into broken connections for users who did nothing wrong. Measure the slowest request you expect to serve, then set the deadline above it, with room to spare.
Requests That Never End
Two kinds of long-lived request behave differently under draining, and both surprise beginners who expect one rule to cover them.
A streaming response, such as a server-sent events stream, keeps its connection busy for as long as the stream runs. Hyper sees an unfinished request, so the connection task never exits, and the drain waits. The stream itself has to end for the drain to finish. The usual fix is a shared cancellation token that the shutdown code cancels when the signal arrives, and the stream ends when it sees the token cancelled. The token is cancelled inside the signal future, before the server starts waiting on connections, because after serve returns it is already too late.
A WebSocket behaves the opposite way. Once the upgrade completes and the 101 Switching Protocols response goes out, the HTTP request is finished as far as hyper is concerned. The connection task exits, the drain does not wait for the socket, and the socket's own task is dropped when main returns and the runtime shuts down. The client sees an abnormal close instead of a clean close frame. The fix is the same token idea in reverse: keep track of open sockets, cancel them when shutdown starts, and send a close frame before main returns.
Neither case changes the basic drain. Both are about handlers that outlive a single request and response, and both need the handler itself to cooperate with shutdown. For ordinary handlers that return a response and finish, draining just works.
Closing the Database Pool After serve Returns
The lines after serve are where cleanup belongs, and the database pool is the most important cleanup. Closing the pool waits for its connections to finish their work and then closes them, so no query is cut off halfway.
// src/main.rs
use axum::{routing::get, Router};
use sqlx::PgPool;
#[tokio::main]
async fn main() {
let database_url = std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let pool = PgPool::connect(&database_url)
.await
.expect("could not connect to Postgres");
let app = Router::new()
.route("/", get(|| async { "Hello!" }))
.with_state(pool.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
println!("Server stopped, closing pool.");
pool.close().await;
println!("Pool closed, exiting.");
}
The pool.clone() is cheap: the pool is a handle to shared state, and cloning it shares the same connections. The original pool stays in main so it can be closed after serve returns. Closing before serve returns would break in-flight handlers that still need the database, which is why the order matters: drain first, close second, exit third.
Testing the Drain
The drain cannot be tested with the usual one-shot test helper, because that helper sends a request straight to the router without a listener or a server. Draining is a property of the running server, so the test has to run a real server. The honest way to test it is the manual run described at the top of this page, scripted so it can be repeated.
# Terminal 1 - start the server in the background and record its process id
cargo run &
SERVER_PID=$!
# Terminal 2 - start a slow request in the background
curl -s http://127.0.0.1:3000/slow > /tmp/slow_answer.txt &
sleep 1
# Terminal 2 - stop the server while the request is running
kill -TERM $SERVER_PID
# Terminal 2 - a new request is refused at once
curl -s http://127.0.0.1:3000/slow
# curl: (7) Failed to connect to 127.0.0.1 port 3000: Connection refused
# Terminal 2 - wait for the slow request, then read its answer
wait
cat /tmp/slow_answer.txt
# slow request finished
# Terminal 2 - the server exited cleanly
wait $SERVER_PID
echo $?
# 0
Each line checks one promise. The slow answer proves the in-flight request finished. The refused connection proves new ones were turned away. The exit code 0 proves the process ended cleanly instead of being killed. If any of those three fails, the drain is broken, and the usual cause is a missing SIGTERM branch or a missing with_graceful_shutdown call.
Common Beginner Mistakes
Only handling Ctrl+C
// Wrong - works on a laptop, killed mid-request in a container
axum::serve(listener, app)
.with_graceful_shutdown(async {
tokio::signal::ctrl_c().await.unwrap();
})
.await
.unwrap();
docker compose stop and most process managers send SIGTERM, not SIGINT. With only the Ctrl+C branch, the SIGTERM kills the process at once, and every in-flight request dies with it. The fix is the two-branch shutdown_signal from the examples above.
Forgetting to await serve
// Wrong - the server future is dropped and the server never runs
axum::serve(listener, app).with_graceful_shutdown(shutdown_signal());
axum::serve returns a future, and a future that is never awaited never runs. The compiler warns about the unused future, and the program exits at once. The fix is the .await after the whole chain, which is also what makes the code after it run only after the drain finishes.
Calling process exit inside the signal handler
// Wrong - exits at once, in-flight requests never finish
tokio::select! {
_ = tokio::signal::ctrl_c() => { std::process::exit(0); }
}
std::process::exit ends the process immediately, wherever it is called from. Placed inside the signal handling, it defeats the entire purpose of graceful shutdown. The signal future should only complete, letting serve do the draining and return normally, and main should end by returning, not by exiting.
Expecting the drain to wait for background tasks
with_graceful_shutdown waits for connection tasks, not for every task the program spawned. A background task started with tokio::spawn keeps running independently, and when main returns the runtime is dropped and the task is cancelled at its next await point. If background work must finish before exit, track it explicitly and wait for it after serve returns, in the same place the pool is closed.
Final Complete Example
Here is everything from the page in one program: both signals, the slow route, the drain, the pool close, and the deadline.
// src/main.rs
use axum::{routing::get, Router};
use sqlx::PgPool;
use std::time::Duration;
async fn slow() -> &'static str {
tokio::time::sleep(Duration::from_secs(3)).await;
"slow request finished"
}
async fn shutdown_signal() {
let ctrl_c = async {
tokio::signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("failed to install SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
#[tokio::main]
async fn main() {
let database_url = std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let pool = PgPool::connect(&database_url)
.await
.expect("could not connect to Postgres");
let app = Router::new()
.route("/slow", get(slow))
.route("/health", get(|| async { "OK" }))
.with_state(pool.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
let server = axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal());
match tokio::time::timeout(Duration::from_secs(10), server).await {
Ok(result) => {
result.unwrap();
println!("Server stopped cleanly.");
}
Err(_) => {
eprintln!("Shutdown timed out after 10 seconds, exiting anyway.");
}
}
pool.close().await;
println!("Pool closed, exiting.");
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
sqlx = { version = "=0.9.0", features = ["postgres", "runtime-tokio"] }
Run it, start a slow request, send SIGTERM, and watch the three promises hold: the slow answer arrives, new connections are refused, and the process exits with code 0 after closing its pool.
Summary
Draining is a question of who gets served and who gets turned away, and the answer is decided by timing, not by importance. A request that arrived before the signal is already inside, so it is finished. A request that arrives after the signal is outside, so it is refused. Everything else on the page follows from that one split: the listener must close first, the in-flight requests must finish second, and cleanup must run third.
The decision framework is short. Use the two-signal shutdown whenever the server runs under a process manager or in a container, because that is where SIGTERM arrives. Add a deadline whenever a request can outlive the platform's patience, because a drain without a deadline is a shutdown that may never happen. And treat the two long-lived exceptions, streams that never end and sockets that outlive their request, as handler problems rather than server problems: the server can only wait for work it can see, so work that never ends has to be told to end by the code that started it.