Sub topic 13
Keeping the runtime responsive: spawn_blocking
This chapter assumes you can write basic async fn code, know what tokio::spawn and .await do, and understand that a future only makes progress when the runtime polls it. It also assumes you have seen Send and 'static bounds on spawned tasks.
Why blocking breaks an async runtime
Tokio runs many tasks on a small number of worker threads. By default the multi-thread runtime starts one worker per CPU core. A task gives its worker back only when it reaches an .await that returns Pending. This is cooperative scheduling. The runtime cannot interrupt a task that is in the middle of a poll.
If a task runs for a long time without awaiting, its worker thread is stuck. The other tasks queued on that worker cannot run, and timers and I/O events for them are not processed. A few stuck tasks can freeze a service that otherwise looks idle.
Two kinds of work cause this:
- Blocking calls. These park the thread:
std::thread::sleep,std::fsfunctions, synchronous database or HTTP clients, and waiting on astd::sync::Mutexthat another thread holds. - CPU-bound loops. These keep the thread busy: hashing, compression, parsing a large document, image processing.
The following program uses a current-thread runtime, which has exactly one worker, so the effect is easy to see.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let ticker = tokio::spawn(async {
for i in 0..5 {
println!("tick {i}");
sleep(Duration::from_millis(100)).await;
}
});
sleep(Duration::from_millis(50)).await;
// Blocks the only worker thread for 500 ms.
std::thread::sleep(Duration::from_millis(500));
ticker.await.unwrap();
}tick 0 prints immediately. The second tick is due at about 100 ms, but it prints only after the 500 ms block ends. During that time nothing else in the program can run. On a multi-thread runtime the same bug is harder to spot, because other workers hide it until enough tasks block at once.
Moving the work with spawn_blocking
tokio::task::spawn_blocking takes a synchronous closure and runs it on a separate pool of threads, called the blocking pool. It returns a JoinHandle that you can .await. While the closure runs, the async worker threads are free to poll other tasks.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let ticker = tokio::spawn(async {
for i in 0..5 {
println!("tick {i}");
sleep(Duration::from_millis(100)).await;
}
});
sleep(Duration::from_millis(50)).await;
tokio::task::spawn_blocking(|| {
std::thread::sleep(Duration::from_millis(500));
})
.await
.unwrap();
ticker.await.unwrap();
}Now the ticks keep arriving about every 100 ms while the blocking call runs. The only code change is wrapping the blocking call.
Passing data in and getting results out
The closure passed to spawn_blocking must be Send + 'static, like a spawned task. It cannot borrow local variables, so move owned data in and return the result.
#[tokio::main]
async fn main() {
let numbers: Vec<u64> = (1..=5_000_000).collect();
let total = tokio::task::spawn_blocking(move || {
numbers.iter().map(|n| n * n % 7).sum::<u64>()
})
.await
.unwrap();
println!("total = {total}");
}The .await returns Result<T, JoinError>. The error appears if the closure panics or if the runtime shuts down before the closure runs. The unwrap above would panic in those cases. A service should match on the error instead:
#[tokio::main]
async fn main() {
let result = tokio::task::spawn_blocking(|| {
if true {
panic!("bad input");
}
1u32
})
.await;
match result {
Ok(v) => println!("value {v}"),
Err(e) if e.is_panic() => println!("closure panicked"),
Err(e) => println!("join failed: {e}"),
}
}A panic inside the closure is caught by the runtime and does not crash the process. The panic message is still printed to stderr by the default panic hook.
How the blocking pool behaves
The blocking pool differs from the async workers in ways that matter for design.
| Property | Async worker threads | Blocking pool |
|---|---|---|
| Count | One per core by default | Up to 512 by default |
| Created | At runtime start | On demand, when work is queued |
| Idle behavior | Stay alive | Exit after about 10 seconds idle |
| Work type | Futures that return `Pending` often | Closures that run to completion |
| Can be cancelled | Yes, at an `.await` | No, once started |
You can change the pool size with Builder::max_blocking_threads when you build the runtime by hand. The limit is a ceiling, not a target. If more closures are queued than there are threads, the extra ones wait in a queue.
Because the pool can grow to hundreds of threads, it is a poor tool for large amounts of CPU-bound work. Running 500 hashing jobs at once on 8 cores only adds context switching. Two better options exist:
- Limit concurrency with a
tokio::sync::Semaphore. Acquire a permit before callingspawn_blockingand release it when the job finishes. - Use a dedicated CPU pool such as
rayon, and send the result back to the async task through atokio::sync::oneshotchannel.
Related tools
Tokio's own async wrappers. tokio::fs functions such as tokio::fs::read already call spawn_blocking internally, because most operating systems have no truly asynchronous file API. Using them is fine. For many small file operations in a row, one spawn_blocking around a block of std::fs calls can be cheaper than many separate hops.
block_in_place. tokio::task::block_in_place lets the current task run blocking code on its own worker thread. Tokio first hands the worker's other queued tasks to another worker. The closure can borrow local data, which spawn_blocking cannot. It panics on a current-thread runtime. Prefer spawn_blocking unless borrowing is essential.
Blocking calls from synchronous contexts. Calling Handle::block_on or futures::executor::block_on inside an async task can deadlock or panic. Do the reverse: keep blocking code outside the async path, or wrap it in spawn_blocking.
Common errors
- Holding a
std::sync::Mutexguard while doing slow work. Other tasks that calllock()block their worker threads. Keep critical sections short, or move the slow work tospawn_blocking. - Using a synchronous client library in a handler. A blocking HTTP or database client stalls the worker for the whole request. Use an async client, or wrap each call in
spawn_blocking. - Long loops with no
.await. A loop that processes a million items can starve the runtime. Move it tospawn_blocking, or inserttokio::task::yield_now().awaitperiodically so other tasks get a turn. - Trying to borrow in the closure. The error
closure may outlive the current functionmeans you needmoveand owned data, or anArc. - Using
spawn_blockingfor a loop of async calls. The closure is synchronous. You cannot.awaitinside it, so it is the wrong tool for waiting on I/O.
A rough guide: if a stretch of code between two .await points takes more than about 10 to 100 microseconds, consider moving it off the async workers. Measure first. tokio-console and the runtime metrics help you find tasks with long poll times.
Exercise
A handler running in tokio::spawn computes a password hash that takes 200 ms of CPU time, then returns it. The service handles hundreds of requests per second on an 8-core machine. Which approach do you choose, and why? Name one risk of using plain spawn_blocking here and one way to reduce it.
Show answer
Run the hash in tokio::task::spawn_blocking (or a dedicated rayon pool) so the async workers keep polling other tasks, and .await the handle to get the hash. Calling the hash directly in the handler would block a worker for 200 ms per request and freeze other tasks on that worker. The risk is that the blocking pool can grow up to 512 threads, so a burst of requests starts many hashes at once. That oversubscribes the 8 cores and raises latency for every request. Reduce it by guarding the call with a tokio::sync::Semaphore sized near the core count, so extra requests wait for a permit instead of starting more hashing threads.