Rust
December 2, 2026 10 min read

Asynchronous Programming in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What Is Asynchronous Programming?

Asynchronous programming allows a program to start an operation and make progress on other work while waiting for that operation to complete.

Consider a simple example.

Suppose your application needs to:

  1. Fetch student information from an API.
  2. Fetch fee information from a database.
  3. Send a notification.

With synchronous programming, these operations may happen one after another.

With asynchronous programming, independent operations can make progress concurrently.

Synchronous Example

fn main() {
println!("Task 1 started");
println!("Task 1 completed");

println!("Task 2 started");
println!("Task 2 completed");
}

Asynchronous Programming

Async programming allows tasks to pause when waiting and resume when their required result becomes available.

This is particularly useful for operations involving network requests, databases, and file I/O.

2. Understanding async

The async keyword is used to define an asynchronous function or block.

Example:

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

However, there is something important to understand.

Calling an async function does not immediately execute its body.

Instead, it creates a value called a Future.

For example:

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

fn main() {
let future = say_hello();

println!("Future created");
}

Output:

Future created

Notice that Hello Rust is not printed.

Why?

Because the Future has not been executed by an asynchronous runtime or otherwise polled.

3. What Is a Future?

A Future represents a value that may become available later.

You can think of it as a task that has not finished yet.

For example:

  1. A web request waiting for a response.
  2. A database query waiting for results.
  3. A file operation waiting to complete.

Rust provides the Future trait.

A simplified definition looks like this:

trait Future {
type Output;

fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output>;
}

You do not normally need to implement this trait manually when starting with async Rust.

Rust generates Future implementations for async functions.

4. What Is an Async Runtime?

Rust's standard library provides the Future abstraction, but it does not include a built-in asynchronous runtime.

A runtime executes and schedules asynchronous tasks.

Popular Rust asynchronous runtimes include:

  1. Tokio
  2. async-std

In this course, we will use Tokio because it is widely used for network applications and backend development.

Installing Tokio

Open your Rust project folder.

Run:

cargo add tokio --features full

This adds Tokio to your Cargo.toml.

Alternatively, add it manually:

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

The full feature enables a broad set of Tokio features, including its runtime, timers, synchronization tools, and networking support.

5. Your First Async Program Using Tokio

Create or update src/main.rs.

#[tokio::main]
async fn main() {
println!("Hello from async Rust!");
}

Run:

cargo run

Output:

Hello from async Rust!

Explanation:

  1. async fn main() defines an asynchronous main function.
  2. #[tokio::main] creates a Tokio runtime.
  3. Tokio executes the async main function.

The Rust compiler does not allow an ordinary async fn main() as the executable entry point without a runtime or another mechanism to execute it.

6. Understanding await

The await keyword waits for an asynchronous operation to produce its result.

Example:

async fn get_student() -> String {
String::from("Hemant")
}

#[tokio::main]
async fn main() {
let student = get_student().await;

println!("Student: {}", student);
}

Output:

Student: Hemant

Explanation:

let student = get_student().await;
  1. get_student() creates a Future.
  2. .await waits for the Future to complete.
  3. The resulting String is assigned to student.

Important: .await can only be used inside an async context.

7. Understanding tokio::time::sleep()

Tokio provides an asynchronous sleep function.

Example:

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

async fn task() {
println!("Task started");

sleep(Duration::from_secs(2)).await;

println!("Task completed");
}

#[tokio::main]
async fn main() {
task().await;
}

Output:

Task started
Task completed

The second message appears after approximately two seconds.

Notice the difference between:

std::thread::sleep()

and:

tokio::time::sleep().await

Thread sleep

Async sleep

Blocks the current thread

Suspends the current async task

Uses std::thread::sleep()

Uses tokio::time::sleep()

Other tasks on that thread cannot run

Runtime can execute other tasks

8. Understanding tokio::spawn()

Tokio provides tokio::spawn() to create a new asynchronous task.

Example:

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

#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
println!("Child task started");

sleep(Duration::from_secs(2)).await;

println!("Child task completed");
});

println!("Main task running");

handle.await.unwrap();
}

Possible Output:

Main task running
Child task started
Child task completed

Explanation:

  1. tokio::spawn() creates a new asynchronous task.
  2. handle stores the JoinHandle.
  3. .await waits for that task to finish.
  4. unwrap() handles a possible task failure.

