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?
answer
- a timeout is a race
- the loser gets dropped
- dropping is not rollback
- keep the loser to resume it
basics
~20 sA 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.
solid answer
~40 sIn Rust a timeout is a race between the work and a timer, and whatever runs the race holds both futures. When the timer completes first, a typical timeout wrapper returns and drops the write's future, cancelled at whichever `.await` it was parked on, with no signal beyond its locals' `Drop`. That stops the worker, not the database: if the request was already sent, the server may commit it after the worker gave up. So a timed-out write is unknown rather than failed: leave the message unacknowledged so it is redelivered, and make the write idempotent so the retry is harmless. If the work should continue past the deadline, use a race that hands the loser back, such as `futures::future::select`, and await it later.
code
rust · 25 linesuse futures::future::{self, Either};
use smol::Timer;
use std::pin::pin;
use std::time::Duration;
async fn db_write(id: u32) -> u32 {
Timer::after(Duration::from_millis(200)).await;
println!("db: wrote payment {id}");
id
}
fn main() {
smol::block_on(async {
let write = pin!(db_write(7));
let deadline = Timer::after(Duration::from_millis(50));
match future::select(write, deadline).await {
Either::Left((id, _timer)) => println!("written in time: {id}"),
Either::Right((_fired, write)) => {
println!("slow: deadline passed, write kept");
let id = write.await; // the same future resumes; nothing restarts
println!("finished late: {id}");
}
}
});
}go deeper
Recall that a timeout in Rust is a race: when the timer wins, the work's future is dropped and stops at its pending .await.
Explain why timed out means unknown: the drop stops your code, not the server, so a request already sent may still commit.
Show the production fix: no acknowledgement on timeout, idempotent writes for redelivery, and select when the work must outlive the deadline.
Decide which operations may be abandoned at a deadline and which must finish, and pick dropping or returning races to match.
## A timeout is a race whose loser is dropped Rust's standard library has no async timer, so a timeout always comes from a runtime or a helper crate. Whatever the API looks like, it works the same way underneath: it **holds two futures**, the work and a timer (owning them, or borrowing pinned ones), polls both, and completes as soon as one of them does. When the timer wins, the wrapper returns a timeout result and the **work's future is dropped**. Dropping a future is how Rust cancels it. The future never gets polled again, so it stops at the `.await` it was parked on; its live locals and any nested future it was awaiting are dropped synchronously. It receives no error value and has no chance to run more async code. For a payment worker that awaits a database write inside a timeout, that means: - the write's future stops at its pending `.await`; - nothing after that point in the worker runs, including the acknowledgement; - destructors of values the future held do run. ## What timed out tells you, and what it does not A timeout tells you that *your* side stopped waiting. It says nothing about the far side. Consider where the write future could have been when it was dropped: | Where the future was parked | Did the write land? | |---|---| | Waiting to get a connection | No, nothing was sent | | Waiting for the request to be sent | Possibly partly sent; the server may reject or apply it | | Waiting for the reply | The server may already have committed | Because of the last two rows, the honest status is **unknown**. The safe reaction for a message-driven worker is: 1. Do not acknowledge the message, so the broker redelivers it. 2. Make the write **idempotent**, for example an insert keyed by the payment id that ignores a duplicate, so the redelivery cannot charge twice. 3. Acknowledge only after a write you have seen succeed. Acknowledging on timeout is the dangerous choice: if the write never landed, the payment is lost. ## Keeping the work instead of losing it Not every race drops the loser. Two shapes are common: - **Dropping races**, such as `smol::future::or` or the `race` method in futures-lite, return only the winner's output; the loser is dropped when the race itself is. - **Returning races**, such as `futures::future::select`, give you back the loser. `select(write, timer)` resolves to `Either::Left((output, timer))` or `Either::Right((timer_output, write))`, so on a timeout you still hold the unfinished `write` future and can log a slow-write warning and then await it to completion. Everything the losing future owned is dropped with it. A pooled connection it had checked out goes back through its guard's `Drop`, possibly with a request half-written on it, which is why a careful pool discards a connection whose request was interrupted instead of reusing it. The second shape lets you react to a deadline without cancelling anything: the same future resumes from where it was parked, nothing restarts, and nothing is lost. The trade-off is that you must decide what to do with the future you got back; if you simply let it fall out of scope, it is dropped and cancelled after all. ## Limits of a timeout A timeout can only take effect when the work's `poll` returns. Two consequences follow: - a loop that never reaches an `.await` cannot be timed out on the same task, because the timer is never polled while that loop runs; - a timeout cancels the future, not an independent task it spawned; whether a spawned task stops is decided by its own handle and executor; - a deadline that fires often is a signal to look at the work, not just to raise the limit, because every firing leaves an unknown outcome behind. The example below races a 200 ms write against a 50 ms timer with `futures::future::select` and smol. The timer wins, `select` returns the unfinished write, and the worker awaits it anyway, so the write completes late instead of being cancelled.
- What should the payment worker do with the message after its write times out?Leave it unacknowledged, or reject it so it is redelivered, and make the database write idempotent, for example keyed by the payment id, so the retry cannot charge twice. Acknowledging on timeout loses the payment whenever the write did not land.
- Can a timeout stop a CPU-bound loop that never reaches an .await?No. A race can only act when the work's `poll` returns, and a loop with no `.await` never returns from `poll`; the timer is not even polled while it runs on the same task. Long computations need `.await` points or a separate thread.
- When would you choose `futures::future::select` over a race that drops the loser?When the deadline should trigger a reaction, such as a warning, a metric or a fallback, without abandoning the work. `select` returns the unfinished future, which can be awaited later, so nothing is cancelled unless you drop it yourself.
- A timed-out write definitely never reached the database.
- The timeout throws an error into the inner future so it can roll back.
- After a timeout the inner future keeps running in the background.
- A timeout can interrupt a loop that never reaches an .await.
- Acknowledging the message on timeout is safe because the write was cancelled.