skip to content

Cancellation and Drop

Dropping a future cancels it at its last .await, so code after that point never runs. Interviewers ask what cancellation safety means and why there is no async drop.

on this pageshow

questions

5

In Rust, when a payment worker's async fn future is dropped while suspended at `db_write(id).await`, which of its statements still run?

level: middleimportance: must knowfreq 62%

answer

  1. futures run only while polled
  2. drop ends polling for good
  3. stops at the pending .await
  4. live locals still get Drop

basics

~20 s

Dropping the future cancels it: no statement after the pending .await ever runs, so the acknowledgement is skipped. Statements before it already ran, and each local still alive at that .await has its Drop run as the future is dropped.

solid answer

~50 s

A Rust future does nothing unless something polls it, and dropping it means it is never polled again; that is the whole cancellation mechanism, and `Future` has no cancel method. An `async fn` can only stop at a suspension point, so when its future is dropped while parked at `db_write(id).await`, everything before that `.await` has already executed and nothing after it ever will: the acknowledgement line is simply never reached. Dropping the future drops its state machine, which drops the inner `db_write` future and every local still alive at that point, so a guard like `_guard` runs its `Drop` synchronously. What the drop cannot undo is work already handed to the outside world: if the database received the write, it may still commit. The message ends up written but unacknowledged, and a broker with at-least-once delivery hands it out again.

code

rust · 38 lines
rust
use smol::Timer;
use std::time::Duration;

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

async fn db_write(id: u32) {
    Timer::after(Duration::from_millis(200)).await; // a slow database
    println!("db: wrote payment {id}");
}

async fn handle(id: u32) {
    let _guard = InFlight("msg-7");
    println!("start: payment {id}");
    db_write(id).await;
    println!("ack: payment {id}"); // never runs if the future is dropped above
}

fn main() {
    smol::block_on(async {
        let timed_out = smol::future::or(
            async {
                handle(7).await;
                false
            },
            async {
                Timer::after(Duration::from_millis(50)).await;
                true
            },
        )
        .await;
        println!("timed out: {timed_out}");
    });
}

go deeper

for a junior

Recall that a future only makes progress while it is polled, so dropping it stops it for good and nothing after the pending .await runs.

for a middle

Explain the state machine: suspension points are the only places it stops, live locals are dropped synchronously, and the awaited inner future is dropped with it.

for a senior

Point out what a drop cannot undo: a request already sent may complete, so write-then-acknowledge code needs idempotent writes and redelivery.

for a principal

Frame every .await in a side-effecting function as a possible exit, and decide which effects must be ordered or made idempotent around those exits.

