FAQ - Help and questions

Why does one slow handler stall my whole async web server, and what is spawn_blocking?

#tokio#spawn-blocking#async#performancepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

An async runtime has few threads, and a task that blocks one (thread::sleep, heavy computation, a blocking file or database call) stops other tasks sharing it. Move such work into tokio::task::spawn_blocking, which runs it on a separate thread pool, and await the result.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Async tasks share a small number of worker threads and give way to each other only at .await points. Code that never awaits keeps its thread busy. This program makes the effect visible by using a runtime with a single thread (flavor = "current_thread") and a second task that counts a tick every 10 ms:

rust
use std::{sync::{atomic::{AtomicU32, Ordering}, Arc}, time::Duration};

async fn ticks_while(work: impl std::future::Future<Output = ()>) -> u32 {
    let ticks = Arc::new(AtomicU32::new(0));
    let t = ticks.clone();
    let ticker = tokio::spawn(async move {
        loop {
            tokio::time::sleep(Duration::from_millis(10)).await;
            t.fetch_add(1, Ordering::SeqCst);
        }
    });
    tokio::task::yield_now().await;
    work.await;
    ticker.abort();
    ticks.load(Ordering::SeqCst)
}

// A runtime with a single thread makes the effect easy to see: one blocked task blocks them all.
#[tokio::main(flavor = "current_thread")]
async fn main() {
    let blocked = ticks_while(async {
        std::thread::sleep(Duration::from_millis(200)); // blocking call inside async code
    }).await;
    println!("ticks while the work blocked the runtime: {blocked}");

    let offloaded = ticks_while(async {
        tokio::task::spawn_blocking(|| std::thread::sleep(Duration::from_millis(200))).await.unwrap();
    }).await;
    println!("ticks while the work ran on spawn_blocking: more than 5 = {}", offloaded > 5);
}
text
ticks while the work blocked the runtime: 0
ticks while the work ran on spawn_blocking: more than 5 = true
  • With std::thread::sleep inside the async block the counter task got 0 ticks in 200 ms: the only thread was blocked.
  • With the same sleep inside spawn_blocking, the runtime kept running other tasks and more than 5 ticks happened.

A multi-threaded runtime (the default of #[tokio::main]) hides this better, because other threads keep working, but it degrades the same way once all worker threads are blocked.

In a handler the pattern is:

rust
let hash = tokio::task::spawn_blocking(move || expensive_hash(&password)).await.unwrap();

spawn_blocking returns a JoinHandle; awaiting it gives Result<T, JoinError>, where the error means the closure panicked. Handle it rather than unwrapping in production code.

Common mistakes#

  • Moving things into the closure by reference: it must own its data (move), because it runs on another thread.
  • Using spawn_blocking for work that is really async, such as a database call through an async driver.
  • Heavy computation on very many requests at once: the blocking pool has a limit too. Cap the concurrency (see the thread on queues).

What counts as blocking?#

Anything that holds the thread without awaiting: sleeping, reading a file with std::fs, a CPU-heavy loop such as password hashing (see the thread on argon2), a synchronous network or database call.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet