Async Rust
Futures and polling, `async`/`.await`, runtimes such as Tokio, `Pin`, cancellation, and blocking inside async code.
15 questions
JuniorTheoryCommonYou call an async fn but never .await its result — what runs, and what does rustc say?
You call an async fn but never .await its result — what runs, and what does rustc say?
Nothing in the body runs: the call only builds a lazy Future holding the arguments, which is dropped unpolled. rustc warns unused implementer of `Future` that must be used, noting that futures do nothing unless awaited or polled.
Common mistakes
- ✗Expecting the body to start running at the call, as a JavaScript
Promisedoes - ✗Reading the warning as cosmetic and missing that the side effects never happen
- ✗Thinking a runtime picks up an unawaited future and runs it in the background
Follow-up questions
- →How would you start the work now and collect its result later in Tokio?
- →Why does dropping an unpolled
Futureamount to cancelling it?
MiddleTheoryCommonHow do async and .await work in Rust, and how is that unlike async in JavaScript or C#?
How do async and .await work in Rust, and how is that unlike async in JavaScript or C#?
The compiler turns an async fn into a state machine implementing Future, a state per .await, which an executor drives by calling poll. A JS Promise or C# Task starts at the call on a built-in runtime; a Rust Future waits.
Common mistakes
- ✗Assuming a Rust
Futurestarts at the call, as aPromiseor aTaskdoes - ✗Picturing each
async fnas a green thread with its own stack - ✗Thinking
stdships the runtime that polls futures
Follow-up questions
- →What decides the size of the state machine generated for an
async fn? - →Who calls
pollagain after a leaf future returnedPending, and how is it told to?
MiddleDebuggingCommonFix an async handler that blocks the Tokio runtime with sync I/O, sleep and a CPU loop
Fix an async handler that blocks the Tokio runtime with sync I/O, sleep and a CPU loop
std::fs::read, thread::sleep and the hash loop never reach an .await, so they hold the worker thread and the tasks queued on it stall. Await tokio::fs::read and tokio::time::sleep, and move the loop into spawn_blocking.
Common mistakes
- ✗Believing Tokio preempts a long-running task the way the OS preempts a thread
- ✗Fixing the blocking I/O but leaving a long CPU loop on the async worker
- ✗Starting a nested runtime inside a task, which panics in Tokio
Follow-up questions
- →When is
tokio::task::yield_nowenough instead ofspawn_blocking? - →Why is
spawn_blockinga poor fit for a job that runs for the whole life of the program?
MiddleTheoryCommonHow does tokio::spawn(fut) in the async runtime Tokio differ from fut.await in concurrency and panics?
How does tokio::spawn(fut) in the async runtime Tokio differ from fut.await in concurrency and panics?
fut.await runs the future inside the current task, which does nothing else meanwhile. spawn starts a new task at once, maybe on another thread; its JoinHandle yields Result<T, JoinError>, and a panic there comes back as an Err.
Common mistakes
- ✗Expecting a spawned task to wait until its
JoinHandleis awaited - ✗Writing two
.awaitcalls in a row and expecting them to overlap - ✗Assuming a panic in a spawned task crashes the caller or the process
Follow-up questions
- →What happens to a spawned task when its
JoinHandleis dropped, and how do you cancel it? - →When is the joining macro
tokio::join!a better choice than spawning two tasks?
MiddleDesignCommonYour team is building two Rust services on an 8-core machine. The first resizes uploaded images: each job decodes a 20 MB photo, scales it and encodes a JPEG, taking about 300 ms of pure CPU time with no I/O in between. The second is a TCP proxy that holds 10,000 client connections, most of them idle while they wait for the next packet, and forwards bytes to a backend. Constraints: the resizer must keep all cores busy without starving the code that accepts new jobs; the proxy must not spend a gigabyte of memory on per-connection stacks. For each service, choose OS threads or async tasks, explain how the cooperative scheduling of tasks differs from the preemptive scheduling of threads, and say what goes wrong if you pick the other model.
Your team is building two Rust services on an 8-core machine. The first resizes uploaded images: each job decodes a 20 MB photo, scales it and encodes a JPEG, taking about 300 ms of pure CPU time with no I/O in between. The second is a TCP proxy that holds 10,000 client connections, most of them idle while they wait for the next packet, and forwards bytes to a backend. Constraints: the resizer must keep all cores busy without starving the code that accepts new jobs; the proxy must not spend a gigabyte of memory on per-connection stacks. For each service, choose OS threads or async tasks, explain how the cooperative scheduling of tasks differs from the preemptive scheduling of threads, and say what goes wrong if you pick the other model.
Resizer: threads, one per core (say, rayon): CPU work never reaches an .await and would hog an async worker. Proxy: async tasks, a few hundred bytes per idle connection, not a stack. The OS preempts threads; tasks yield only at .await.
Common mistakes
- ✗Believing a runtime preempts a CPU-bound task the way the OS preempts a thread
- ✗Treating async as faster for every workload rather than better at waiting
- ✗Ignoring the per-thread stack cost when one thread serves each idle connection
Follow-up questions
- →How would you call the resizer from an async web handler without stalling the runtime?
- →Where does sending CPU work from async code to the data-parallelism library
rayonpay off?
MiddleTheoryCommonWhy does async Rust need an async runtime such as Tokio, and what breaks if you mix runtimes?
Why does async Rust need an async runtime such as Tokio, and what breaks if you mix runtimes?
std defines Future but nothing that polls it: a runtime brings the executor, an async I/O reactor and timers. Pick by target and ecosystem: Tokio for servers, embassy for embedded. I/O types are tied to their reactor: Tokio's panic outside it.
Common mistakes
- ✗Believing
stdships an executor and Tokio merely adds faster I/O - ✗Expecting a runtime mix-up to fail at compile time rather than panic at run time
Follow-up questions
- →What does the attribute macro
#[tokio::main]expand into? - →When is a single-threaded
current_threadruntime the better choice?
SeniorDebuggingCommonFix an async function that holds a std::sync::MutexGuard across .await
Fix an async function that holds a std::sync::MutexGuard across .await
MutexGuard is not Send, so tokio::spawn rejects a future holding it across .await, and a task asleep with the lock stalls others, even deadlocks. Take the batch out in a block, then await; use tokio::sync::Mutex only across awaits.
Common mistakes
- ✗Expecting
drop(guard)before.awaitto make the futureSendagain in rustc 1.99 - ✗Reaching for
tokio::sync::Mutexby default, though it is slower and needed only across an await - ✗Overlooking the deadlock when a task suspends holding a
stdlock on a single-threaded runtime
Follow-up questions
- →Why does an
Rcor aRefCellborrow held across.awaitcause the same error? - →How would a message-passing actor task that owns the buffer replace the lock here?
SeniorTheoryCommonWhy does the Tokio task spawner tokio::spawn require Send + 'static, and what makes a future non-Send?
Why does the Tokio task spawner tokio::spawn require Send + 'static, and what makes a future non-Send?
A task may outlive its caller and hop worker threads at any .await, so it must own its data and be Send. An Rc, a RefCell borrow or a MutexGuard held across .await breaks that; use async move, Arc, short scopes or spawn_local.
Common mistakes
- ✗Thinking a non-
Sendvalue breaks the future even when its scope ends before any.await - ✗Expecting the
current_threadflavor to relax the bounds oftokio::spawn; onlyspawn_localdropsSend, and it still needs'static - ✗Cloning everything into the task instead of sharing through
Arcand scoping non-Sendvalues
Follow-up questions
- →How do you run several non-
Sendfutures concurrently on one thread in Tokio? - →Why can the scoped-thread helper
thread::scopeborrow locals whiletokio::spawncannot?
JuniorTheoryOccasionalWhat does .await do, and why is it allowed only inside async code?
What does .await do, and why is it allowed only inside async code?
.await polls the inner Future; on Pending the async body saves its locals, returns Pending and gives the thread back to the executor, resuming at that spot on the next poll. A plain fn cannot suspend, so .await there is E0728.
Common mistakes
- ✗Thinking
.awaitblocks the thread the waythread::sleeporjoindoes - ✗Confusing
.awaitwith spawning: it runs the future inside the current task, not beside it - ✗Believing the
asyncbody restarts from the top after eachPending
Follow-up questions
- →Which local variables end up stored inside the
Futureat an await point? - →Why can a long loop with no
.awaitstall other tasks on the same worker thread?
MiddleTheoryOccasionalWhy does std ship no async runtime, and what do an executor and a reactor each do?
Why does std ship no async runtime, and what do an executor and a reactor each do?
Servers, embedded and games need different schedulers, so std gives only Future, Waker and Context. The executor queues tasks and polls the woken ones; the reactor watches I/O through epoll, kqueue or IOCP and calls wake().
Common mistakes
- ✗Swapping the roles: thinking the reactor polls tasks and the executor talks to the OS
- ✗Believing the executor busy-polls every task instead of only the woken ones
- ✗Assuming
stdomits a runtime because async is unstable, not to stay target-neutral
Follow-up questions
- →What goes wrong if a leaf future returns
Pendingwithout storing theWaker? - →How does a work-stealing executor balance tasks across its worker threads?
SeniorTheoryOccasionalWhat does the compiler turn an async fn into, and what decides that future's size and Send?
What does the compiler turn an async fn into, and what decides that future's size and Send?
Into an anonymous enum implementing Future, a state per .await holding the arguments and the locals live across it. Its size is the largest state, so a buffer kept across .await bloats it; it is Send if those values are, and !Unpin.
Common mistakes
- ✗Thinking every local of the function is stored, not only those live across an
.await - ✗Assuming the future is boxed on the heap and therefore pointer-sized
- ✗Believing an
async fnfuture isSendwhenever its output type is
Follow-up questions
- →How would you shrink a future that holds a 64 KB buffer across an
.await? - →Why does a recursive
async fnfail to compile withoutBox::pin(E0733)?
SeniorTheoryOccasionalasync fn in traits is stable since Rust 1.75 — what still does not work, and when do you box the future?
async fn in traits is stable since Rust 1.75 — what still does not work, and when do you box the future?
Each impl returns its own hidden future type, so the trait is not dyn compatible (E0038), and callers cannot require Send. For that, write -> impl Future<Output = T> + Send; for dyn, return Pin<Box<dyn Future + Send>> or use async_trait.
Common mistakes
- ✗Assuming the compiler boxes the future so that a trait with
async fnworks asdyn - ✗Expecting the future returned by a trait's
async fnto beSendautomatically - ✗Pulling in
async_traitfor generic code, where the nativeasync fnalready works
Follow-up questions
- →What does the
async_fn_in_traitlint warn about on a public trait? - →What does boxing the future cost on every call compared with the native form?
SeniorTheoryOccasionalWhat is cancellation safety, and what does Tokio's racing macro select! do to losing branches?
What is cancellation safety, and what does Tokio's racing macro select! do to losing branches?
select! runs the first ready branch and drops the other futures — that is cancellation. A future is cancel-safe if dropping it at an .await loses nothing: recv and read are; read_exact and write_all lose their partial progress.
Common mistakes
- ✗Thinking
select!pauses the losing branches instead of dropping them - ✗Assuming every Tokio I/O method is cancel-safe,
read_exactandwrite_allincluded - ✗Confusing cancellation safety with being
Unpinor pinned
Follow-up questions
- →How do you keep a partially read frame when a
select!loop may cancel the read? - →Why does a timer created inside a
select!loop body never fire under steady traffic?
SeniorDesignOccasionalAn HTTP API built on the async runtime Tokio runs in Kubernetes. On a rolling deploy the pod gets SIGTERM and is killed with SIGKILL 30 seconds later. Today the process exits at once: in-flight requests see connection resets, a background task that flushes metrics every 10 seconds loses its last batch, and a queue consumer drops the message it was halfway through. Constraints: stop accepting new connections immediately; let in-flight requests finish, but give up on them after 20 seconds; the metrics task and the consumer must finish their current unit of work and then stop; no task may still be running when main returns. Design the shutdown: how the process learns about the signal, how every task is told to stop, how you wait for them under a deadline, and what happens to work that misses it.
An HTTP API built on the async runtime Tokio runs in Kubernetes. On a rolling deploy the pod gets SIGTERM and is killed with SIGKILL 30 seconds later. Today the process exits at once: in-flight requests see connection resets, a background task that flushes metrics every 10 seconds loses its last batch, and a queue consumer drops the message it was halfway through. Constraints: stop accepting new connections immediately; let in-flight requests finish, but give up on them after 20 seconds; the metrics task and the consumer must finish their current unit of work and then stop; no task may still be running when main returns. Design the shutdown: how the process learns about the signal, how every task is told to stop, how you wait for them under a deadline, and what happens to work that misses it.
Await ctrl_c and SIGTERM via tokio::signal, then cancel a shared CancellationToken: the accept loop stops, and each task checks it in select! between units of work. Track tasks in a TaskTracker; wait under timeout, then abort the rest.
Common mistakes
- ✗Expecting a dropped
JoinHandleto cancel its task, though it only detaches it - ✗Waiting for tasks with no deadline, so one stuck request carries the shutdown past SIGKILL
- ✗Cancelling a worker mid-unit instead of letting it finish its current message first
Follow-up questions
- →How would you keep the consumer's message from being lost if the deadline hits mid-processing?
- →What would a
tokio::sync::watchchannel give you here instead of aCancellationToken?
SeniorTheoryOccasionalWhy does async Rust need Pin, and why can pinning still not stop a Box<i32> from moving?
Why does async Rust need Pin, and why can pinning still not stop a Box<i32> from moving?
After its first poll an async state machine may hold references into its own fields, so a move would leave them dangling; Pin promises it stays put until dropped. Unpin types opt out: Box<i32> is Unpin, so pinning restricts nothing.
Common mistakes
- ✗Believing
Pinallocates the value or moves it to the heap - ✗Reading
Unpinas 'cannot be pinned' rather than 'pinning restricts nothing' - ✗Explaining
Pinwithout the self-references a future holds after its first poll
Follow-up questions
- →How do
std::pin::pin!andBox::pindiffer in where the pinned future lives? - →Why does a hand-written combinator need a pin projection to poll a future stored in a field?