medium.com 5 min read Original Source

Let’s Learn Rust 008: Async/Await and Tokio

In the last article we covered threads. Threads are great for CPU-heavy work where you actually want parallel execution across multiple cores. But a huge chunk of real-world programming is waiting. Waiting for a database to respond. Waiting for an HTTP request to come back. Waiting for a file to finish reading.

Spinning up a full OS thread just to sit and wait is wasteful. This is where async comes in, and it is one of the areas where Rust really stands out once you get past the initial learning curve.

I will be upfront: async Rust has a steeper learning curve than threads. When I first read about futures and polling it felt abstract. So we will start from the ground up and build toward real patterns you will actually use in production.

1. What Is Async and Why Does It Exist?

The classic analogy is a restaurant. A synchronous waiter takes your order, walks to the kitchen, stands there and waits for the food, brings it back, then goes to the next table. An async waiter takes your order, drops it at the kitchen, serves three other tables while the food is being prepared, then comes back when it is ready.

Both waiters are doing the same work. The async one is just not wasting time standing around.

In code, synchronous looks like this:

String {
let result = make_http_request(); // blocks the whole thread for 2 seconds
result
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn fetch_data() -> String {
    let result = make_http_request(); // blocks the whole thread for 2 seconds
    result
}
fn fetch_data() -> String {
    let result = make_http_request(); // blocks the whole thread for 2 seconds
    result
}

The whole thread is frozen while waiting. In Python you have seen this with requests.get(), one slow call blocks everything. In Java you would typically throw this onto a background thread to avoid the freeze. In Rust, async lets you handle thousands of these waits efficiently without the overhead of a full thread per task.

2. The async and await Keywords

Mark a function as async and it returns a Future instead of a value directly:

async fn say_hello() {
    println!("Hello from async!");
}
async fn say_hello() {
    println!("Hello from async!");
}

To run it, you await it:

async fn main() {
    say_hello().await;
}
async fn main() {
    say_hello().await;
}

A Future in Rust is a value that represents work that will be done at some point. Calling say_hello() does nothing on its own. It creates a Future. Calling .await on it actually runs it.

This is similar to JavaScript’s Promise or Python’s coroutine, but with one key difference. Rust Futures do absolutely nothing until you await them or hand them to a runtime. There is no background execution happening automatically.

3. You Need a Runtime

This is the part that surprises people coming from JavaScript or Python. Rust has no built-in async runtime. The language gives you the Future type and the async/await syntax. You bring the runtime yourself.

The standard choice is Tokio. Add it to your Cargo.toml:

[dependencies]
tokio = { version = "1", features = ["full"] }
[dependencies]
tokio = { version = "1", features = ["full"] }

Then use the #[tokio::main] macro to set up the runtime:

#[tokio::main]
async fn main() {
    println!("Running on Tokio!");
}
#[tokio::main]
async fn main() {
    println!("Running on Tokio!");
}

That macro wraps your main function in a Tokio runtime. Without it you cannot use .await at the top level.

4. Writing Your First Real Async Function

Let’s write something practical. A function that simulates fetching data with a delay:

String {
sleep(Duration::from_millis(500)).await;
format!("User #{}", id)
}
#[tokio::main]
async fn main() {
let user = fetch_user(1).await;
println!("{}", user);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use tokio::time::{sleep, Duration};

async fn fetch_user(id: u32) -> String {
    sleep(Duration::from_millis(500)).await;
    format!("User #{}", id)
}
#[tokio::main]
async fn main() {
    let user = fetch_user(1).await;
    println!("{}", user);
}
use tokio::time::{sleep, Duration};

async fn fetch_user(id: u32) -> String {
    sleep(Duration::from_millis(500)).await;
    format!("User #{}", id)
}
#[tokio::main]
async fn main() {
    let user = fetch_user(1).await;
    println!("{}", user);
}

The sleep here is Tokio’s async sleep, not std::thread::sleep. The difference matters. std::thread::sleep blocks the entire thread. tokio::time::sleep yields control back to the runtime so other tasks can run while this one waits.

In Python this is the difference between asyncio.sleep() and time.sleep(). Same idea.

5. Running Tasks Concurrently

The real power comes when you run multiple async tasks at the same time. tokio::spawn works like thread::spawn but for async tasks:

String {
sleep(Duration::from_millis(500)).await;
format!("User #{}", id)
}
#[tokio::main]
async fn main() {
let task1 = tokio::spawn(fetch_user(1));
let task2 = tokio::spawn(fetch_user(2));
let task3 = tokio::spawn(fetch_user(3));
let (u1, u2, u3) = tokio::join!(task1, task2, task3);
println!("{}", u1.unwrap());
println!("{}", u2.unwrap());
println!("{}", u3.unwrap());
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use tokio::time::{sleep, Duration};

async fn fetch_user(id: u32) -> String {
    sleep(Duration::from_millis(500)).await;
    format!("User #{}", id)
}
#[tokio::main]
async fn main() {
    let task1 = tokio::spawn(fetch_user(1));
    let task2 = tokio::spawn(fetch_user(2));
    let task3 = tokio::spawn(fetch_user(3));
    let (u1, u2, u3) = tokio::join!(task1, task2, task3);
    println!("{}", u1.unwrap());
    println!("{}", u2.unwrap());
    println!("{}", u3.unwrap());
}
use tokio::time::{sleep, Duration};

async fn fetch_user(id: u32) -> String {
    sleep(Duration::from_millis(500)).await;
    format!("User #{}", id)
}
#[tokio::main]
async fn main() {
    let task1 = tokio::spawn(fetch_user(1));
    let task2 = tokio::spawn(fetch_user(2));
    let task3 = tokio::spawn(fetch_user(3));
    let (u1, u2, u3) = tokio::join!(task1, task2, task3);
    println!("{}", u1.unwrap());
    println!("{}", u2.unwrap());
    println!("{}", u3.unwrap());
}

All three calls run concurrently. Total time is roughly 500ms, not 1500ms. In Java you would typically manage an ExecutorService and a thread pool to get the same result. In Python you would use asyncio.gather(). Rust’s tokio::join! macro does the same job and the compiler verifies the types at compile time.

6. Async Error Handling

Async functions return Results just like regular functions and the ? operator works the same way:

Result {
if url.starts_with("https") {
Ok(format!("Data from {}", url))
} else {
Err(format!("Insecure URL: {}", url))
}
}

async fn process() -> Result {
let data = fetch_data("https://example.com").await?;
println!("Processing: {}", data);
Ok(())
}
#[tokio::main]
async fn main() {
match process().await {
Ok(_) => println!("Done"),
Err(e) => println!("Failed: {}", e),
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

async fn fetch_data(url: &str) -> Result<String, String> {
    if url.starts_with("https") {
        Ok(format!("Data from {}", url))
    } else {
        Err(format!("Insecure URL: {}", url))
    }
}

async fn process() -> Result<(), String> {
    let data = fetch_data("https://example.com").await?;
    println!("Processing: {}", data);
    Ok(())
}
#[tokio::main]
async fn main() {
    match process().await {
        Ok(_) => println!("Done"),
        Err(e) => println!("Failed: {}", e),
    }
}
async fn fetch_data(url: &str) -> Result<String, String> {
    if url.starts_with("https") {
        Ok(format!("Data from {}", url))
    } else {
        Err(format!("Insecure URL: {}", url))
    }
}

async fn process() -> Result<(), String> {
    let data = fetch_data("https://example.com").await?;
    println!("Processing: {}", data);
    Ok(())
}
#[tokio::main]
async fn main() {
    match process().await {
        Ok(_) => println!("Done"),
        Err(e) => println!("Failed: {}", e),
    }
}

Nothing special to learn here. Error handling in async code follows the exact same patterns from article 006.

7. Channels in Async Code

In the last article we used std::sync::mpsc for communication between threads. In async code you use Tokio’s channels. The API is similar but built for async tasks:

use tokio::sync::mpsc;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = mpsc::channel(32); // buffer of 32 messages
    tokio::spawn(async move {
        for i in 0..5 {
            tx.send(format!("message {}", i)).await.unwrap();
        }
    });
    while let Some(msg) = rx.recv().await {
        println!("Received: {}", msg);
    }
}
use tokio::sync::mpsc;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = mpsc::channel(32); // buffer of 32 messages
    tokio::spawn(async move {
        for i in 0..5 {
            tx.send(format!("message {}", i)).await.unwrap();
        }
    });
    while let Some(msg) = rx.recv().await {
        println!("Received: {}", msg);
    }
}

The 32 is the channel buffer size. If the sender fills the buffer and the receiver has not caught up, the sender waits. This gives you natural backpressure, something you have to implement manually in most other async systems.

8. tokio::select! for Racing Tasks

select! lets you wait on multiple async operations and react to whichever finishes first. This is useful for timeouts, cancellation, or picking between two data sources:

&'static str {
sleep(Duration::from_secs(5)).await;
"slow result"
}
async fn fast_task() -> &'static str {
sleep(Duration::from_millis(100)).await;
"fast result"
}
#[tokio::main]
async fn main() {
tokio::select! {
result = slow_task() => println!("Slow won: {}", result),
result = fast_task() => println!("Fast won: {}", result),
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use tokio::time::{sleep, Duration};

async fn slow_task() -> &'static str {
    sleep(Duration::from_secs(5)).await;
    "slow result"
}
async fn fast_task() -> &'static str {
    sleep(Duration::from_millis(100)).await;
    "fast result"
}
#[tokio::main]
async fn main() {
    tokio::select! {
        result = slow_task() => println!("Slow won: {}", result),
        result = fast_task() => println!("Fast won: {}", result),
    }
}
use tokio::time::{sleep, Duration};

async fn slow_task() -> &'static str {
    sleep(Duration::from_secs(5)).await;
    "slow result"
}
async fn fast_task() -> &'static str {
    sleep(Duration::from_millis(100)).await;
    "fast result"
}
#[tokio::main]
async fn main() {
    tokio::select! {
        result = slow_task() => println!("Slow won: {}", result),
        result = fast_task() => println!("Fast won: {}", result),
    }
}

