skip to content

In a Rust async handler, why does a blocking compression call or `std::thread::sleep` stall other tasks, and how do you offload it?

level: middleimportance: must knowfreq 66%

answer

  1. cooperative, not preemptive
  2. yields only at a Pending .await
  3. the thread is held, not the task
  4. a separate pool for blocking work

basics

~20 s

A Rust task yields its thread only when an .await returns Pending, so a blocking call holds the executor thread and other tasks on it wait. Move the call to a thread pool, for example smol::unblock, and await the result.

solid answer

~50 s

Rust executors are cooperative: when an executor polls a task, the code runs synchronously until it reaches an `.await` that returns `Poll::Pending`, and only then can the thread poll anything else. A blocking compression call, `std::fs::read` on a slow disk, `std::thread::sleep` or a long CPU loop has no `.await` inside, so it keeps the executor thread for its whole duration and every other task on that thread waits; on a single-threaded executor that is every task. rustc does not warn about it, because a blocking call is ordinary safe code. The fix is to move the work off the executor threads: `smol::unblock(move || compress(&buf)).await` (or `blocking::unblock`) runs the closure on a separate thread pool and gives back a future. CPU-heavy batches belong on a pool sized to the cores, and Tokio offers its own `spawn_blocking` for the same job.

code

rust · 27 lines
rust
use std::time::{Duration, Instant};

// Stands in for a blocking compression call from a synchronous library.
fn compress_blocking(input: &[u8]) -> usize {
    std::thread::sleep(Duration::from_millis(200));
    input.len() / 2
}

async fn handler_blocking(id: u8) -> usize {
    compress_blocking(&[id; 64]) // no .await: this thread is stuck for 200 ms
}

async fn handler_offloaded(id: u8) -> usize {
    smol::unblock(move || compress_blocking(&[id; 64])).await
}

fn main() {
    smol::block_on(async {
        let t = Instant::now();
        let (a, b) = futures::join!(handler_blocking(1), handler_blocking(2));
        println!("blocking:  {a} {b} in ~{} ms", t.elapsed().as_millis() / 100 * 100);

        let t = Instant::now();
        let (a, b) = futures::join!(handler_offloaded(1), handler_offloaded(2));
        println!("offloaded: {a} {b} in ~{} ms", t.elapsed().as_millis() / 100 * 100);
    });
}

go deeper

for a junior

Recall that an async task gives up its thread only at an .await that is not ready, so std::thread::sleep or a slow synchronous call freezes other tasks.

for a middle

Explain cooperative polling, why join! on two blocking handlers takes the sum of their times, and how smol::unblock moves a closure to a separate pool.

for a senior

Spot hidden blocking in review (std::fs, std::sync locks, CPU loops), separate blocking-I/O pools from CPU pools, and use clippy's disallowed_methods to keep known offenders out.

for a principal

Own the policy: which crates may run on executor threads, how big blocking pools may grow, and how the team detects a regression before latency does.