A spawned Tokio task generally must satisfy the Send + 'static requirements. This is why moving owned values into spawned tasks is common.

9. Running Multiple Async Tasks Concurrently

One of the biggest benefits of asynchronous programming is that multiple tasks can make progress concurrently.

Example:

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

async fn task1() {
println!("Task 1 started");

sleep(Duration::from_secs(2)).await;

println!("Task 1 completed");
}

async fn task2() {
println!("Task 2 started");

sleep(Duration::from_secs(2)).await;

println!("Task 2 completed");
}

#[tokio::main]
async fn main() {
let first = tokio::spawn(task1());
let second = tokio::spawn(task2());

first.await.unwrap();
second.await.unwrap();
}

Possible Output:

Task 1 started
Task 2 started
Task 1 completed
Task 2 completed

Both tasks wait for approximately two seconds concurrently rather than waiting four seconds sequentially.

The exact output order can vary.

10. Understanding tokio::join!

You can use tokio::join! to run multiple Futures concurrently and wait for all of them.

Example:

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

async fn get_student() -> String {
sleep(Duration::from_secs(2)).await;

String::from("Hemant")
}

async fn get_course() -> String {
sleep(Duration::from_secs(2)).await;

String::from("Rust")
}

#[tokio::main]
async fn main() {
let (student, course) = tokio::join!(
get_student(),
get_course()
);

println!("Student: {}", student);
println!("Course: {}", course);
}

Output:

Student: Hemant
Course: Rust

Both operations take approximately two seconds of waiting time rather than four seconds when awaited sequentially.

Difference Between join! and spawn()


tokio::join!

tokio::spawn()

Runs Futures concurrently in the current task

Creates a separate Tokio task

Returns results together

Returns JoinHandles

Does not require spawning separate tasks

Spawned tasks have Send + 'static requirements

Useful for coordinating several operations

Useful for independently scheduled tasks

11. Understanding tokio::try_join!

Sometimes multiple operations can fail.

Tokio provides try_join! to wait for multiple Results.

If one Future returns an error, the macro returns that error and drops the remaining Futures.

Example:

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

async fn get_student() -> Result<String, String> {
sleep(Duration::from_secs(1)).await;

Ok(String::from("Hemant"))
}

async fn get_course() -> Result<String, String> {
sleep(Duration::from_secs(1)).await;

Ok(String::from("Rust"))
}

#[tokio::main]
async fn main() {
let result = tokio::try_join!(
get_student(),
get_course()
);

match result {
Ok((student, course)) => {
println!("Student: {}", student);
println!("Course: {}", course);
}

Err(error) => {
println!("Error: {}", error);
}
}
}

Output:

Student: Hemant
Course: Rust

Here, both functions return Result, so try_join! can propagate an error.

12. Understanding Async Functions with Parameters

Async functions can accept parameters just like regular functions.

Example:

async fn calculate_fee(amount: i32) -> i32 {
amount + 500
}

#[tokio::main]
async fn main() {
let total = calculate_fee(3000).await;

println!("Total Fee: {}", total);
}

Output:

Total Fee: 3500

You can also use async functions with multiple parameters.

async fn student_details(name: &str, course: &str) {
println!("Name: {}", name);
println!("Course: {}", course);
}

#[tokio::main]
async fn main() {
student_details("Hemant", "Rust").await;
}

13. Async Programming with Error Handling

Async functions can return Result<T, E> just like normal functions.

Example:

async fn get_student(id: u32) -> Result<String, String> {
if id == 1 {
Ok(String::from("Hemant"))
} else {
Err(String::from("Student not found"))
}
}

#[tokio::main]
async fn main() {
match get_student(1).await {
Ok(name) => println!("Student: {}", name),
Err(error) => println!("Error: {}", error),
}
}

Output:

Student: Hemant

Using the ? Operator

You can also use ? with asynchronous operations.

async fn get_student(id: u32) -> Result<String, String> {
if id == 1 {
Ok(String::from("Hemant"))
} else {
Err(String::from("Student not found"))
}
}

async fn show_student() -> Result<(), String> {
let student = get_student(1).await?;

println!("Student: {}", student);

Ok(())
}

#[tokio::main]
async fn main() {
if let Err(error) = show_student().await {
println!("Error: {}", error);
}
}

