skip to content

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%

answer

  1. every .await is a possible exit
  2. document safety per method
  3. one commit point, idempotent writes
  4. signal for shutdown, drop for abandonment
  5. test by dropping at each await

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.

solid answer

~50 s

I'd start from the fact that any `.await` can be the last line that runs. First, every async method in shared code states in its docs whether it is cancellation-safe, and code that times out or races a future may only drop safe ones; an unsafe future must be kept alive and resumed instead. Second, state that must survive a cancelled call lives in a struct, not in a future's locals. Third, side-effecting flows have one commit point, writes are idempotent and acknowledgements come last, so a drop anywhere means a retry, not a loss. Fourth, planned shutdown uses a cooperative signal the task checks, and work that must finish runs in its own task. Cleanup is an explicit async `close` with a cheap synchronous `Drop` fallback. Tests drop each handler at every await. The trade-off is effort: make everything safe, or confine where cancellation may happen.

go deeper

for a junior

Recall that any .await can be the last line that runs, because dropping a future cancels it there.

for a middle

Explain how documented cancel safety, state kept in structs and acknowledge-last ordering each stop a drop from losing data.

for a senior

Show how you would find unsafe drops in review and tests: raced futures, timeouts around multi-step I/O, and handlers dropped mid-write.

for a principal

Weigh making every building block cancellation-safe against confining cancellation to a few reviewed points, and justify the mix your team adopts.

## The problem the rule has to solve In async Rust, a future is cancelled by being dropped, and that can happen at **any `.await`**: a timeout fires, a race picks another branch, a client disconnects and its handler is dropped, an executor aborts a task. The code after that point never runs, and only synchronous destructors execute. Nothing in the type system marks which functions survive this, so a team needs a rule. The goal is not zero cancellation; it is that cancellation never loses or duplicates business data, and that cleanup still happens. ## Part one: classify and document - **Every public async method in shared code states its cancel safety** in its docs: safe, or not safe and why. Libraries already do this; Tokio's API docs, for example, carry a cancel-safety section on many of its async methods. - **Dropping is only allowed on safe futures.** A timeout, a race or a loop that recreates a future each iteration may only wrap methods documented as safe. - **Unsafe futures are resumed, not recreated.** Pin the future outside the loop and poll the same one each iteration, or use a race that returns the loser, such as `futures::future::select`, so nothing is dropped mid-operation. - **Resumable state lives in structs.** Buffers, cursors and partial frames go in fields reached through `&mut self`, never only in a future's locals. ## Part two: structure effects around a commit point For a payment worker that reads a message, writes to the database and acknowledges it: 1. Make the write **idempotent**, for example keyed by the payment id. 2. Treat the successful write as the single **commit point**. 3. **Acknowledge last**, only after the commit has been observed. With that order, a drop before the commit means nothing happened and the message is redelivered; a drop after it means the redelivery is deduplicated. At-least-once delivery plus idempotency turns every cancellation into, at worst, a retry. ## Part three: cleanup and shutdown - **Async cleanup is explicit.** Resources that need I/O to close expose an `async fn close(self)`; `Drop` stays a cheap synchronous fallback that logs or resets, because stable Rust has no async destructor. - **Planned shutdown is cooperative.** For deploys and graceful stop, send a signal (a cancellation token, a watch channel, a closed channel) that tasks check at points they choose, so they can finish a batch, flush and close. Dropping is reserved for **abandonment**, such as a deadline or a gone client, where the code was already written to survive it. - **Work that must finish is not owned by a droppable caller.** Run it in its own task so a dropped request handler cannot cut it off, and check how the executor's task handle behaves on drop, since some executors cancel the task and others detach it. ## Enforcing it - **Tests that cancel deliberately.** A harness polls a handler k times with a no-op waker and fake I/O that returns `Pending` between steps, drops it, and checks invariants (no acknowledgement without a write, no half-written record) for every k until the handler completes. - **Review checklist.** Every new timeout or race names the futures it may drop and their documented safety; every new resource with async teardown shows its `close` and its `Drop` fallback. - **Observability.** The `Drop` fallback logs when a value was dropped without `close`, so missed cleanups show up as a metric rather than as leaks. ## Trade-offs | Option | Buys | Costs | |---|---|---| | Make every shared method cancellation-safe | Callers can race and time out freely | More state in structs, harder code | | Allow cancellation only at a few top-level points | Simple inner code | Every new timeout needs review | | Cooperative shutdown everywhere | Graceful cleanup | Tasks must check the signal; slow to stop | | Idempotent writes with acknowledge-last | Drops become retries | Deduplication keys and storage | No option is free, and the choice depends on how often the service is cancelled in practice: a public API with aggressive client timeouts and frequent disconnects needs cancellation-safe building blocks far more than a batch worker that is only ever stopped for deploys. Most teams combine them: idempotency and acknowledge-last everywhere, cancellation-safe building blocks, drops confined to clearly reviewed places, and cooperative signals for planned shutdown.

  • Would you ban timeouts and races on futures that are not cancellation-safe?
    No; ban dropping them, not racing them. A race that returns the loser, such as `futures::future::select`, or a future pinned outside a loop and resumed each iteration, never drops the operation mid-way. The rule targets the drop, so reviewers check where every raced future ends up.
  • Where does a cooperative cancellation token fit beside cancelling by drop?
    A token is a shared signal the task checks at points it chooses, so it can finish a batch, flush and close; a drop gives no such chance. Use tokens for planned shutdown and deploys, and keep drops for abandonment such as a deadline or a disconnected client, in code already written to survive them.
  • How do you test that a handler survives cancellation at every .await?
    Wrap its future in a harness that polls it k times with a no-op waker, drops it and checks invariants such as no acknowledgement without a write, for k = 1, 2 and so on until it completes. Fake I/O that returns Pending between steps makes each suspension point reachable deterministically.

  • Cancellation safety is a memory-safety issue the compiler already handles.
  • Only code inside a select macro can ever be cancelled.
  • Making every future cancellation-safe is free, so require it everywhere without review.
  • Graceful shutdown can just drop tasks, since Drop runs the async cleanup.
  • Acknowledge before writing so the broker never redelivers the message.