## Cooperative scheduling: where a Rust task can stop A Rust **task** is a top-level future that an executor polls. Polling is an ordinary function call: the executor calls `poll`, the generated state machine runs the code of the `async fn` from where it last stopped, and it returns only when it either finishes (`Poll::Ready`) or reaches an `.await` on a future that is not ready (`Poll::Pending`). Between two such points the code is plain synchronous Rust. Nothing in the language or in a typical executor can interrupt it, so scheduling is **cooperative**: each task decides when to yield by reaching a pending `.await`. That model is efficient precisely because yields are cheap and explicit. It also means one piece of code that never yields can hold the thread hostage. ## What counts as blocking Anything that keeps the thread busy or asleep without returning `Pending`: - **blocking system calls**: `std::fs::read`, `std::net::TcpStream::read`, a DNS lookup through `std::net::ToSocketAddrs`; - **synchronous libraries**: a compression, image or database client crate whose API is a plain `fn` that waits on I/O or computes for a long time; - **sleeping**: `std::thread::sleep` puts the whole thread to sleep, unlike a runtime timer future; - **CPU-heavy loops**: hashing a large buffer or parsing megabytes of input; no system call is involved, yet the thread is just as unavailable; - **waiting on a `std::sync` primitive**: a contended `Mutex::lock` or a `Receiver::recv` from `std::sync::mpsc` blocks the thread. ## What it does to the other tasks The snippet in this question's code examples runs two handlers concurrently with `futures::join!` under `smol::block_on`. Each handler calls a function that sleeps 200 ms to stand in for a blocking compression call. Joined, they take about **400 ms**, not 200 ms: `join!` interleaves its futures on one thread, and neither handler ever returns `Pending`, so the second cannot start until the first finishes. On a server the symptoms are the same at a larger scale: 1. every task scheduled on the blocked worker thread stops making progress; 2. I/O readiness and timer events pile up, so unrelated requests see latency spikes; 3. with a single-threaded executor, the whole program freezes for the duration of the call. A multi-threaded executor softens this, but each blocking call still removes one worker for as long as it runs, and enough concurrent ones exhaust the pool. ## Why the compiler does not catch it A blocking call is safe, well-typed code, so rustc has nothing to reject, and neither rustc nor clippy's default lints look for it. Clippy can help only if you configure it: listing `std::thread::sleep` or a library's blocking entry points under `disallowed-methods` in `clippy.toml` makes `clippy::disallowed_methods` warn on every call. That list applies to the whole crate, not just async code, so teams usually scope it to the crates that run on an executor. ## How to offload | work | where it should run | Rust tool | |---|---|---| | a blocking I/O call or a synchronous library call | a separate pool of threads that may block | `smol::unblock` / `blocking::unblock`; Tokio's `spawn_blocking` | | one long-lived blocking loop | its own thread | `std::thread::spawn` plus a channel back to async code | | CPU-heavy batches | a pool sized to the number of cores | a dedicated compute pool such as Rayon's, with the result sent back | | waiting for time to pass | stay on the executor | a timer future such as `smol::Timer::after` instead of `std::thread::sleep` | `smol::unblock` is a re-export of `blocking::unblock`, whose signature is `fn unblock<T, F>(f: F) -> Task<T> where F: FnOnce() -> T + Send + 'static, T: Send + 'static`. The closure runs on the blocking crate's pool, which grows on demand up to a default of **500 threads** (adjustable with the `BLOCKING_MAX_THREADS` environment variable), and the returned `Task<T>` is a future the handler awaits. Because the closure may run on another thread after the handler has moved on, it must own its data: move the input buffer in, rather than borrowing it. Offloading frees the executor thread, but it does not make the work cheaper. A pool of blocking threads still needs a bound, and many CPU-bound jobs sent to a pool that can grow to 500 threads oversubscribe the cores; that is why CPU work goes to a pool sized to the hardware.

  • Does wrapping the blocking call in an `async` block, as in `async { compress(&buf) }.await`, solve the problem?
    No. An `async` block only creates a future; when it is polled, `compress` still runs synchronously on the executor thread with no `.await` inside it to yield at. Making code async changes when it runs, not where. Only handing it to another thread, as `smol::unblock` does, frees the executor.
  • A handler hashes a 50 MB upload in a tight loop with no I/O. Is that blocking, and where should it run?
    Yes: a CPU-bound loop holds the executor thread as surely as a blocking system call, because it never reaches a pending `.await`. Send it to a compute pool sized to the number of cores and await the result through a channel or task handle; a large blocking-I/O pool is the wrong home because many such jobs at once could oversubscribe the CPUs.
  • Why must the closure passed to `smol::unblock` be `Send + 'static`?
    Because it runs on a different thread from a shared pool and may outlive the stack frame of the handler that created it. `Send` lets it cross to that thread, and `'static` rules out borrowed references to the handler's locals, so you move owned data in, for example the buffer to compress.

One cook working several orders moves to another dish whenever one is in the oven, which is an .await that is not ready yet. If the cook stops to hand-whisk for ten minutes, a blocking call, every other order waits; offloading hands the whisking to a prep cook and checks back when it is done.

  • Believing an async fn yields automatically when it calls a slow function.
  • Thinking rustc or clippy warns about thread::sleep in async code by default.
  • Wrapping a blocking call in an async block and calling it non-blocking.
  • Saying CPU-bound loops are safe because they do not do I/O.
  • Expecting join! to run two blocking handlers in parallel on one thread.