Sub topic 11
Putting it together: graceful shutdown
This chapter assumes you know Tokio basics (tokio::spawn, JoinHandle), the select! macro, Drop, and the earlier chapters on cancellation by drop and CancellationToken. A graceful shutdown combines those pieces. It tells tasks to stop, waits for them to finish their current step, and releases resources in a known order.
Why abort is not enough
JoinHandle::abort cancels a task at its next await point. The task gets no chance to flush a buffer, commit a transaction, or send a final message. Only Drop implementations run. For work that must finish cleanly, you need the task to take part in its own shutdown.
A graceful shutdown has three steps:
- Signal: tell every task that shutdown has begun.
- Drain: let each task finish its current unit of work and exit its loop.
- Wait: join every task before the program exits, so cleanup completes.
The signal
A CancellationToken from tokio_util is the signal. Cancelling a parent token also cancels every child token created with child_token(). Each worker holds a child, so you can also cancel one worker without affecting the others.
A complete example
Each worker loops on select!. One branch waits for cancellation. The other does a step of work.
use std::time::Duration;
use tokio::time::sleep;
use tokio_util::sync::CancellationToken;
async fn worker(id: u32, token: CancellationToken) {
loop {
tokio::select! {
_ = token.cancelled() => {
println!("worker {id}: shutting down");
break;
}
_ = sleep(Duration::from_millis(50)) => {
println!("worker {id}: tick");
}
}
}
}
#[tokio::main]
async fn main() {
let token = CancellationToken::new();
let handles: Vec<_> = (0..2)
.map(|id| tokio::spawn(worker(id, token.child_token())))
.collect();
sleep(Duration::from_millis(120)).await;
token.cancel();
for handle in handles {
handle.await.unwrap();
}
}The program prints a few ticks per worker, then each worker prints its shutdown line. main returns only after both handles resolve.
token.cancelled() is cancel safe, so losing a race to the sleep branch drops nothing. A fresh sleep is created each iteration, which is fine here because the sleep is a step timer, not an overall deadline.
Finishing the current step
In the example, cancellation is only noticed between steps. If a step is itself an await that select! can drop, the step would be cut off. Put work that must not be interrupted in the handler body, not in a branch future. Once a branch handler starts running, select! has already dropped the other futures, so the handler runs to completion unless it awaits something that is itself cancelled.
Bounding the wait
A task that never checks its token would hang shutdown forever. Wrap the join phase in timeout, and abort stragglers once the grace period ends.
use std::time::Duration;
use tokio::time::{sleep, timeout};
use tokio_util::sync::CancellationToken;
#[tokio::main]
async fn main() {
let token = CancellationToken::new();
let child = token.child_token();
let handle = tokio::spawn(async move {
// Ignores the token on purpose, to show the fallback.
let _ = child;
sleep(Duration::from_secs(60)).await;
});
token.cancel();
let abort = handle.abort_handle();
match timeout(Duration::from_millis(200), handle).await {
Ok(_) => println!("clean exit"),
Err(_) => {
println!("grace period over, aborting");
abort.abort();
}
}
}Passing handle into timeout moves it, so the code takes an AbortHandle first. When the timeout fires, the join future is dropped. Dropping a JoinHandle detaches the task and does not cancel it, which is why the explicit abort() is needed.
Order of cleanup
Shut down in dependency order. Stop accepting new work first, then drain workers, then close shared resources such as connections. Drop guards inside tasks run on both clean exit and abort, so they are the safety net for the abort path.
Exercise
In the timeout example, why call abort.abort() after the timeout elapses instead of relying on the timeout dropping the JoinHandle?
Show answer
Dropping a JoinHandle detaches the task. The task keeps running in the background. Only abort() cancels it at its next await point.
Exercise
What are the three phases of a graceful shutdown, and which Tokio call implements the third?
Show answer
Signal (cancel the token), drain (workers finish the current step and exit), and wait (await every JoinHandle). The third phase uses handle.await on each handle, optionally wrapped in timeout.