Sub topic 15
Shutting down cleanly
This chapter assumes you can spawn tasks and handle their JoinHandle results. It also assumes you know Tokio channels, select!, and the idea that dropping a future cancels it. Here you combine those pieces so a service stops without losing work.
What happens if you do nothing
When main returns, the Tokio runtime is dropped. Every task that has not finished is dropped at its next .await. No destructors you wrote for in-flight work run, no buffered data is flushed, and no connection gets a closing message. In a toy program that is fine. In a service it means half-written files and clients that see a reset connection.
A clean shutdown has three steps:
- Detect that shutdown was requested, for example from Ctrl+C or SIGTERM.
- Tell every task to stop what it is doing and finish its cleanup.
- Wait for those tasks to finish, with a time limit so one stuck task cannot hang the process.
Step 1: Detect the request
tokio::signal::ctrl_c() returns a future that completes when the process receives Ctrl+C. It needs the signal feature, which features = ["full"] includes. On Unix, tokio::signal::unix::signal(SignalKind::terminate()) gives you SIGTERM, which is what container orchestrators send before killing a process.
Step 2: Tell the tasks
You need a one-to-many notification. Tokio offers a few ways to build one.
| Mechanism | How it signals | Notes |
|---|---|---|
| `watch` channel | Sender writes a new value, each receiver sees `changed()` | Receivers that start late still see the current value. Fits a "stop" flag. |
| `broadcast` channel | Each message goes to every receiver | Receivers can lag and miss messages. Fine for a single "stop" event. |
| `CancellationToken` | `cancel()` wakes every `cancelled()` future | Lives in the separate `tokio-util` crate. Supports child tokens. |
| Dropping an `mpsc` sender | `recv()` returns `None` | Good for "no more work is coming". |
This chapter uses watch because it needs no extra crate. A late receiver can still call changed() correctly, because watch tracks which version each receiver has seen.
Step 3: Wait, with a deadline
JoinSet holds a group of spawned tasks and yields their results as they finish. Its join_next() returns None when the set is empty. It also gives you abort_all() for the fallback path. The full pattern looks like this:
use std::time::Duration;
use tokio::sync::watch;
use tokio::task::JoinSet;
use tokio::time::{sleep, timeout};
async fn worker(id: u32, mut shutdown: watch::Receiver<bool>) {
loop {
tokio::select! {
_ = shutdown.changed() => {
println!("worker {id}: shutdown requested");
break;
}
_ = sleep(Duration::from_millis(200)) => {
println!("worker {id}: did a unit of work");
}
}
}
// Cleanup that must run before the task ends.
sleep(Duration::from_millis(50)).await;
println!("worker {id}: cleaned up");
}
#[tokio::main]
async fn main() {
let (tx, rx) = watch::channel(false);
let mut set = JoinSet::new();
for id in 0..3 {
set.spawn(worker(id, rx.clone()));
}
drop(rx);
// Wait for Ctrl+C, or stop after one second so the demo ends on its own.
tokio::select! {
_ = tokio::signal::ctrl_c() => println!("ctrl-c received"),
_ = sleep(Duration::from_secs(1)) => println!("demo time is up"),
}
println!("broadcasting shutdown");
tx.send(true).expect("at least one worker is still listening");
let drain = async {
while let Some(result) = set.join_next().await {
if let Err(e) = result {
eprintln!("a worker failed: {e}");
}
}
};
if timeout(Duration::from_secs(5), drain).await.is_err() {
eprintln!("deadline passed, aborting the remaining workers");
set.abort_all();
}
println!("exited cleanly");
}Some details in this program matter:
shutdown.changed()is cancel safe. If thesleepbranch wins, dropping thechanged()future loses nothing. The next loop iteration creates a new one that still sees any change made in the meantime.- The cleanup after the loop sits outside the
select!. Once the worker leaves the loop, nothing can cancel the cleanup except the outerabort_all(). drop(rx)removes the original receiver. If every worker had already exited,tx.sendwould return an error, because awatchsender with no receivers has nobody to tell.- The
drainfuture borrowssetmutably.timeoutconsumes it, so the borrow ends beforeset.abort_all()runs. - A worker that panics shows up as
Err(JoinError)fromjoin_next(). The drain loop logs it and keeps waiting for the others.
An alternative: let channel closure be the signal
You do not always need a separate shutdown channel. If tasks pull work from an mpsc channel, dropping every sender ends their recv() loop. You can reuse that to wait for completion too. Give each worker a clone of a "done" sender it never sends on. When every worker exits, its clone drops, and the main task's recv() returns None.
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let (done_tx, mut done_rx) = mpsc::channel::<()>(1);
for id in 0..3u64 {
let done = done_tx.clone();
tokio::spawn(async move {
sleep(Duration::from_millis(100 * (id + 1))).await;
println!("worker {id} finished");
drop(done); // dropped here, or earlier if the task panics
});
}
drop(done_tx);
// Returns None only after every clone has been dropped.
done_rx.recv().await;
println!("all workers are done");
}This pattern is compact, and it still signals completion if a task panics, because unwinding drops the sender. The cost is that you get no per-task result, so use JoinSet when you need errors.
Shutting down a server
A TCP server has an extra concern: the accept loop. Race listener.accept() against the shutdown signal inside select!. When shutdown wins, break out of the loop and stop accepting. Each connection task should hold its own watch::Receiver clone, finish the request it is serving, and then return. TcpListener::accept is cancel safe, so a connection is never half-accepted and lost.
Stopping the accept loop first is the important ordering. If you tell connection tasks to stop while the listener still accepts, new connections keep arriving with nobody to handle them.
Edge cases
- Blocking tasks cannot be cancelled.
spawn_blockingclosures run to completion on their own threads. Dropping the runtime waits for them, which can hang the process.Runtime::shutdown_timeout(duration)bounds that wait. It only helps if you built the runtime yourself instead of using#[tokio::main]. abort()cancels at the next.await. A task stuck in a loop with no.awaitnever sees the abort. This is the same rule as for blocking the runtime.- A second Ctrl+C. Many services treat the first signal as "drain" and the second as "exit now". You can implement this by awaiting
ctrl_c()again inside the drainselect!. - Detached tasks. Tasks started with plain
tokio::spawnand no stored handle are invisible to your shutdown logic. Anything that needs cleanup should be tracked in aJoinSetor have its handle kept. - Lost wakeups with
Notifyorbroadcast. If a task is not yet listening when the signal fires, it can miss it.watchavoids this, because it stores the latest value.
Exercise
In the first example, main calls set.abort_all() after the timeout fires. A worker is in the middle of its post-loop cleanup, which is an .await on a 50 ms sleep, and the deadline passes at that moment. What happens to that worker, and what would you change if the cleanup must not be interrupted?
Show answer
The abort takes effect at the worker's next suspension point. Here the pending sleep(...).await is that point, so the worker is dropped there and the rest of its cleanup never runs. join_next() would report a cancelled JoinError. To protect cleanup that must complete, either give the drain a longer deadline, or move the critical step into its own task that is not part of the aborted JoinSet, or use spawn_blocking for synchronous cleanup. A closure on spawn_blocking is not cancelled by abort() once it has started.