Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 12 · Concurrency & async

    12.3Async, futures & Tokio

    How async Rust runs, why a future does nothing until it's awaited, and how to run, cancel and offload work with the Tokio runtime.

    About 35 minutesAdvanced

    On this page
    1. Concept map
    2. Futures are lazy
    3. Running futures concurrently
    4. Spawning a task
    5. Cancelling: drop the future
    6. Never block the runtime
    7. Which one should I use?
    8. Under the hood
    9. Common pitfalls
    10. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    What an async function returnsPromise<T>Task<T>impl Future<Output = T>
    When the work startsWhen you call the function (promises are eager)When you call the method (tasks are hot)When the future is first awaited or polled (futures are lazy)
    What runs async codeThe event loop built into the runtimeThe thread pool built into the runtimeA runtime crate you add, usually Tokio: #[tokio::main]
    Wait for several at oncePromise.allTask.WhenAlltokio::join!
    Take the first to finishPromise.race; the others keep runningTask.WhenAny; the others keep runningtokio::select!; the others are dropped
    Cancel an operationPass an AbortSignal all the way downPass a CancellationToken all the way downDrop the future; it stops at its current .await

    async and .await look almost the same in Rust as in TypeScriptC#. The model underneath is different in three ways that change how you write code. A Rust future does nothing until something awaits it. There’s no built-in runtime to run it: you add one, and almost everyone uses Tokio. And cancelling an operation is as simple as dropping its future. This lesson covers each, then the rule async code depends on: never block the thread you’re running on.

    Futures are lazy

    Here’s an async function that waits a few milliseconds, the way a network call would, and the code that calls it twice:

    TypeScript
    users.ts
    import { setTimeout as sleep } from "node:timers/promises";
    
    async function loadUser(id: number): Promise<string> {
      await sleep(5);
      return `user ${id}`;
    }
    
    const first = await loadUser(1);
    const second = await loadUser(2);
    console.log(`${first}, ${second}`);
    C#
    Users.cs
    var first = await LoadUser(1);
    var second = await LoadUser(2);
    Console.WriteLine($"{first}, {second}");
    
    static async Task<string> LoadUser(int id)
    {
        await Task.Delay(5);
        return $"user {id}";
    }
    Rust
    use std::time::Duration;
    use tokio::time::sleep;
    
    async fn load_user(id: u32) -> String {
        sleep(Duration::from_millis(5)).await;
        format!("user {id}")
    }
    
    #[tokio::main]
    async fn main() {
        let first = load_user(1).await;
        let second = load_user(2).await;
        println!("{first}, {second}");
    }

    Output

    user 1, user 2
    • async fn load_user(id: u32) -> String declares the type of the result, not of the call. Calling it returns a future, a value of some type that implements Future<Output = String>, much as an async function returns Promise<string>an async method returns Task<string>.
    • .await goes after the expression, not before it. That makes chains read left to right: client.get(url).send().await?.json().await?.
    • #[tokio::main] turns async fn main into a normal main that starts the Tokio runtime and runs the async body on it. Rust’s standard library defines the Future trait but doesn’t include a runtime to run futures, so you add one as a dependency:
    # Cargo.toml
    [dependencies]
    tokio = { version = "1", features = ["full"] }
    
    • tokio::time::sleep waits without blocking the thread. std::thread::sleep would block it; more on that below.

    The difference that matters most is when the work starts. Call an async function in TypeScriptC# and it begins running straight away, up to its first real wait:

    eager.ts
    async function loadUser(id: number): Promise<string> {
      console.log(`loading user ${id}`);
      return `user ${id}`;
    }
    
    const pending = loadUser(1);
    console.log("promise created");
    console.log(await pending);

    Output

    loading user 1
    promise created
    user 1
    Hot.cs
    var pending = LoadUser(1);
    Console.WriteLine("task created");
    Console.WriteLine(await pending);
    
    static async Task<string> LoadUser(int id)
    {
        Console.WriteLine($"loading user {id}");
        await Task.Delay(1);
        return $"user {id}";
    }

    Output

    loading user 1
    task created
    user 1

    The same code in Rust prints in a different order:

    async fn load_user(id: u32) -> String {
        println!("loading user {id}");
        format!("user {id}")
    }
    
    #[tokio::main]
    async fn main() {
        let pending = load_user(1);
        println!("future created");
        println!("{}", pending.await);
    }

    Output

    future created
    loading user 1
    user 1

    load_user(1) ran none of the function’s body. It only built a future: a value holding the argument and a note of where to start. The body runs when pending.await asks for the result. A future you never await never runs at all:

    async fn save(name: &str) {
        println!("saved {name}");
    }
    
    #[tokio::main]
    async fn main() {
        save("draft"); // never awaited: nothing happens
        save("final").await;
    }

    Output

    saved final

    The compiler warns about the first call, with a note that futures do nothing unless you .await or poll them. In TypeScript the equivalent mistake is a “floating” promise that runs with nobody waiting for it; in Rust it doesn’t run at all.In C#, a forgotten await still runs the task, with nobody watching for its exceptions; in Rust the work doesn’t happen at all.

    Mental model shiftA future is a plan, not a running job

    A PromiseA Task represents work that’s already under way. A Rust future is a description of work, like an unstarted iterator: it runs only while something polls it. That’s why you can cancel any future without passing a token into it, why futures can be combined freely before anything starts, and why you have to choose how to run several of them at once.

    Running futures concurrently

    Because awaiting is what runs a future, awaiting two futures one after the other runs them one after the other. To run them at the same time, hand both to tokio::join!, Rust’s Promise.allTask.WhenAll. Here user 1 takes longer than user 2:

    TypeScript
    both.ts
    import { setTimeout as sleep } from "node:timers/promises";
    
    async function loadUser(id: number, delayMs: number): Promise<string> {
      await sleep(delayMs);
      console.log(`loaded user ${id}`);
      return `user ${id}`;
    }
    
    const [first, second] = await Promise.all([loadUser(1, 50), loadUser(2, 5)]);
    console.log(`${first}, ${second}`);
    C#
    Both.cs
    var users = await Task.WhenAll(LoadUser(1, 50), LoadUser(2, 5));
    Console.WriteLine(string.Join(", ", users));
    
    static async Task<string> LoadUser(int id, int delayMs)
    {
        await Task.Delay(delayMs);
        Console.WriteLine($"loaded user {id}");
        return $"user {id}";
    }
    Rust
    use std::time::Duration;
    use tokio::time::sleep;
    
    async fn load_user(id: u32, delay_ms: u64) -> String {
        sleep(Duration::from_millis(delay_ms)).await;
        println!("loaded user {id}");
        format!("user {id}")
    }
    
    #[tokio::main]
    async fn main() {
        let (first, second) = tokio::join!(load_user(1, 50), load_user(2, 5));
        println!("{first}, {second}");
    }

    Output

    loaded user 2
    loaded user 1
    user 1, user 2

    User 2 finishes first, so both were waiting at the same time. join! returns a tuple of the results in the order you listed them, whichever finished first. It runs the futures concurrently on the current task: it polls each in turn while they wait, so they take turns on one thread rather than running in parallel. That’s ideal for I/O, where the futures spend nearly all their time waiting.

    Spawning a task

    tokio::spawn hands a future to the runtime as a separate task, which starts running straight away (on any of the runtime’s threads), like a Promise you don't await yetTask.Run. It returns a JoinHandle, and awaiting the handle gives you the result:

    use std::time::Duration;
    use tokio::time::sleep;
    
    async fn load_user(id: u32, delay_ms: u64) -> String {
        sleep(Duration::from_millis(delay_ms)).await;
        println!("loaded user {id}");
        format!("user {id}")
    }
    
    #[tokio::main]
    async fn main() {
        let handle = tokio::spawn(load_user(1, 50)); // starts running now
        let second = load_user(2, 5).await;
        let first = handle.await.unwrap();
        println!("{first}, {second}");
    }

    Output

    loaded user 2
    loaded user 1
    user 1, user 2

    handle.await returns a Result, which is Err if the task panicked or was aborted. Because a spawned task can run on any thread and can outlive the function that spawned it, tokio::spawn has the same two bounds as thread::spawn: the future must be 'static (it owns its data, so use async move and Arc rather than borrowing locals), and it must be Send. A future is Send only if everything it holds across an .await is Send, because the runtime may resume it on a different thread after each .await. So an Rc or a std::sync::MutexGuard kept alive across an .await makes the task impossible to spawn. Send & Sync explains the rule.

    Cancelling: drop the future

    TypeScriptC# can’t stop an async operation from the outside: you pass an AbortSignala CancellationToken into it, and every level checks it or passes it on. In Rust, a future only makes progress while it’s polled, so to cancel it you stop polling it and drop it. Here a report takes 200 ms but we’ll only wait 10:

    TypeScript
    report.ts
    import { setTimeout as sleep } from "node:timers/promises";
    
    async function buildReport(signal: AbortSignal): Promise<string> {
      await sleep(200, undefined, { signal });
      console.log("report finished");
      return "report";
    }
    
    try {
      const report = await buildReport(AbortSignal.timeout(10));
      console.log(`got ${report}`);
    } catch {
      console.log("timed out");
    }
    C#
    Report.cs
    using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(10));
    try
    {
        var report = await BuildReport(timeout.Token);
        Console.WriteLine($"got {report}");
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine("timed out");
    }
    
    static async Task<string> BuildReport(CancellationToken token)
    {
        await Task.Delay(200, token);
        Console.WriteLine("report finished");
        return "report";
    }
    Rust
    use std::time::Duration;
    use tokio::time::{sleep, timeout};
    
    async fn build_report() -> String {
        sleep(Duration::from_millis(200)).await;
        println!("report finished");
        String::from("report")
    }
    
    #[tokio::main]
    async fn main() {
        match timeout(Duration::from_millis(10), build_report()).await {
            Ok(report) => println!("got {report}"),
            Err(_) => println!("timed out"),
        }
    }

    Output

    timed out

    build_report takes no token. tokio::time::timeout polls it alongside a timer; when the timer wins, timeout returns Err and drops the report’s future. The future stops at the .await it was paused on, so "report finished" never prints. Its local variables are dropped as usual, so files close and locks unlock. Any future can be cancelled this way, including ones from libraries that know nothing about cancellation.

    tokio::select! is the general form: it waits on several futures, runs the branch of the first one to finish, and drops the rest.

    use std::time::Duration;
    use tokio::time::sleep;
    
    async fn fetch_from(server: &str, delay_ms: u64) -> String {
        sleep(Duration::from_millis(delay_ms)).await;
        println!("{server} finished");
        format!("reply from {server}")
    }
    
    #[tokio::main]
    async fn main() {
        let reply = tokio::select! {
            reply = fetch_from("primary", 50) => reply,
            reply = fetch_from("mirror", 5) => reply,
        };
        println!("{reply}");
    }

    Output

    mirror finished
    reply from mirror

    Compare Promise.race: it gives you the first result, but the losing promise keeps running in the background, and here it would still print primary finished later.Compare Task.WhenAny: it gives you the first task to finish, but the others keep running unless you also cancel their tokens. With select!, the loser is gone: primary finished never prints.

    Never block the runtime

    A Tokio runtime runs many tasks on a few threads (by default, one per CPU core). A task gives its thread back only at an .await. So anything that holds a thread for a long time without awaiting, such as a CPU-heavy loop, std::thread::sleep, or a blocking call like std::fs::read, stalls every other task waiting for that thread. It’s the same rule as Node’s event loop, where a long synchronous loop freezes everything.It’s the same reason you don’t call .Result or Thread.Sleep inside async C# code, only stricter: when its threads are blocked, the .NET thread pool slowly injects more, but Tokio keeps its fixed set of worker threads, so a blocked worker stays blocked.

    For CPU-heavy work or blocking calls, tokio::task::spawn_blocking runs a closure on a separate pool of threads meant for blocking, and gives you a handle to await:

    TypeScript
    primes.ts
    import { Worker, isMainThread, parentPort } from "node:worker_threads";
    
    function countPrimes(limit: number): number {
      let count = 0;
      for (let n = 2; n < limit; n++) {
        let isPrime = true;
        for (let d = 2; d * d <= n; d++) {
          if (n % d === 0) {
            isPrime = false;
            break;
          }
        }
        if (isPrime) {
          count++;
        }
      }
      return count;
    }
    
    if (isMainThread) {
      // A long loop would block the event loop, so it runs on a worker thread.
      const count = await new Promise<number>((resolve, reject) => {
        const worker = new Worker(new URL(import.meta.url));
        worker.once("message", resolve);
        worker.once("error", reject);
      });
      console.log(`${count} primes below 50000`);
    } else {
      parentPort?.postMessage(countPrimes(50_000));
    }
    C#
    Primes.cs
    // A long loop would hold up the caller, so it runs on the thread pool.
    var count = await Task.Run(() => CountPrimes(50_000));
    Console.WriteLine($"{count} primes below 50000");
    
    static int CountPrimes(int limit) => Enumerable.Range(2, limit - 2).Count(IsPrime);
    
    static bool IsPrime(int n)
    {
        for (var d = 2; d * d <= n; d++)
        {
            if (n % d == 0)
            {
                return false;
            }
        }
        return true;
    }
    Rust
    fn count_primes(limit: u32) -> usize {
        (2..limit)
            .filter(|&n| (2..).take_while(|d| d * d <= n).all(|d| n % d != 0))
            .count()
    }
    
    #[tokio::main]
    async fn main() {
        let count = tokio::task::spawn_blocking(|| count_primes(50_000))
            .await
            .unwrap();
        println!("{count} primes below 50000");
    }

    Output

    5133 primes below 50000

    While the closure runs on the blocking pool, the runtime’s own threads stay free for other tasks. The same goes for blocking I/O: use Tokio’s async versions where they exist (tokio::time::sleep, tokio::fs, tokio::net), and wrap a blocking library call in spawn_blocking where they don’t. For long-running parallel computation, an ordinary thread from the first lesson in this module is often simpler than async.

    Which one should I use?

    WhatWhenWhyHow
    .await in sequenceEach step needs the previous step’s result.Simplest: reads like synchronous code.let user = load_user(1).await;
    tokio::join!A fixed set of independent operations, all needed.Runs them concurrently on the current task, with no spawning and no 'static or Send bounds.let (a, b) = tokio::join!(load(1), load(2));
    tokio::spawnWork that should run on its own, possibly in parallel, or a number of tasks you only know at run time.Starts immediately on any runtime thread; the handle can be awaited or aborted later.let handle = tokio::spawn(async move { ... }); handle.await?
    tokio::select!, timeoutThe first of several results wins, or an operation needs a deadline.The losers are dropped, which cancels them.timeout(Duration::from_millis(500), op).await
    spawn_blockingCPU-heavy work or a blocking call inside async code.Keeps the runtime’s threads free for other tasks.tokio::task::spawn_blocking(|| work()).await?
    Threads (thread::scope, thread::spawn)Parallel CPU work with no I/O to wait on.No runtime needed, and scoped threads can borrow local data.See Threads, channels & shared state.

    The same choice as a path through the questions, when you have some work to run off the current flow:

    Thread, scoped thread, async task or spawn_blocking?
    1. Are you inside async code, and does the work burn CPU or call something that blocks?

      Yes

      Use tokio::task::spawn_blockingIt runs the closure on Tokio's blocking pool and gives you a handle to .await.

      No
    2. Is the work mostly waiting: network calls, timers, many connections at once?

      Yes

      Use async tasks: tokio::join! for a few, tokio::spawn for many or long-lived onesThousands of waiting tasks share a few threads.

      No
    3. Does the work borrow local data and end before your function returns?

      Yes

      Use std::thread::scopeThreads borrow with plain references and are joined for you.

      No
    4. Otherwise: Use std::thread::spawn with a move closure, and keep its JoinHandle to join it later.

    Rule of thumb: use async for waiting and threads for computing. Inside async code, await things one after another when each needs the last, use join! to wait for several at once, and spawn a task when work should run on its own. Anything that blocks or computes for more than a moment goes to spawn_blocking.

    Under the hood

    A future is any type that implements the standard library’s Future trait, which has one method: poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>. poll either returns Poll::Ready(value), or returns Poll::Pending after arranging to be woken up: it hands the waker in cx to whatever it’s waiting on (a timer, a socket), which calls wake() when there’s progress. The runtime then polls it again. Nothing runs between polls, which is why futures are lazy and why dropping one cancels it. Here’s a hand-written future that asks to be polled twice more before it finishes:

    use std::future::Future;
    use std::pin::Pin;
    use std::task::{Context, Poll};
    
    struct Countdown(u32);
    
    impl Future for Countdown {
        type Output = &'static str;
    
        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            if self.0 == 0 {
                return Poll::Ready("liftoff");
            }
            println!("polled: {} to go", self.0);
            self.0 -= 1;
            cx.waker().wake_by_ref(); // ready to be polled again right away
            Poll::Pending
        }
    }
    
    #[tokio::main]
    async fn main() {
        println!("{}", Countdown(2).await);
    }

    Output

    polled: 2 to go
    polled: 1 to go
    liftoff

    You’ll rarely write poll yourself. The compiler turns each async fn into a state machine: an enum with one variant per .await point, holding the local variables that are still needed there. Each poll runs the body from the current point to the next .await that isn’t ready. C# does the same for async methods, but the caller starts the state machine immediately and the resulting Task lives on the heap.A JavaScript engine suspends and resumes async functions in a similar way, but it starts them when they’re called, and every promise is a heap object. A Rust future is a plain value: it can sit on the stack or inside another future, with no allocation, until you spawn it.

    Pin guarantees the future won’t be moved in memory once polling starts, because the state machine may hold references into itself (a local borrowing another local across an .await). .await, join! and spawn handle pinning for you.

    #[tokio::main] is shorthand for building a runtime and blocking the real main on your async code:

    fn main() {
        tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(async {
                println!("hello from Tokio");
            });
    }

    Output

    hello from Tokio

    The multi-threaded runtime starts one worker thread per CPU core. Idle workers steal tasks from busy ones, which is why a spawned task can resume on a different thread after any .await, and why spawned futures must be Send. #[tokio::main(flavor = "current_thread")] runs everything on one thread instead, much like Node's event loopa UI thread's synchronization context.

    Common pitfalls

    Common pitfallAwaiting one by one is not concurrent

    TypeScriptC# code often starts two operations and then awaits them, because promisestasks are already running by the time you await. In Rust, the futures don’t start until they’re awaited, so this runs them one after the other:

    use std::time::Duration;
    use tokio::time::sleep;
    
    async fn load_user(id: u32, delay_ms: u64) -> String {
        sleep(Duration::from_millis(delay_ms)).await;
        println!("loaded user {id}");
        format!("user {id}")
    }
    
    #[tokio::main]
    async fn main() {
        let first = load_user(1, 50);
        let second = load_user(2, 5);
        println!("{}, {}", first.await, second.await); // one after the other
    }

    Output

    loaded user 1
    loaded user 2
    user 1, user 2

    User 1 finishes first even though it’s slower, because user 2 hadn’t started. Use tokio::join!(first, second) to run them together, or tokio::spawn to start one in the background.

    Common pitfallHolding a std Mutex lock across .await

    A std::sync::MutexGuard held across an .await blocks the thread for every other task that wants the lock, and can deadlock if the task holding it is waiting to run on that same thread. Spawned tasks can’t do it at all: the guard isn’t Send, so tokio::spawn rejects the future, and clippy’s await_holding_lock lint flags it everywhere else. Either drop the guard before the .await, or, when you really need to keep the lock while you wait, use tokio::sync::Mutex, whose lock() is itself awaited:

    use std::sync::Arc;
    use std::time::Duration;
    use tokio::sync::Mutex;
    use tokio::time::sleep;
    
    async fn record_visit(log: Arc<Mutex<Vec<String>>>, page: &str) {
        let mut entries = log.lock().await; // waits without blocking the thread
        sleep(Duration::from_millis(2)).await; // fine: this guard can be held across .await
        entries.push(page.to_string());
    }
    
    #[tokio::main]
    async fn main() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let handles: Vec<_> = ["home", "about", "blog"]
            .into_iter()
            .map(|page| tokio::spawn(record_visit(Arc::clone(&log), page)))
            .collect();
        for handle in handles {
            handle.await.unwrap();
        }
        println!("{} visits", log.lock().await.len());
    }

    Output

    3 visits

    For short updates that never wait while locked, std::sync::Mutex is fine in async code, and faster.

    Common pitfallDropping a JoinHandle doesn't cancel the task

    Dropping a future cancels it, but a spawned task belongs to the runtime: dropping its JoinHandle only means nobody waits for the result, and the task keeps running. To stop it, call handle.abort(). And when main returns, the runtime shuts down and drops every task still running, so await the handles of tasks whose work must finish.

    Try it yourself

    Exercise: port this to Rust

    Port this program to Rust. It fetches three prices at the same time and gives up if they take longer than 500 ms in total.

    Starting code in TypeScript
    prices.ts
    import { setTimeout as sleep } from "node:timers/promises";
    
    async function fetchPrice(item: string, signal: AbortSignal): Promise<number> {
      await sleep(5, undefined, { signal });
      switch (item) {
        case "apple":
          return 120;
        case "bread":
          return 250;
        default:
          return 99;
      }
    }
    
    const signal = AbortSignal.timeout(500);
    try {
      const [apple, bread, milk] = await Promise.all([
        fetchPrice("apple", signal),
        fetchPrice("bread", signal),
        fetchPrice("milk", signal),
      ]);
      console.log(`total: ${apple + bread + milk} cents`);
    } catch {
      console.log("prices took too long");
    }
    Starting code in C#
    Prices.cs
    using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
    try
    {
        var prices = await Task.WhenAll(
            FetchPrice("apple", timeout.Token),
            FetchPrice("bread", timeout.Token),
            FetchPrice("milk", timeout.Token));
        Console.WriteLine($"total: {prices.Sum()} cents");
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine("prices took too long");
    }
    
    static async Task<int> FetchPrice(string item, CancellationToken token)
    {
        await Task.Delay(5, token);
        return item switch
        {
            "apple" => 120,
            "bread" => 250,
            _ => 99,
        };
    }

    Expected output

    total: 469 cents
    Show a hint

    Write async fn fetch_price(item: &str) -> u32 that sleeps 5 ms with tokio::time::sleep, then matches the item. In main, put tokio::join! of the three calls inside an async block, and pass that block to tokio::time::timeout with a 500 ms limit. No token is needed.

    Show a solution
    use std::time::Duration;
    use tokio::time::{sleep, timeout};
    
    async fn fetch_price(item: &str) -> u32 {
        sleep(Duration::from_millis(5)).await;
        match item {
            "apple" => 120,
            "bread" => 250,
            _ => 99,
        }
    }
    
    #[tokio::main]
    async fn main() {
        let all = async {
            tokio::join!(
                fetch_price("apple"),
                fetch_price("bread"),
                fetch_price("milk")
            )
        };
        match timeout(Duration::from_millis(500), all).await {
            Ok((apple, bread, milk)) => println!("total: {} cents", apple + bread + milk),
            Err(_) => println!("prices took too long"),
        }
    }

    tokio::join! runs the three futures concurrently and returns their results as a tuple. Wrapping it in an async block makes one future that timeout can poll and, if the time runs out, drop: that cancels all three fetches without passing a signal or token through them. match on the Result handles both outcomes.

    Saved in this browser only.