Async Rust
Async code lets a few threads serve thousands of requests that are mostly waiting. In Rust, an async function returns a future, and a future does nothing until someone awaits it. A runtime like Tokio polls the futures and wakes them when data is ready. To keep this fast, never block a worker thread, never hold a std Mutex guard across an await, and remember that a future can be dropped, and so cancelled, at any await.
Author: bezzad
Contents
The problem: thousands of requests that wait
On sale day, our shop API has 10,000 open requests. Most of them are not computing anything. They wait: for the database, for the payment provider, for the next bytes from a slow phone.
- One OS thread per request works, but each thread needs its own stack memory, and switching between thousands of threads costs CPU time.
- Async code splits the work into small tasks. When a task must wait, it gives the thread back, and the thread runs another task.
- The result: a handful of threads (often one per CPU core) can serve all 10,000 requests.
An async function returns a future
use std::time::Duration;
async fn fetch_price(sku: &str) -> u64 {
println!("fetching price for {sku}");
// stands for a database call
tokio::time::sleep(Duration::from_millis(50)).await;
4999
}
#[tokio::main]
async fn main() {
let price = fetch_price("shoe-42"); // nothing runs yet
println!("before await");
let cents = price.await; // now the body runs
println!("price: {cents}");
}
This prints “before await” first, and only then “fetching price”.
- Calling an async function does not run its body. It returns a future: a value that describes work that can be done later.
- Futures are lazy. Nothing happens until the future is awaited or polled. If you forget the await, the work never happens. The compiler warns you: “futures do nothing unless you .await or poll them”.
- The await keyword runs the future until it finishes. While it waits, the current task pauses, and the thread is free for other tasks.
How a future runs: poll and wake
A future is a state machine. The compiler turns your async function into it. Every await is a point where the state machine can stop and later go on.
- The runtime calls the poll method of the future.
- If the future cannot go on (the database has not answered yet), it returns Pending. Before that, it gives a waker to the thing it waits for.
- When the answer arrives, the waker tells the runtime: “this task can go on”.
- The runtime polls the future again. This time it goes on from the last await, and maybe returns Ready with the value.
So no thread sits and waits. A thread only works on tasks that can make progress right now.
A runtime: Tokio
The Rust standard library defines the Future trait, but it has no runtime. You choose one. Tokio is the most used runtime for servers.
- The tokio main attribute starts a runtime and runs your async main function on it.
- By default it is multi-threaded: one worker thread per CPU core. Tasks can move between worker threads.
- Tokio also gives timers, network sockets, channels, async locks and a pool of extra threads for blocking work.
Waiting for two things at once: join
The product page needs the price and the reviews. They do not depend on each other:
async fn fetch_reviews(sku: &str) -> Vec<String> {
tokio::time::sleep(Duration::from_millis(50)).await;
vec![format!("Great {sku}!")]
}
async fn product_page(sku: &str) -> (u64, Vec<String>) {
// Both run at the same time inside this one task:
// about 50 ms, not 100 ms.
tokio::join!(fetch_price(sku), fetch_reviews(sku))
}
Two awaits one after the other would take about 100 ms. The join macro polls both futures together, so the waiting overlaps. It all happens inside one task, so it is concurrent, but not in parallel on two cores.
Spawning tasks
For work that should run on its own, possibly on another core, use the spawn function of Tokio. It starts a new task and returns a JoinHandle:
use tokio::task::JoinSet;
async fn warm_price_cache(skus: Vec<String>) -> u64 {
let mut tasks = JoinSet::new();
for sku in skus {
// each one is a separate task
tasks.spawn(async move { fetch_price(&sku).await });
}
let mut total = 0;
while let Some(result) = tasks.join_next().await {
total += result.expect("price task panicked");
}
total
}
- Tasks are cheap. Starting one costs about as much as a small allocation, not like an OS thread.
- A spawned future must be Send and ’static. It may move to another worker thread, and it may live longer than the function that started it. So it must own its data. That is why the async block uses move and owns sku.
- Dropping a JoinHandle does not stop the task. The task keeps running in the background (it is detached). To stop it, call the abort method. A JoinSet aborts all its tasks when it is dropped.
- Awaiting the handle returns a Result. It is an Err if the task panicked or was aborted.
Never block a worker thread
A worker thread can only switch tasks at an await. If a task runs a long time without reaching an await, the thread is stuck, and every other task on it waits.
Typical blocking calls inside async code:
- The sleep function of the standard library (in the thread module). Use the sleep function of Tokio with await instead.
- CPU-heavy work like password hashing, making a PDF, or resizing images.
- Blocking I/O from the standard library, like the fs module, or a database driver that is not async.
The fix for CPU-heavy or blocking code is the spawn_blocking function. It runs the closure on a separate pool of threads made for blocking work:
fn hash_password(password: &str) -> String {
// stands for a slow, CPU-heavy hash like Argon2
format!("hashed:{}", password.len())
}
// Bad: the worker thread is stuck while hashing
async fn register_bad(password: String) -> String {
hash_password(&password)
}
// Good: the hashing runs on the blocking pool
async fn register(password: String) -> String {
tokio::task::spawn_blocking(move || hash_password(&password))
.await
.expect("hashing task panicked")
}
- The blocking pool has its own threads (up to 512 by default in Tokio), so the async workers stay free.
- Use it for work that takes long, not for every small function. Each call has a cost.
- A spawn_blocking task cannot be aborted once it has started. It runs to the end.
Never hold a std Mutex guard across an await
A std Mutex is fine in async code for short, synchronous changes. The danger is keeping the guard while the task waits:
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Default)]
struct AppState {
recently_viewed: Mutex<HashMap<u64, Vec<String>>>,
}
async fn log_view(user_id: u64, sku: &str) {
// stands for a network call
tokio::time::sleep(Duration::from_millis(5)).await;
println!("user {user_id} viewed {sku}");
}
async fn view_product(
state: Arc<AppState>,
user_id: u64,
sku: String,
) {
{
let mut viewed = state.recently_viewed.lock().unwrap();
viewed.entry(user_id).or_default().push(sku.clone());
} // the guard is dropped here, before any await
log_view(user_id, &sku).await;
}
fn start(state: Arc<AppState>) {
tokio::spawn(view_product(state, 1, "shoe-42".to_string()));
}
What goes wrong if the lock block is removed, so the guard lives across the await:
- The std MutexGuard is not Send. Then the whole future is not Send, and the spawn function of Tokio refuses it with the error “future cannot be sent between threads safely”.
- Where it does compile (for example on a single-thread runtime), the task pauses while holding the lock. Another task on the same thread tries to lock and blocks the thread. The first task can never run again to release the lock: a deadlock.
- Calling drop on the guard just before the await is not enough for the Send check today. The compiler still treats the guard as alive across the await. Use a block, as above, or move the locking code into a normal (not async) function.
If you really must hold a lock across an await, for example around one shared connection, use the Mutex of Tokio (in its sync module). Its lock method is async. It is slower, so the Tokio documentation recommends the std Mutex for plain data.
Cancellation: a future can stop at any await
Dropping a future cancels it. It stops at the await where it was waiting and never goes on. This happens more often than people think:
use tokio::time::timeout;
async fn price_or_cached(sku: &str, cached: u64) -> u64 {
match timeout(Duration::from_secs(2), fetch_price(sku)).await {
Ok(cents) => cents,
Err(_) => cached, // the fetch_price future was dropped
}
}
async fn serve_until_ctrl_c() {
tokio::select! {
cents = fetch_price("shoe-42") => println!("price: {cents}"),
_ = tokio::signal::ctrl_c() => println!("shutting down"),
}
}
- The timeout function drops the inner future when time is up.
- The select macro waits for the first branch to finish and drops all the others.
- A web framework drops the handler future when the client closes the connection.
So every await is a place where your function may end. Before you wrap code in a timeout or a select, ask: “Is it safe if this stops here?”
- Keep important multi-step work in its own spawned task. A spawned task is not cancelled when the caller stops waiting for it.
- Make steps idempotent, for example with an idempotency key for the payment, so a retry is safe.
- Check the documentation for “cancel safety” before you use a method inside select in a loop. For example, receiving from a Tokio mpsc channel is cancel safe: no message is lost.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| Calling an async function without await | Nothing happens (only a compiler warning). | Await it, or spawn it on purpose. |
| The standard sleep function in async code | The worker thread stops for everybody. | The sleep function of Tokio, with await. |
| CPU-heavy work directly in a handler | Other requests wait, latency jumps. | spawn_blocking, or a separate thread pool. |
| A std Mutex guard alive across an await | The future is not Send, or a deadlock. | Lock in a short block with no await inside. |
| The Tokio Mutex for every map | Slower code than needed. | The std Mutex for plain data. |
| Two awaits in a row for independent calls | Waiting time adds up. | The join macro, or a JoinSet. |
| A timeout around many steps that change data | Half-done work after a cancel. | A spawned task, idempotent steps, compensation. |
| Expecting a dropped JoinHandle to stop the task | The task keeps running. | Call abort, or use a JoinSet. |
Summary in 7 lines
- Async lets a few threads serve many requests that wait. Each await is a point where a task can pause.
- An async function returns a future, and futures are lazy: nothing runs until you await or poll them.
- A runtime such as Tokio polls futures and wakes them when data is ready. Rust has no built-in runtime.
- Use the join macro to wait for independent work together, and Tokio’s spawn function for separate tasks that must be Send and ’static.
- Never block a worker thread. Move CPU-heavy and blocking work to spawn_blocking.
- Never keep a std Mutex guard alive across an await. Lock in a short block.
- Dropping a future cancels it at its current await. Plan for it with spawned tasks and idempotent steps.