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, and basic Tokio use (#[tokio::main], tokio::spawn, mpsc channels). It also assumes you have seen tokio::select! and know that the branches that lose a race are dropped. The examples need tokio with the full feature and tokio-util in Cargo.toml.
What cancel safe means
A future is cancel safe if dropping it before it completes loses nothing. After the drop, the program is in a state where you can start the same operation again and get the result you would have wanted.
An operation that is not cancel safe leaves a mess when it is dropped halfway. Data it already took from a source may be gone. Bytes it already wrote may be half of a message.
Cancel safety is not a property of Rust or of the compiler. The compiler cannot check it. It is a documented promise by the author of each future, and for your own async fn it is something you must judge yourself.
How data gets lost
An async fn compiles into a state machine. Local variables that live across an .await are stored inside that state machine. When the future is dropped, those locals are dropped with it.
This function reads two messages and returns them together:
use std::time::Duration;
use tokio::{sync::mpsc, time::sleep};
async fn read_two(rx: &mut mpsc::Receiver<u32>) -> (u32, u32) {
let first = rx.recv().await.unwrap();
let second = rx.recv().await.unwrap();
(first, second)
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tokio::spawn(async move {
let _ = tx.send(1).await;
sleep(Duration::from_millis(200)).await;
let _ = tx.send(2).await;
});
tokio::select! {
pair = read_two(&mut rx) => println!("pair: {pair:?}"),
_ = sleep(Duration::from_millis(100)) => println!("timed out"),
}
println!("next: {:?}", rx.recv().await);
}The program prints timed out and then next: Some(2). Message 1 was received into the local first. The timer won the race, read_two was dropped, and first went with it. No error was reported and no panic happened. The message is gone.
Each call to rx.recv() is cancel safe on its own. The function that combines two of them is not, because it holds state between the two awaits.
Judging an operation
Ask one question: if this future is dropped at any of its await points, can I run the operation again with nothing missing?
Signs that an operation is probably not cancel safe:
- It holds data in a local variable across an
.await, asread_twodoes. - It moves data out of a shared source (a channel, a socket buffer) in one step and finishes using it in a later step.
- It performs a multi-step write, so a drop leaves half the output written.
Signs that an operation is probably cancel safe:
- It has a single await point that either completes and hands over a value, or does nothing observable.
- All the state it needs lives outside the future, in a struct that you own.
Common Tokio operations
The Tokio documentation states the cancel safety of each method. Check it for anything not listed here.
| Operation | Cancel safe? | What is lost if dropped |
|---|---|---|
| `mpsc::Receiver::recv` | Yes | Nothing. The message stays in the channel. |
| `Interval::tick` | Yes | Nothing. The next tick is still scheduled. |
| `sleep` | Yes | Nothing, but a fresh `sleep` restarts from zero. |
| `TcpListener::accept` | Yes | Nothing. The connection stays in the backlog. |
| `AsyncReadExt::read` | Yes | Nothing. No bytes are consumed unless it returns. |
| `mpsc::Sender::send(msg)` | Yes, with a caveat | The message was not sent, but `msg` was moved into the future and is dropped. |
| `AsyncReadExt::read_exact` | No | Bytes read so far are discarded. |
| `AsyncBufReadExt::read_line` | No | A partial line may already be consumed. |
| `AsyncWriteExt::write_all` | No | An unknown prefix of the data was already written. |
The send row shows that "cancel safe" has a limit. The channel stays consistent, but you lose your own value. If the message matters, you need the technique in the next section.
Restructuring code that is not cancel safe
Three approaches cover most cases.
Reserve before you send
Sender::reserve waits for capacity and returns a permit. It does not take your message. Sending with a permit cannot fail and does not wait, so no message is lost whichever branch wins:
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
async fn send_or_cancel(
tx: &mpsc::Sender<String>,
msg: String,
token: &CancellationToken,
) -> Result<(), String> {
tokio::select! {
permit = tx.reserve() => match permit {
Ok(p) => {
p.send(msg);
Ok(())
}
Err(_) => Err(msg),
},
_ = token.cancelled() => Err(msg),
}
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<String>(1);
let token = CancellationToken::new();
let sent = send_or_cancel(&tx, "hello".to_string(), &token).await;
println!("sent: {sent:?}, received: {:?}", rx.recv().await);
token.cancel();
let blocked = send_or_cancel(&tx, "later".to_string(), &token).await;
println!("after cancel: {blocked:?}");
}The function returns Err(msg) when it gives up, so the caller still owns the message and can retry or log it. In the second call both branches are ready, and select! picks one at random. Either result is valid, because the message is returned if it was not sent.
Resume the same future
Pin the future outside the race and poll it by &mut. When the other branch wins, the future is not dropped, so its local state survives. This fixes read_two without changing it:
use std::time::Duration;
use tokio::{sync::mpsc, time::sleep};
async fn read_two(rx: &mut mpsc::Receiver<u32>) -> (u32, u32) {
let first = rx.recv().await.unwrap();
let second = rx.recv().await.unwrap();
(first, second)
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tokio::spawn(async move {
let _ = tx.send(1).await;
sleep(Duration::from_millis(200)).await;
let _ = tx.send(2).await;
});
let read = read_two(&mut rx);
tokio::pin!(read);
let pair = loop {
tokio::select! {
pair = &mut read => break pair,
_ = sleep(Duration::from_millis(150)) => println!("still waiting"),
}
};
println!("pair: {pair:?}");
}This prints still waiting and then pair: (1, 2). Two rules apply. After the future completes, never poll it again, and the break above ensures that. While the future is alive, it still holds its mutable borrow of rx, so you cannot use rx anywhere else in the meantime.
Move the state out of the future
Put the partial state in a struct that outlives the future, and make each step small. For example, read into a buffer you own and parse complete messages from it. Each read call is cancel safe, and the buffer keeps whatever was already received. This is how most framed-protocol decoders are written.
A related option is to run the multi-step operation in its own spawned task and talk to it through channels. Spawned tasks are not dropped when a select! branch loses, so the operation always runs to the end.
Cancel safe operations in loops
When every branch is cancel safe, you can create the futures fresh on each iteration. Nothing is lost when a branch loses:
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"),
}
}
}Both rx.recv() and tick.tick() are cancel safe. When the tick wins, the pending recv is dropped and the message stays in the channel for the next iteration. The interval is created once, outside the loop, so its schedule is kept. A sleep created inside the loop restarts every iteration, which is a different kind of loss: the elapsed waiting time.
Common errors
- Assuming
async fnis cancel safe. It is only as safe as its await points. Any function that stores a value in a local and then awaits again needs the check described above. - Trusting a method name.
readis cancel safe andread_exactis not, and the names look alike. Look up the exact method in the documentation. - Polling a completed future again. Reusing a pinned future after it returned
Readyis a bug and may panic. Break out of the loop or set it up again. - Restarting a deadline by accident. A
sleepbuilt inside aselect!loop gives each iteration its own full timeout, not one overall limit. - Doing important work in a losing branch. The branch you race against should only wait. If a handler does the real work, that work runs after the race and is not affected by cancellation. A future that does the work inside the race can be cut off.
Exercise
A function does let line = reader.read_line(&mut buf).await?; inside a select! branch racing a shutdown signal in a loop. Why can this lose data, and how would you restructure it?
Show answer
read_line is not cancel safe. If the shutdown branch wins after read_line has already consumed some bytes from the reader, dropping the future discards that partial line (or leaves it only in buf, depending on the reader). To restructure, keep a persistent buffer and use a cancel-safe read such as read or fill_buf, assembling lines yourself. Alternatively, pin the read_line future and poll it by &mut across iterations, or move the reading into its own task that forwards complete lines through a channel.
Exercise
In the read_two example, why does rx.recv().await after the select! return Some(2) and not Some(1)?
Show answer
read_two had already taken message 1 from the channel and stored it in the local first. When the timer branch won, read_two was dropped and first was dropped with it, so the message was not put back. The channel only held message 2.