skip to content

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%

answer

  1. Drop::drop is a plain fn
  2. await needs an async context
  3. async drop is nightly-only
  4. explicit close, sync fallback

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.

solid answer

~50 s

Destructors run wherever a value goes out of scope: in sync code, during a panic, or while a cancelled future is being dropped, and nothing guarantees an executor is there to poll more work. So `fn drop(&mut self)` is synchronous, and writing `.await` in it is rejected with E0728, "`await` is only allowed inside `async` functions and blocks". As of Rust 1.99, an `AsyncDrop` trait exists only behind the unstable `async_drop` feature. On stable, give the type an explicit `async fn close(self)` that does the network work and marks the value closed, and keep `Drop` as a cheap synchronous fallback: log it, reset the socket, or hand the resource to a cleanup task over a channel. Don't call `block_on` inside `Drop`: it stalls the executor thread, and `futures::executor::block_on` panics when nested inside another futures executor.

code

rust · 12 lines
rust
struct Conn;
impl Conn {
    async fn send_goodbye(&mut self) {}
}
impl Drop for Conn {
    fn drop(&mut self) {
        self.send_goodbye().await;
    }
}
fn main() {
    let _c = Conn;
}

go deeper

for a junior

Recall that Drop::drop is a normal synchronous function, so it cannot contain .await, and stable Rust has no async destructor.

for a middle

Explain why: destructors run during panics, sync scopes and cancellation, where no executor may be available to poll more work.

for a senior

Show the stable pattern: an explicit async close that consumes the value, a cheap Drop fallback, and no block_on inside destructors.

for a principal

Decide where a codebase's async cleanup lives, such as explicit close methods or a supervising task, and how missed closes are detected.

## Why a destructor cannot await In Rust, a value's destructor is the `drop` method of the `Drop` trait, and its signature is fixed: `fn drop(&mut self)`. It is an ordinary synchronous function. The compiler calls it at the end of a scope, when a value is overwritten, during unwinding after a panic, and when a containing value, including a cancelled future, is dropped. Awaiting needs an async context: an `.await` turns the enclosing function into a state machine that someone must poll to completion. A destructor has no such caller. It may run in plain synchronous code with no executor at all, in the middle of a panic, or inside an executor that is itself tearing down a task. If drop could suspend, the language would have to say who polls the rest and what happens to the value's memory in the meantime. That is why stable Rust has **no async Drop**. A suspended destructor would also raise questions about the value itself. Its memory would have to stay valid until the async destructor finished, which the unstable `async_drop_in_place` function spells out as a safety requirement, and every generic container that drops its elements, such as `Vec<T>`, would need a way to await each one. Those are among the open design questions the unstable work is exploring. ## What the compiler says Writing `self.send_goodbye().await` inside `fn drop` is a compile error, not a warning. rustc 1.99.1 reports E0728, "`await` is only allowed inside `async` functions and blocks", pointing at the `.await`. The error is about the context: `drop` is not async, and its signature cannot be changed. ## The unstable AsyncDrop The standard library contains a `core::future::AsyncDrop` trait whose method is `async fn drop(self: Pin<&mut Self>)`, but as of Rust 1.99 it is still marked unstable under the `async_drop` feature and compiles only on nightly. Production code on stable Rust must not rely on it; treat it as experimental work, not as a tool you can use. ## Patterns that work on stable The common shape splits **cleanup** (async, explicit) from **destruction** (sync, automatic): 1. **An explicit async close.** Give the type `async fn close(self)` or `shutdown(self)` that sends the goodbye frame, flushes and waits for the peer. Taking `self` by value makes the value unusable afterwards. Set a `closed` flag at the end. 2. **A synchronous fallback in `Drop`.** If `closed` is still false, the value was dropped without a proper close: by an early return, a `?`, a panic or cancellation. Do only cheap synchronous work there: log a warning, reset the connection, release a slot. 3. **Hand-off to a cleanup task.** If the fallback really needs async work, send the resource over a channel to a long-lived task that performs the async close. A non-blocking send is fine inside `Drop`. 4. **A supervisor that owns the resource.** Let one task own connections and close them on shutdown, so individual handles never need async destruction. The fallback matters because **cancellation can drop the close itself**. `close(self)` owns the session, so if its future is dropped mid-way, or before its first poll, the session is dropped with `closed` still false and the fallback runs. The example below shows both paths. ## What not to do - **Don't block in `Drop`.** Calling a `block_on` function from a destructor stalls the executor thread it runs on, and may deadlock if the awaited I/O needs that same thread. `futures::executor::block_on` refuses to nest and panics with "cannot execute `LocalPool` executor from within another executor". - **Don't assume `Drop` always runs.** `std::mem::forget` is safe, so a destructor can be skipped; effects that must happen belong in the explicit close. - **Don't spawn from `Drop` without knowing a runtime is running there.** A spawn function that needs a runtime context will fail when the value is dropped outside it. | Approach | Async work? | Runs on cancellation? | |---|---|---| | `async fn close(self)` | Yes | Only if it finishes | | `Drop` fallback | No | Yes | | Channel hand-off from `Drop` | Yes, in another task | Yes | | `AsyncDrop` | Yes | Nightly-only |

  • What happens to the session when its `close` future is cancelled half-way?
    The future owns `self`, so dropping it drops the session with `closed` still false and the `Drop` fallback runs. That is why the fallback must be correct on its own: it is the only cleanup a cancelled close gets.
  • Why not call `futures::executor::block_on` inside `drop` to run the async close?
    Drop often runs on an executor thread. `futures::executor::block_on` refuses to nest and panics with "cannot execute `LocalPool` executor from within another executor"; executors that allow nesting park the worker while the I/O it waits on may need that thread, which can deadlock, and every other task on that worker stalls.
  • Can stable Rust 1.99 use `AsyncDrop`?
    No. `core::future::AsyncDrop`, with `async fn drop(self: Pin<&mut Self>)`, is gated behind the unstable `async_drop` feature and compiles only on nightly. Stable code models async cleanup as an explicit method.

  • You can write async fn drop in a Drop impl on stable Rust.
  • Calling block_on inside Drop is a safe way to run async cleanup.
  • Rust awaits an async close automatically when a value leaves scope.
  • Drop does not run when a future is cancelled, so cleanup is skipped.
  • The AsyncDrop trait is stable and replaces Drop for async types.

Assumes Rust 1.99, where AsyncDrop is still unstable behind the async_drop feature; a later release could stabilise it.