Async, Await and Tokio
Part 1 · Rust. Learn why web servers use async Rust, how async fn and .await work, and how Tokio runs many tasks at once with join! and spawn.
Here is the last big idea before we meet Laravel Rust: async. It sounds scary, but the core idea fits in a coffee-shop story.
Why async? The waiter analogy
Picture a café with one waiter. A customer orders a latte. The waiter walks to the kitchen, hands over the order, and then stands there staring at the kitchen door until the coffee is ready. Meanwhile ten other customers wait to order. That is blocking: the waiter does nothing useful while waiting.
A smarter waiter hands over the order, then goes to take the next customer’s order, and comes back when the bell rings. Still one waiter, but many customers served at the same time. That is async.
A web server is that waiter. Most of a request’s time is spent waiting: for the database, for a file, for another website to reply. While one request waits, async lets the server work on others. This is how one small program handles thousands of visitors.
async fn and .await
In Rust you mark a function async, and use .await at the points where it might have to wait.
use tokio::time::{sleep, Duration};
async fn prepare_latte() -> String { sleep(Duration::from_millis(500)).await; // "waiting for the kitchen" String::from("Latte is ready")}async fnmeans calling it does not run it immediately. It returns a future: a promise of a value that will exist later.sleep(...)is Tokio’s pretend-wait (like a kitchen taking half a second)..awaitsays “pause this function here until the wait is over, and let other work run in the meantime.”- When the wait ends, the function continues and returns its
String.
Important
Futures are lazy. Calling prepare_latte() without .await does nothing at all; the compiler even warns unused implementer of `Future` that must be used. Always .await it (or hand it to something that does).
You can only use .await inside an async fn or an async block. Using it in a normal function gives an error like error[E0728]: `await` is only allowed inside `async` functions and blocks.
Tokio: the engine that runs futures
A future does not run itself; something has to drive it. That something is an async runtime. The most popular one is Tokio. Rust’s standard library does not include a runtime, so we add the crate (remember Cargo from the last lessons):
[package]name = "rusty-bean-async"version = "0.1.0"edition = "2024"
[dependencies]tokio = { version = "1", features = ["full"] }features = ["full"] switches on everything we need: the runtime, timers, and task tools.
#[tokio::main]
main cannot be async on its own. The attribute macro from the previous lesson fixes that:
use tokio::time::{sleep, Duration};
async fn prepare_latte() -> String { sleep(Duration::from_millis(500)).await; String::from("Latte is ready")}
#[tokio::main]async fn main() { let message = prepare_latte().await; println!("{}", message);}Latte is ready#[tokio::main] rewrites main into a regular function that starts the Tokio runtime and runs your async code inside it. Then .await works as expected.
Doing things at the same time: tokio::join!
Now the payoff. Suppose a customer orders a latte (500 ms) and a croissant (300 ms). Awaiting one after the other takes about 800 ms:
let latte = prepare_latte().await;let croissant = warm_croissant().await;With tokio::join!, both start together and we wait for both:
use tokio::time::{sleep, Duration, Instant};
async fn prepare_latte() -> String { sleep(Duration::from_millis(500)).await; String::from("Latte ready")}
async fn warm_croissant() -> String { sleep(Duration::from_millis(300)).await; String::from("Croissant warm")}
#[tokio::main]async fn main() { let start = Instant::now();
let (latte, croissant) = tokio::join!(prepare_latte(), warm_croissant());
println!("{} and {}", latte, croissant); println!("Took about {} ms", start.elapsed().as_millis() / 100 * 100);}Latte ready and Croissant warmTook about 500 mstokio::join!(a(), b())is a function-like macro. It runs both futures together.- It gives back a tuple with both results, in the order you wrote them. We unpack it with
let (latte, croissant) = .... - The total time is the slowest task (500 ms), not the sum (800 ms).
- The last line takes the elapsed milliseconds and cuts off the last two digits (
/ 100 * 100truncates; it does not round), so a real run of 503 ms prints as 500. The output stays stable unless your machine is very slow.
Tip
Notice that join! is a macro, which is why it has a !. Laravel Rust has its own version, task::try_join!, for running several async calls at once and stopping early if one returns an error.
A tiny simulated concurrent fetch
Web handlers often need data from several places at once. Here we pretend to ask a menu service and a stock service:
use tokio::time::{sleep, Duration};
async fn fetch_menu() -> Vec<String> { sleep(Duration::from_millis(200)).await; vec![String::from("Latte"), String::from("Mocha")]}
async fn fetch_stock(item: &str) -> u32 { sleep(Duration::from_millis(150)).await; if item == "Latte" { 12 } else { 4 }}
#[tokio::main]async fn main() { let (menu, latte_stock) = tokio::join!(fetch_menu(), fetch_stock("Latte")); println!("Menu: {:?}, latte stock: {}", menu, latte_stock);}Menu: ["Latte", "Mocha"], latte stock: 12Both “requests” are in flight together, so the whole thing takes about 200 ms instead of 350.
Async closures
You met closures in the last lesson. A closure can be async too: put async before the bars, and calling it gives you a future to .await.
use tokio::time::{sleep, Duration};
#[tokio::main]async fn main() { let brew = async |name: String| { sleep(Duration::from_millis(100)).await; format!("{name} brewed") };
println!("{}", brew(String::from("Latte")).await); println!("{}", brew(String::from("Mocha")).await);}Latte brewedMocha brewedAn async closure is handy when a framework asks, “what async work should I do for each request?”. Laravel Rust routes and callbacks can be written this way. Async closures are stable in recent Rust (1.85 and later).
async move
Like ordinary closures, async blocks and async closures borrow what they use by default. Adding move makes them own the values they capture, which is exactly what a spawned task needs (see the warning below). You can write async move { ... } for a block and async move |x| ... for a closure. Laravel Rust code uses both forms, for example async move blocks and lazy async closures.
use tokio::time::{sleep, Duration};
#[tokio::main]async fn main() { let drink = String::from("Latte");
// An async block that takes ownership of `drink` let task = tokio::spawn(async move { sleep(Duration::from_millis(100)).await; format!("{drink} brewed") }); println!("{}", task.await.unwrap());
// An async closure that owns the `suffix` it captured let suffix = String::from("with oat milk"); let brew = async move |name: String| { sleep(Duration::from_millis(100)).await; format!("{name} {suffix}") }; println!("{}", brew(String::from("Mocha")).await);}Latte brewedMocha with oat milkAfter the async move block, drink belongs to the task, so you can no longer use it in main.
Launching background work: tokio::spawn
join! waits for everything inside one function. Sometimes you want to start a task that runs independently, like sending a receipt email while the customer already sees “Thanks!”. That is tokio::spawn:
use tokio::time::{sleep, Duration};
async fn send_receipt(order_id: u32) -> String { sleep(Duration::from_millis(200)).await; format!("Receipt sent for order {}", order_id)}
#[tokio::main]async fn main() { let handle = tokio::spawn(send_receipt(7));
println!("Customer sees: Thanks!");
let result = handle.await.unwrap(); println!("{}", result);}Customer sees: Thanks!Receipt sent for order 7tokio::spawn(...)starts the future as its own task right away and returns aJoinHandle.- The next
println!runs without waiting, which is why “Thanks!” prints first. handle.awaitwaits for the task to finish. It returns aResult(the task could have crashed), so we.unwrap()for now.
Warning
A spawned task may outlive the function that created it, so it must own its data. If you try to use a borrowed local variable, the compiler complains about lifetimes: error[E0597]: `x` does not live long enough (with a note that the value must be borrowed for 'static). Fix it by moving ownership in (clone the data, or use async move { ... }).
Warning
Never do slow, blocking work (like std::thread::sleep or a huge computation) inside async code. It freezes the waiter. Use tokio::time::sleep for waiting, and Tokio’s spawn_blocking for heavy CPU work. Laravel Rust does this for you with things like password hashing, which it runs on Tokio’s blocking pool.
Where this shows up in web frameworks
Axum, the web framework that Laravel Rust is built on, is itself built on Tokio. Every request handler is just an async fn: it can .await the database while other visitors are served. In Laravel Rust you will write handlers like that, await things such as dispatch().await? for queued jobs, and use task::try_join! and friends from the laravel::task helpers. The ? operator from the error-handling lesson works inside async functions too, as long as the function returns a Result.
Try it yourself
- Write an
async fn brew(name: &str, ms: u64) -> Stringthat sleeps formsmilliseconds and returns"<name> brewed". Run three brews together withtokio::join!. - Which is faster, awaiting two 300 ms tasks one after another or with
join!? Roughly how long does each take?
Show solution
use tokio::time::{sleep, Duration};
async fn brew(name: &str, ms: u64) -> String { sleep(Duration::from_millis(ms)).await; format!("{} brewed", name)}
#[tokio::main]async fn main() { let (a, b, c) = tokio::join!( brew("Latte", 300), brew("Mocha", 200), brew("Espresso", 100), ); println!("{}, {}, {}", a, b, c);}Latte brewed, Mocha brewed, Espresso brewedFor question 2: one after another takes about 600 ms; with join! it takes about 300 ms, the length of the slowest task.
Recap
- Async lets one program serve many requests by switching to other work while one waits.
async fnreturns a lazy future;.awaitpauses until it is ready.- Tokio is the runtime that drives futures;
#[tokio::main]starts it. tokio::join!runs several futures together;tokio::spawnstarts an independent task.- Axum, and so Laravel Rust, are built on Tokio, so web handlers are
async fn.
What’s next
You now have the Rust toolkit the web needs. Time to meet the framework that puts it to work: start with What is Laravel Rust?.
0 of 35 lessons complete