Sub topic 11
Putting it together: graceful shutdown
This chapter combines the tools from earlier chapters into one shutdown procedure. It assumes you know tokio::select!, CancellationToken, JoinHandle::abort and timeout, and that you have used tokio::spawn and mpsc channels.
A graceful shutdown lets in-flight work reach a safe stopping point before the process exits. It is the opposite of killing the process in the middle of a write. The pieces are:
- Something that asks tasks to stop.
- Tasks that notice the request and finish cleanly.
- A deadline, so one stuck task cannot block exit forever.
The three phases
Every shutdown in a Tokio program follows the same order.
- Trigger. Something decides it is time to stop. Usually this is Ctrl-C, SIGTERM, a fatal error in one task, or a test finishing.
- Signal and drain. The program tells tasks to stop accepting new work. Tasks finish what they have started, and queued work is processed or deliberately discarded.
- Wait with a deadline, then force. The program awaits every task under a
timeout. Tasks still running when it expires are aborted.
Two ways to say "stop"
The example below uses both of these signalling mechanisms.
| Mechanism | Who notices | Best for |
|---|---|---|
| `CancellationToken` | Any task that awaits `token.cancelled()` in a `select!` | Tasks that run until told to stop, such as tickers, accept loops and pollers |
| Closing a channel | The receiver, when `recv()` returns `None` | Pipelines, where a stage should finish its queue and then end |
Closing a channel is often the better way to drain work. When the producer drops its Sender, the receiver still gets every buffered item before it sees None. The consumer needs no token and no special shutdown code. Its normal loop ends, and nothing in the queue is lost.
A token is better for tasks with no natural end of input. Child tokens (token.child_token()) let you cancel one subsystem without touching the others. Cancelling the parent cancels all children.
The full example
Add these dependencies. The full feature of Tokio includes the signal and time features used here.
[dependencies]
tokio = { version = "1", features = ["full"] }
tokio-util = "0.7"The program starts a producer and a slower consumer, waits for Ctrl-C (or 350 ms, so the demo ends by itself), and then shuts down in the three phases.
use std::time::Duration;
use tokio::{
signal,
sync::mpsc,
task::JoinSet,
time::{interval, sleep, timeout},
};
use tokio_util::sync::CancellationToken;
async fn producer(tx: mpsc::Sender<u32>, token: CancellationToken) {
let mut tick = interval(Duration::from_millis(40));
let mut n = 0;
loop {
tokio::select! {
_ = token.cancelled() => {
println!("producer: stop requested");
break;
}
_ = tick.tick() => {
if tx.send(n).await.is_err() {
break; // receiver is gone
}
n += 1;
}
}
}
// tx is dropped here, which closes the channel
}
async fn consumer(mut rx: mpsc::Receiver<u32>) {
while let Some(n) = rx.recv().await {
sleep(Duration::from_millis(100)).await; // slow work
println!("consumer: processed {n}");
}
println!("consumer: channel drained, exiting");
}
#[tokio::main]
async fn main() {
let token = CancellationToken::new();
let (tx, rx) = mpsc::channel(8);
let mut tasks = JoinSet::new();
tasks.spawn(producer(tx, token.child_token()));
tasks.spawn(consumer(rx));
// Phase 1: trigger
tokio::select! {
_ = signal::ctrl_c() => println!("main: ctrl-c received"),
_ = sleep(Duration::from_millis(350)) => println!("main: demo time is up"),
}
// Phase 2: signal
token.cancel();
// Phase 3: wait with a deadline
let drain = async {
while let Some(result) = tasks.join_next().await {
if let Err(e) = result {
println!("main: a task failed: {e}");
}
}
};
let outcome = timeout(Duration::from_secs(2), drain).await;
if outcome.is_err() {
println!("main: grace period over, aborting the rest");
tasks.abort_all();
while tasks.join_next().await.is_some() {}
}
println!("main: shutdown complete");
}The producer runs faster than the consumer, so the channel holds a few items when cancel() is called. The output shows the producer stopping first. The consumer then keeps printing processed lines for the buffered items, prints channel drained, and main reports completion. The exact numbers vary from run to run.
Why the example is built this way
JoinSet instead of loose JoinHandles. A JoinSet owns its tasks. join_next() returns results as tasks finish, abort_all() cancels everything that remains, and dropping the set aborts all its tasks. With plain tokio::spawn you must keep every handle yourself, and a forgotten handle means a detached task that nothing waits for.
The deadline wraps the whole drain. timeout is applied once around the loop that waits for all tasks. It is not applied per task. The total shutdown time is then bounded by one number, which is what a process supervisor with a kill timeout cares about.
The abort_all fallback still joins. After abort_all(), the loop while tasks.join_next().await.is_some() {} waits until every aborted task has actually stopped. An aborted task is cancelled at its next await point, not instantly. Each aborted task yields a JoinError with is_cancelled() true, and the loop ignores those.
The token goes to the producer only. The consumer ends when the channel closes. Giving it a token as well would create a second way to stop it, which could discard queued items. Choose per task whether the stop request means "finish the queue" or "stop now".
Edge cases
The loop body is not cancelled by `select!`
Once a select! branch wins, its handler runs to completion. In the producer, tx.send(n).await sits inside the handler. If the channel is full and the consumer is stuck, the producer waits there and never checks the token again. For shutdown to stay responsive, race the blocking operation too. The reserve() pattern from the cancel-safety chapter does this: select! over tx.reserve() and token.cancelled(), and send only after the permit arrives.
Panics and errors
A task that panics returns a JoinError from join_next(), and e.is_panic() is true. The example prints it and carries on, so one failed task does not stop the others from being awaited. If a failure should shut down the whole program, call token.cancel() when you see it.
Tasks that spawn tasks
Only tasks spawned through the JoinSet are tracked by it. A worker that calls tokio::spawn internally creates a detached task, and nothing waits for it. Spawn such children into a JoinSet that the worker owns and awaits before it returns. The TaskTracker type in tokio_util::task is an alternative when you cannot hold handles. You call close() on the tracker and then wait().await.
Blocking code
A task running synchronous work such as a long computation or std::thread::sleep never reaches an await point. It cannot see the token, and abort() cannot stop it. timeout will not fire on time either. Put such work in spawn_blocking and give it its own check, such as an AtomicBool it reads periodically. Dropping the Tokio runtime waits for spawn_blocking tasks without a limit. Runtime::shutdown_timeout puts a limit on that wait.
Cleanup that needs `await`
Drop is synchronous, so a drop guard cannot flush a buffer over the network. Put that flush in the normal exit path, after the loop breaks and before the task returns. Keep the drop guard as a last-resort fallback for the case where the task is aborted.
A second Ctrl-C
Users press Ctrl-C again when shutdown seems slow. The grace-period timeout covers this on its own. If you also want an immediate exit on the second press, race signal::ctrl_c() against the drain future in the same select!.
SIGTERM
Containers and process managers send SIGTERM, not SIGINT. On Unix, use tokio::signal::unix::signal(SignalKind::terminate()) and race its recv() with ctrl_c() in the trigger step.
Checklist
- Every long-lived task has a stop path: a token branch in its
select!, or an input channel that closes. - Every
.awaitinside a handler that could block indefinitely is itself raced against the token. - Tasks are owned by a
JoinSetorTaskTracker, not detached. - The wait for tasks is bounded by one
timeout, followed byabort_all()and a final join. - Blocking work has its own stop flag.
Exercise
In the example, the consumer has no CancellationToken. Why are the items still in the channel at shutdown not lost, and what would change if you replaced the producer's break on cancellation with tasks.abort_all() in main?
Show answer
When the producer breaks out of its loop it drops its only Sender, which closes the channel. recv() keeps returning buffered items and only returns None once the buffer is empty, so the consumer processes every queued item before it exits. With abort_all() the consumer is aborted at its next await point, for example during its sleep or recv. Items still in the channel are dropped along with the receiver and are never processed. abort_all() is the forceful fallback, not the graceful path.
Exercise
Change the program so a task that ignores cancellation (for example async { loop { sleep(Duration::from_secs(1)).await } }) is added to the JoinSet. Describe what the output shows and why the final while tasks.join_next().await.is_some() {} is needed after abort_all().
Show answer
The extra task never sees the token, so the drain future cannot finish. After 2 seconds timeout returns Err, and the program prints "grace period over, aborting the rest". abort_all() only schedules cancellation, and each task stops at its next await point. The final join loop waits until every aborted task has actually ended, so nothing is still running when main prints "shutdown complete". Each aborted task returns a JoinError with is_cancelled() true, and the loop discards it.