Stopping the Server with Ctrl-C
Learn how to stop your Axum server gracefully using Ctrl-C, so it finishes active requests and releases resources cleanly during development.
Every time you run cargo run and your Axum server starts listening on port 3000, you eventually need to stop it. The simplest way is to press Ctrl-C in the terminal where the server is running. That sends an interrupt signal to your program, and Rust's default behavior is to terminate the process immediately.
For a tiny hello-world server, immediate termination is fine. But as soon as your server handles real work - like writing to a database, uploading a file, or sending a response that takes a few hundred milliseconds - an abrupt kill can cut that work off midway. A request that was half-processed disappears without a response. A file write stops in the middle and may leave a corrupted file on disk.
Graceful shutdown solves this. Instead of killing everything instantly, your server stops accepting new connections, finishes the requests it is already handling, and then exits. Axum provides a built-in way to do this with one method call, and it works perfectly with the Ctrl-C signal.
What "Graceful Shutdown" Actually Means
Imagine a restaurant closing for the night. An abrupt shutdown is like turning off the lights while customers are still eating and the kitchen is still cooking. A graceful shutdown is like locking the front door so no new customers enter, letting everyone inside finish their meal, and then turning off the lights after the last customer leaves.
For a web server, the "front door" is the TCP listener - the thing that accepts incoming connections. The "customers" are the active HTTP requests currently being processed by your handlers. A graceful shutdown does these three things:
- Stops accepting new connections.
- Waits for all currently active handlers to finish.
- Exits the process cleanly.
That way no request is ever cut short, and no resource (database connection, file handle, temporary file) is left in a half-written state. During development this matters because it prevents confusing "connection reset" errors in your browser or API client when you stop and restart the server repeatedly.
How Axum Supports Graceful Shutdown
Axum's Router does not shut itself down. The shutdown logic belongs to the server that runs the router. Since Axum 0.7, that server is created with axum::serve. Earlier versions used axum::Server::bind. Both of these provide a method called with_graceful_shutdown.
That method takes a future - an async block or function that resolves when shutdown should begin. The server then runs normally, but as soon as that future resolves, it stops accepting new connections and waits for active requests to finish.
The most common future to pass is tokio::signal::ctrl_c(). This function waits until the user presses Ctrl-C and then resolves. It is part of Tokio's signal feature, so you must enable that feature in your Cargo.toml.
What is a Future?:
In async Rust, a future is a value that represents work that may not be finished yet. You can think of it as a promise that will eventually produce a result or just complete. tokio::signal::ctrl_c() returns a future that completes when the user presses Ctrl-C. Axum waits for that future as part of its shutdown process.
Enabling the Tokio Signal Feature
Your Cargo.toml already lists tokio as a dependency because the #[tokio::main] macro and the async runtime come from there. But not all Tokio features are enabled by default. The signal feature includes the code for listening to operating system signals like Ctrl-C.
Open Cargo.toml and make sure the tokio dependency line includes signal in its feature list. If you previously added the full feature, you already have it, but it is good practice to list only what you need.
Here is a minimal Cargo.toml with the required dependencies for a graceful Axum server:
[package]
name = "my-axum-app"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }
The three Tokio features serve different purposes:
macrosgives you the#[tokio::main]attribute.rt-multi-threadprovides the multi-threaded runtime that#[tokio::main]uses by default.signalis the one that gives youtokio::signal::ctrl_c().
The net feature, which TcpListener::bind needs, comes along automatically, because axum's own default features enable it for you - so this list really is enough for the example below.
If you don't include signal, you will get a compile error saying the signal module is not available. We'll cover that mistake later.
Basic Example - Server Without Graceful Shutdown
Before adding graceful shutdown, your main.rs probably looks like this:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, world!" }));
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).await.unwrap();
}
This works. The server starts, listens, and responds to requests. When you press Ctrl-C, the entire process stops immediately. Any handler that is in the middle of executing gets dropped. Later you will write handlers that do more than return a static string - they might read from a database, deserialize JSON, or write a file. Those are exactly the operations that need to finish before the process dies.
Adding Graceful Shutdown with with_graceful_shutdown
We will now modify the axum::serve call to include with_graceful_shutdown. The method expects one argument: a future that resolves when shutdown should start. We will pass a small async function that waits for Ctrl-C.
Here is the complete updated main.rs:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, world!" }));
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();
}
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("failed to listen for ctrl-c");
println!("Shutting down gracefully...");
}
Notice what changed:
- We added
.with_graceful_shutdown(shutdown_signal())betweenaxum::serve(listener, app)and.await. - We defined an async function
shutdown_signalthat waits forctrl_c()and then prints a message. - The
awaitandunwrapnow apply to the whole chain, not justaxum::serve.
When you run this code, the server starts just like before. But now when you press Ctrl-C, Tokio's signal handler wakes up, ctrl_c() returns, and Axum begins its graceful shutdown sequence. The message "Shutting down gracefully..." appears in the terminal, and after any active requests finish, the process exits.
Step-by-Step Walkthrough of the Shutdown Process
Let's trace exactly what happens when you press Ctrl-C with this code running:
- The operating system sends a SIGINT signal to your process.
- Tokio's signal handler, which was set up by
tokio::signal::ctrl_c(), receives that signal and resolves the future. - The
shutdown_signalfunction prints its message and then returns. - Axum's
with_graceful_shutdownfuture has now completed, so the server stops accepting new TCP connections on port 3000. - If any handlers are currently executing (for example, a handler that is waiting for a database query), Axum waits for them to finish.
- Once all active handlers return,
axum::serve(...).awaitresolves. - The
mainfunction returns, and the Tokio runtime shuts down.
That is the entire graceful shutdown sequence. It happens in a fraction of a second for a simple server, but for a server under load with slow handlers, it might take a few seconds while requests finish.
Testing Graceful Shutdown with a Slow Handler
To see graceful shutdown in action, you need a handler that takes some time to complete. The simple "Hello, world!" handler finishes in microseconds, so you won't notice the difference between abrupt and graceful termination. Let's create a handler that sleeps for three seconds before responding.
Add a new route /slow to your router and a handler like this:
use axum::{routing::get, Router};
use std::time::Duration;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello, world!" }))
.route("/slow", get(slow_handler));
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();
}
async fn slow_handler() -> &'static str {
tokio::time::sleep(Duration::from_secs(3)).await;
"Slow response finished"
}
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("failed to listen for ctrl-c");
println!("Shutting down gracefully...");
}
Now follow these steps to observe the difference:
- Run the server with
cargo run. - Open a second terminal and send a request to
/slowusingcurl http://127.0.0.1:3000/slow. - Immediately switch back to the first terminal (where the server is running) and press Ctrl-C.
- Watch what happens.
If you had no graceful shutdown, the server would die instantly, and the curl command in the other terminal would show a connection reset error. With graceful shutdown, the server prints "Shutting down gracefully..." but does not exit immediately. It waits until the slow_handler finishes sleeping, sends the response to the waiting curl client, and only then exits. In the second terminal, curl will print "Slow response finished" after the three seconds are up.
This is the clearest demonstration of why graceful shutdown is important: a request that started before you pressed Ctrl-C still gets a proper response.
What If You Use an Older Version of Axum (0.6 and earlier)?
Axum's API changed significantly in version 0.7. Before that, you did not use axum::serve. Instead, you created a server with axum::Server::bind and then called serve on it. The graceful shutdown method was the same name, with_graceful_shutdown, but the surrounding code looked different.
If you are reading tutorials or older code that uses axum::Server, here is how you would write the same graceful shutdown pattern:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, world!" }));
let addr = "127.0.0.1:3000".parse().unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::Server::bind(&addr)
.serve(app.into_make_service())
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("failed to listen for ctrl-c");
println!("Shutting down gracefully...");
}
The main differences are:
axum::Server::bind(&addr)instead oftokio::net::TcpListener::bind.- The address is a
SocketAddr, so you need to parse the string. servetakesapp.into_make_service()instead of justapp.
If you are using the latest Axum (0.8), use the axum::serve version. We will stick with that for the rest of this page.
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, world!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("failed to listen for ctrl-c");
}
Use the version that matches the Axum dependency in your Cargo.toml. If you started this project recently, you are almost certainly on 0.7 or newer.
Common Mistakes When Adding Graceful Shutdown
Beginners often run into a few predictable problems when they first implement this. Here are the ones you are most likely to see.
Forgetting the signal Feature on Tokio
If your Cargo.toml looks like this:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
Then tokio::signal::ctrl_c() will not compile. You will see an error message like:
error[E0433]: cannot find `signal` in `tokio`
This happens because the signal module is behind a feature flag. The fix is simple: add "signal" to the features list.
Compilation Error:
Missing the signal feature is the most common reason beginners cannot get graceful shutdown working. Always check your Cargo.toml first when you see "could not find signal in tokio".
Not Awaiting the Shutdown Future
tokio::signal::ctrl_c() returns a future. That future does nothing until you .await it. If you write:
async fn shutdown_signal() {
tokio::signal::ctrl_c();
}
The function returns immediately, and Axum thinks shutdown should start right away. Your server will shut down as soon as it starts, before you ever get to press Ctrl-C. The ctrl_c() future is created but never awaited, so it is dropped. A future that is dropped does no work.
Always write .await after ctrl_c().
Ignoring the Result from ctrl_c()
tokio::signal::ctrl_c() returns a Result. It can fail if the operating system refuses to install a signal handler, though this is rare on normal systems. The common pattern is to call .expect("failed to listen for ctrl-c"). This will panic with a clear message if it fails, which is acceptable in a small development program.
If you ignore the result with something like let _ = tokio::signal::ctrl_c().await;, you might not notice that signal handling failed and your server will never shut down gracefully. That is why .expect is better in this context. (Note the .await is still required - without it, the future is created and dropped immediately, which is the same "not awaiting" mistake as the previous section.)
Calling std::process::exit in a Handler
Some beginners try to stop the server by calling std::process::exit(0) inside a handler when they receive a certain request. That kills the entire process immediately, bypassing any graceful shutdown logic. It defeats the purpose of using with_graceful_shutdown. The correct way to stop the server programmatically is to trigger the shutdown future, not to call process::exit.
Verifying That Your Server Shuts Down Cleanly
After you add the graceful shutdown code, run the server and then press Ctrl-C. In your terminal, you should see something like this:
Server running at http://127.0.0.1:3000
Shutting down gracefully...
And then your command prompt returns. The exact timing depends on whether any requests were in flight. With no active requests, the shutdown is instant. With a slow request, it waits for that request to finish.
Everything Working:
If you see the "Shutting down gracefully..." message and your terminal returns to the prompt without any error messages, your graceful shutdown implementation is working correctly.
If you don't see that message, either you forgot to print it in your shutdown_signal function, or the ctrl_c() future never resolved because the signal feature is missing (which would have caused a compile error) or because you didn't await it.
Graceful Shutdown and the Development Loop
Stopping and restarting the server is something you do constantly during development. You change a handler, press Ctrl-C, run cargo run again, and test. Without graceful shutdown, each of those restarts could leave your browser or API client with a broken connection. That leads to confusing "connection reset" errors, and you might waste time thinking your code is broken when the real problem was just an abrupt server stop.
With graceful shutdown, the development loop becomes much cleaner:
- Make your code change.
- Press Ctrl-C in the server terminal.
- Server finishes any active requests and exits.
- Run
cargo runagain. - Continue testing.
No broken connections, no corrupted output, no confusion.
Long-Running Requests Can Delay Shutdown:
Graceful shutdown waits for all active requests to finish. If you have a handler that runs for a very long time (like a never-ending stream or a buggy infinite loop), your server will not exit when you press Ctrl-C. It will wait forever. In development, this usually means you need to fix the handler. In production, you would add a timeout to the shutdown process, but that is beyond this page.
Extending Beyond Ctrl-C (Briefly)
The graceful shutdown pattern you learned here is not limited to Ctrl-C. In production, servers often need to respond to other signals, such as SIGTERM, which is what process managers like Docker or systemd send when they want a container to stop. You could replace tokio::signal::ctrl_c() with tokio::signal::unix::signal(SignalKind::terminate()) on Unix systems. That is a small change, but it requires platform-specific code.
For now, remember that with_graceful_shutdown accepts any future. Whatever future you give it determines when the shutdown begins. The Ctrl-C future is the simplest and most useful for your local development loop.
Summary
You now know how to stop your Axum server gracefully with Ctrl-C. The core idea is that with_graceful_shutdown lets you define a future that signals when the server should stop accepting new connections. Axum then waits for active requests to complete before exiting. This is a small change to your main.rs, but it makes your development loop much more pleasant and prevents subtle errors caused by abrupt process termination.
The most important takeaway is this: a graceful shutdown is not about making the server exit faster - it's about making it exit cleanly. It ensures that every request gets a proper response and every resource is left in a consistent state.
As you continue learning Axum, you will encounter handlers that interact with databases and files. Those handlers take time, and graceful shutdown is what protects them when you need to stop the server. Keep this pattern in your main.rs from the very beginning, and you won't have to think about it again.