Sub topic 12
Why blocking code ignores your timeout
This chapter assumes you know how tokio::time::timeout and tokio::spawn work, and that cancellation means dropping a future. It explains why a timeout can't interrupt code that never reaches an .await. It then shows how to move blocking work off the async threads and how to stop it cooperatively.
The timeout only gets control at await points
Earlier chapters showed that a future is cancelled only when it is dropped, and that this can only happen while the future is suspended at an .await. A timeout is built on the same rule. timeout wraps your future in a Timeout future. Each time the runtime polls the wrapper, it polls your inner future first. If the inner future returns Pending, the wrapper checks whether the deadline has passed.
Now suppose the inner future calls a function that blocks the thread. The call to poll does not return until the blocking call finishes. The wrapper has no code running during that time, so it can't check the clock. The timer also can't help, because the runtime thread that would process it is stuck inside your function.
use std::time::{Duration, Instant};
use tokio::time::timeout;
#[tokio::main]
async fn main() {
let start = Instant::now();
let result = timeout(Duration::from_millis(100), async {
std::thread::sleep(Duration::from_secs(2));
"done"
})
.await;
println!("{:?} after {:.1?}", result, start.elapsed());
}This prints Ok("done") after 2.0s. The 100 ms deadline had long passed. But the inner future finished on its first poll, so the wrapper saw Ready and never looked at the deadline.
When the timeout fires late
Add a real await after the blocking call and the outcome changes. The inner future now returns Pending once the thread wakes up. The wrapper then checks the deadline and finds it expired.
use std::time::{Duration, Instant};
use tokio::time::{sleep, timeout};
#[tokio::main]
async fn main() {
let start = Instant::now();
let result = timeout(Duration::from_millis(100), async {
std::thread::sleep(Duration::from_secs(2));
sleep(Duration::from_secs(10)).await;
"done"
})
.await;
println!("{:?} after {:.1?}", result.is_err(), start.elapsed());
}This prints true after 2.0s. The timeout works, but it reports the failure about 1.9 seconds late. The deadline is a lower bound on when you get an error, not an upper bound.
The damage spreads beyond one task
A blocked worker thread also stops every other task scheduled on it. On the multi-threaded runtime, one blocked thread is one fewer worker, and tasks queued on it wait. On a current_thread runtime, a single blocking call freezes the whole program: timers, I/O, and other tasks all wait.
This is why blocking code in async functions is a bug even when no timeout is involved. The timeout just makes the symptom visible. Typical sources are:
std::thread::sleep,std::fs, andstd::netcalls.- Synchronous database or HTTP clients.
- Locks held for a long time, such as a
std::sync::Mutexguard while another thread works. - CPU-heavy loops: hashing, compression, parsing a large file, or any long computation.
The last one needs no blocking API at all. A tight loop that never awaits blocks the thread exactly like thread::sleep does.
Fix 1: use the async version
If an async version of the operation exists, use it. tokio::time::sleep instead of std::thread::sleep, tokio::fs instead of std::fs, tokio::net instead of std::net, and tokio::sync::Mutex when a guard must be held across an .await. Each of these suspends the task and returns the thread to the runtime. That gives the timeout a chance to run.
Fix 2: move blocking work to spawn_blocking
When no async version exists, run the work on Tokio's blocking thread pool with tokio::task::spawn_blocking. The closure runs on a separate thread. The async task gets a JoinHandle that it can await, so it suspends normally and the timeout works.
There is a catch. Dropping a JoinHandle detaches the task. It does not stop it. For a blocking closure, the thread keeps running until the closure returns, even if the timeout fired and nobody wants the result. Rust can't interrupt a thread from outside.
To stop the work early, make the closure cooperative. Give it a flag to check and have it return when the flag is set.
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::time::Duration;
use tokio::{task, time::timeout};
#[tokio::main]
async fn main() {
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
let mut handle = task::spawn_blocking(move || {
let mut steps = 0u64;
while !flag.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(20));
steps += 1;
}
steps
});
// Pass &mut handle so the handle survives a timeout.
match timeout(Duration::from_millis(100), &mut handle).await {
Ok(joined) => println!("finished: {:?}", joined),
Err(_) => {
println!("timed out, asking the thread to stop");
stop.store(true, Ordering::Relaxed);
let steps = handle.await.unwrap();
println!("blocking work stopped after {steps} steps");
}
}
}Passing &mut handle matters. JoinHandle is Unpin, so a mutable reference to it is itself a future. When the timeout drops that reference, the handle is still yours and you can await it after signalling the stop flag.
Fix 3: block_in_place on the multi-threaded runtime
tokio::task::block_in_place runs a blocking closure on the current worker thread, but first tells the runtime to move the other queued tasks to a different worker. It avoids the cost of moving data into a 'static closure, because the closure can borrow local variables. It has two limits. It panics on a current_thread runtime. And it blocks the calling task itself, so a timeout wrapped around that same task still can't fire until the closure returns. Treat it as a way to protect other tasks, not as a way to make one task cancellable.
Fix 4: break up CPU-bound loops
A long computation can stay in async code if it periodically yields. tokio::task::yield_now().await suspends the task for one scheduling round. That creates an await point, and the timeout can then check its deadline.
use std::time::Duration;
use tokio::{task::yield_now, time::timeout};
async fn sum_squares(n: u64) -> u64 {
let mut total = 0u64;
for i in 0..n {
total = total.wrapping_add(i.wrapping_mul(i));
if i % 10_000 == 0 {
yield_now().await;
}
}
total
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
match timeout(Duration::from_millis(50), sum_squares(u64::MAX)).await {
Ok(total) => println!("total: {total}"),
Err(_) => println!("timed out"),
}
}This prints timed out after roughly 50 ms, even on a single-threaded runtime. Choose the yield interval so that the time between yields stays well below the precision you need. Yielding on every iteration adds overhead. Yielding every few seconds makes the timeout equally coarse.
For work that is heavy enough, spawn_blocking or a dedicated thread (or a pool such as Rayon, with results sent back over a oneshot channel) is usually the better design. Yielding suits loops that are mostly light and that already live in async code.
Choosing an approach
| Situation | Approach | Timeout works? | Work can be stopped? |
|---|---|---|---|
| An async API exists | Use it | Yes | Yes, by drop |
| Synchronous library call | `spawn_blocking` | Yes, on the handle | Only if it checks a flag |
| Blocking call, need to borrow locals, multi-threaded runtime | `block_in_place` | No, for the calling task | No |
| Long CPU loop inside async code | `yield_now` at intervals | Yes, with some lag | Yes, by drop |
| Heavy, long-running computation | Dedicated thread or Rayon plus a `oneshot` | Yes, on the receiver | Only if it checks a flag |
Spotting the problem in practice
Symptoms of blocking in async code include timeouts that fire seconds late, unrelated tasks that stall, and latency spikes that grow with load. A few habits help:
- Review every function called from async code for hidden synchronous I/O,
std::sync::Mutexlocks held for long, and heavy loops. - Run suspicious paths on a
current_threadruntime in tests. A blocked thread then freezes everything and the bug is obvious. - Use
tokio-consoleor tracing to find tasks with long poll times. A healthy task polls for microseconds. A poll lasting tens of milliseconds deserves a look.
Exercise
A handler runs timeout(Duration::from_secs(1), async { expensive_hash(&data); store(hash).await }), where expensive_hash is a synchronous function that takes 5 seconds and never awaits. What does the caller observe, and how would you change the code so the caller gets an error after about one second and the hashing thread can still be stopped?
Show answer
The timeout cannot fire while expensive_hash holds the thread. After about 5 seconds, the inner future polls store(hash).await. If that returns Pending, the wrapper then sees the expired deadline and returns Err(Elapsed) about 4 seconds late. If store completes on its first poll, the caller gets Ok instead. To fix it, run the hash in spawn_blocking with an Arc<AtomicBool> stop flag that the hash loop checks. Await the handle by &mut inside the timeout. On Err(Elapsed), set the flag and await the handle so the thread exits promptly. The timeout now fires at about one second because the async task is suspended on the handle.