Skip to content
systemcoding.dev
Concurrency

Cancel Tokio Tasks with select! and CancellationToken

Cancel async work in Tokio by dropping futures, racing them with select!, and signalling many tasks at once with tokio-util's CancellationToken.

7 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the Rust, Go and Erlang logos.

Cancellation in async Rust works differently from threads. You cannot kill a thread safely, but you can stop a future simply by never polling it again, and dropping a future does exactly that. Everything else in Tokio's cancellation story follows from that one fact: a future that is dropped at an .await point stops there, runs its destructors and never resumes. This post shows the three tools that build on it, which are JoinHandle::abort, the select! macro and tokio_util::sync::CancellationToken, and explains the hazard each one carries. It uses Tokio 1.x and tokio-util 0.7 on Rust 1.90, and assumes you know how to spawn a task.

Dropping is cancelling

A future makes progress only when polled. When the owner drops it, all the local variables it held at its current await point are dropped in order, and nothing after that point runs. That makes cancellation cheap and mostly automatic, and it also means code after an .await may simply never execute. A future cancelled between two writes leaves the second write undone. This is the central design constraint: anything that must complete as a unit cannot have an .await in the middle of it, unless you accept being cancelled there.

Aborting a spawned task

A spawned task is owned by the runtime, not by you. Dropping its JoinHandle detaches it and it keeps running. To cancel it, call abort:

src/main.rsrust
use std::time::Duration;
use tokio::time::sleep;

struct Noisy(&'static str);
impl Drop for Noisy {
    fn drop(&mut self) { println!("dropped {}", self.0); }
}

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(async {
        let _guard = Noisy("worker guard");
        loop {
            println!("working");
            sleep(Duration::from_millis(100)).await;
        }
    });

    sleep(Duration::from_millis(150)).await;
    handle.abort();
    let result = handle.await;
    println!("cancelled: {}", result.unwrap_err().is_cancelled());
}
Text
working
working
dropped worker guard
cancelled: true

The task printed at 0 ms and 100 ms. abort at 150 ms made the runtime drop the task's future at its sleep, which ran Noisy's destructor. Awaiting the handle then returns Err(JoinError) whose is_cancelled is true. The timing is approximate; the two "working" lines are certain because 150 ms falls between the second and third wake-ups.

Racing futures with select!

tokio::select! waits on several futures at once and runs the branch of whichever finishes first. All the losing futures are dropped, which is how it cancels them. A deadline is the classic use:

src/main.rsrust
use std::time::Duration;
use tokio::time::sleep;

async fn slow_job() -> &'static str {
    sleep(Duration::from_millis(300)).await;
    "job finished"
}

#[tokio::main]
async fn main() {
    tokio::select! {
        out = slow_job() => println!("{out}"),
        _ = sleep(Duration::from_millis(100)) => println!("timed out, job dropped"),
    }
}
Text
timed out, job dropped

For this exact case tokio::time::timeout is shorter, but select! generalizes to a shutdown signal, a channel message or a second connection. Branches are polled in random order by default to avoid starving one of them; add biased; as the first line inside the macro to poll them top to bottom when order matters.

Cancellation safety

The documentation for each async method says whether it is cancel safe, meaning it can be dropped in select! without losing data. tokio::sync::mpsc::Receiver::recv is cancel safe: if the branch loses, no message is taken. AsyncReadExt::read_exact is not: if it is cancelled after reading part of the buffer, those bytes are consumed and lost. The same applies to your own functions that do two steps with an await between them.

The usual remedy is to move the non-cancel-safe future out of the select! and pin it, so the same future is polled repeatedly rather than recreated on every loop pass.

Telling many tasks to stop: CancellationToken

abort needs a handle for every task and gives the task no chance to clean up properly. For a group, use CancellationToken from the tokio-util crate (enable tokio-util = "0.7" in Cargo.toml). A token is cheap to clone, and cancelling any clone wakes every task awaiting cancelled().

src/main.rsrust
use std::time::Duration;
use tokio::time::sleep;
use tokio_util::sync::CancellationToken;

