Run Blocking Code in Tokio with spawn_blocking
Move blocking calls and heavy computation off Tokio's worker threads with spawn_blocking so one slow task cannot stall every other task on the runtime.

Tokio runs thousands of tasks on a handful of worker threads, and that arrangement only works if tasks give the thread back quickly. A task that calls a blocking function, such as reading a large file with std::fs, hashing a password or waiting on a synchronous database driver, keeps its worker thread for the whole call. On a runtime with four workers, four such tasks freeze everything else: no accepts, no timers, no replies. tokio::task::spawn_blocking is the standard escape hatch. This post shows the symptom, the fix and the limits, using Tokio 1.x and Rust 1.90, and builds on the earlier post about how an async runtime polls tasks.
What "blocking" means to the scheduler
The executor can only switch tasks at .await points. Between two awaits, a task owns its thread. Tokio's documentation gives a rule of thumb: code should not spend more than tens to hundreds of microseconds between awaits. A function that sleeps, waits on a lock held by a slow thread, does synchronous file or network I/O, or loops over a big input without yielding violates that rule.
Here is a task that blocks a current-thread runtime, with a second task that should have run in the meantime:
use std::time::Duration;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let ticker = tokio::spawn(async {
for i in 1..=3 {
println!("tick {i}");
tokio::time::sleep(Duration::from_millis(50)).await;
}
});
tokio::time::sleep(Duration::from_millis(10)).await;
std::thread::sleep(Duration::from_millis(500)); // blocks the only worker
println!("blocking call finished");
ticker.await.unwrap();
}tick 1
blocking call finished
tick 2
tick 3The ticker printed its first tick, then main blocked the only thread for half a second. The ticker was due at 50 ms and could not run until 510 ms. On the default multi-threaded runtime the symptom is subtler: other workers carry on, but you have lost one of them for the duration, and enough blocked tasks produce the same freeze.
The fix: spawn_blocking
spawn_blocking takes a closure and runs it on a separate pool of threads reserved for blocking work. It returns a JoinHandle that you await like any task handle. While the closure runs on a blocking-pool thread, the async workers stay free.
use std::time::Duration;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let ticker = tokio::spawn(async {
for i in 1..=3 {
println!("tick {i}");
tokio::time::sleep(Duration::from_millis(50)).await;
}
});
let result = tokio::task::spawn_blocking(|| {
std::thread::sleep(Duration::from_millis(120));
"blocking work done"
})
.await
.unwrap();
println!("{result}");
ticker.await.unwrap();
}tick 1
tick 2
tick 3
blocking work doneThe ticker ran its three ticks, at roughly 0, 50 and 100 ms, during the 120 ms the closure spent sleeping on another thread. The .await on the handle returns the closure's return value wrapped in a Result, where the Err case means the closure panicked or the runtime shut down. Output order is stable here because the ticks finish before the 120 ms sleep ends, but the exact timings vary with machine load.
Why the closure must be 'static
spawn_blocking requires the closure to be Send + 'static, so it cannot borrow local variables from the async function. Clone or move what it needs. A frequent compile error, "borrowed value does not live long enough", shows up when someone passes a reference to a local buffer; move the buffer into the closure and return it, or wrap shared data in an Arc.
use std::sync::Arc;
#[tokio::main]
async fn main() {
let data = Arc::new(vec![1u64, 2, 3, 4, 5]);
let shared = Arc::clone(&data);
let sum = tokio::task::spawn_blocking(move || shared.iter().sum::<u64>())
.await
.unwrap();
println!("sum = {sum}, still have {} items", data.len());
}sum = 15, still have 5 itemsThe pool has limits
The blocking pool is not free. By default Tokio allows up to 512 blocking threads, created on demand and released after an idle period, and the max_blocking_threads setting on the runtime builder changes that cap. When the cap is reached, new blocking jobs queue until a thread frees up. That is an important property: spawn_blocking moves blocking work off the async workers, but it does not make unlimited blocking work fast. A thousand simultaneous 10-second blocking calls queue behind 512 threads.
A blocking task cannot be cancelled once it starts. Aborting its JoinHandle stops you waiting for the result, but the closure keeps running to the end. If the work must be stoppable, have it check an AtomicBool or a channel flag at regular points, and design the loop around that.
Which work belongs where
| Work | Where to run it |
|---|---|
| Waiting on sockets, timers, channels | async tasks |
std::fs calls, synchronous drivers, std::thread::sleep | spawn_blocking |
| Short CPU bursts (microseconds) | directly in the task |
| Long CPU-bound loops (hashing, compression, image work) | a dedicated thread pool such as Rayon, called from spawn_blocking or a channel |
The Tokio documentation on CPU-bound work recommends a separate pool for heavy computation, because spawn_blocking threads are meant for work that waits, and saturating them with CPU-bound jobs can starve the file and database calls that share the pool. For small and occasional computation, spawn_blocking is perfectly fine.
An alternative for files: tokio::fs
tokio::fs::read already uses spawn_blocking internally, because most operating systems do not offer truly asynchronous file I/O through the regular APIs. Calling it is the same as wrapping std::fs::read yourself, with less code. On Linux, io_uring can do real asynchronous file I/O, and the later posts in this cluster cover runtimes built on it.
Finding the culprit
Blocking bugs rarely announce themselves. A service works in testing, then in production its latency graph grows spikes, and no single request is slow in isolation. Three clues point at blocking code. Timers fire late: a tokio::time::interval of one second that shows two-second gaps means the thread that should have run it was busy. Throughput collapses when concurrency rises, because every worker is stuck inside a slow call and new work queues behind it. And CPU stays low while latency is high, which is the signature of waiting rather than computing.
The remedy is to look at what each task does between awaits. Common offenders are std::fs reads, std::net sockets, synchronous database or HTTP clients, Mutex::lock on a standard mutex held by a slow thread, password hashing with bcrypt or Argon2, JSON parsing of very large documents and compression. The later post on finding tasks that block the executor shows how to confirm it with tooling instead of guessing.
Setting the pool size deliberately
You can bound the blocking pool when you build a runtime explicitly:
use tokio::runtime::Builder;
fn main() {
let rt = Builder::new_multi_thread()
.worker_threads(4)
.max_blocking_threads(32)
.enable_all()
.build()
.unwrap();
rt.block_on(async {
let n = tokio::task::spawn_blocking(|| 6 * 7).await.unwrap();
println!("n = {n}");
});
}n = 42A smaller blocking pool protects the machine from a burst of blocking calls that would otherwise spawn hundreds of threads, each with its own stack. A larger one lets more slow calls overlap. Choose based on what the blocking work does: a call that waits on a remote server costs only a parked thread, while a call that burns CPU competes with your async workers for cores.


