Sub topic 4
Bounding work with timeout
This chapter assumes you know basic Rust, async/await, the Tokio runtime (#[tokio::main], tokio::spawn), and the Drop trait. Earlier chapters showed that a future does nothing until it is polled, and that cancelling a future means dropping it. timeout puts those two ideas to practical use.
What timeout does
tokio::time::timeout takes a Duration and a future. It returns a new future that polls the inner future and also watches a timer. If the inner future finishes first, you get Ok(value). If the timer fires 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 milliseconds. It never waits the full five seconds.
The return type is Result<T, Elapsed>, where T is whatever the inner future produces. If the inner future itself returns a Result, you end up with a nested one: Result<Result<T, E>, Elapsed>. The outer layer tells you whether the deadline passed. The inner layer tells you whether the operation succeeded.
Timeout is cancellation by drop
timeout does not ask the inner future to stop. It drops it. The future is dropped at whichever .await it was suspended on, so any code after that point never runs. Locals that were alive at that point are dropped normally, and their Drop implementations run.
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 line never printed does not appear. The guard's destructor runs because the future's state is dropped, but the rest of work is skipped.
Handling the result
A common pattern is to convert Elapsed into your own error type. Elapsed implements std::error::Error, so the ? operator works if your error type can be built from it.
use std::time::Duration;
use tokio::time::{sleep, timeout};
async fn fetch() -> Result<u32, String> {
sleep(Duration::from_millis(20)).await;
Ok(42)
}
async fn fetch_bounded() -> Result<u32, String> {
match timeout(Duration::from_millis(100), fetch()).await {
Ok(inner) => inner,
Err(_) => Err("request timed out".to_string()),
}
}
#[tokio::main]
async fn main() {
println!("{:?}", fetch_bounded().await);
}Matching on the outer result first keeps the two failure kinds separate. That lets you retry on a timeout but not on a real error, for example.
Common mistakes
- Assuming side effects were undone. If the future had already written half of a file or sent half of a request, dropping it does not roll that back. Design operations so a partial run is safe, or clean up in a
Dropguard. - Putting the timeout on the wrong scope. A timeout around one step bounds only that step. To bound a whole multi-step operation, wrap the entire async block once.
- Expecting it to stop blocking code. The timer can only fire when the task yields at an
.await. A later chapter covers why blocking code ignores your timeout.
Exercise
What does timeout(Duration::from_secs(1), fut).await return if fut is async { Ok::<u32, String>(7) } and completes in time? What happens to fut if the deadline passes first?
Show answer
It returns Ok(Ok(7)). The outer Ok means no timeout occurred, and the inner Ok(7) is the future's own result. If the deadline passes first, it returns Err(Elapsed) and fut is dropped at its current await point, so its remaining code never runs.