Lesson 5 of 9 · 25m
Timeouts, Cancellation, and the Shape of Clean Shutdown
Treat cancellation as a first-class protocol: drop safety, timeout scopes, resource cleanup, and deterministic shutdown ordering.
Cancellation is where async Rust stops being a convenient concurrency model and starts being a correctness discipline. In production, tasks are cancelled by timeouts, connection teardown, deploys, configuration reloads, and parent task failure. If cleanup only happens on the happy path, the unhappy path will eventually corrupt state or leak resources.
Dropping a future cancels it
There is no cancellation signal hidden inside .await. Cancelling a task normally means the runtime drops the future. Destructors run, but async cleanup does not magically continue:
tokio::select! {
result = work() => result?,
_ = shutdown.notified() => {
// work() future is dropped here
}
}Any state machine suspended inside work() disappears at its current await point. Rust preserves memory safety, not business-level completion. Files may be half written, database transactions may roll back, and remote systems may already have received side effects.
Timeout placement determines meaning
A total operation timeout and a read-step timeout are different contracts:
tokio::time::timeout(Duration::from_secs(3), fetch_profile(id)).await??; // whole operation
tokio::time::timeout(Duration::from_secs(3), read_response()).await??; // one stepPut timeouts at the boundary where a deadline is meaningful: request deadline, handshake deadline, idle read deadline, or total job budget. Do not sprinkle arbitrary timeouts inward and hope they compose.
Cancellation safety is a property of each operation
tokio::select! documentation uses the phrase cancellation safety for a reason. Some operations can be cancelled without losing data; others can consume or partially process data before being interrupted. Receiving from a channel, reading from a socket, and committing a transaction each have different semantics. If losing the operation would duplicate or lose work, shield it, structure it, or record recovery state.
Graceful shutdown is orchestration, not a boolean
A useful shutdown sequence stops accepting new work, notifies workers, finishes or abandons in-flight work within a deadline, closes senders so consumers drain, joins tasks with a timeout, and only then releases shared resources.
A broadcast CancellationToken is a good start, but it does not join tasks for you. Use JoinSet or explicit handles to know what is still running:
let mut set = tokio::task::JoinSet::new();
set.spawn(worker(shutdown.clone()));
shutdown.cancel();
while let Some(result) = set.join_next().await {
result?;
}Idempotency beats perfect cancellation
You will not achieve exactly-once side effects across networks using task cancellation. Design retries and idempotency keys so a cancelled operation can be repeated safely. The correct mental model is not "prevent cancellation inside side effects" but "make ambiguous outcomes recoverable."
Field notes
- A timeout error means the future was dropped; it does not prove the remote work stopped.
- Async destructors do not exist. If cleanup itself needs
.await, move it into explicit lifecycle code. - Test cancellation by injecting pauses at await points, not just by sending one SIGTERM to a happy service.
Was this lesson helpful?