Sub topic 4
Bounding work with timeout
This chapter assumes you know Rust ownership, the Drop trait, async/await syntax, and the basics of the Tokio runtime (#[tokio::main], tokio::spawn). It builds on the previous chapters: a future does nothing until polled, a task can only stop at an await point, and cancelling a future means dropping it.
What timeout does
tokio::time::timeout takes a Duration and a future. It returns a new future that resolves to Result<T, Elapsed>. If the inner future finishes first, you get Ok(value). If the deadline passes first, you get Err(Elapsed), and the inner future is dropped.
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[tokio::main]
async fn main() {
let slow = async {
sleep(Duration::from_secs(5)).await;
"done"
};
match timeout(Duration::from_millis(100), slow).await {
Ok(value) => println!("finished: {value}"),
Err(_elapsed) => println!("timed out"),
}
}This program prints timed out after about 100 ms. It does not wait five seconds.
The wrapper is a Timeout<F> struct that holds the inner future and a Sleep timer. Each time it is polled, it polls the inner future first. If that is still pending, it polls the timer. When the timer is ready, it returns Err(Elapsed). The inner future is dropped when the Timeout itself is dropped or consumed, which happens right after you receive the error.
Because the inner future is polled first, a future that is already ready wins even when the deadline has also passed. A timeout of Duration::ZERO around an immediately ready future still returns Ok.
Timeout is cancellation by drop
A timeout adds no new cancellation mechanism. It uses the one you already know: dropping the future. The inner future stops at whatever await point it last reached. Code after that point never runs, and local variables are dropped in the usual way.
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
after timeoutThe guard's Drop runs when the future is dropped. The line never printed does not appear, because work was suspended at sleep(...).await and never resumed.
Two consequences follow.
- Work done before the last await point is already finished and not rolled back. If
workhad written half of a file before the sleep, that half stays written. - Cleanup has to live in
Dropimplementations, not in code after an.await. The chapter on drop guards covers this in detail.
Handling the result
The return type is a nested result when the inner future is itself fallible. For example, wrapping a function that returns Result<T, E> gives Result<Result<T, E>, Elapsed>. The outer layer says whether the deadline passed. The inner layer is the operation's own outcome.
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn fetch() -> Result<u32, String> {
sleep(Duration::from_millis(20)).await;
Err("connection refused".to_string())
}
#[tokio::main]
async fn main() {
match timeout(Duration::from_millis(200), fetch()).await {
Ok(Ok(n)) => println!("value {n}"),
Ok(Err(e)) => println!("operation failed: {e}"),
Err(_) => println!("deadline exceeded"),
}
}Keeping the two layers distinct matters. A timeout is not the same as a failure of the operation, and callers often retry one and not the other.
Elapsed implements std::error::Error, and it converts into std::io::Error with kind TimedOut. That lets you flatten the layers when the inner error is also an io::Error:
use std::io;
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn read_something() -> io::Result<u32> {
sleep(Duration::from_millis(500)).await;
Ok(7)
}
async fn bounded() -> io::Result<u32> {
timeout(Duration::from_millis(50), read_something()).await?
}
#[tokio::main]
async fn main() {
let err = bounded().await.unwrap_err();
println!("{:?}", err.kind());
}This prints TimedOut. The ? converts Elapsed into io::Error, and the remaining io::Result becomes the function's return value.
Choosing where to put the timeout
A timeout bounds exactly the future it wraps, and nothing more. Where you place it decides what is bounded.
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn step(n: u32) {
sleep(Duration::from_millis(40)).await;
println!("step {n} complete");
}
#[tokio::main]
async fn main() {
// Per-step: each step gets its own 50 ms budget.
for n in 1..=3 {
let _ = timeout(Duration::from_millis(50), step(n)).await;
}
// Overall: the three steps share one 100 ms budget.
let all = async {
for n in 4..=6 {
step(n).await;
}
};
let result = timeout(Duration::from_millis(100), all).await;
println!("overall finished in time: {}", result.is_ok());
}The per-step loop completes all three steps, because each takes 40 ms against a 50 ms limit. The overall timeout wraps a block of three 40 ms steps, which need about 120 ms. It stops during step 6 and prints false. Steps 4 and 5 print their messages, and step 6 never does.
| Placement | What it bounds | Typical use |
|---|---|---|
| Around one call | That single operation | Connecting, reading one response |
| Around a block | The sum of several operations | A whole request handler |
| Around each retry plus one outer timeout | Each attempt and the total | Retry loops with a hard limit |
For a retry loop, use both levels. The per-attempt timeout stops one hung attempt from consuming the entire budget. The outer timeout guarantees the function returns by a known time.
timeout versus timeout_at
timeout measures a duration from the moment you call it. tokio::time::timeout_at takes a tokio::time::Instant instead. Use it when several operations must share one absolute deadline and you do not want to compute the remaining time yourself.
use std::time::Duration;
use tokio::time::{sleep, timeout_at, Instant};
#[tokio::main]
async fn main() {
let deadline = Instant::now() + Duration::from_millis(100);
for n in 1..=5 {
let res = timeout_at(deadline, sleep(Duration::from_millis(30))).await;
println!("step {n}: {}", if res.is_ok() { "ok" } else { "timed out" });
}
}Steps 1 to 3 finish at 30, 60, and 90 ms. Step 4 would end at 120 ms, so it times out at 100 ms. Step 5 times out immediately, because the deadline is already in the past.
Note that this is tokio::time::Instant, not std::time::Instant. Tokio's version is what the paused test clock controls, which a later chapter uses.
Timeouts do not cancel the world
A timeout stops the future it wraps. It does not necessarily stop everything that future started. Three cases need attention.
- Spawned tasks keep running. If the wrapped future called
tokio::spawnand is awaiting theJoinHandle, dropping the future drops the handle. Dropping aJoinHandledetaches the task, and it continues in the background. To stop it, callabort()on the handle, or use aCancellationToken. Both appear in later chapters. - Remote work continues. If the future sent an HTTP request or a database query, dropping it closes your side of the connection. The server may still finish the work. A timeout bounds how long you wait, not what the other side does.
- Partial effects remain. As noted above, anything completed before the last await point stays done. Design operations so a half-finished state is either harmless or repaired by a drop guard.
When timeout cannot fire
timeout can only fire when the runtime gets control back. The timer is checked when the Timeout future is polled, and a future can only be polled between await points of other code on the same thread. If the wrapped future runs a long computation, or calls a blocking function such as std::thread::sleep, without yielding, the poll does not return. The deadline passes, but nobody is there to notice.
use std::time::Duration;
use tokio::time::timeout;
#[tokio::main]
async fn main() {
let blocked = async {
std::thread::sleep(Duration::from_millis(300));
"finished anyway"
};
let result = timeout(Duration::from_millis(50), blocked).await;
println!("{result:?}");
}This prints Ok("finished anyway"). The future never yielded, so the first poll ran for 300 ms and returned a ready value. Because the inner future is polled before the timer, it is ready and wins. The timeout has no effect.
The fix is to use tokio::time::sleep for waiting, or to move genuinely blocking work to tokio::task::spawn_blocking and await its handle inside the timeout. A later chapter covers this pitfall fully.
Common mistakes
- Ignoring the outer layer. Writing
timeout(d, op).await.unwrap()turns a slow operation into a panic. Match on the result instead. - Creating the timeout inside a loop and expecting a total limit. Each iteration gets a fresh budget. Wrap the whole loop, or use
timeout_atwith a fixed instant. - Assuming the work is undone. Check what the wrapped future did before its last await.
- Using
std::time::Instantwithtimeout_at. The types differ, and the compiler will reject it. - Treating
Elapsedas an operation error. It says nothing about why the operation was slow.
Exercise
A function runs timeout(Duration::from_secs(2), handle_request()).await. handle_request first spawns a background task with tokio::spawn, then awaits that task's JoinHandle. The request takes 5 seconds. After the timeout returns Err(Elapsed), does the background task stop? What would you change so it does?
Show answer
No. Dropping the future drops the JoinHandle, which detaches the task, so it keeps running to completion. To stop it, keep the handle reachable and call abort() on it when the timeout fires, or give the task a CancellationToken and cancel it when you see Elapsed. A drop guard that calls abort() on the handle also works, because it runs when the future is dropped.
Exercise
You need a function that tries a flaky operation up to 5 times, giving each attempt 1 second, but must return within 3 seconds in total. Which timeout placement do you use, and which function makes the total limit easy to express?
Show answer
Put a 1-second timeout around each attempt, and wrap the whole retry loop in an outer limit. Create let deadline = Instant::now() + Duration::from_secs(3) using tokio::time::Instant and use timeout_at(deadline, ...) around the loop, or around each attempt, so every attempt shares the same absolute deadline.