Async Reliability · 19 min · free lesson

Cancellation Safety

Expect a future to be dropped at any await point.

Core idea

Selecting or timing out a future may drop it before completion.

A task is cancelled after one external effect completed but before acknowledgement.
Cancellation does not undo effects that already happened.

Understand it

Selecting or timing out a future may drop it before completion. Keep partial state consistent across await points, or wrap the operation so retrying cannot duplicate or lose external effects.

An owned future can be cancelled by dropping it before its first poll, before its body has run, or between polls after it has suspended. Work already completed before that point remains completed. A dropped future does not reverse a file write, database transaction, sent message, or charge to an external service. This creates a gap between “the caller did not receive a result” and “nothing happened.” Retry logic must account for that gap.

Consider save_record().await followed by send_ack().await. If the task stops between the two awaits, the record exists but the acknowledgement may not. Repeating the whole operation could create a duplicate record. Give each request a stable identifier and design the save as idempotent, or use a transaction/outbox pattern when the storage and notification must coordinate. Store enough progress that a restarted worker can decide what remains. A timeout tells the caller how long it waited, not whether the remote side performed the action.

Draw cancellation points on a three-step operation: prepare, commit, notify. At each point, list which externally visible effects already happened and what a retry would do. Test by injecting cancellation after the commit boundary. A guard can release an in-process mutex when dropped, but it cannot roll back arbitrary external effects. For spawned tasks, also check the runtime's ownership rules: dropping a handle may detach rather than cancel. Define both the cancellation path and the normal completion path before selecting a timeout or select! branch.

Read the code

use std::{cell::Cell, future::Future, task::{Context, Poll, Waker}};
fn main() {
    let saved = Cell::new(false);
    let acknowledged = Cell::new(false);
    let mut operation = Box::pin(async {
        saved.set(true);
        std::future::pending::<()>().await;
        acknowledged.set(true);
    });
    let mut cx = Context::from_waker(Waker::noop());
    assert!(matches!(operation.as_mut().poll(&mut cx), Poll::Pending));
    drop(operation);
    assert!(saved.get());
    assert!(!acknowledged.get());
    println!("saved={} acknowledged={}", saved.get(), acknowledged.get());
}

One explicit poll saves state and then suspends. Dropping the future cancels the remaining acknowledgement, while saved=true remains observable.

Practice starter

async fn save_then_ack() {
    save_record().await;
    // Cancellation here means saved,
    // but not acknowledged.
    send_ack().await;
}

Practise this code in Playground ↗

Try it

Run the complete example and predict saved=true acknowledged=false. Then remove the poll line, change assert!(saved.get()) to assert!(!saved.get()), and predict that neither effect occurs. Relate this local demonstration to idempotent external operations.

What success looks like: You can point to where each flag is set and say why a retry must be idempotent after a drop.

Check your understanding

What cancels an ordinary owned future, including one that has not been polled?

Reveal the answer
  1. Dropping that future; its body may not have started or may have suspended
  2. Only reaching the end of the async body
  3. Dropping any runtime join handle always cancels its task

A future can be dropped before its first poll or between polls. Dropping a task handle has separate runtime-specific semantics and may detach its task. Cancellation does not undo effects already performed.

Go deeper

Common misconception: “A future always runs to the end of its body once it has started.”

Selecting or timing out a future may drop it before completion. The code after its suspension point then never runs, and effects already performed stay in place.

  1. Construct without running: Creating the async block captures references but does not execute saved.set(true). Dropping it now would leave both flags false.
  2. Poll until pending: The explicit first poll sets saved=true and reaches pending().await, returning Poll::Pending before the acknowledgement.
  3. Drop the owned future: Dropping operation cancels the remaining future. The previous saved effect remains true and acknowledged stays false; dropping a runtime task handle has separate semantics.

Transfer challenge: Move saved.set(true) after the pending await and predict both flags after the same poll and drop. Then say what a retry would need to know under each ordering.

Connections

  • Pinning Intuition: Promise that a value will not move in memory
  • Blocking in Async Code: Keep executor threads available to poll other futures
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Cancellation Safety (courseId "concurrency", lessonId "async-cancellation")
Link: https://crabrix.com/learn/concurrency/async-cancellation/
Goal: Selecting or timing out a future may drop it before completion.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=concurrency/async-cancellation) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.