Learn Rust · 13/14

Asynchronous Rust (Async/Await)

8 min read

Asynchronous Rust (Async/Await) 🦀

Welcome to the exciting world of Asynchronous Rust! If you've ever dealt with tasks that take a while to complete, like fetching data from a network or reading a large file, you've probably encountered situations where your program just...stops and waits. Async Rust is here to change that, allowing your programs to handle multiple things at once without getting bogged down.


1. Introduction to Asynchronous Programming: Why Async?

The Problem: The Waiting Game

Imagine you're a librarian in a very popular, but slightly inefficient, library. A person comes to you and asks for a specific book. You go to the shelves, search for it, and while you're gone, a long line forms at your desk. Nobody else can be helped until you return with that one book. This is what synchronous, or "blocking," programming is like. When a program performs a task that takes time (like a network request), it blocks everything else from happening until that task is complete.

In the world of servers and network services, this is a huge problem. If your web server can only handle one request at a time, it won't be able to serve many users effectively.

The Solution: Asynchronous Programming

Asynchronous programming is a way to tell your program: "Hey, this task might take a while. While you're waiting for it to finish, feel free to work on other things." It's like our librarian, instead of making everyone wait, takes a request, sends an assistant to find the book, and in the meantime, helps the next person in line. When the assistant returns with the book, the librarian can then give it to the original requester.

In Rust, this is achieved with async/await. This allows a program to handle a large number of concurrent tasks on a small number of operating system threads. This is especially beneficial for I/O-bound tasks, which are tasks that spend most of their time waiting for input/output operations like network requests or database queries.

Interesting Fact: The concept of async/await was popularized by other languages like C# and JavaScript, but Rust's implementation has some unique, powerful features, like being "zero-cost," which means you only pay for what you use in terms of performance.


2. The Future Trait and State Machines

The Core Idea: A Promise of a Value

At the heart of async Rust is the Future trait. A Future is a value that represents a computation that may not be complete yet. Think of it as a voucher for a value you'll receive in the... well, future! This is similar to Promises in JavaScript.

A key difference in Rust is that Futures are lazy. They don't do anything until they are actively "polled." It's like having a ticket for a free pizza; the pizza won't magically appear at your door. You have to go to the pizza place and give them the ticket to get it.

The simplified definition of the Future trait looks something like this:

rust
trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
  • Output: The type of value the future will produce when it's done.
  • poll: This is the method that an async runtime calls to see if the future is ready. It can return one of two things:
    • Poll::Ready(value): The future is complete, and here's the result!
    • Poll::Pending: The future is not ready yet. When it is ready to make progress again, it will notify the runtime via the Waker in the Context.

Under the Hood: The State Machine 🤖

When you write an async function, the Rust compiler does something magical behind the scenes. It transforms your function into a state machine. This state machine implements the Future trait.

Every .await point in your function becomes a state in this machine. When a future is polled and it's not ready yet (Poll::Pending), it saves its current state and yields control back to the runtime. When it's woken up later, it resumes from where it left off.

This is a powerful concept because it allows Rust to manage asynchronous operations with very low overhead, without needing a garbage collector or heavy runtime support.


3. Using async and await Syntaxes

Now for the fun part! While understanding Futures and state machines is great, Rust provides the async and await keywords to make working with asynchronous code much more ergonomic and feel almost like writing synchronous code.

async: Creating a Future

The async keyword can be used in front of a function (fn), a block, or a closure. This tells the compiler to turn that piece of code into a state machine that implements the Future trait.

rust
// This function now returns a Future that will eventually produce a u32
async fn my_async_function() -> u32 {
    // some asynchronous work here
    42
}

When you call my_async_function(), it doesn't execute the code inside immediately. Instead, it returns a Future that represents that computation.

await: Waiting for a Future to Complete

The await keyword is used inside an async function or block to pause execution until a Future is ready. It's the action of "polling" the future until it returns Poll::Ready.

rust
async fn another_async_function() {
    println!("Before awaiting");
    let result = my_async_function().await;
    println!("After awaiting, the result is: {}", result);
}

When you use .await, it doesn't block the entire thread. Instead, it yields control back to the async runtime, which can then run other tasks. Once the awaited future is complete, the runtime will schedule this task to continue its execution.

Here's a more complete example that simulates a network request:

rust
use std::time::Duration;

async fn fetch_data_from_server() -> String {
    // Simulate a network delay
    tokio::time::sleep(Duration::from_secs(2)).await;
    "Hello from the server!".to_string()
}

#[tokio::main]
async fn main() {
    let data = fetch_data_from_server().await;
    println!("{}", data);
}

Important Note: You can only use .await inside an async function or block.


4. Introduction to Tokio: The Async Runtime Ecosystem 🚀

So, we've learned that futures need to be polled to make progress. But what is responsible for polling them? That's where an async runtime comes in. Rust itself doesn't ship with a built-in runtime. This gives developers the flexibility to choose a runtime that best fits their needs.

