Go to content
Web development

Designing Cancellation-Safe Rust Async Operations

When you write async Rust, the caller can stop an operation before it finishes. The operation runs as a future, a value that an executor advances by polling it. If a future is waiting at an await, its caller can drop it, and Rust will not resume it. Rust runs the future’s destructor, but that does not undo changes made outside the future or restore data it moved into temporary state. The Future trait documentation explains how polling reports whether work is ready or still pending.

An operation is cancellation-safe when your code can handle its data and state after its future is dropped. For an operation callers can restart, dropping it and starting again does not lose progress or corrupt state. For other operations, protect a short section that changes shared state, or wait first and make the change only after the wait succeeds. Tokio’s select! documentation shows what happens: when one branch wins, Rust drops the futures for the other branches.

Find the state that outlives the future

An await splits an async function into parts. When a future returns Pending, it pauses there. If its caller drops the future while it waits, the function does not continue past the await, and Rust drops the future’s local variables. A buffer or message stored only in those variables disappears. Bytes the function already read and changes it already made outside the future can remain.

Consider a line reader that reads one byte at a time until it finds a newline. If next_line() keeps its partial-line buffer in a local variable, a competing select! branch can win while next_line() waits for more input. The reader then drops the future and its buffer. The next call starts with an empty buffer even though the input stream has already advanced. The Comprehensive Rust cancellation lesson uses this pattern to show why the reader should keep partial bytes in state that survives each call.

A restartable reader stores that progress on the reader object:

struct LinesReader<R> {
    reader: R,
    partial_line: Vec<u8>,
    byte: [u8; 1],
}

Each call to next_line() continues filling partial_line; it removes and returns the completed line only after reading its newline. If the caller drops one next_line() future while it waits for input, the next call can continue from the saved bytes. This is a structural sketch, not a complete parser: the implementation still needs to define how it handles end-of-file, invalid text, and read errors.

Use the same approach for other operations: store partial progress somewhere that outlives the future, such as a field on self or a mutable value owned by the caller. If the other side receives a database request or network write before cancellation, local state cannot tell you whether the change happened. Before the next call repeats the action, have it check or reconcile the result. Retrying an external request does not guarantee that it happens exactly once.

Decide whether callers can safely restart

For an operation callers can restart, ask what they observe after dropping its future and calling it again. Tokio says an operation is cancellation-safe when dropping and recreating its incomplete future has the same effect as doing nothing. Its documentation warns that receive operations in a select! loop need this property so they do not lose messages.

Tokio documents which of its I/O methods are safe to cancel. AsyncReadExt::read is cancellation-safe: if cancellation interrupts the call, it either returns data or reads nothing. Tokio lists read_exact, read_to_end, read_to_string, and AsyncWriteExt::write_all as not cancellation-safe because the caller can lose track of partial progress. These classifications apply to the Tokio methods in its documentation, not to every Rust I/O API.

For writes, keep the bytes that have not been written so the caller can retry from the right position. Tokio’s write_all_buf takes a mutable bytes::Buf and advances it as it writes bytes, so the caller can see the progress. The Oxide cancellation-safety discussion describes this as an alternative to write_all when cancellation interrupts a write that takes multiple steps.

Whether a caller can restart safely depends on what the operation promises. A reader that saves partial bytes can continue without losing input. The caller can discard a notification it no longer needs after cancellation. Tokio’s select! documentation also says that waiting for some queued resources, such as a mutex lock or semaphore permit, is not cancellation-safe. When cancellation drops a waiting future, it loses its place in the queue, which determines who gets a resource next. That costs the waiter its place but does not corrupt the protected state.

Keep temporary invariants out of cancellable waits

A critical section is a short span of code that keeps an invariant true. An invariant is a condition that must hold for other code to use data safely. Suppose a future removes an item from a shared collection, waits for another service, and then puts the item back. If the caller drops the future during that wait, the item stays removed. Rust drops the lock guard, but neither Rust nor the mutex puts the item back.

When possible, change shared state without awaiting while you hold a lock. Acquire the lock, update the state, and release the lock before you await:

let item = {
    let mut queue = queue.lock().unwrap();
    queue.pop_front()
};

if let Some(item) = item {
    send_item(item).await?;
}

This example intentionally removes the item before sending it, so it still needs a policy for cancellation or failure during send_item. The short lock protects the queue’s internal consistency; it does not guarantee delivery. If the application must not lose the item, retain it in durable or caller-owned state until the send is confirmed.

A Tokio mutex lets a lock guard remain live across an await, but that does not make the guarded data safe if the future is dropped. The Oxide RFD on cancellation safety warns that Tokio mutexes do not mark themselves as poisoned after cancellation or a panic. Later code therefore gets no automatic warning that cancellation or a panic might have broken the protected invariant. For shared state that needs asynchronous coordination, one owner can receive messages and make changes without exposing partly updated state. For a short section that has no contention and does not cross an await, a synchronous mutex may fit. Choose a mutex based on the data’s invariants and how long your code holds the lock.

Wait before transferring ownership or causing side effects

A single async call can combine a wait that callers can cancel with an action that takes ownership of important data. Separate the wait from the action when callers need to keep the data if they cancel while waiting.

For example, Sender::send(message).await waits for room in the channel and then sends the message. In a select!, cancellation during the wait drops the send future and the message it owns. Tokio’s Sender::reserve separates these actions: first wait for permission to send, then send through that permission without another await. Keep the message in state owned by the caller until the reservation succeeds:

async fn send_pending(
    tx: &tokio::sync::mpsc::Sender<String>,
    pending: &mut Option<String>,
    cancel: &tokio_util::sync::CancellationToken,
) -> Result<(), tokio::sync::mpsc::error::SendError<()>> {
    let permit = tokio::select! {
        permit = tx.reserve() => permit.map_err(|_| {
            tokio::sync::mpsc::error::SendError(())
        })?,
        _ = cancel.cancelled() => return Ok(()),
    };

    if let Some(message) = pending.take() {
        permit.send(message);
    }

    Ok(())
}

The caller stores the message in pending, outside the future that select! drops. If cancellation wins, pending still holds the message. If the reservation succeeds, the code takes the message and sends it without another await. If the channel closes, the function returns an error and leaves the message in pending. This example uses a simplified error type. Production code should choose an error that tells the caller whether it still owns the message.

A reservation does not save the sender’s place in Tokio’s FIFO queue. If cancellation interrupts the wait for capacity, the sender loses that place even though the caller still owns the message. The RustConf cancellation notes explain the distinction: waiting to send protects the message, but cancellation can still change who gets a place in the queue next.

Some actions take several steps and cannot safely restart. If callers need the same work to continue after a timeout or cancellation request, move it to a background task and keep its join handle so a later call can wait for it again. Tokio requires spawned task futures to meet a 'static bound. This means the future cannot borrow data that lives only briefly in a local variable. Spawning also changes who owns the work and what happens at shutdown. Use it when the work should outlive the caller, not as a general fix for cancellation.

Document what dropping each future means

Rust’s type system generally does not prove that an async operation is cancellation-safe. Check the method’s documentation, then trace what the future owns and changes before each await. Ask what happens if the caller drops it after it consumes input, advances a stream, acquires a resource, or changes shared state. Tokio’s select! documentation classifies individual methods, but your code must still keep its own invariants true.

Document what callers should expect: whether they can restart, whether they can recover partial progress, whether a side effect already happened, and whether cancellation makes them lose their place in a queue. A cancellation token signals that someone requested a stop. It does not prevent the caller from dropping the future at another await. If work must continue after the caller stops waiting, give it an owner that outlives the caller.

More in Web development Back to top ↑