async fn worker(id: u32, token: CancellationToken) {
    loop {
        tokio::select! {
            _ = token.cancelled() => {
                println!("worker {id}: flushing and stopping");
                return;
            }
            _ = sleep(Duration::from_millis(100)) => {
                println!("worker {id}: tick");
            }
        }
    }
}

#[tokio::main]
async fn main() {
    let token = CancellationToken::new();
    let mut handles = Vec::new();
    for id in 1..=2 {
        handles.push(tokio::spawn(worker(id, token.clone())));
    }
    sleep(Duration::from_millis(150)).await;
    token.cancel();
    for h in handles { h.await.unwrap(); }
}
Text
worker 1: tick
worker 2: tick
worker 1: flushing and stopping
worker 2: flushing and stopping

Each worker ticked once at 100 ms, then cancel at 150 ms woke both. The order of the two shutdown lines, and of the two tick lines, depends on scheduling and may swap. Notice what is different from abort: the worker chooses to stop, so it can finish the current unit of work, flush a buffer and close a connection before returning. This cooperative style is how you shut down a service, and the later post on graceful shutdown builds on it.

Child tokens and a deadline

token.child_token() creates a token that is cancelled when its parent is, but can also be cancelled on its own. That lets you stop one subtree of tasks without stopping the whole program. To cancel by time, spawn a task that sleeps then cancels, or race the work against a sleep as shown above.

src/main.rsrust
use tokio_util::sync::CancellationToken;

fn main() {
    let parent = CancellationToken::new();
    let child = parent.child_token();
    child.cancel();
    println!("child cancelled: {}, parent cancelled: {}",
             child.is_cancelled(), parent.is_cancelled());
    parent.cancel();
    println!("parent cancelled: {}", parent.is_cancelled());
}
Text
child cancelled: true, parent cancelled: false
parent cancelled: true

When to choose which

Use abort for disposable tasks where partial work does not matter. Use select! for a bounded operation with a deadline or a competing event. Use CancellationToken for anything that holds resources or must finish a record before stopping. A common mistake is to use abort everywhere and then discover that a half-written file or a leaked transaction is the result, because the task never ran its cleanup code after the await it was stopped at.

A cancellation hazard in practice

Consider a task that moves money between two in-memory accounts by awaiting a lock on each. If the task is cancelled between the withdrawal and the deposit, the money disappears. Nothing panicked and no error was returned; the future was simply never polled again. The fix is not to avoid cancellation but to design for it: make the two steps a single operation with no await between them, hold both locks first and then mutate, or record intent in a log that a recovery step replays. The same reasoning applies to a task that reads a length prefix and then the body of a message. A select! that cancels it between the two reads leaves the stream in the middle of a frame.

Two guidelines follow. First, put .await points where being stopped is acceptable, and keep multi-step state changes between awaits. Second, treat every future you pass to select! as something that may be dropped at any await, and read its documentation for the cancel-safety note. Tokio documents the property on the methods it applies to, for example on mpsc::Receiver::recv, TcpListener::accept and the read family, and on the macro itself.

Using a pinned future across loop iterations

When a branch is not cancel safe, you can keep the future alive across iterations of a loop, so each pass resumes the same future instead of starting a new one:

src/main.rsrust
use std::time::Duration;
use tokio::time::sleep;

async fn long_task() -> &'static str {
    sleep(Duration::from_millis(250)).await;
    "long task done"
}

#[tokio::main]
async fn main() {
    let fut = long_task();
    tokio::pin!(fut);
    let mut ticks = 0;
    loop {
        tokio::select! {
            out = &mut fut => { println!("{out} after {ticks} ticks"); break; }
            _ = sleep(Duration::from_millis(100)) => { ticks += 1; }
        }
    }
}
Text
long task done after 2 ticks

tokio::pin! fixes the future in place so &mut fut can be polled repeatedly. The 100 ms branch wins twice, at 100 ms and 200 ms, without restarting long_task; the task then completes at 250 ms. Without the pin, each loop pass would build a fresh long_task() that restarts its 250 ms sleep and it would never finish.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.