The ? operator propagates the error from get_student() to show_student().

14. Async Programming with HTTP Requests

One of the most common uses of async Rust is making HTTP requests.

For this example, we will use the reqwest library.

Step 1: Install Dependencies

Run:

cargo add reqwest --features json
cargo add serde --features derive
cargo add tokio --features full

Step 2: Create the Program

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Post {
id: u32,
title: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let response = reqwest::get(
"https://jsonplaceholder.typicode.com/posts/1"
)
.await?;

let post: Post = response.json().await?;

println!("Post ID: {}", post.id);
println!("Title: {}", post.title);

Ok(())
}

Example Output:

Post ID: 1
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit

The exact title is supplied by the API and may change.

Explanation

  1. reqwest::get() sends an HTTP GET request.
  2. .await waits for the response.
  3. response.json() converts the response body into the Post structure.
  4. Deserialize allows Serde to deserialize JSON into Rust data.
  5. ? propagates possible errors.

This is similar to calling an API from a Laravel backend application.

15. Understanding Async vs Multithreading

Both asynchronous programming and multithreading can help applications handle multiple tasks.

However, they work differently.


Async Programming

Multithreading

Uses Futures and an async runtime

Uses operating-system threads

Tasks can pause while waiting

Threads execute independently

Excellent for I/O-bound operations

Useful for parallel CPU-intensive work

Tasks are generally lightweight

Threads usually have greater resource overhead

Uses async and await

Uses thread::spawn()

Important: Async programming does not automatically mean that code runs on multiple CPU cores.

An asynchronous runtime can execute many tasks on one thread or across multiple threads.

16. Understanding Blocking Operations

A blocking operation prevents the current thread from doing other work while it waits.

Example:

std::thread::sleep(std::time::Duration::from_secs(5));

Using this directly inside an async task can block a Tokio worker thread.

Prefer:

tokio::time::sleep(
std::time::Duration::from_secs(5)
).await;

For blocking operations that cannot be made asynchronous, Tokio provides spawn_blocking().

Example:

#[tokio::main]
async fn main() {
let result = tokio::task::spawn_blocking(|| {
let mut total = 0;

for number in 1..=1_000_000 {
total += number;
}

total
})
.await
.unwrap();

println!("Total: {}", result);
}

This moves the blocking or CPU-intensive closure to Tokio's blocking thread pool.

17. Common Mistakes


Mistake

Explanation

Calling an async function without awaiting or spawning it

The Future is created but not executed

Using await outside an async context

.await must be inside an async function or block

Forgetting to configure a runtime

Async code needs an executor to be polled

Using blocking sleep in an async task

It blocks the runtime worker thread

Confusing concurrency with parallelism

Concurrent tasks do not necessarily execute simultaneously

Forgetting error handling

Async operations can also fail

Using borrowed local data in tokio::spawn() incorrectly

Spawned tasks generally require 'static data

18. Practice Exercises

Exercise 1:

Create an async function called hello().

Display:

Hello from async Rust

Call it from a Tokio main function.

Exercise 2:

Create an async function called get_name() that returns a String.

Use .await to get the result.

Exercise 3:

Create two async functions:

  1. get_student()
  2. get_course()

Use tokio::join! to execute them concurrently.

Exercise 4:

Create an async function that returns:

Result<i32, String>

Use match to handle the result.

Exercise 5:

Make an HTTP GET request using reqwest and display the response status.

19. Mini Project: Async Student Information System

Create a small application that retrieves student and course information asynchronously.

Requirements

  1. Create an async function named get_student().
  2. Create an async function named get_course().
  3. Make both functions wait for one second.
  4. Use tokio::join! to execute them concurrently.
  5. Display both results.

Complete Code

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

async fn get_student() -> String {
sleep(Duration::from_secs(1)).await;

String::from("Hemant")
}

async fn get_course() -> String {
sleep(Duration::from_secs(1)).await;

String::from("Rust Programming")
}

#[tokio::main]
async fn main() {
println!("Fetching student information...");

let (student, course) = tokio::join!(
get_student(),
get_course()
);

println!("Student Name: {}", student);
println!("Course: {}", course);

println!("Information received successfully!");
}

Expected Output

Fetching student information...
Student Name: Hemant
Course: Rust Programming
Information received successfully!

Both asynchronous operations take approximately one second of waiting time when run concurrently.