Concurrency in Depth · 19 min · free with an account

Cancellation Safety

Lesson preview · about 30%

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.

Start with the idea

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.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep