Sub topic 13
Keeping the runtime responsive: blocking code
This chapter assumes you know how to write async fn, use .await, and spawn tasks on Tokio. It also assumes you know basic thread concepts and the Arc and Mutex types. By the end you will be able to spot code that stalls the runtime and move it somewhere safe.
Why blocking is a problem
An async runtime runs many tasks on a small number of worker threads. Tokio's multi-threaded runtime starts one worker per CPU core by default. A task only gives up its thread when it returns Poll::Pending, which happens at an .await that is not ready yet.
If a task runs long computations or calls a blocking function between two .await points, it keeps its worker thread the whole time. The other tasks scheduled on that thread cannot run. Timers fire late, sockets go unserviced, and the program looks frozen even though the CPU is busy.
The rule of thumb: a task should spend no more than tens of microseconds to a few milliseconds between .await points.
Common sources of blocking:
std::thread::sleepstd::fscalls and synchronous network clientsstd::sync::Mutex::lockwhen the lock is held for a long time elsewhere- CPU-heavy work such as hashing, compression, parsing large files, or image processing
- Receiving from a
std::sync::mpscchannel
Seeing the problem
This program uses a runtime with a single worker thread to make the effect obvious. One task blocks with std::thread::sleep, and a second task tries to print a tick every 100 ms.
use std::time::Duration;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let ticker = tokio::spawn(async {
for i in 0..5 {
println!("tick {i}");
tokio::time::sleep(Duration::from_millis(100)).await;
}
});
let blocker = tokio::spawn(async {
println!("blocking start");
std::thread::sleep(Duration::from_secs(1));
println!("blocking end");
});
ticker.await.unwrap();
blocker.await.unwrap();
}The ticker prints tick 0, then waits. The blocker starts and holds the only thread for a full second. The remaining ticks cannot begin until it finishes. With several workers the same bug is harder to see, because other threads hide it until every worker is blocked at once, usually under load.
Replace std::thread::sleep with tokio::time::sleep(...).await and the ticks interleave with the other task as expected.
Moving work off the runtime with spawn_blocking
tokio::task::spawn_blocking runs a closure on a separate pool of threads that exist for blocking work. It returns a JoinHandle that you await like any other task.
use std::time::Duration;
fn slow_checksum(data: Vec<u8>) -> u64 {
std::thread::sleep(Duration::from_millis(200));
data.iter().map(|&b| b as u64).sum()
}
#[tokio::main]
async fn main() {
let data = vec![1u8; 1_000];
let handle = tokio::task::spawn_blocking(move || slow_checksum(data));
let ticker = tokio::spawn(async {
for i in 0..3 {
println!("still responsive {i}");
tokio::time::sleep(Duration::from_millis(50)).await;
}
});
let sum = handle.await.unwrap();
ticker.await.unwrap();
println!("checksum = {sum}");
}The closure is FnOnce, takes no arguments, and must be Send + 'static, for the same reason spawned tasks must be. That is why data is moved in. The async tasks keep running while the blocking pool does the slow work.
Properties of the blocking pool
- The pool grows on demand up to a limit, 512 threads by default, and idle threads exit after a timeout. You can change the limit with
Builder::max_blocking_threads. - A closure that is already running cannot be cancelled. Dropping or aborting the
JoinHandledoes not stop it. It runs to completion and its result is discarded. - A closure that has not started yet can be cancelled by aborting the handle.
- If the closure panics, awaiting the handle returns
Err(JoinError). - At shutdown, the runtime waits for running blocking closures unless you use
shutdown_timeoutorshutdown_background.
Choosing the right tool
| Situation | Tool | Why |
|---|---|---|
| Short blocking call, such as one file read | `spawn_blocking` or `tokio::fs` | `tokio::fs` already uses the blocking pool internally. |
| CPU-heavy work, such as hashing or compression | `spawn_blocking` for moderate work, a dedicated thread pool such as rayon for sustained heavy work | The blocking pool can grow to hundreds of threads, which oversubscribes the CPU. |
| Blocking loop that lives for the whole program | `std::thread::spawn` | It does not occupy a blocking pool slot forever. |
| Synchronous library that you must call | `spawn_blocking` | The library cannot yield. |
| Long async loop that never awaits anything pending | `tokio::task::yield_now().await` at intervals | It lets other tasks run. |
For long CPU work, a common pattern is to send the job to a rayon pool and receive the result through a tokio::sync::oneshot channel. That keeps both the async workers and the CPU under control.
Cooperative yielding
Not all stalls come from obviously blocking calls. A loop that processes a large in-memory buffer with no .await hogs the thread, even though it contains no blocking function.
use std::time::Duration;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let worker = tokio::spawn(async {
let mut total = 0u64;
for i in 0..50_000_000u64 {
total = total.wrapping_add(i);
if i % 5_000_000 == 0 {
tokio::task::yield_now().await;
}
}
println!("total = {total}");
});
let ticker = tokio::spawn(async {
for i in 0..3 {
println!("tick {i}");
tokio::time::sleep(Duration::from_millis(1)).await;
}
});
worker.await.unwrap();
ticker.await.unwrap();
}yield_now returns Pending once and wakes the task immediately, so the scheduler can run other tasks before coming back. This works for occasional yielding. If the work is large, spawn_blocking is usually the better choice, because it also lets the work run in parallel with the async workers.
Tokio's own resources, such as channels and sockets, take part in a cooperative budget. Each task gets a number of operations per poll, and when it runs out, the next operation returns Pending even if data is ready. This stops one busy task from starving the others, but it does not help with your own loops.
Blocking and locks
std::sync::Mutex is fine in async code when two conditions hold. The lock is held briefly, and the guard is never held across an .await. Tokio's documentation actually recommends it for short critical sections, because it is cheaper than tokio::sync::Mutex.
Holding a std::sync::MutexGuard across an .await has two problems. The future becomes !Send, so tokio::spawn rejects it. Even in a single-threaded runtime, another task may try to take the same lock while the first one is suspended, and that blocks the thread forever, which is a deadlock.
The tokio::sync::Mutex from the previous chapter avoids this, at the cost of more overhead. Use it when you must hold the lock across an .await.
Detecting blocking in practice
- Run with
tokio-consoleor enabletracingto find tasks with long poll times. - Look for latency spikes in timers: a
sleep(10ms)that wakes after 500 ms means something blocked a worker. - Test with
#[tokio::main(flavor = "current_thread")]. If anything stalls on one thread, it is hiding behind extra workers on a bigger runtime. - Search for
std::thread::sleep,std::fs,reqwest::blocking, and similar in async code.
How the pieces relate
Summary of rules
- Never call blocking functions directly in async code. Use the async equivalent or
spawn_blocking. - Keep the time between
.awaitpoints short. - Pass owned data into
spawn_blockingclosures withmove. - Remember that running blocking closures cannot be cancelled.
- Use
std::sync::Mutexfor short critical sections that never span an.await. Usetokio::sync::Mutexotherwise. - For heavy parallel CPU work, prefer a dedicated thread pool.
Exercise
A service runs on Tokio's multi-threaded runtime. A handler calls std::fs::read_to_string on a large file directly inside an async fn. Under light load everything works, but under heavy load other requests become slow and timers fire late. Explain why, and show one way to fix the handler.
Show answer
std::fs::read_to_string blocks the worker thread until the read completes. With few requests, other workers handle the remaining tasks. Under heavy load, many handlers block at once and every worker thread can end up occupied, so no thread is free to poll the other tasks or fire timers. Fix it by using tokio::fs::read_to_string(path).await, which performs the read on the blocking pool, or by wrapping the call: tokio::task::spawn_blocking(move || std::fs::read_to_string(path)).await.unwrap(). The second form returns a nested result: the outer unwrap handles a JoinError, and the inner value is still an io::Result<String>.
Exercise
You start a spawn_blocking closure that loops for ten seconds, and then call handle.abort() after one second. Does the closure stop? What happens to its result?
Show answer
No. A blocking closure that has already started cannot be cancelled, because Tokio has no way to interrupt a running thread. Aborting the handle only means the result is discarded. The closure keeps running for the full ten seconds and occupies a blocking-pool thread, and runtime shutdown will wait for it unless you use shutdown_timeout or shutdown_background. To make it stoppable, have the closure check an AtomicBool flag or a channel at each loop iteration and return early.