Sub topic 6
Cancel safety: what is lost when a branch is dropped
This chapter assumes you know Rust ownership and the Drop trait, async/await basics, tokio::spawn, and tokio::sync::mpsc. It also assumes you know that select! drops the futures that lose the race.
The problem
When one branch of select! finishes, Tokio drops every other branch future. Dropping a future stops it at its last .await. Any work it had already done is gone unless that work was stored somewhere outside the future.
An operation is cancel safe if dropping its future before completion loses nothing, so you can call it again and continue as if nothing happened. An operation is not cancel safe if dropping it can lose data or leave a task half done.
Cancel-safe examples
mpsc::Receiver::recv is cancel safe. If the future is dropped before it returns a message, the message stays in the channel. The next recv call gets it. Interval::tick is also cancel safe, because the interval keeps its schedule outside the future.
The loop below relies on both properties.
use std::time::Duration;
use tokio::{
sync::mpsc,
time::{interval, sleep},
};
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tokio::spawn(async move {
for i in 0..3 {
tx.send(i).await.unwrap();
sleep(Duration::from_millis(30)).await;
}
});
let mut tick = interval(Duration::from_millis(100));
loop {
tokio::select! {
maybe = rx.recv() => match maybe {
Some(n) => println!("got {n}"),
None => {
println!("channel closed");
break;
}
},
_ = tick.tick() => println!("tick"),
}
}
}Each time the tick wins, the recv future is dropped. Each time a message wins, the tick future is dropped. No message is lost in either case.
A not-cancel-safe example
mpsc::Sender::send(msg) takes ownership of msg. If you race it against another branch and the other branch wins, the send future is dropped, and msg is dropped with it. The message is lost, and you cannot get it back.
The fix is to split the operation into a part that can be cancelled and a part that cannot. reserve waits for capacity in the channel and is cancel safe. It returns a permit, and Permit::send is synchronous, so it cannot be interrupted.
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
async fn send_or_cancel(
tx: &mpsc::Sender<String>,
msg: String,
token: &CancellationToken,
) -> bool {
tokio::select! {
permit = tx.reserve() => match permit {
Ok(p) => {
p.send(msg);
true
}
Err(_) => false,
},
_ = token.cancelled() => false,
}
}Here msg is not moved into any future inside select!. If the token wins, msg is still owned by the function and is dropped normally. If the permit wins, the send cannot fail for lack of capacity.
How to judge cancel safety
Ask what state the future holds that exists nowhere else. Common cases:
| Operation | Cancel safe? | Why |
|---|---|---|
| `mpsc::Receiver::recv` | Yes | Messages stay in the channel |
| `Interval::tick` | Yes | The schedule lives in the interval |
| `sleep` | Yes | It holds no data, only a deadline |
| `Sender::send(msg)` | No | The future owns `msg` and drops it |
| Your own `async fn` that reads, then writes | Usually no | A drop between the steps leaves the work half done |
The Tokio documentation states the cancel safety of each method. Check it before you put a method in a select! branch, especially in a loop.
A custom async fn is not cancel safe if it has several .await points with side effects between them. For example, if it removes an item from a queue, then awaits a network call, a drop at the second await loses the item. To make it safe, perform the side effect after the last await, or run the whole operation in a spawned task so that select! only drops a JoinHandle and the task keeps running.
Common errors
- Putting a read that fills a local buffer in a
select!branch. Bytes already read into the buffer inside the future are lost when it is dropped. - Assuming a method is safe because it compiles. The compiler does not check cancel safety.
- Creating a fresh future in every loop iteration when you meant to resume one. The next chapter covers that.
Exercise
A loop uses tokio::select! to race rx.recv() against token.cancelled(). Is it safe if the cancelled branch wins and the loop exits? Now suppose the second branch is a custom async fn process() that pops a job from a queue, then awaits an HTTP call. Why is that a problem?
Show answer
The recv branch is safe: a dropped recv future leaves unread messages in the channel. The custom process() is a problem because if the other branch wins while it waits on the HTTP call, the future is dropped after the job was already removed from the queue, so the job is lost. Fix it by moving the pop to after the HTTP call, or by spawning the work and racing only the JoinHandle.