Course › Week 4 · Async and plugging into Laravel › Day 1 · lesson 22 of 42 · 20 min reading + 45–60 min practice
async, await and tokio
What a future is, why it does nothing until awaited, and running tasks at the same time.
On this page
- Setup
- 1. async fn, .await, and #[tokio::main]
- 2. A future does nothing until awaited
- 3. Awaiting one after another adds up
- 4. join!: wait for several at once
- 5. tokio::spawn: a task that runs on its own
- 6. JoinSet: many tasks, results as they finish
- 7. Never block inside async
- 8. A timeout around any future
- Coming from PHP
- Practice
- Remember
The rayon lesson was about computing on every core. This week is about waiting: for an HTTP API, for a database, for a file. A program that calls 50 APIs one after another spends almost all its time doing nothing. Async lets one thread start all 50 calls and handle each answer when it arrives.
A PHP request almost never does this; it waits for each Http::get in turn. (Laravel’s Http::pool is the exception, and it is the same idea.) In Rust, async needs a runtime that runs the waiting tasks, and the standard one is tokio. Every crate this week (reqwest, sqlx) runs on it.
Setup
cargo add tokio --features full
full turns on everything: timers, networking, the multi-threaded runtime. Fine while learning; a library would pick only the features it needs.
1. async fn, .await, and #[tokio::main]
An async fn does not run when you call it. It returns a future: a value that represents work that will finish later. .await runs the future until it is done and gives you its result. While it waits, the runtime is free to run other tasks.
#[tokio::main] turns main into an async function and starts the tokio runtime around it.
use std::time::Duration;
use tokio::time::sleep;
/// Pretends to call the API: waits ms milliseconds, then answers.
async fn fetch_booking(id: u64, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("booking {id}")
}
#[tokio::main]
async fn main() {
let booking = fetch_booking(5521, 200).await;
println!("{booking}");
}
booking 5521tokio::time::sleep waits without blocking the thread: the async version of a pause. It stands in for a network call all day today, so the examples run anywhere and the timings are predictable.
2. A future does nothing until awaited
Like an iterator adapter (the iterators lesson), a future is lazy. Call an async function without .await and nothing happens at all, and the compiler warns:
use std::time::Duration;
use tokio::time::sleep;
/// Pretends to send a reminder: waits, then reports.
async fn send_reminder(id: u64) {
sleep(Duration::from_millis(50)).await;
println!("reminder sent for booking {id}");
}
#[tokio::main]
async fn main() {
send_reminder(5521);
println!("done");
}
warning: unused implementer of `Future` that must be used
--> src/main.rs:13:5
|
13 | send_reminder(5521);
| ^^^^^^^^^^^^^^^^^^^
|
= note: futures do nothing unless you `.await` or poll them
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by defaultdoneNo reminder was sent: the future was created and dropped. Forgetting .await is the most common async bug, and this warning is the only thing that catches it, which is one more reason this course treats warnings as errors.
3. Awaiting one after another adds up
Three calls of 300 ms each, awaited in turn, take 900 ms. Each .await waits for its call to finish before the next one starts:
use std::time::{Duration, Instant};
use tokio::time::sleep;
/// Pretends to call the API: waits ms milliseconds, then answers.
async fn fetch_booking(id: u64, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("booking {id}")
}
#[tokio::main]
async fn main() {
let start = Instant::now();
let a = fetch_booking(5521, 300).await;
let b = fetch_booking(5522, 300).await;
let c = fetch_booking(5523, 300).await;
println!("{a}, {b}, {c}");
println!("took about {} ms", start.elapsed().as_millis() / 100 * 100);
}
booking 5521, booking 5522, booking 5523
took about 900 msThe time is rounded down to 100 ms so the page shows what you will see, not this machine’s exact microseconds.
4. join!: wait for several at once
tokio::join! runs several futures at the same time on the current task and waits until all of them are done. The total is the longest one, not the sum:
use std::time::{Duration, Instant};
use tokio::time::sleep;
/// Pretends to call the API: waits ms milliseconds, then answers.
async fn fetch_booking(id: u64, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("booking {id}")
}
#[tokio::main]
async fn main() {
let start = Instant::now();
let (a, b, c) = tokio::join!(
fetch_booking(5521, 300),
fetch_booking(5522, 300),
fetch_booking(5523, 300),
);
println!("{a}, {b}, {c}");
println!("took about {} ms", start.elapsed().as_millis() / 100 * 100);
}
booking 5521, booking 5522, booking 5523
took about 300 msOne thread, three waits overlapping. This is the whole point of async: not faster work, but no time wasted waiting in a line. join! is the equivalent of Http::pool in Laravel.
It suits a fixed handful of futures known in the code. For a list of unknown length, use section 6.
5. tokio::spawn: a task that runs on its own
tokio::spawn hands a future to the runtime as a separate task, which starts right away, in the background, possibly on another thread. It returns a JoinHandle; awaiting it gives the task’s result.
Because the task may outlive the function that spawned it, it must own everything it uses: an async move block, the async version of the move closure from the closures lesson.
use std::time::Duration;
use tokio::time::sleep;
/// Pretends to call the API: waits ms milliseconds, then answers.
async fn fetch_booking(id: u64, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("booking {id}")
}
#[tokio::main]
async fn main() {
let id: u64 = 5524;
let handle = tokio::spawn(async move { fetch_booking(id, 200).await });
println!("spawned, doing other work meanwhile");
match handle.await {
Ok(booking) => println!("task finished: {booking}"),
Err(error) => eprintln!("task failed: {error}"),
}
}
spawned, doing other work meanwhile
task finished: booking 5524Awaiting a JoinHandle returns a Result, like thread::join in the rayon lesson: the task may have panicked. A panic in a task never takes the rest of the program down with it.
6. JoinSet: many tasks, results as they finish
For a list of jobs, spawn each into a JoinSet and collect the results with join_next(), which returns them in the order they finish: the fastest first. Here five fetches with different delays:
use std::time::{Duration, Instant};
use tokio::task::JoinSet;
use tokio::time::sleep;
/// Pretends to call the API: waits ms milliseconds, then answers.
async fn fetch_booking(id: u64, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("booking {id}")
}
#[tokio::main]
async fn main() {
let start = Instant::now();
let jobs: [(u64, u64); 5] = [
(5521, 500),
(5522, 100),
(5523, 300),
(5524, 200),
(5525, 400),
];
let mut tasks: JoinSet<String> = JoinSet::new();
for (id, ms) in jobs {
tasks.spawn(fetch_booking(id, ms));
}
while let Some(result) = tasks.join_next().await {
match result {
Ok(booking) => println!("{booking}"),
Err(error) => eprintln!("a task failed: {error}"),
}
}
println!(
"all 5 in about {} ms",
start.elapsed().as_millis() / 100 * 100
);
}
booking 5522
booking 5524
booking 5523
booking 5525
booking 5521
all 5 in about 500 mswhile let Some(x) = … loops for as long as the expression gives Some: here, until every task has been collected. It is let … else turned into a loop.
Five calls in the time of the slowest. Spawning thousands of tasks this way would also fire thousands of requests at once at somebody’s API; the reqwest lesson adds a limit.
7. Never block inside async
The runtime runs many tasks on few threads, switching at every .await. A function that blocks the thread without an .await, like std::thread::sleep or a long CPU loop, stops every other task on that thread. The program still compiles and runs, just slowly:
use std::time::{Duration, Instant};
#[tokio::main(flavor = "current_thread")]
async fn main() {
let start = Instant::now();
tokio::join!(blocking_wait(1), blocking_wait(2), blocking_wait(3));
println!("took about {} ms", start.elapsed().as_millis() / 100 * 100);
}
/// Wrong: std's sleep blocks the whole thread, so nothing else runs meanwhile.
async fn blocking_wait(n: u32) {
std::thread::sleep(Duration::from_millis(300));
println!("call {n} done");
}
call 1 done
call 2 done
call 3 done
took about 900 msThe same join! as section 4, now 900 ms instead of 300: the three calls ran one after the other, because none of them ever gave the thread back. (flavor = "current_thread" runs everything on one thread, which makes the effect easy to see; with more threads it is subtler, and still there.)
The rules: inside async code, use async versions (tokio::time::sleep, tokio::fs, reqwest, sqlx). For heavy CPU work, hand it to tokio::task::spawn_blocking, which runs it on a separate pool of threads made for that, or to rayon.
8. A timeout around any future
tokio::time::timeout wraps any future: if it does not finish in time, you get an Err and the future is dropped, which cancels it. This is how every network call in this course gets a deadline:
use std::time::Duration;
use tokio::time::{sleep, timeout};
/// Pretends to call the API: waits ms milliseconds, then answers.
async fn fetch_booking(id: u64, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("booking {id}")
}
#[tokio::main]
async fn main() {
for (id, ms) in [(5521, 100), (5522, 3_000)] {
match timeout(Duration::from_secs(1), fetch_booking(id, ms)).await {
Ok(booking) => println!("{booking}"),
Err(_) => eprintln!("booking {id}: no answer within 1 s, gave up"),
}
}
}
booking 5521
booking 5522: no answer within 1 s, gave upThe second call never finished, and nothing had to be written to stop it: dropping a future stops it at its next .await. A PHP script stuck on a slow call can only be killed from outside.
Coming from PHP
Laravel’s closest equivalent is the HTTP client’s pool, which sends several requests at once and waits for all of them:
<?php
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
$responses = Http::pool(fn (Pool $pool) => [
$pool->get('http://localhost:8000/api/bookings/5521'),
$pool->get('http://localhost:8000/api/bookings/5522'),
$pool->get('http://localhost:8000/api/bookings/5523'),
]);
That is join! for HTTP requests only, and only inside one call. Rust’s async works for any waiting, database queries and timers included, and lets tasks run in the background, be cancelled, or race against a timeout. The price is the runtime: async functions can only be awaited from async code, which is why main itself becomes async.
PracticeThe Book ch. 17.1–17.3, and a race
Read chapter 17 of the Book up to the end of 17.3. The Book uses its own helper crate, trpl; the ideas are the same as tokio’s.
Exercise: the fastest mirror
Two replicas answer the same request with different delays. Use tokio::select! to take whichever answers first and drop the other: tokio::select! { a = fetch_booking(5521, 300) => …, b = fetch_booking(5521, 100) => … }. Print which one won.
Show the solution
use std::time::Duration;
use tokio::time::sleep;
/// Pretends to call the API: waits ms milliseconds, then answers.
async fn fetch_booking(id: u64, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("booking {id}")
}
#[tokio::main]
async fn main() {
let winner = tokio::select! {
booking = fetch_booking(5521, 300) => format!("primary: {booking}"),
booking = fetch_booking(5521, 100) => format!("replica: {booking}"),
};
println!("{winner}");
}
replica: booking 5521select! waits for the first branch to finish and drops the others, cancelling them. It is the general form of timeout: a timeout is a race against a timer.
Remember
- Async is for waiting, rayon is for computing; a future does nothing until it is awaited.
join!for a few futures,JoinSetor a stream for many; never block the thread inside async code.
Tomorrow: real HTTP calls with reqwest, with timeouts, status codes, retries, and a limit on how many run at once.