Skip to main content
Be Bitwise
RustAsync & Networking

Async/Await Basics

Rust's async system lets you write concurrent code that reads top-to-bottom like a normal function. Tasks are lightweight, scheduled by a runtime rather than the OS.

The Idea

Async code pauses at .await points and lets other tasks run:

rust
// make_request stands in for an HTTP client call (reqwest, say)
async fn fetch_data(url: &str) -> String {
// This could take seconds - while waiting, other tasks run
let response = make_request(url).await;
response.text().await
}

Futures

An async fn returns a Future - a value that will produce a result eventually:

rust
async fn hello() -> String {
String::from("hello")
}
async fn caller() {
// Calling hello() returns a Future, it doesn't execute yet
let future = hello();
// The future executes when you .await it
let result = future.await;
println!("{}", result);
}

.await is only allowed inside an async fn or async block, so something outside async code has to start the first future. That's the runtime's job.

The runner can't run async code (it's Rust 1.40 on the 2015 edition, with no Tokio), but it can show the machinery underneath. Countdown implements Future by hand, and block_on is the smallest executor there is: it polls until it gets Ready. The unsafe line builds a waker that does nothing, which is all a busy-polling loop needs.

Try itPredict how many poll() lines appear, then comment out the block_on line and the println! after it: creating the future on its own prints nothing.
Rust (1.40.0)

The Tokio Runtime

Rust ships no async runtime in the standard library. You pick one. Tokio is the de facto choice:

rust
// Cargo.toml:
// [dependencies]
// tokio = { version = "1", features = ["full"] }
#[tokio::main]
async fn main() {
let result = hello().await;
println!("{}", result);
}
Key Concept

Rust's async model is zero-cost. The compiler turns each async fn into a hand-rolled state machine. No GC, no hidden allocator, no runtime overhead for a future that isn't being polled. An idle future costs you nothing but the bytes holding its state.

Concurrent Execution

Run multiple tasks concurrently:

rust
use tokio::join;
async fn fetch_users() -> Vec<String> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
vec!["Alice".into(), "Bob".into()]
}
async fn fetch_posts() -> Vec<String> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
vec!["Post 1".into(), "Post 2".into()]
}
#[tokio::main]
async fn main() {
// Both run concurrently - total time ~1 second, not 2
let (users, posts) = join!(fetch_users(), fetch_posts());
println!("Users: {:?}", users);
println!("Posts: {:?}", posts);
}

Spawning Tasks

tokio::spawn starts a task that runs independently of the one that spawned it. You get back a JoinHandle: await it if you want the result, or drop it and the task carries on regardless:

rust
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
// runs on the runtime's worker threads
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6 * 7
});
// Do other work...
let result = handle.await.unwrap(); // Err only if the task panicked or was cancelled
println!("{}", result);
}

Async and Ownership

The borrow checker doesn't take a holiday for async code. The usual move is to hand ownership to the async block outright:

rust
#[tokio::main]
async fn main() {
let data = String::from("hello");
let handle = tokio::spawn(async move {
// data is moved into this task
println!("{}", data);
});
// data is no longer valid here
handle.await.unwrap();
}

The move keyword shifts ownership into the async block so the data outlives whatever scope spawned it.