This prints “Fast won: fast result” because fast_task finishes first and slow_task gets cancelled. In Go this is a core language feature done with a select statement over channels. In Java it takes considerably more boilerplate to express cleanly. In Python asyncio.wait() with FIRST_COMPLETED does the same thing but the ergonomics are rougher.

9. A Real Pattern: Parallel Calls with Timeout

Here is something you will actually use. Fetch multiple things in parallel but give up if it takes too long:

Result {
sleep(Duration::from_millis(id as u64 * 200)).await;
Ok(format!("Result for id {}", id))
}
#[tokio::main]
async fn main() {
let results = tokio::join!(
timeout(Duration::from_secs(1), fetch(1)),
timeout(Duration::from_secs(1), fetch(2)),
timeout(Duration::from_secs(1), fetch(6)), // takes 1200ms, will timeout
);
for result in [results.0, results.1, results.2] {
match result {
Ok(Ok(data)) => println!("Got: {}", data),
Ok(Err(e)) => println!("Task error: {}", e),
Err(_) => println!("Timed out"),
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use tokio::time::{sleep, Duration, timeout};

async fn fetch(id: u32) -> Result<String, String> {
    sleep(Duration::from_millis(id as u64 * 200)).await;
    Ok(format!("Result for id {}", id))
}
#[tokio::main]
async fn main() {
    let results = tokio::join!(
        timeout(Duration::from_secs(1), fetch(1)),
        timeout(Duration::from_secs(1), fetch(2)),
        timeout(Duration::from_secs(1), fetch(6)), // takes 1200ms, will timeout
    );
    for result in [results.0, results.1, results.2] {
        match result {
            Ok(Ok(data)) => println!("Got: {}", data),
            Ok(Err(e)) => println!("Task error: {}", e),
            Err(_) => println!("Timed out"),
        }
    }
}
use tokio::time::{sleep, Duration, timeout};

async fn fetch(id: u32) -> Result<String, String> {
    sleep(Duration::from_millis(id as u64 * 200)).await;
    Ok(format!("Result for id {}", id))
}
#[tokio::main]
async fn main() {
    let results = tokio::join!(
        timeout(Duration::from_secs(1), fetch(1)),
        timeout(Duration::from_secs(1), fetch(2)),
        timeout(Duration::from_secs(1), fetch(6)), // takes 1200ms, will timeout
    );
    for result in [results.0, results.1, results.2] {
        match result {
            Ok(Ok(data)) => println!("Got: {}", data),
            Ok(Err(e)) => println!("Task error: {}", e),
            Err(_) => println!("Timed out"),
        }
    }
}

Three calls running concurrently. The third one takes 1200ms which exceeds the 1 second timeout so it gets cancelled. This pattern shows up everywhere in production services and async Rust makes it clean to express.

10. Async vs Threads: When to Use Which

Use threads when the work is CPU-heavy. Compressing files, processing images, running algorithms. You want real parallel execution across cores.

Use async when the work is I/O-heavy. HTTP requests, database queries, reading files. You are mostly waiting and you want to handle many of those waits efficiently on fewer threads.

In Python the choice is partly forced because the GIL limits threads for CPU work. In Java virtual threads from Project Loom are a newer addition that gives similar async-style concurrency. In C++ async support exists but the ergonomics are nowhere near as clean.

Tokio under the hood runs a thread pool and distributes async tasks across those threads. You get real parallelism from the thread pool and efficient I/O handling from the async model at the same time.

Summary

Async functions return Futures and .await runs them. Tokio is the runtime. tokio::spawn for concurrent tasks, tokio::join! to wait on multiple, tokio::select! to race tasks against each other, and Tokio channels for async communication.

Async Rust has a reputation for being hard. The difficulty is mostly in the mental model shift, not in the syntax. Once you stop thinking about calling a function and start thinking about creating scheduled work, it becomes much more intuitive. I spent about a week going back and forth on it before it clicked. Stick with it.

What’s Next

Next up is a deep dive into closures and iterators. Two of the most used features in day-to-day Rust and there is a lot of depth beyond what we have touched on so far.

Happy coding and safe assembling!

Follow this series and join us in mastering Rust from scratch!