Async
A server holding ten thousand connections spends almost all its time waiting: for a database reply, for the next packet, for a timer. A thread per connection means ten thousand stacks and constant switching in the OS kernel. Async code waits differently: an operation that cannot continue gives control back, and the same thread does other work until the event arrives.
In Rust this is built on the Future trait — a value you can poll with the poll method: ready or not yet. async fn and .await let you write ordinary sequential code, and the compiler turns it into a state machine that implements Future. Unlike a Promise in JavaScript, a Future is lazy: until it is polled, nothing happens. It is polled by a runtime — the standard library has none, and it is almost always Tokio.
The price of the model is new concepts and new traps. The state machine can refer to its own fields, so it is pinned in memory with Pin. A task yields its thread only at .await, so a blocking call or a MutexGuard living across an .await slows down its neighbours. And cancellation is simply dropping a Future, which loses data in select! if a branch is not cancellation safe. The topic covers async layer by layer — from the Future trait to select!.
Topic map
- Futures and Polling — the
Futuretrait and thepollmethod,Poll::ReadyandPoll::Pending;Wakerand the "store it and wake" contract; an executor onstdwithWakeandthread::park; aFutureis lazy, unlike aPromise. - async and await —
async fnreturnsimpl Future;.awaitis a suspension point of the state machine; a forgotten.awaitand E0728; the size of aFuture;async fnin traits, E0038 fordynandPin<Box<dyn Future>>. - Async Runtimes — the executor, the reactor and timers; a task versus
.await; a toy executor on a channel; Tokio and#[tokio::main];tokio::spawnandSend + 'static; why runtimes cannot be mixed; tasks versus threads. - Pin and Unpin — self-reference inside a
Futureafter.await;Pinpromises the value will not move; theUnpinauto trait;pin!on the stack andBox::pinon the heap; polling through&mutand projection withpin-project. - Async Pitfalls — a blocking call holds the worker thread;
spawn_blockingand async counterparts; aMutexGuardacross.awaitmakes theFuturenotSend;dropdoes not help, a block does; recursion and E0733. - Async Concurrency —
.awaitcalls in a row run one after another;join!interleaves inside one task,spawngives parallelism;JoinHandleandabort;select!, cancellation as dropping, and cancellation safety.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Calling an async fn without .await | The body never runs; only warning: unused implementer of `Future` that must be used |
Calling std::thread::sleep, std::fs::read or a long loop inside a task | The worker thread is fully occupied and neighbouring tasks stall; you need async counterparts or spawn_blocking |
Holding a std::sync::Mutex guard across .await | error: future cannot be sent between threads safely for tokio::spawn, and a deadlock in a single-threaded runtime |
Polling an async block through &mut without pinning | error[E0277]: `&mut {async block@…}` is not a future — you need pin! or Box::pin |
Declaring an async fn in a trait that you need as dyn | error[E0038]: the trait `Store` is not dyn compatible — the method has to return Pin<Box<dyn Future>> |
Writing .await calls in a row instead of join! | The requests run one after another and the latencies add up |
Putting a future that is not cancellation safe into a select! branch in a loop | Partially read data is lost when another branch wins |
Why it matters in interviews
Async is a mandatory topic for backend and networking Rust positions: almost all server code is written on Tokio. At middle level interviewers check the polling model, laziness and working with spawn and join!; at senior level — Pin, Send requirements, blocking and cancellation in select!.
What interviewers usually check:
- How
Futureandpollwork, who polls aFutureand when, and whyWakerexists. - What the compiler turns an
async fninto and how a RustFuturediffers from a JavaScriptPromise. - Why you need a runtime like Tokio and why
tokio::spawnrequiresSend + 'static. - What
PinandUnpinare and when you have to think about them. - What happens if you call blocking code or hold a
MutexGuardacross.await. - How
join!differs fromspawnand howselect!can lose data.