Sub topic 3
Cancellation means dropping the future
This chapter assumes you know ownership and the Drop trait, async/await syntax, and the basics of the Tokio runtime. It also assumes you have read the earlier chapters on lazy futures and await points. Here we put those two ideas together to explain how cancellation works in async Rust.
The working model
Most languages give you a cancel operation. You call cancel() on a task or pass a cancellation flag, and the work stops in some defined way. Async Rust has no such operation for futures. A future is stopped by dropping it: the code that owns the future stops polling it and lets its destructor run.
That one rule explains the rest of this topic:
- A future that is never polled does nothing, so a dropped future that never started simply never runs.
- A future that has been polled to an
.awaitis suspended. If its owner drops it there, execution never resumes. Every local variable the future was holding at that await is dropped, in reverse order of creation. - The future gets no notice and no chance to return an error. The only code that runs is
Dropimplementations.
Mermaid diagrams must use the diagram fence, so here is the model as a diagram.
Dropping a future that never started
Because futures are lazy, calling an async fn only builds a value. Dropping that value cancels the call before it begins.
async fn say_hello() {
println!("hello");
}
#[tokio::main]
async fn main() {
let fut = say_hello();
drop(fut);
println!("dropped without running");
}This prints only dropped without running. The body of say_hello never executed, so there was nothing to clean up.
Dropping a future that is suspended
Now suppose the future has already run to an await point. The next example uses tokio::time::timeout only as a convenient way to drop a future after 50 milliseconds. The next chapter covers timeout properly.
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
async fn job() {
let _a = Guard("a");
println!("step 1");
sleep(Duration::from_secs(10)).await;
let _b = Guard("b");
println!("step 2");
}
#[tokio::main]
async fn main() {
let _ = timeout(Duration::from_millis(50), job()).await;
println!("after timeout");
}The output is:
step 1
drop a
after timeoutRead it against the model. job ran until the sleep could not finish, and timeout then dropped it. The guard a was alive at the await, so its destructor ran. The guard b was never created, because the code after the await never executed.
What to take from this
- The cancelled future's state is exactly the set of locals alive at the await where it was suspended.
- Code after that await is skipped. It is not run later and it is not run in a "cancelled" mode.
- Nothing is returned from
job. Its caller (heretimeout) is the one that reports that something was dropped.
Cancellation is not rollback
Dropping a future runs destructors. It does not undo side effects that already happened. If a function changes shared state, awaits, and then changes more state, a cancellation at the await leaves the first change in place and skips the second.
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn transfer(from: &AtomicI64, to: &AtomicI64, amount: i64) {
from.fetch_sub(amount, Ordering::SeqCst);
sleep(Duration::from_millis(100)).await;
to.fetch_add(amount, Ordering::SeqCst);
}
#[tokio::main]
async fn main() {
let a = AtomicI64::new(100);
let b = AtomicI64::new(0);
let result = timeout(Duration::from_millis(50), transfer(&a, &b, 30)).await;
println!("cancelled: {}", result.is_err());
println!("a = {}, b = {}", a.load(Ordering::SeqCst), b.load(Ordering::SeqCst));
}The program prints cancelled: true and a = 70, b = 0. Thirty units left a and never arrived in b. The total is now 70, not 100.
This is the central hazard of cancellation. A function that is correct when it runs to completion can leave data inconsistent when it is dropped at an await. Two ways to avoid it:
- Do not hold an inconsistent state across an await. In the example, update both balances with no await between the two updates, or take both under one lock.
- Put the undo step in a destructor, so it runs on every exit path, including a drop. Later chapters cover this pattern, called a drop guard.
Only await points can be cancelled
A future is dropped by its owner between polls, and a poll runs until the next await that is not ready. Code between two awaits is never interrupted. That has two consequences.
First, the stretch of code between awaits behaves like an uninterruptible block. In the transfer example, if the fetch_sub and fetch_add had no await between them, no cancellation could separate them.
Second, a future that never reaches an await cannot be cancelled, because nobody regains control to drop it. A long loop with no .await holds the thread, and a timeout waiting on the same thread cannot fire. A later chapter covers this blocking pitfall.
An await that is already ready is also not a stopping point in practice. If rx.recv().await finds a message waiting, it completes at once, without yielding to the caller.
Dropping an outer future drops the inner ones
An async block that awaits another future owns it. When the outer future is dropped, the inner future is dropped too, and so on down the chain. You cancel a whole tree of awaited futures by dropping the root, and you do not need to cancel each part.
The tree stops at spawned tasks. tokio::spawn hands the future to the runtime, and the runtime owns it from then on. The caller keeps only a JoinHandle, and dropping a JoinHandle detaches the task rather than stopping it.
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn parent() {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(100)).await;
println!("spawned task finished");
});
handle.await.unwrap();
println!("parent finished");
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(20), parent()).await;
println!("timed out: {}", result.is_err());
sleep(Duration::from_millis(200)).await;
}The output is:
timed out: true
spawned task finishedparent was dropped at handle.await, so parent finished never printed. The spawned task kept running, because it belongs to the runtime. To stop a spawned task you must ask for it explicitly, with JoinHandle::abort or with a cancellation signal that the task watches. Both are covered in later chapters.
| What is dropped | What happens to it |
|---|---|
| An unpolled future | Nothing ran, so nothing is undone |
| A suspended future | Live locals are dropped, the rest of the body is skipped |
| A future awaited inside the dropped one | Dropped too, recursively |
| A `JoinHandle` | The task is detached and keeps running |
| A side effect already performed | Stays in place, with no rollback |
Drop is synchronous
Cancellation can only run Drop::drop, and drop is a normal function. It cannot use .await. If cleanup needs async work, such as flushing a connection or sending a goodbye message, you cannot do it inside the destructor of a cancelled future.
Common ways to handle this, which later chapters develop:
- Make the cleanup synchronous when possible, for example by closing a file descriptor or releasing a lock.
- From
drop, hand the async work to the runtime withtokio::spawn, if you are inside a runtime. - Avoid relying on cancellation for operations that need orderly async teardown. Use a cooperative signal instead, so the task can finish its cleanup in normal code.
Common errors
- Assuming code after an await always runs. Code after any await in a future can be skipped if the future is dropped. Treat each await as a possible exit.
- Assuming a timeout stops spawned work. It stops only what the dropped future owns. A spawned task continues unless you abort it or signal it.
- Holding a partial update across an await. As in the
transferexample, this is how cancellation corrupts state. Look for mutations before an await that depend on mutations after it. - Using
let _ = guard;. This drops the guard at once. Use a named binding. - Expecting an error inside the cancelled future. The future never learns it was cancelled. Only its destructors run.
Exercise
A function sync_user runs db.mark_syncing(id).await, then api.push(id).await, then db.mark_synced(id).await. A caller wraps it in a timeout, and the timeout fires while api.push is waiting. What state is the database left in, and name two ways to prevent a user from staying stuck in the "syncing" state?
Show answer
The user stays marked as syncing, because mark_syncing completed and the later mark_synced call was skipped when the future was dropped at the api.push await. Two fixes: create a guard value after mark_syncing whose Drop performs a synchronous reset (or schedules the reset), so it runs when the future is dropped; or avoid cancelling mid-way by running the whole sequence in a spawned task that the timeout does not own, and handle the outcome through its JoinHandle. Another option is to make the state change a single step, so there is no state in between.
Exercise
In the parent example above, what would you change so that the spawned task stops when the timeout fires?
Show answer
Keep the JoinHandle reachable and call abort() on it when the parent is cancelled, for example by wrapping it in a guard whose Drop calls handle.abort(). Alternatively, give the spawned task a cancellation signal, such as a CancellationToken, and cancel that signal when the parent is dropped.