Chapter 13 of 16 · Part III, Concurrency and systems
Async without a runtime in the box
Rust futures are cold and need an executor, unlike hot C# Tasks. Wakers, cancellation by drop, join against WhenAll, Send bounds and Pin, for .NET engineers.
This chapter assumes borrowing, Send, and C# async are familiar. Follow the four-shard program, then the cancellation section. Those explain the behavior you will use first; waker internals and Pin are worth revisiting once you can trace a future through a timeout.
Rust's async syntax will look familiar to a C# engineer. What happens after you call an async function is different, though, and that difference shapes how you run and cancel work.
The syntax is nearly identical:
async fn fetch_config(url: &str) -> Result<String, reqwest::Error> {
let response = reqwest::get(url).await?;
response.text().await
}
async fn and .await, postfix instead of prefix. Under that, two different designs, and the differences are not cosmetic. They change what a call does, where memory is allocated, how work is canceled, and which errors you will spend a Tuesday afternoon on.
Tasks are hot, futures are cold
In C#, calling an async method starts it. The body runs synchronously on the calling thread until it hits an await on something that has not completed, and the Task you get back represents work already in progress. Task.Run schedules onto the thread pool immediately.
In Rust, calling an async fn runs none of it. You get back a value implementing Future, and that value is inert. Nothing happens until something polls it, which happens when you .await it or hand it to a runtime.
let fut = fetch_config("https://example.com/config"); // nothing has happened
let body = fut.await?; // now it runs
That distinction produces one very specific bug. Better to see it than to be warned about it.
// This does not fetch anything.
let pending: Vec<_> = urls.iter().map(|u| fetch_config(u)).collect();
// ... other work you expected to overlap with four in-flight requests ...
let mut bodies = Vec::new();
for f in pending {
bodies.push(f.await?);
}
You wrote it expecting the four requests to be in flight during the middle section, the way urls.Select(FetchConfigAsync).ToList() would be in C#. They were not. The loop at the bottom runs them strictly one after another, so the wall clock is the sum of four latencies instead of the maximum. Nothing crashed. Nothing warned. The code has not gained concurrency; whether its overhead is measurable depends on the workload.
The compiler warns when you discard an unused future directly:
warning: unused implementer of `Future` that must be used
--> src/main.rs:31:5
|
31 | fetch_config(url);
| ^^^^^^^^^^^^^^^^^
|
= note: futures do nothing unless you `.await` or poll them
= note: `#[warn(unused_must_use)]` on by default
That note line is the whole design in one sentence. But bind the future to a variable, or collect it into a Vec, and the lint has nothing to complain about. You asked for a value and you got one.
The fix is to say what you meant. futures::future::join_all polls the whole collection concurrently on the current task. tokio::spawn per future hands each one to the runtime as an independent task, which is the closest thing to what C# did for you automatically.
To be fair, C# has the mirror-image trap and it bites just as often. Select is lazy, so an IEnumerable of tasks that never gets materialized starts nothing either, and passing a lazy sequence into Task.WhenAll starts the tasks at enumeration time rather than at projection time. The .ToList() in idiomatic C# is doing real work. The difference is that in C# the laziness is in LINQ and you can drop it, while in Rust the laziness is in the language and you cannot.
What a future actually is
Here is the entire trait, from the standard library, plus the enum it returns, which lives next door in std::task:
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
pub enum Poll<T> {
Ready(T),
Pending,
}
Read that as a question and two possible answers. Something asks the future to make progress. The future either finishes and hands back a value, or says not yet.
Compare it with what C# does. Task is a heap object with an internal continuation list. When you await something incomplete, the generated code calls AwaitUnsafeOnCompleted, which registers your state machine as a continuation on the awaited task. Completion is a push: whoever finishes the I/O walks the continuation list and schedules the resumption. The Task has identity, it can be handed around, awaited twice, stored in a dictionary.
Rust chose the opposite direction. Nobody pushes into a future. A caller pulls, repeatedly, until the future says Ready. Without Boats, who did much of the design work on this, wrote up why, and the short version is that a poll model lets a future be a plain value with no heap identity, no allocation, and no reference counting. That is the property that makes everything else in this chapter possible: because a future is just a value you own, awaiting one inside another can embed it as a field rather than allocate it separately, and destroying one is just dropping a value.
Now the deliberately simplified model, so I can correct it. If polling is a pull, the obvious implementation of a runtime is a loop: poll the future, and if it returns Pending, poll it again. That would work, and it would also spin one CPU core at full tilt while waiting for a socket. Nobody wants that.
Wakers, and why a pull model needs them
The second parameter is the fix. Context carries a Waker, and the contract is this: if a future returns Pending, it must first arrange for that Waker to be woken when the situation changes. The runtime then stops polling and goes to sleep. When the waker fires, the runtime puts the task back on its run queue and polls it again.
The wakers are registered at the leaves. A read on a tokio::net::TcpStream bottoms out in a future that talks to Tokio's reactor rather than to another future. When that leaf's poll finds the socket not readable, it clones the waker out of the Context, hands it to the reactor along with the registered file descriptor, then returns Pending. That Pending propagates up through every .await in the call chain to the top, and the whole task suspends. Later the reactor's epoll or kqueue or IOCP call reports the socket readable, the reactor calls wake(), and the scheduler polls the task again from the top.
From the top matters. The runtime does not resume in the middle of your call stack the way a thread does. It calls poll on the outermost future, which reads its state discriminant, jumps to the right resume point, and calls poll on the inner future it was waiting on, which does the same thing, down to the leaf. A deep await chain re-walks itself on every wakeup. That is cheap, because each step is a discriminant check and a direct call with no virtual dispatch, and it explains how dropping the state machine can stop further polling. Cleanup itself can still do work.
There is no scheduler in the standard library
The language defines what a Future is. It ships no runtime to execute one. No thread pool, no timer, no I/O reactor. std::future and std::task are types and traits and nothing else.
You pick a runtime, and in practice that means Tokio:
#[tokio::main]
async fn main() {
let body = fetch_config("https://example.com/config").await.unwrap();
println!("{}", body);
}
Coming from .NET, where the thread pool and the synchronization context are simply there, this feels like an omission. The reason is that Rust targets environments with no operating system, no threads, and no allocator. A mandatory work-stealing scheduler would exclude embedded firmware, kernel modules, and anything running on bare metal, all of which want async for exactly the reason everyone wants it, which is doing several things on one stack. There is also no single right scheduler: a work-stealing pool and a thread-per-core design have genuinely different tradeoffs, and freezing one into the standard library would have picked a winner in 2019.
The cost is real and you should not let anyone talk you out of noticing it. Because AsyncRead and AsyncWrite are not in the standard library either, runtimes define their own, and a library written against Tokio's I/O types usually needs Tokio. The traits that would have made runtimes interchangeable do not exist at the level everyone shares. This is a genuine place where .NET is ahead, not by design brilliance but by having one owner who shipped a batteries-included answer and made everybody use it.
My recommendation is not to be clever. Use Tokio unless you have a specific reason not to, and treat "this crate needs a different runtime" as a reason to look for a different crate.
A complete program, and the C# it replaces
Enough theory. Here is something you can paste into a fresh cargo new project with tokio = { version = "1", features = ["full"] } in Cargo.toml and run. It queries four shards concurrently with a per-shard deadline, and it prints its cleanup so you can see when it happens.
use std::time::Duration;
use tokio::task::JoinSet;
use tokio::time::{sleep, timeout};
#[derive(Debug)]
struct Shard {
id: u32,
rows: u64,
}
/// Stands in for a pooled connection. The Drop impl is the point of the example.
struct ShardConn(u32);
impl Drop for ShardConn {
fn drop(&mut self) {
println!(" closing connection to shard {}", self.0);
}
}
/// Pretend this is a network round trip. Note what it does not take:
/// no cancellation token, no deadline, no awareness of its caller.
async fn query_shard(id: u32) -> Shard {
let _conn = ShardConn(id);
let latency = match id {
1 => 100,
2 => 200,
3 => 300,
_ => 700,
};
sleep(Duration::from_millis(latency)).await;
Shard { id, rows: u64::from(id) * 1_000 }
}
#[tokio::main]
async fn main() {
let mut set = JoinSet::new();
for id in 1..=4 {
set.spawn(async move {
match timeout(Duration::from_millis(450), query_shard(id)).await {
Ok(shard) => Ok(shard),
Err(_elapsed) => Err(id),
}
});
}
let mut total = 0u64;
let mut ok = 0u32;
let mut timed_out = Vec::new();
while let Some(joined) = set.join_next().await {
match joined.expect("shard task panicked") {
Ok(shard) => {
println!("shard {} returned {} rows", shard.id, shard.rows);
total += shard.rows;
ok += 1;
}
Err(id) => {
println!("shard {} timed out", id);
timed_out.push(id);
}
}
}
println!("{total} rows from {ok} shards, timed out: {timed_out:?}");
}
Output:
closing connection to shard 1
shard 1 returned 1000 rows
closing connection to shard 2
shard 2 returned 2000 rows
closing connection to shard 3
shard 3 returned 3000 rows
closing connection to shard 4
shard 4 timed out
6000 rows from 3 shards, timed out: [4]
The useful result is the final total: shards 1, 2, and 3 contribute 1,000 + 2,000 + 3,000 rows, while shard 4 exceeds its 450 ms deadline. Its cleanup line still appears because the owned future is dropped. Read this as a simulated run, not a promise about log ordering or real network timings.
The C# equivalent, in full. This needs .NET 9 or later for Task.WhenEach, and assumes implicit usings.
record Shard(int Id, long Rows);
sealed class ShardConn : IDisposable
{
private readonly int _id;
public ShardConn(int id) => _id = id;
public void Dispose() => Console.WriteLine($" closing connection to shard {_id}");
}
static class Program
{
static async Task<Shard> QueryShardAsync(int id, CancellationToken ct)
{
using var conn = new ShardConn(id);
int latency = id switch { 1 => 100, 2 => 200, 3 => 300, _ => 700 };
await Task.Delay(latency, ct);
return new Shard(id, id * 1000L);
}
static async Task<(Shard? Shard, int Id)> RunShardAsync(int id)
{
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(450));
try
{
return (await QueryShardAsync(id, cts.Token), id);
}
catch (OperationCanceledException)
{
return (null, id);
}
}
static async Task Main()
{
var tasks = Enumerable.Range(1, 4).Select(RunShardAsync).ToList();
long total = 0;
int ok = 0;
var timedOut = new List<int>();
await foreach (var task in Task.WhenEach(tasks))
{
var (shard, id) = await task;
if (shard is not null)
{
Console.WriteLine($"shard {shard.Id} returned {shard.Rows} rows");
total += shard.Rows;
ok++;
}
else
{
Console.WriteLine($"shard {id} timed out");
timedOut.Add(id);
}
}
Console.WriteLine(
$"{total} rows from {ok} shards, timed out: [{string.Join(", ", timedOut)}]");
}
}
The C# version demonstrates the same result using a cancellation token passed into Task.Delay. In the Rust version, the timeout wrapper owns the query future and drops it on timeout. The comparison is about these two cancellation mechanisms: neither one proves that an actual remote database stopped processing a query.
Cancellation is drop, and that cuts both ways
Canceling a future is dropping it. No token threaded through eleven layers, no cooperative check, no OperationCanceledException. tokio::time::timeout holds the inner future as a field, and when the timer fires first it returns Err and lets the inner future fall out of scope. Dropping the state machine drops every field it held, which is why ShardConn printed its line for shard 4 without anyone writing cleanup code for the canceled path.
select! is the general form:
tokio::select! {
result = fetch_config(url) => handle(result),
_ = tokio::time::sleep(Duration::from_secs(2)) => timeout_path(),
}
In this example, select! owns both branch futures and drops the losing one. If a branch instead borrows a future stored outside the macro, that future can survive the selection. Dropping a future also does not undo work already sent to a remote service, and dropping a Tokio JoinHandle detaches its task rather than canceling it.
That is the good half. The bad half is that a future can be canceled at any await point, whether or not its author considered the possibility.
The shape of the bug is always the same:
loop {
tokio::select! {
msg = rx.recv() => process(msg),
// Wrong. read_exact is not cancellation safe. Every time rx.recv()
// wins the race, the partially filled buffer and the bytes already
// taken off the socket go on the floor, and the next iteration
// starts a fresh read_exact from wherever the stream now sits.
res = socket.read_exact(&mut buf) => {
if res.is_ok() { frames += 1; }
}
}
}
The subtlety here is progress: a canceled read_exact may have consumed part of the message, and restarting it from the beginning can lose track of that progress. The compiler does not establish cancellation safety. In particular, branch futures are dropped before a selected handler runs, so a handler can often access a buffer that a branch borrowed.
The fix is to move the non-cancellation-safe work into its own task, or to hold the future across loop iterations with tokio::pin! so it is polled to completion instead of recreated each time. Both are more code than the broken version, which is why the broken version keeps getting written.
The related problem is making a section of async work not cancelable, which C# engineers usually assume is trivial because it is. In C# you simply do not check the token, and the work runs to completion. In Rust the caller can drop you at any await, and there is no way to refuse. The only real answer is tokio::spawn, because a spawned task is owned by the runtime, and dropping its JoinHandle detaches the task rather than canceling it. If you want it stopped, you call abort() explicitly.
join is not WhenAll, exactly
Two ways to run several futures at once, and confusing them is a performance bug rather than a correctness one.
join! and join_all poll all of their futures on the current task, on one thread. They give you concurrency, meaning overlapped I/O waits, and nothing else. If the futures do real CPU work, join! is strictly serial.
tokio::spawn and JoinSet hand each future to the scheduler as an independent task, which a multi-threaded runtime can run on different worker threads. That is parallelism, and it is why the worked example above used JoinSet.
In C# the distinction does not exist in the same place, because tasks are already hot and already scheduled by the time you get them. Task.WhenAll is just a join over things that are running anyway. Coming from that model, the instinct is to reach for join_all and expect the thread pool to show up. It does not.
The cost of spawn is the Send + 'static bound, which brings us to the error you are actually going to hit.
The Send bound problem
The guard-across-await mistake is so common that rustc has a dedicated diagnostic for it. Here is code that looks obviously fine:
use std::sync::{Arc, Mutex};
struct Cache {
entries: Mutex<Vec<String>>,
}
async fn refresh(cache: Arc<Cache>) {
let mut entries = cache.entries.lock().unwrap();
let fresh = fetch_names().await;
entries.extend(fresh);
}
#[tokio::main]
async fn main() {
let cache = Arc::new(Cache { entries: Mutex::new(Vec::new()) });
tokio::spawn(refresh(cache)).await.unwrap();
}
And here is what you get:
error: future cannot be sent between threads safely
--> src/main.rs:16:18
|
16 | tokio::spawn(refresh(cache)).await.unwrap();
| ^^^^^^^^^^^^^^ future returned by `refresh` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not
implemented for `MutexGuard<'_, Vec<String>>`
note: future is not `Send` as this value is used across an await
--> src/main.rs:9:31
|
8 | let mut entries = cache.entries.lock().unwrap();
| ------- has type `MutexGuard<'_, Vec<String>>` which is not `Send`
9 | let fresh = fetch_names().await;
| ^^^^^ await occurs here, with `mut entries` maybe used later
note: required by a bound in `tokio::spawn`
Read the three parts. The error is reported at the spawn, because that is where the Send bound is required. The help line names the guilty type. The note names the actual line, and the phrase await occurs here, with mut entries maybe used later is the whole explanation: the guard has to be stored as a field of the future so it survives the suspension, which makes the future contain a MutexGuard, which makes the future not Send, which makes it unspawnable.
You will look for an error code and not find one. This diagnostic is printed without one. It is a special case that rustc substitutes for the generic unsatisfied-trait-bound message you would otherwise get, which does carry a code, E0277.
The mechanism is an operating system rule leaking upward. On several platforms the lock that std::sync::Mutex sits on must be released by the thread that acquired it, so MutexGuard is !Send everywhere for portability. A work-stealing runtime can resume a task on a different worker thread after an await. The type system propagates the !Send all the way out to the spawn.
Three fixes, in the order I would try them.
Restructure so the lock is not held across the await. Usually the right answer, because it also shortens the critical section.
async fn refresh(cache: Arc<Cache>) {
let fresh = fetch_names().await;
cache.entries.lock().unwrap().extend(fresh);
}
Scope the guard explicitly when you need the locked data before the await. An inner block makes the drop point unambiguous to the compiler and to the next reader.
async fn refresh(cache: Arc<Cache>) {
let stale = {
let entries = cache.entries.lock().unwrap();
entries.iter().take(10).cloned().collect::<Vec<_>>()
}; // guard dropped here
let fresh = fetch_missing(&stale).await;
cache.entries.lock().unwrap().extend(fresh);
}
An explicit drop(entries) before the await also works on current compilers, whose analysis tracks whether a value is still live at each suspension point. Historically it did not, which is why you will find forum threads insisting you need a block. The block still reads better.
Use tokio::sync::Mutex only if you genuinely must hold the lock across an await, for instance while writing to a socket you have exclusive access to. Its guard is Send, and it costs more than the standard one for uncontended locks. Tokio's own guidance is to prefer std::sync::Mutex in async code and reach for the async one deliberately.
The same error appears when a non-Send value such as Rc survives an await in a future passed to tokio::spawn. RefCell<T> is Send when T: Send, but is not Sync; an owned RefCell<T> is therefore a different case from a shared reference or an Arc<RefCell<T>>. Check the exact type named by the diagnostic.
Pin, and why self-reference forces it
Back to poll, and the part I skipped. Why Pin<&mut Self> rather than &mut Self?
Look at what a compiled async fn contains:
async fn run() {
let buf = String::from("hello world");
let n = count_words(&buf).await;
println!("{n}");
}
The generated future for run holds buf as a field, because buf must survive the suspension. It also holds the count_words future as a field, because that is what nesting means. And the count_words future holds &buf, a reference into a sibling field of the same struct.
That is a self-referential struct. Move it in memory and the reference points at the old location. Almost every Rust type is safe to move with a memcpy, there are no move constructors, and the whole language leans on that. The state machines async generates are the exception.
Pin restricts moving an address-sensitive value after it has been pinned. An ordinary newly created async future can be moved before it is pinned for polling. Once pinned, a future that is not Unpin must remain at its location until it is dropped, even after it returns Ready. Completion alone does not remove the pinning guarantee. See the pin module documentation for the lifetime of that promise.
Most of the time this is invisible. You meet it in two places. First, recursion:
error[E0733]: recursion in an async fn requires boxing
--> src/main.rs:5:1
|
5 | async fn walk(node: &Node) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
6 | walk(child).await;
| ----------------- recursive call here
|
= note: a recursive `async fn` must introduce indirection such as
`Box::pin` to avoid an infinitely sized future
A future that embeds itself has no finite size, so the compiler stops you. The fix is Box::pin(walk(child)).await, which puts the inner future behind a pointer. C# does async recursion without thinking about it, because every Task is already a heap object and the state machines never nest. That is a real ergonomic cost on the Rust side, paid in exchange for the flat non-recursive case being allocation-free.
Second, select! in a loop over a future you want to keep across iterations. tokio::pin!(fut) pins it to the stack frame so it can be polled repeatedly without being recreated. The std::pin module docs are worth a slow read once, and then you can mostly forget them.
Both languages build a state machine, and both allocate somewhere
C# rewrites an async method into a type implementing IAsyncStateMachine, with a field per local that survives an await, a field per distinct awaiter type, and an integer for the resume point. In a release build that type is a struct, zero-initialized on the stack; in a debug build the compiler emits a class instead, which helps certain debugging scenarios. If the method completes synchronously, the state machine need not be heap allocated. The returned Task<T> can still allocate when its result is not covered by a cached task; code inside the method can allocate too. Stephen Toub's walkthrough is the definitive account, and this is a heavily compressed version of it.
The old story, which you will still find repeated, is that on first suspension the state machine gets boxed and the Task is a second, separate heap object. That was true on .NET Framework, where the first suspension of a call allocated the box, a MoveNextRunner, an Action delegate, and the Task itself, on top of ExecutionContext capture.
Modern .NET does not do that. The builder allocates an AsyncStateMachineBox<TStateMachine> which derives from Task<TResult> and holds the state machine as a strongly typed field. It is the task. One allocation, on first suspension only, reused for every later suspension of that call. For methods returning ValueTask or ValueTask<T> you can go further: annotate the method with [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] and the box is rented from a pool and returned on completion, giving amortized zero allocation. That pooling does not apply to Task-returning methods, because a Task can outlive the call and be awaited again.
For a typical modern Task-returning async method, first suspension can allocate a combined task and state-machine object. Synchronous completion avoids that box, but does not guarantee an allocation-free call. Task caching, the return type, the async builder, and the method body all affect the result.
Rust's number is different in a way that matters at depth. Because awaiting an inner future embeds it as a field, a chain of ten async fn calls compiles to one struct nested ten deep, whose total size is known at compile time. tokio::spawn allocates once to put that struct in the task cell. The nine inner levels cost nothing. Tyler Mandry, from the compiler team, wrote up how the layout works, including how variants that cannot be live at the same time get overlapped so the size is closer to the maximum than the sum.
| Case | C# | Rust |
|---|---|---|
| Call with no suspension | no state-machine box; the result task or body may still allocate | no allocation required for the future itself; its body may allocate |
| First suspension, N levels deep | one box per suspending method, so up to N | none, the levels are fields of one struct |
| Handing work to the scheduler | already allocated as the Task | one allocation in spawn |
| Async recursion | no ceremony, but one box per suspended level | requires Box::pin, one allocation per level |
| Trait method returning a future | no extra cost, Task is already a type-erased heap object | no allocation with static dispatch, one Box per call with #[async_trait] |
That table is the honest summary. Rust wins on deep chains of ordinary calls, which is the common case in a network service. C# wins on recursion and on dynamic dispatch, where its uniform heap-allocated Task is exactly the indirection Rust has to add by hand.
At scale, in a real system
The place this stops being academic is a gateway or proxy holding tens of thousands of connections.
One task per connection is the normal shape. Each task is one allocation containing the whole future for that connection's handler. Suppose the handler's future is 4 KB, which is not hard to reach once you have a couple of buffers and a TLS session in scope across awaits. At 50,000 connections that is 4096 times 50,000, a little over 200 MB of resident memory in futures alone. Arithmetic, not a benchmark. It is also visible and boundable, which is the part I like: std::mem::size_of_val on your future tells you before you deploy. The .NET equivalent is spread across per-connection Task objects and their state machine boxes, and is harder to see in a single number, though a dump will show it.
Future size is a real tuning knob. A big match arm that only runs on the error path still contributes its locals to the size of every instance of that future. Boxing the cold branch shrinks the hot one.
The other thing that bites at scale is blocking. A poll that does not return promptly holds its worker thread hostage, and Tokio's default worker count is the number of cores. Call a synchronous file read or a CPU-heavy compression routine inside an async function and you have removed one of, say, eight workers until it finishes. Do it on all of them and the runtime stops. tokio::task::spawn_blocking exists for exactly this, and Tokio's post on preemption explains how the runtime tries to keep long-running tasks from starving others.
.NET's thread pool can add workers in response to blocked work, which can soften some stalls. It does not make blocking safe: thread-pool starvation can still cause severe delays and outages. Tokio's async worker pool does not grow to compensate in the same way. In both runtimes, use asynchronous I/O and isolate genuinely blocking work.
Async in traits is still a rough edge
Async functions in traits have been stable since Rust 1.75, released in December 2023. That is real progress and you should use them. Two limitations remain.
First, you cannot add a Send bound to the returned future from outside the trait, so a public trait with async fn gets a warning:
warning: use of `async fn` in public traits is discouraged as auto trait bounds
cannot be specified
--> src/lib.rs:7:5
|
7 | async fn fetch(&self, url: Url) -> HtmlBody;
| ^^^^^
|
= note: you can suppress this lint if you plan to use the trait only in your
own code, or do not care about auto traits like `Send` on the `Future`
help: you can alternatively desugar to a normal `fn` that returns `impl Future`
and add any desired bounds such as `Send`, but these cannot be relaxed
without a breaking API change
|
7 - async fn fetch(&self, url: Url) -> HtmlBody;
7 + fn fetch(&self, url: Url) -> impl Future<Output = HtmlBody> + Send;
|
Without a promised Send bound on the returned future, generic callers cannot assume that future is safe to spawn across worker threads. A particular implementation may still return a Send future. You can expose fn ... -> impl Future<Output = ...> + Send, or use the Rust team's suggested trait-variant approach to provide local and Send variants.
Second, a trait with async fn is not dyn compatible. You cannot make a dyn Handler out of it, which rules out the plugin and middleware patterns you would reach for instinctively. The workaround is the async_trait macro, which rewrites every method to return a boxed future and costs one allocation per call.
C# has none of these problems. An interface method returning Task<T> has worked since 2012, dispatches dynamically, and composes with everything. IAsyncEnumerable<T> and await foreach have been in the language since C# 8; the Rust equivalent, AsyncIterator, is still nightly-only, and the ecosystem uses the Stream trait from the futures crate instead.
The function-coloring complaint applies to both languages equally, so I will not repeat it as if it were a Rust problem. An async function can only be awaited from an async function, in C# as much as in Rust, and .Result is as bad an idea as block_on.
The mistakes you will actually make
Building a collection of futures and expecting concurrency. Recognize it by wall-clock time equal to the sum of the parts. Fix with join_all for concurrency on one task, or JoinSet for parallelism across workers.
Holding a MutexGuard or an Rc across an await. Recognize it by the error pointing at your spawn rather than at your lock. Fix by shortening the critical section, not by switching to tokio::sync::Mutex reflexively.
Putting a non-cancellation-safe operation in a select! loop. Recognize it by data that vanishes under load and never in tests, because the losing branch only loses when both branches are actually racing. Fix by reading the cancel-safety note on every method you put in a branch, before you write the loop.
Blocking inside async. Look for queued work, poor throughput, and occupied worker threads. Both .NET and Tokio can suffer. In Tokio, use spawn_blocking for blocking operations and bound CPU-heavy parallel work rather than flooding that pool.
Assuming dropping a JoinHandle cancels the task. It detaches it. Call abort(), or hold the handle.
Reaching for async when you do not need it. A CLI tool that makes three HTTP calls does not need a runtime. Rust's synchronous story is genuinely good, and ureq or a plain thread pool will be simpler and compile faster. The .NET habit of making everything async because everything is already async does not transfer.
Checking yourself
Why does building a Vec of futures and awaiting them in a loop take as long as doing them one at a time? Because futures are inert until polled. The Vec holds four state machines that have executed nothing; the loop then drives them to completion strictly in sequence. Concurrency requires something that polls them all, like join_all or a task per future.
Why does poll need a Context at all, when it could just be called again? Because polling in a loop would spin the CPU. The Context carries a Waker that the future must register before returning Pending, so the runtime knows when it is worth polling again and can sleep in the OS event queue until then.
A colleague holds a std::sync::MutexGuard across an await and the error points at tokio::spawn, twenty lines away. Why there? The guard must be stored as a field of the future to survive the suspension, which makes the whole future not Send. spawn is simply the first place a Send bound is required, so that is where the obligation fails.
Your service closes connections cleanly on shutdown in C# using IAsyncDisposable. What is the Rust equivalent? There is not one yet. Drop cannot await, so anything requiring network I/O to shut down needs an explicit async fn close(self) that callers must call. This is a case where the C# design is straightforwardly better today.
Get the next deep dive by email
New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.
You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.
Written by Zeeshan Adil
I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.