Async Rust
Asynchronous programming in Rust — futures as lazy state machines, async/await, polling and wakers, executors and the Tokio runtime, spawning tasks, select and join, Pin in brief, blocking pitfalls, and when to use async.
Threads are great for CPU work, but each OS thread costs memory and context switches. A server handling 100,000 mostly idle connections needs something lighter. Rust's answer is async/await: write sequential-looking code that suspends while waiting for I/O, multiplexed onto a few threads by a runtime.
Futures are lazy state machines
An async fn returns a future — a value representing a computation that will complete later. Unlike JavaScript promises, Rust futures are lazy: nothing happens until the future is polled (by .await or an executor).
async fn fetch_user(id: u64) -> User { /* ... */ }
let fut = fetch_user(1); // nothing runs yet
let user = fut.await; // now it runs (inside another async context)The compiler transforms each async fn into a state machine: an enum with one variant per .await point, holding the local variables live across that point. No heap allocation per call, no garbage collector — zero-cost async.
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
// Poll::Ready(value) — finished; Poll::Pending — not yet, I'll wake youPolling and wakers
The executor never busy-waits: a future that returns Pending has arranged for its waker to be called when progress is possible; only then is it polled again.
The runtime: Tokio
The standard library defines Future but ships no executor. You choose a runtime; Tokio is the de facto standard (alternatives: smol, async-std, embassy for embedded). Tokio provides a multi-threaded work-stealing scheduler, an I/O reactor (epoll/kqueue/IOCP), timers, async TCP/UDP/files, channels and synchronisation primitives.
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main] // starts the runtime
async fn main() -> anyhow::Result<()> {
let listener = TcpListener::bind("0.0.0.0:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move { // a lightweight task per connection
let mut buf = [0u8; 1024];
while let Ok(n) = socket.read(&mut buf).await {
if n == 0 { break; }
let _ = socket.write_all(&buf[..n]).await; // echo
}
});
}
}A Tokio task is a few hundred bytes; hundreds of thousands are normal. Spawned futures must be Send + 'static on the multi-threaded runtime (they may move between worker threads).
Concurrency inside a task: join and select
.await in sequence runs things one after another. To run several futures concurrently:
// Run both concurrently, wait for both
let (user, orders) = tokio::join!(fetch_user(id), fetch_orders(id));
// Fallible version: stops at the first error
let (user, orders) = tokio::try_join!(fetch_user(id), fetch_orders(id))?;
// Race: whichever finishes first; the other is DROPPED (cancelled)
tokio::select! {
res = fetch_from_primary() => handle(res),
res = fetch_from_replica() => handle(res),
_ = tokio::time::sleep(Duration::from_secs(2)) => println!("timeout"),
}
// Or wrap anything in a timeout
let user = tokio::time::timeout(Duration::from_secs(2), fetch_user(id)).await??;
// Many dynamic tasks
let mut set = tokio::task::JoinSet::new();
for url in urls { set.spawn(fetch(url)); }
while let Some(res) = set.join_next().await { println!("{:?}", res); }Cancellation in Rust async is simply dropping the future: it stops at its current .await point and never resumes. Code between awaits must leave state consistent ("cancellation safety"), which matters inside select! loops.
Pin, briefly
The state machine generated for an async fn can contain references to its own fields (a local variable borrowed across an .await). Moving such a struct in memory would invalidate those internal pointers. Pin<&mut T> is a guarantee that the value won't be moved again, which is why poll takes Pin<&mut Self>. Day-to-day you meet it only when storing futures (Box::pin(fut)) or writing low-level code; .await handles it for you.
Don't block the executor
The same rule as JavaScript and Python's asyncio (The event loop): a task that blocks a worker thread stalls every task scheduled on it.
async fn bad() {
std::thread::sleep(Duration::from_secs(1)); // ✗ blocks the worker thread
let data = std::fs::read("big.bin").unwrap(); // ✗ blocking I/O
let hash = expensive_cpu_work(&data); // ✗ long CPU work
}
async fn good() -> anyhow::Result<()> {
tokio::time::sleep(Duration::from_secs(1)).await; // ✓
let data = tokio::fs::read("big.bin").await?; // ✓
let hash = tokio::task::spawn_blocking(move || expensive_cpu_work(&data)).await?; // ✓ separate pool
Ok(())
}Holding a std::sync::Mutex guard across an .await is also a common bug (and makes the future non-Send); use tokio::sync::Mutex if you must hold a lock across awaits, or restructure so you don't.
The ecosystem
| Need | Crate |
|---|---|
| Runtime | tokio |
| HTTP server | axum, actix-web, hyper |
| HTTP client | reqwest |
| gRPC | tonic |
| Databases | sqlx, tokio-postgres, sea-orm |
| Utilities | futures (combinators, streams), tokio-util, tower (middleware) |
| Tracing | tracing + tracing-subscriber |
// A minimal axum endpoint
use axum::{routing::get, Router, extract::Path, Json};
async fn get_user(Path(id): Path<u64>) -> Json<User> {
Json(load_user(id).await)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{id}", get(get_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}When to use async
| Use async | Use threads / Rayon |
|---|---|
| Network servers and clients with many concurrent connections | CPU-bound computation |
| Lots of waiting on I/O, timers, external services | A handful of concurrent tasks |
| Embedded systems without an OS (embassy) | Simplicity matters more than scale |
Async adds complexity: "function colouring" (async spreads to callers), harder-to-read compiler errors, and choosing a runtime. Don't adopt it for a CLI tool that makes three HTTP calls — a blocking client is fine.
- async fn returns a lazy future, compiled into a state machine with no per-call allocation.
- Futures make progress only when polled; wakers tell the executor when to poll again.
- Rust has no built-in runtime; Tokio provides the scheduler, reactor, timers and async I/O.
- tokio::spawn for tasks; join!/try_join! for concurrency; select! and timeout for races; dropping a future cancels it.
- Never block the executor: use async APIs and spawn_blocking.
- Use async for high-concurrency I/O; threads or Rayon for CPU work.