## Cancellation is just dropping In Rust, an `async fn` call returns a **future**: a value of an anonymous type that implements `Future`. The body does not run when you call the function. It runs piece by piece, each time an executor calls the future's `poll` method, and it pauses whenever it reaches an `.await` on something that is not ready yet. That design gives Rust a very simple cancellation model: **a future that is no longer polled makes no further progress, and a future that is dropped can never be polled again.** There is no `cancel` method on the `Future` trait (its one required method is `poll`), no exception thrown into the function and no callback. Whoever owns the future cancels it by letting it go: an explicit `drop(fut)`, a variable leaving scope, a timeout or race that discards the loser, or an executor discarding a task it has been told to abort. That makes cancellation routine in async Rust rather than exotic. Cancelling an operating-system thread from outside is so dangerous that the standard library offers no way to do it, because the thread could be stopped anywhere. A future can only stop at points the compiler already knows about, so dropping one is an ordinary, safe operation that happens all the time. ## Where an async fn can stop The compiler turns an `async fn` into a **state machine**. Each `.await` is a possible suspension point, and the state machine stores whatever locals are still needed after it. Code between two suspension points runs inside a single call to `poll`, and the owner can only drop the future between polls. So for a payment worker like this: 1. `let _guard = InFlight("msg-7");` runs on the first poll. 2. `println!("start: ...")` runs on the first poll. 3. `db_write(id).await` polls the inner future; it returns `Pending`, and the outer future is parked here. 4. `println!("ack: ...")` runs only if the outer future is polled again after the write finishes. If the owner drops the outer future during step 3, steps 1 and 2 have happened and step 4 never will. The **last completed `.await` is the boundary**: nothing after the pending one runs. | Statement | Runs if dropped during the write? | |---|---| | Code before the pending `.await` | Yes, it already ran | | The inner `db_write` future | Dropped, never polled again | | Code after the pending `.await` | Never | | `Drop` of locals alive at that point | Yes, during the drop | ## What runs during the drop Dropping a future drops its state machine, and that is ordinary Rust destruction: - every local that is still alive at the suspension point, such as `_guard`, has its `Drop` run; - the nested future it was awaiting is dropped too, and so on down the chain, so a timer or I/O registration inside it is released by that future's own `Drop`; - all of this is **synchronous**: no further `.await` runs, because there is nobody left to poll. A future dropped before its first poll runs none of its body at all; only the arguments it captured are dropped. ## What a drop cannot undo Cancellation stops *your* code, not the rest of the world. If `db_write` had already sent its request, the database may still commit it after the worker gave up. The outcome is therefore **unknown**, not failed. For the payment worker that means: - the acknowledgement was skipped, so a broker with at-least-once delivery will redeliver the message; - the write may have landed, so the redelivered message must not charge twice; make the write idempotent, for example keyed by the payment id; - any cleanup the worker needs must be in `Drop` of something it holds, because no line after the `.await` gets a chance to run. ## Seeing it run The example below races the worker against a 50 ms timer using smol, a small runtime, so no Tokio is needed. The timer wins, the race drops the worker's future, and the output shows the start line and the guard's `Drop` but never the acknowledgement. Whether the drop comes from a timeout, a race or an aborted task, the rule is the same: the future stops at the `.await` it was parked on, and only destructors run after that. It also means a reviewer can list every place a function might stop by reading it: each `.await`, including ones hidden inside macros, is one, and each deserves the question of what happens if the function ends there.

  • What runs if the worker's future is dropped before it is ever polled?
    None of the body: an async fn starts executing only on the first poll, so not even the first `println!` runs. The arguments the future captured are still dropped, so their `Drop` impls run.
  • Can the future be cancelled in the middle of synchronous code between two .await points?
    No. The code between two suspension points runs inside one `poll` call, and the owner can only drop the future between polls. That code always reaches the next `.await`, a return or a panic before cancellation can take effect.
  • Is aborting a spawned task different from dropping a future?
    Aborting ends with the executor dropping the task's future, so the same rule holds: it stops at its current `.await` and only destructors run. What differs is ownership: after spawning, the executor owns the future, and whether dropping the handle cancels is the executor's choice (smol's `Task` cancels on drop, Tokio's `JoinHandle` detaches).

A kitchen ticket: the cook works on it only when called, and pauses whenever waiting on the oven. Tear up the ticket during a wait and the dish is never plated or served, but whatever is already in the oven keeps baking, and the cook still clears the station.

  • Dropping a future lets it finish in the background.
  • Code after the .await still runs once the inner operation completes.
  • A cancelled future leaks its locals, so their Drop never runs.
  • Rust futures receive a cancellation signal they can catch.
  • Cancellation can interrupt a future in the middle of synchronous code.
  • Dropping the future rolls back the write it already sent.
open as a page

In Rust, what makes an async read method cancellation-safe, and why does a frame reader collecting bytes into a local `Vec` lose data when dropped?

level: seniorimportance: must knowfreq 50%

basics

~20 s

An async method is cancellation-safe when dropping its future before completion loses nothing, so a later call resumes cleanly. A frame reader that moves bytes into a local Vec loses them on drop, because that Vec lives only in the future.

open as a page

In Rust, when a timeout fires before a payment write's future completes, what happens to that future, and can the write still have landed?

level: middleimportance: should knowfreq 48%

basics

~20 s

A timeout wrapper drops the write's future at its pending .await, so the worker never runs the code after it. Dropping is not rollback: if the request already reached the database, the write may still commit, so the outcome is unknown, not failed.

open as a page

In Rust, why can't a connection type's `Drop` impl await a graceful close, and how do you structure async cleanup instead?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Drop::drop(&mut self) is synchronous, so .await in it fails with E0728, and as of Rust 1.99 async drop is unstable and nightly-only. Put async cleanup in an explicit async fn close(self) the caller awaits, with Drop as a synchronous fallback.

open as a page

As the lead of a Rust async service, what team rule would you set for which operations must be cancellation-safe and how cleanup is structured?

level: principalimportance: should knowfreq 28%

basics

~20 s

Require every shared async method to document its cancellation safety, let timeouts and races drop only safe ones, keep resumable state outside futures, and order effects so a drop means a retry. Async cleanup goes in explicit close methods.

open as a page