Sub topic 8
Cleaning up when a future is dropped
This chapter assumes you know the Drop trait, async/await, and basic Tokio use (#[tokio::main], tokio::spawn). It also assumes you know from earlier chapters that cancelling a future means dropping it, and that a future can only be dropped at an await point. Here we deal with the consequence: when a future is dropped, none of the code after its current .await runs. If that code was supposed to release a resource, undo a change, or notify someone, you need a different mechanism.
What actually runs when a future is dropped
An async fn compiles to a state machine. At each .await, the state machine stores the local variables that are still alive. Dropping the future drops exactly those stored values, in reverse order of declaration, as if the function had returned early. Nothing else runs.
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
async fn work() {
let _guard = Noisy("work state");
sleep(Duration::from_secs(10)).await;
println!("never printed");
}
#[tokio::main]
async fn main() {
let _ = timeout(Duration::from_millis(50), work()).await;
println!("after timeout");
}The output is dropping work state followed by after timeout. The println! after the sleep never runs, but Drop for _guard does. This is the only hook you get, so cleanup that must survive cancellation belongs in a Drop implementation.
Three details decide whether that hook fires:
- Only variables that exist at the suspended await point are dropped. A guard declared after the
.awaitwas never created, so there is nothing to drop. - Dropping the outer future drops every inner future it was awaiting, recursively. A guard deep in a call chain still runs.
- A future that was created but never polled holds only its captured arguments. Those are dropped, but no body code ever ran, so no guard exists.
Use a named binding for guards
The most common mistake with guards is binding them to _.
let _ = Noisy("a"); // dropped immediately, at the end of this statement
let _guard = Noisy("b"); // lives until the end of the scopelet _ = expr; does not bind anything, so the value is dropped at once. A guard written that way protects nothing across the await. Use _guard or any other name starting with an underscore.
Guards for state you must restore
A typical case is a counter of in-flight requests. If a handler increments the counter and decrements it at the end, a timeout skips the decrement and the counter drifts upward. Put the decrement in Drop.
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct InFlight(Arc<AtomicUsize>);
impl InFlight {
fn new(counter: &Arc<AtomicUsize>) -> Self {
counter.fetch_add(1, Ordering::SeqCst);
InFlight(Arc::clone(counter))
}
}
impl Drop for InFlight {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
async fn handle(counter: Arc<AtomicUsize>) {
let _guard = InFlight::new(&counter);
sleep(Duration::from_secs(10)).await;
}
#[tokio::main]
async fn main() {
let counter = Arc::new(AtomicUsize::new(0));
let _ = timeout(Duration::from_millis(50), handle(counter.clone())).await;
println!("in flight after timeout: {}", counter.load(Ordering::SeqCst));
}This prints in flight after timeout: 0. The increment and the guard's creation happen in the same place, so the decrement is guaranteed whether the function returns normally, returns early with ?, panics, or is cancelled.
Rollback guards with a commit step
Sometimes you want cleanup only when the operation did not finish. The pattern is a guard that runs an undo action on drop, plus a disarm method that you call once the work has succeeded.
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Rollback<F: FnOnce()> {
undo: Option<F>,
}
impl<F: FnOnce()> Rollback<F> {
fn new(undo: F) -> Self {
Self { undo: Some(undo) }
}
fn disarm(mut self) {
self.undo = None;
}
}
impl<F: FnOnce()> Drop for Rollback<F> {
fn drop(&mut self) {
if let Some(undo) = self.undo.take() {
undo();
}
}
}
async fn book(reserved: Arc<AtomicUsize>, takes: Duration) -> &'static str {
reserved.fetch_add(1, Ordering::SeqCst);
let counter = Arc::clone(&reserved);
let guard = Rollback::new(move || {
counter.fetch_sub(1, Ordering::SeqCst);
});
sleep(takes).await; // stands in for a slow confirmation step
guard.disarm();
"booked"
}
#[tokio::main]
async fn main() {
let reserved = Arc::new(AtomicUsize::new(0));
let limit = Duration::from_millis(200);
let fast = timeout(limit, book(reserved.clone(), Duration::from_millis(10))).await;
let slow = timeout(limit, book(reserved.clone(), Duration::from_secs(10))).await;
println!("fast: {:?}", fast.is_ok());
println!("slow: {:?}", slow.is_ok());
println!("reserved: {}", reserved.load(Ordering::SeqCst));
}The fast call commits, the slow call is rolled back, and the program prints reserved: 1. Consuming self in disarm makes it impossible to use the guard after committing.
Broken invariants: half-finished updates
Guards also matter for data that is shared between tasks. Suppose a task holds a tokio::sync::Mutex guard, changes one field, awaits, and then changes a second field. If the future is dropped between the two changes, the mutex guard is released, but the data is left half-updated. Tokio's mutex does not poison, so the next task sees the inconsistent state with no warning.
There are three ways to handle this:
- Make the update atomic from the perspective of other tasks: compute everything first, then apply both changes with no
.awaitin between. - Use a rollback guard that restores the old values unless the update completes.
- Do not hold a lock across an await point at all. Send the work to a dedicated task through a channel instead.
The first option is the simplest and also avoids deadlock risk from holding locks across awaits.
Drop cannot await
Drop::drop is a synchronous function. You cannot write .await in it, and blocking in it blocks the executor thread that dropped the future. That limits what cleanup you can do directly. Closing a network connection cleanly, flushing a buffer to an async writer, or sending a goodbye message all need async I/O.
The options, from simplest to most involved:
- Make the cleanup synchronous and fast. Atomic updates,
Mutex::lockon astdmutex held briefly,try_sendon a channel, and closing a file descriptor all qualify. - Hand the async part to a task. In
drop, spawn a task that performs the cleanup. - Send a cleanup request over a channel to a long-lived cleanup task that owns the resource.
- Provide an explicit
async fn close(self)for the normal path, and keepDroponly as a fallback.
The following example uses option 2.
use std::time::Duration;
use tokio::runtime::Handle;
use tokio::time::{sleep, timeout};
struct Connection {
name: &'static str,
}
impl Drop for Connection {
fn drop(&mut self) {
let name = self.name;
// Drop can run outside a runtime, so check before spawning.
if let Ok(handle) = Handle::try_current() {
handle.spawn(async move {
sleep(Duration::from_millis(20)).await; // pretend: send a close frame
println!("{name}: closed asynchronously");
});
}
}
}
async fn query() {
let _conn = Connection { name: "db" };
sleep(Duration::from_secs(10)).await;
}
#[tokio::main]
async fn main() {
let _ = timeout(Duration::from_millis(50), query()).await;
println!("timed out");
sleep(Duration::from_millis(100)).await; // give the cleanup task time to run
}The output is timed out, then db: closed asynchronously. The cleanup runs after the timeout returns, not before. If your code depends on the cleanup having finished (for example, to reuse the same connection slot), it cannot assume that.
Rules for writing `Drop` in async code
- Keep it short and non-blocking. A slow
dropstalls the worker thread that is polling other tasks. - Do not panic. A panic in
dropwhile the thread is already unwinding from another panic aborts the process. - Make it idempotent when there is also an explicit close path. Track a
closed: boolor anOptionfor the resource, and havedropdo nothing if it was already released. - Do not rely on
Dropfor correctness of data that must be durable. A process kill skips it entirely, and so doesstd::mem::forget.
Choosing a cleanup strategy
The middle path matters. If you control the task, asking it to stop with a token lets it run real async cleanup code in its normal control flow, which a Drop cannot do. Use Drop as the safety net for the cases where the future is dropped without warning, such as a timeout or a losing select! branch.
Spawned tasks follow the same rules
JoinHandle::abort drops the task's future at its next await point, so guards inside the task run. Dropping a JoinHandle does not cancel the task at all. It only detaches it. If a task is mid-poll on another worker thread when you call abort, the cancellation takes effect once that poll returns. Do not assume cleanup has finished the instant abort() returns. Await the handle to wait for it. The result is a JoinError whose is_cancelled() is true.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Cleanup written after the final `.await` | Skipped on cancellation | Move it into a guard's `Drop` |
| `let _ = Guard::new();` | Guard dropped at once | Bind it as `let _guard = ...` |
| Blocking call inside `Drop` | Stalls the worker thread | Spawn or send to a cleanup task |
| `tokio::spawn` in `Drop` without a runtime check | Panic outside a runtime | Use `Handle::try_current()` |
| Counter updated before the guard exists | Leaks if cancelled in between | Create the guard in the same step as the update |
Exercise
A function starts with let _ = InFlight::new(&counter); followed by sleep(Duration::from_secs(10)).await;. A timeout cancels it after 50 ms. What is the counter value at the moment the sleep is running, and what is it after the timeout? How would you fix the code?
Show answer
The counter is already back to its starting value while the sleep is running. let _ = ... does not bind the guard, so it is dropped at the end of that statement, and the decrement runs immediately. The guard therefore does not cover the await at all, and the timeout makes no difference to the count. The fix is to bind the guard to a name, let _guard = InFlight::new(&counter);, so it lives until the end of the function or until the future is dropped at the await point.