Concurrency in Depth · 19 min · free lesson

Cancellation Safety

In Rust, an async task is cancelled by dropping its future.

Core idea

Cancellation is a drop; state between awaits must survive it or not exist.

Lesson map: a tokio::select between a request read and a timeout, above the rule that cancellation is a drop.
Tokio select sketch: read_request, handle, timeout and log are application-provided; completed effects are not rolled back.

Understand it

Cancellation commonly drops a future when its owner stops polling it. Local values are dropped, but external effects already performed are not automatically reversed. That makes cleanup automatic but means a future must be cancel-safe — losing a half-consumed buffer or a partially applied write between awaits is the classic bug.

Cancellation in async Rust commonly occurs when the owner drops a future, often after an awaited operation yields. The future's local values are dropped, which can release in-process resources such as a mutex guard. External effects are different: a write already accepted by a database or a message already sent is not rolled back by dropping the future. Even an operation still running in another task or service may continue. A timeout tells the caller it stopped waiting; it does not prove the work never happened.

Draw a two-step operation: save an order, then send a confirmation. Cancellation between the two leaves a saved order without a confirmation. If the caller retries the whole operation, it may create a duplicate. An idempotency key, transaction, or outbox can make the outcome recoverable. A stream parser that has consumed some bytes before cancellation needs a plan for what happens to those bytes; otherwise a later attempt may start in the wrong state.

A strong interview answer names cancellation points, completed effects, and the retry behavior at each point. It also asks who owns a spawned task: dropping a join handle may detach rather than cancel it, depending on the runtime API. Avoid saying every future is cancelled only at an .await or that all in-flight work stops. State what the specific combinator and ownership pattern do, then design cleanup and idempotency around that behavior.

If a selected branch loses a race, inspect whether its future was owned by the selection expression or merely borrowed. That determines whether dropping the expression cancels the work or whether another owner can continue it. A cancellation-safety claim must be about the exact API and ownership pattern, not async code in general.

Interview follow-up: Compare dropping a future, dropping a Tokio JoinHandle and explicitly aborting its task. What can still continue after a timeout?

Read the code

tokio::select! {
    result = read_request() => handle(result),
    _ = timeout => log("gave up"),
}

Tokio select sketch: read_request, handle, timeout and log are application-provided; completed effects are not rolled back.

Practice starter

// Async pseudocode: socket and store are supplied by the caller.
let mut buf = Vec::new();
socket.read_buf(&mut buf).await?;
store(buf).await?;

Try it

Explain what cancel-safety means for a function that buffers between awaits.

What success looks like: You can name one operation that is not cancel-safe and why.

Check your understanding

If this future owns buf, what risk follows from dropping it after the read but before store completes?

Reveal the answer
  1. Dropping any future reverses all earlier socket and database effects.
  2. Consumed bytes may be lost with the dropped future unless their ownership survives cancellation.
  3. Cancelling a caller always aborts every spawned task it created.

Cancellation commonly drops this future’s state; it does not roll back completed effects. The storage API’s ownership and commit semantics decide whether retry is safe.

Go deeper

Common misconception: Cancelling a caller always aborts every spawned task it created.

A spawned task has its own lifetime. Dropping the caller’s future can leave it running, and dropping a Tokio JoinHandle detaches the task rather than aborting it.

  1. Identify the contract: In Rust, an async task is cancelled by dropping its future.
  2. Trace the concrete example: The losing branch is dropped, mid-await, with no warning.
  3. Test the changed constraint: Compare dropping a future, dropping a Tokio JoinHandle and explicitly aborting its task. What can still continue after a timeout?

Transfer challenge: Compare dropping a future, dropping a Tokio JoinHandle and explicitly aborting its task. What can still continue after a timeout?

Connections

  • Blocking an Executor: Why one sync call stalls a runtime
  • Stack and Heap: Where values live and what a move copies
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 "interview", lessonId "q-cancellation")
Link: https://crabrix.com/learn/interview/q-cancellation/
Goal: Cancellation is a drop; state between awaits must survive it or not exist.
Practice: give me the lesson's exercise (crabrix_academy_get_exercise); I will write and run the code in Crabrix.
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.