The most popular and widely used async runtime in the Rust ecosystem is Tokio.

What is Tokio?

Tokio is an asynchronous runtime for Rust that provides the building blocks for writing fast and reliable network applications. It includes:

  • A multi-threaded, work-stealing task scheduler to execute your futures.
  • Asynchronous versions of standard library components like TCP/UDP sockets, file system operations, and timers.
  • Synchronization primitives for asynchronous tasks like channels and mutexes.

Getting Started with Tokio

First, you'll need to add Tokio as a dependency in your Cargo.toml file. It's common to enable the "full" feature flag when you're getting started, as it includes all the necessary components.

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

Now, let's write a simple "Hello, world!" with Tokio.

rust
#[tokio::main]
async fn main() {
    println!("Hello, async world!");
}

The #[tokio::main] macro is a convenient way to set up the Tokio runtime and execute an async main function. It transforms your async fn main() into a regular fn main() that initializes the runtime and runs your async code.

Spawning Tasks with tokio::spawn

A core feature of Tokio is the ability to spawn concurrent tasks. tokio::spawn takes a future and runs it in the background, allowing your program to continue with other work. It returns a JoinHandle, which you can .await to get the result of the spawned task.

rust
use std::time::Duration;

async fn task_one() {
    for i in 1..=5 {
        println!("Task one: {}", i);
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

async fn task_two() {
    for i in 1..=3 {
        println!("Task two: {}", i);
        tokio::time::sleep(Duration::from_millis(1000)).await;
    }
}

#[tokio::main]
async fn main() {
    let handle_one = tokio::spawn(task_one());
    let handle_two = tokio::spawn(task_two());

    // Wait for both tasks to complete
    handle_one.await.unwrap();
    handle_two.await.unwrap();
    
    println!("All tasks are complete!");
}

If you run this code, you'll see the output from both tasks interleaved, demonstrating that they are running concurrently!

Real-world Analogy: A Busy Restaurant Kitchen

Imagine a bustling restaurant kitchen on a Saturday night.

  • Synchronous Kitchen: One chef tries to do everything. They take an order, chop the vegetables, cook the main course, plate it, and then send it out. They won't even look at the next order until the first one is completely finished. The result? A lot of hungry, unhappy customers.

  • Asynchronous Kitchen (with Tokio): You have a head chef (the Tokio runtime) who manages a team of cooks (worker threads).

    • An order comes in (a new task is spawned).
    • The head chef assigns the task of chopping vegetables to one cook.
    • While that cook is busy, another cook can start grilling the steak for a different order. This is non-blocking I/O.
    • If a cook needs to wait for the oven to preheat (an I/O-bound operation), they don't just stand there. They notify the head chef and can be assigned another small task, like getting a plate ready. This is yielding with .await.
    • The head chef efficiently juggles all these tasks, ensuring the kitchen is always making progress on multiple orders at once. This is the role of the scheduler.

This way, the kitchen can handle a massive volume of orders with a limited number of cooks, keeping everything running smoothly and efficiently.


Further Reading and References

Challenge

You are building a backend service that needs to aggregate data from multiple microservices for a single user request. To keep the service responsive, you must fetch the data concurrently.

Your task is to write an asynchronous Rust program using tokio to simulate this scenario.

Requirements:

  1. Define an async function named fetch_user_data that:

    • Accepts a u32 user ID.
    • Simulates a 1-second network delay using tokio::time::sleep.
    • Returns a String with the format: User data for user {id}.
  2. Define another async function named fetch_posts_data that:

    • Accepts a u32 user ID.
    • Simulates a 1.5-second network delay.
    • Returns a String with the format: Posts for user {id}.
  3. Set up your main function as the entry point for a tokio multi-threaded runtime.

  4. Inside main:

    • Use a sample user_id of 101.
    • Execute both fetch_user_data and fetch_posts_data concurrently for the sample user ID.
    • Wait for both operations to complete and retrieve their results.
    • Print the combined results in the following format: Fetched: [user data], [posts data]. For example: Fetched: User data for user 101, Posts for user 101.

Expected result

Your submitted code should be a complete, runnable Rust program that correctly uses tokio for asynchronous concurrency. The evaluation will check for the following:

  • The main function is correctly annotated with #[tokio::main] and defined with async fn.
  • Two functions, fetch_user_data and fetch_posts_data, are correctly defined with the async fn signature, accepting a u32 and returning a String.
  • Each async function correctly uses tokio::time::sleep(...).await to introduce a delay.
  • The main function uses tokio::spawn to launch both fetch functions, creating two separate concurrent tasks.
  • The JoinHandle returned by tokio::spawn is awaited (handle.await) to get the final String result for each task. The potential Result from awaiting the handle should be handled (e.g., using .unwrap() or ?).
  • A println! macro is used at the end of main to print the combined strings in the exact format: Fetched: User data for user 101, Posts for user 101.
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.