Module 18 — Async Rust
Goal
async/await, futures as state machines, the Tokio runtime, and the difference between concurrency and parallelism in practice.
Start here — what this module is really about
Async is about waiting efficiently, and understanding that framing prevents the single biggest misconception: async is not a faster way to compute.
Think about what your program actually does when it fetches a URL, reads a file or queries a database. It sends a request and then does nothing at all for milliseconds — an eternity — while the network or disk responds. A thread that is waiting is a thread doing no work while still holding memory.
Two ways to handle a hundred such waits at once:
- A hundred threads. Each one waits. It works, and each thread costs memory and scheduling overhead.
- One thread that never waits. Whenever a task would block, it puts that task aside and picks up another. When the response arrives, it comes back. That is async.
The result: async is a large win for I/O-bound work (network services, file processing, anything talking to the outside world) and no help at all for CPU-bound work (compression, image processing, computation) — for that, you want threads or rayon from module 17.
Rust's take has two distinctive features:
async fnreturns a value, and does nothing until awaited. Calling one does not start any work; it hands you aFuture, a description of work that can be done. Unlike a JavaScript promise, nothing runs until you.awaitit or hand it to a runtime. An un-awaited future is not a background task — it is a dropped piece of paper.- Rust ships no runtime. The language provides
async/await; the machinery that actually drives futures is a library you choose. Tokio is the default answer, and what this module uses.
The one sentence to remember: async lets one thread serve many waiting tasks — and a future does nothing at all until something awaits it.
Learning objectives
- Distinguish concurrency from parallelism, and I/O-bound from CPU-bound work
- Write
async fnand use.await - Explain what a
Futureis and why async Rust needs a runtime - Use Tokio: tasks,
join!,select!, channels, timeouts - Avoid the classic async pitfalls (blocking the executor, holding locks across
.await)
18.1 When async is the right tool
| Workload | Use |
|---|---|
| CPU-bound (image processing, simulation, parsing gigabytes) | threads / rayon |
| I/O-bound (HTTP requests, database queries, file reads, sockets) | async |
| Tens of thousands of concurrent connections | async |
| A handful of long-running workers | threads |
The distinction: a thread blocked on I/O still costs ~8 KB of stack and a kernel context switch. An async task waiting on I/O costs a few hundred bytes and no kernel involvement. Ten thousand concurrent HTTP requests is trivial for async and painful for threads.
Concurrency is dealing with many things at once (interleaved). Parallelism is doing many things at once (simultaneously, on multiple cores). Async gives you concurrency; whether you also get parallelism depends on the runtime's thread count.
Analogy — the waiter versus the extra kitchen
Threads are hiring more cooks: genuinely more work happening at once, and worth it when the work is chopping. Async is one good waiter serving twenty tables — the moment a table is waiting on the kitchen, they are taking someone else's order. Hiring cooks to stand and wait for the oven is the mistake async fixes; async will not chop your vegetables any faster.
18.2 async and .await
async fn fetch_data(id: u32) -> String {
// pretend this is a network call
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
format!("data for {id}")
}
#[tokio::main]
async fn main() {
let result = fetch_data(1).await;
println!("{result}");
}Two facts that explain most async confusion:
-
async fnreturns aFuture; calling it does nothing.rustlet fut = fetch_data(1); // no work has happened let data = fut.await; // NOW it runsFutures are lazy, like iterators. In JavaScript, calling an
asyncfunction starts it immediately; in Rust it does not. -
.awaityields control, it doesn't block. While this task waits, the runtime runs other tasks on the same thread.
async fn main_flow() {
// Sequential: 300ms total
let a = fetch_data(1).await;
let b = fetch_data(2).await;
let c = fetch_data(3).await;
// Concurrent: ~100ms total
let (a, b, c) = tokio::join!(fetch_data(1), fetch_data(2), fetch_data(3));
}If your async code isn't faster than sequential code, you probably .awaited each future
immediately instead of joining them. This is the single most common async mistake.
async and .await, and what they actually do
async fn fetch_user(id: u32) -> User {
let response = http_get(&format!("/users/{id}")).await; // pause here
parse_user(response)
}
#[tokio::main] // sets up the runtime for main
async fn main() {
let user = fetch_user(1).await; // nothing happens without this
println!("{}", user.name);
}Reading it precisely:
async fnchanges the return type.fetch_userlooks like it returns aUser; it actually returnsimpl Future<Output = User>. That is why calling it without.awaitgives you unused implementer of Future that must be used..awaitmeans "pause here and let the runtime do something else". It is not blocking. The thread is released to run other tasks and comes back when this one can continue..awaitis only legal inside anasyncfunction. That is whymainneeds#[tokio::main]— the attribute rewrites it into a normalmainthat starts a runtime and runs your async body inside it.
And the payoff, which is the reason to bother:
// Sequential: 200ms total — the second starts after the first finishes
let a = fetch_user(1).await;
let b = fetch_user(2).await;
// Concurrent: ~100ms — both in flight, one thread
let (a, b) = tokio::join!(fetch_user(1), fetch_user(2));Note what did not happen: no extra threads. One thread, interleaving two waits. That is the entire value proposition.
18.3 What a Future is
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
pub enum Poll<T> { Ready(T), Pending }The compiler transforms each async fn into a state machine — a struct with one
variant per .await point, storing exactly the local variables that must survive across
that point. When polled, it advances until something returns Pending, then returns
Pending itself, after registering a waker so the runtime knows when to poll again.
Consequences worth knowing:
- Async has no allocation and no runtime cost for the state machine itself; it's a struct on the stack.
- The state machine is why
Pinexists (self-referential structs must not move). - Rust ships no runtime. You choose one:
tokio(dominant, batteries-included),async-std,smol(minimal),embassy(embedded).
Analogy — the ticket you have to hand back in
An async fn does not start work when you call it. It hands you a ticket describing work that could be done — and unlike a promise in JavaScript, nobody is doing anything until you present the ticket at the counter with .await or hand it to the runtime. That is why an un-awaited future is not a background task, it is a piece of paper you dropped.
18.4 Tokio essentials
[dependencies]
tokio = { version = "1", features = ["full"] }Tasks
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
expensive_io().await;
42
});
let value = handle.await.unwrap(); // JoinHandle is itself a Future
println!("{value}");
}tokio::spawn requires the future to be Send + 'static — same reasoning as
thread::spawn.
Running many tasks
let mut handles = vec![];
for id in 0..100 {
handles.push(tokio::spawn(fetch_data(id)));
}
for h in handles {
println!("{}", h.await.unwrap());
}
// or, with the futures crate:
use futures::future::join_all;
let results = join_all((0..100).map(fetch_data)).await;select! — race several futures
use tokio::time::{sleep, Duration};
tokio::select! {
result = fetch_data(1) => println!("got {result}"),
_ = sleep(Duration::from_secs(1)) => println!("timed out"),
}The losing branches are cancelled — dropped mid-execution. This is why async Rust cares about cancellation safety: a future that has done half a state mutation and gets dropped must leave things consistent.
Timeouts
use tokio::time::{timeout, Duration};
match timeout(Duration::from_secs(2), fetch_data(1)).await {
Ok(data) => println!("{data}"),
Err(_) => println!("timed out"),
}Async channels
use tokio::sync::mpsc;
let (tx, mut rx) = mpsc::channel::<String>(32); // bounded, gives backpressure
tokio::spawn(async move {
for i in 0..5 {
tx.send(format!("msg {i}")).await.unwrap();
}
});
while let Some(msg) = rx.recv().await {
println!("{msg}");
}Tokio also provides oneshot (one value, one time), broadcast (many receivers each get
every message), and watch (latest-value only).
Async mutex
use tokio::sync::Mutex;
use std::sync::Arc;
let data = Arc::new(Mutex::new(0));
let d = Arc::clone(&data);
tokio::spawn(async move {
let mut guard = d.lock().await; // .await, doesn't block the thread
*guard += 1;
});Note
Use std::sync::Mutex for short, non-async critical sections — it's faster. Use
tokio::sync::Mutex only when you must hold the lock across an .await.
18.5 The four classic pitfalls
1. Blocking the executor
// ❌ freezes every task on this thread
async fn bad() {
std::thread::sleep(Duration::from_secs(1));
let data = std::fs::read_to_string("big.txt").unwrap();
}
// ✅
async fn good() {
tokio::time::sleep(Duration::from_secs(1)).await;
let data = tokio::fs::read_to_string("big.txt").await.unwrap();
}
// ✅ for genuinely CPU-heavy work
async fn cpu_heavy() {
let result = tokio::task::spawn_blocking(|| {
expensive_computation() // runs on a dedicated blocking pool
}).await.unwrap();
}Any synchronous call that takes more than ~100µs — file I/O, a blocking database driver,
heavy computation — must go through spawn_blocking.
2. Holding a std lock across an .await
// ❌ the guard is not Send; also risks deadlock
let guard = std_mutex.lock().unwrap();
something_async().await;
drop(guard);
// ✅ release before awaiting
let value = { *std_mutex.lock().unwrap() };
something_async().await;3. Sequential awaits where you wanted concurrency
Covered above — use join!, try_join!, or join_all.
4. Async in traits
Historically painful; since Rust 1.75 you can write:
trait Fetcher {
async fn fetch(&self, url: &str) -> String;
}but this is not object-safe. For dyn compatibility, use the async-trait crate, which
desugars to Box<dyn Future>:
#[async_trait::async_trait]
trait Fetcher {
async fn fetch(&self, url: &str) -> String;
}The four ways people break async, and how to spot them
Every async performance mystery is one of these. They share a signature: nothing crashes, everything just goes quiet.
1. Blocking inside an async task. A synchronous file read, a std::thread::sleep, or a heavy computation stops the whole thread — including every other task it was serving.
// ❌ blocks the runtime thread and every task on it
std::thread::sleep(Duration::from_secs(1));
// ✅ yields to the runtime
tokio::time::sleep(Duration::from_secs(1)).await;
// ✅ for genuinely CPU-heavy work
tokio::task::spawn_blocking(|| expensive_computation()).await;2. Holding a lock across an .await. The task pauses while holding the lock; every other task needing it stops too, and a deadlock is one step away. Take the value out, drop the guard, then await.
3. Forgetting to await. No warning that matters, no work done. If a future is not awaited or spawned, it never runs.
4. Sequential awaits that could have been concurrent. Two independent requests awaited one after the other take twice as long for no reason. tokio::join! is the fix, and it is free.
The diagnostic habit: when an async service is inexplicably slow, do not start by profiling the algorithm. Look for where a task sat down and stopped serving the room — a blocking call, or a lock held too long.
Analogy — the waiter who sat down
Every classic async bug is the same scene: your one waiter sat down at a table and stopped serving the room. A blocking call inside an async task, a lock held across an .await, a heavy computation with no yield — the restaurant does not crash, it just quietly stops moving while one table gets attention. When an async service goes mysteriously slow, look for where the waiter sat down.
18.6 A realistic example
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[derive(Debug)]
struct Response { url: String, status: u16, ms: u128 }
async fn fetch(url: &str) -> Result<Response, String> {
let start = std::time::Instant::now();
sleep(Duration::from_millis(50 + (url.len() as u64 * 10))).await; // simulated
if url.contains("bad") {
return Err(format!("failed to fetch {url}"));
}
Ok(Response { url: url.to_string(), status: 200, ms: start.elapsed().as_millis() })
}
async fn fetch_with_retry(url: &str, attempts: u32) -> Result<Response, String> {
let mut last_err = String::new();
for attempt in 1..=attempts {
match timeout(Duration::from_millis(500), fetch(url)).await {
Ok(Ok(resp)) => return Ok(resp),
Ok(Err(e)) => last_err = e,
Err(_) => last_err = format!("timeout on {url}"),
}
sleep(Duration::from_millis(100 * attempt as u64)).await; // backoff
}
Err(last_err)
}
#[tokio::main]
async fn main() {
let urls = vec!["a.com", "bb.com", "bad.com", "cccc.com"];
let handles: Vec<_> = urls
.into_iter()
.map(|u| tokio::spawn(async move { fetch_with_retry(u, 3).await }))
.collect();
for h in handles {
match h.await.unwrap() {
Ok(r) => println!("✓ {} ({}ms)", r.url, r.ms),
Err(e) => println!("✗ {e}"),
}
}
}All four requests run concurrently, each with its own timeout and exponential backoff, on a single thread if you like — and none of it can data-race.
Jargon buster
Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.
| Term | In plain English |
|---|---|
| async | Concurrency by pausing tasks that are waiting, rather than by adding threads. |
Future | A value representing work that can be done later. Does nothing until polled. |
.await | Pause this task until the future is ready, letting other tasks run. |
| runtime / executor | The library that drives futures to completion. Tokio is the common choice. |
#[tokio::main] | Attribute that starts a runtime and runs your async main on it. |
| task | A future handed to the runtime with spawn — async's unit of concurrency. |
| poll | The runtime asking a future "are you ready?". Returns Ready or Pending. |
| waker | The callback telling the runtime a paused future is worth polling again. |
Pin | A guarantee that a value will not move in memory — needed because futures are self-referential. |
| I/O-bound | Work dominated by waiting. Async helps a lot. |
| CPU-bound | Work dominated by computing. Async does not help; use threads. |
spawn_blocking | Move blocking work to a separate thread pool so it cannot stall the runtime. |
join! / select! | Await several futures together — all of them, or the first to finish. |
If you get stuck
The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.
| What you see | What it means | What to do |
|---|---|---|
warning: unused implementer of Future that must be used | You called an async fn and never awaited it. | Add .await, or tokio::spawn it if you want it to run in the background. |
error: await is only allowed inside async functions | .await in a sync function. | Make the function async, or use the runtime's block_on. |
error[E0277]: future cannot be sent between threads safely | Something non-Send (like Rc) is held across an .await. | Use Arc, or restructure so the value is dropped before the await. |
| The service is slow but the CPU is idle | Something is blocking the runtime thread. | Look for synchronous I/O, std::thread::sleep, or a lock held across an await. |
Cannot start a runtime from within a runtime | Nested block_on. | You are already async here — just .await it. |
| Everything hangs after a while | A lock held across an .await, or tasks waiting on each other. | Shorten lock scopes; never hold a guard across an await point. |
Now make it stick: work through the drills for this module, then carry on to Module 19 — Macros, Unsafe & FFI.
