Fix an async handler that blocks the Tokio runtime with sync I/O, sleep and a CPU loop
A web service runs on the multi-threaded Tokio runtime (tokio = { version = "1", features = ["full"] }). When a few clients call the report endpoint at once, every other request on the server slows down to seconds, although nothing errors and the CPU is far from saturated on most cores. Explain what holds up the other tasks, and rewrite report.
Requirements:
- Keep the signature and the result: the same checksum for the same file.
- Keep the 500 ms pause; it is a rate limit.
- No other request may stall while a
reportis running.
use std::time::Duration;
async fn report(path: &str) -> std::io::Result<u64> {
let data = std::fs::read(path)?; // a 200 MB log file
std::thread::sleep(Duration::from_millis(500)); // rate limit
let mut sum = 0u64;
for b in &data {
sum = sum.wrapping_mul(31).wrapping_add(*b as u64); // about 1 s of CPU
}
Ok(sum)
}Find and fix the bug.
std::fs::read, thread::sleep and the hash loop never reach an .await, so they hold the worker thread and the tasks queued on it stall. Await tokio::fs::read and tokio::time::sleep, and move the loop into spawn_blocking.
- Believing Tokio preempts a long-running task the way the OS preempts a thread
- Fixing the blocking I/O but leaving a long CPU loop on the async worker
- Starting a nested runtime inside a task, which panics in Tokio
- When is
tokio::task::yield_nowenough instead ofspawn_blocking? - Why is
spawn_blockinga poor fit for a job that runs for the whole life of the program?
Multitasking in Tokio is cooperative: a task gives up its worker thread only when it reaches an .await and gets Pending. report contains no .await at all, so a call holds the thread the whole time: seconds reading the file, half a second asleep and a second of computation. Every task the scheduler queued on that thread waits until another thread steals it; several concurrent report calls occupy several worker threads, and latency grows for everyone. Nothing errors — it only shows up as latency.
The example needs the tokio crate and does not build without it:
use std::time::Duration;
async fn report(path: &str) -> std::io::Result<u64> {
// async read: the thread is free while the file is being read
let data = tokio::fs::read(path).await?;
// an async timer instead of thread::sleep
tokio::time::sleep(Duration::from_millis(500)).await;
// the computation goes to the pool for blocking work; data moves into the closure
let sum = tokio::task::spawn_blocking(move || {
let mut sum = 0u64;
for b in &data {
sum = sum.wrapping_mul(31).wrapping_add(*b as u64);
}
sum
})
.await
.expect("the checksum task panicked");
Ok(sum)
}spawn_blocking requires a Send + 'static closure, so data is moved in with move rather than borrowed. Awaiting its JoinHandle gives Result<u64, JoinError>: a panic in the closure comes back as an Err. For short stretches of computation, tokio::task::yield_now().await inside the loop works instead of spawn_blocking — the task yields its thread every few thousand iterations; for heavy parallel work, use a rayon pool. A nested runtime through #[tokio::main] does not help: starting a runtime inside a runtime panics with Cannot start a runtime from within a runtime.