Skip to content

Lesson 1 of 9 · 24m

Async Rust Is Not Colored Threads

Build the correct mental model: futures are inert state machines, tasks are runtime-scheduled units, and awaiting is cooperative suspension.

The worst async Rust outages I have debugged were caused by people treating async as a cheaper kind of thread. It is not. An async function is a compiler-generated state machine that does nothing until something polls it. Tokio does not magically make code concurrent; it gives you a scheduler that can interleave many state machines on a small number of OS threads.

A future is inert until polled

This looks like it starts work immediately:

let fut = fetch_user(42);
println!("created");
let user = fut.await?;

It does not. fetch_user(42) only creates a future. No socket is opened, no timer is armed, and no code inside the async block runs until the executor polls it. That distinction matters when you build vectors of futures, store them in structs, or accidentally create them and drop them.

Await points are suspension points

.await is where a future may yield control back to the runtime. Between await points, your code runs synchronously on a worker thread:

async fn handler() {
    let input = read_body().await;       // may yield here
    let transformed = expensive_cpu(input); // blocks the worker until done
    write_response(transformed).await;   // may yield here
}

If expensive_cpu takes 200 milliseconds, it occupies one Tokio worker for 200 milliseconds. With the default multi-thread runtime, that can be a large fraction of your total scheduling capacity. Async does not make CPU-bound work parallel; it makes IO-bound waiting cheap.

Tasks are the unit of concurrency

A future passed to tokio::spawn becomes a task. The runtime can then poll it independently:

let handle = tokio::spawn(async move {
    process_job(job).await
});

let report = handle.await?;

spawn requires a future that is Send + 'static on the normal multi-thread runtime. In practice this means owned or shared data must move into the task; you cannot casually borrow stack values from the caller. The compiler is protecting you from a task outliving the memory it references.

Cooperative scheduling changes your failure modes

Threads are preempted by the operating system. Tasks are not preempted while they are executing synchronous code. A bad loop can starve other tasks:

async fn bad() {
    loop {
        recompute_index_shard(); // no await: never yields
    }
}

The fix is either to move CPU-heavy work to tokio::task::spawn_blocking, introduce explicit tokio::task::yield_now().await, or redesign the job so it is bounded.

Field notes

  • Every .await is a potential cancellation and reordering point.
  • CPU work inside async handlers is worker-thread theft, even when individual requests look fine.

Was this lesson helpful?

Sign in to rate