Async Rust, explained as a restaurant kitchen
Async Rust starts to make sense when you picture a restaurant kitchen.
The tickets
- Future: an order in the waiter’s notepad. It only describes the meal. Nothing cooks until it reaches the kitchen, which is what “futures are lazy” means.
.await: the courses on one ticket, starter then main. They stay on the same ticket.tokio::spawn: hanging the ticket on the order rail. Now it’s a task. The waiter keeps a stub (theJoinHandle) to collect the dish later.
The kitchen
- Worker threads are the chefs, roughly one per CPU core. A chef with nothing to do takes tickets from a busy colleague’s rail. That’s work stealing.
- Poll: a chef takes a ticket and does everything that can be done right now.
- Ready: the dish is plated.
- Pending: it’s in the oven. The chef notes how far they got, tapes the ticket to the oven door and takes the next one from the rail.
- Waker: the taped ticket. It points back to the exact order the kitchen needs to return to.
- Reactor: the kitchen porter listening for the oven timer and the back-door bell. In real life, that’s the operating system saying a socket or timer is ready.
If the chef forgets to tape the ticket to the oven, nobody sees it again. There’s no error, just a table that never gets fed.
Where it hurts
After the oven, any free chef can pick up the ticket, not necessarily the one who started it. That leads to two classic problems:
- “Future is not
Send”: you’ve taped a key that only works for chef one (anRc, or a standardMutexGuardheld across.await) to a ticket chef three might pick up. - Blocking: a chef who stands staring at the oven (
thread::sleep, a synchronous database call, heavy maths) leaves everything on their rail waiting. Send long jobs to the prep room withspawn_blocking.
A one-chef kitchen (the current_thread runtime) avoids the handover rules, but you lose parallelism.
Why channels help
Lots of chefs reaching for one shared pan is Arc<Mutex<T>>: contention, and locks held while dishes are in the oven. Instead, give one chef the sauce station and let the others send requests through the pass, an mpsc channel. If they need an answer, they send a return plate with the request, a oneshot channel.
- One owner, so the borrow checker stops fighting you
- No locks held across
.await - Bounded channels give you backpressure for free
- Drop every sender and the station shuts down cleanly
Async Rust doesn’t hide the kitchen from you. Once you can see it, the compiler errors start to make sense.