If you write JavaScript, you already think asynchronously. You know that await fetch(url) doesn't freeze the page, that Promise.all runs requests side by side, and that a long for loop in a request handler will stall every other request on a Node server. All of that knowledge carries over to Rust. The keywords are even the same: async and await.
What's different is underneath. JavaScript has one event loop, built into the runtime, and it's always there. Rust has no built-in runtime at all. You pick one, and for web servers that's almost always Tokio. Rust futures also behave differently from promises in a few ways that will catch you out if you don't know about them, and Tokio can run your code on several threads at once, which JavaScript never does. That brings back some of the ownership rules from part 3 in a new form.
This part covers how async works in Rust, how to do the things you'd do with Promise.all, Promise.race and setTimeout, how to run work in the background, and how tasks share data safely. At the end we'll write a tiny HTTP server with nothing but Tokio, to see what a framework like Axum does for us from part 10 onwards. Everything here ran on Rust 1.100.0 with Tokio 1.54.1, and the outputs are real.
Why web servers care about async
A web server spends most of its time waiting. A request comes in, the handler asks the database for something, and then nothing happens for a few milliseconds while the database works. Then maybe it calls another API, and waits again. The actual computation is often a tiny fraction of the time.
There are two ways to handle many requests at once. The old way is a thread per connection. Threads are managed by the operating system, and each one has its own stack, typically a few megabytes of reserved memory. A thousand slow connections means a thousand threads, mostly sleeping. That works, but it gets expensive.
The other way is what Node does: a small number of threads, each juggling many tasks. When a task would wait, it steps aside and lets another task run. That's async. A Tokio task is far cheaper than a thread (the Tokio docs put a task at around 64 bytes of overhead), so a server can hold tens of thousands of open connections without much trouble.
Futures are lazy
An async fn in Rust returns a future. A future is a value that represents work that will produce a result later. So far, that's the same as a promise. Here's the first difference:
async fn greet(name: &str) -> String {
println!(" greet({name}) is running");
format!("hello, {name}")
}
#[tokio::main]
async fn main() {
let future = greet("ana");
println!("created the future, nothing has run yet");
let message = future.await;
println!("awaited: {message}");
}
created the future, nothing has run yet
greet(ana) is running
awaited: hello, ana
Calling greet("ana") didn't run any of its body. It built a future and handed it back. The body only ran when we awaited it.
In JavaScript, it's the other way round. Calling an async function starts running it immediately, up to its first await, and the promise you get back is a handle on work that's already happening. If you write const p = fetchUser() and never await p, the request still goes out.
In Rust, an un-awaited future does nothing at all. This is the same idea as the lazy iterators from part 8, and the compiler warns you in the same way:
async fn save() -> Result<(), String> {
println!("saving");
Ok(())
}
#[tokio::main]
async fn main() {
save();
println!("done");
}
warning: unused implementer of `Future` that must be used
--> src/bin/e_noawait.rs:8:5
|
8 | save();
| ^^^^^^
|
= note: futures do nothing unless you `.await` or poll them
Running it prints "done" and never prints "saving". If you forget an await in JavaScript, you get a floating promise that runs anyway, and maybe an unhandled rejection later. In Rust, you get a warning and code that silently doesn't run. Treat that warning as an error. (In a real project, I'd set #![deny(unused_must_use)] or rely on clippy in CI to make it one.)
Also notice the syntax: future.await, not await future. It's a postfix keyword, so it chains nicely: client.get(url).send().await?.json().await? reads left to right.
The runtime
Rust's standard library defines what a future is, but has nothing that runs them. Try making main async without a runtime:
error[E0752]: `main` function is not allowed to be `async`
--> src/bin/e_main.rs:1:1
|
1 | async fn main() {
| ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`
Something has to drive futures forward: call them, notice when they're waiting on a timer or a socket, park them, and wake them up when the operating system says the socket has data. That's the runtime's job, and it's the part that JavaScript bakes in. Rust leaves it to libraries so that the same language can run on a web server, an embedded chip with no operating system, and everything in between.
Tokio is the runtime almost all Rust web code uses. Axum, SQLx, reqwest and most of the ecosystem are built on it. You add it like any other crate:
[dependencies]
tokio = { version = "1", features = ["full"] }
full turns on everything, which is convenient while learning. In a real project you might list only what you use, like ["rt-multi-thread", "macros", "net", "time"], to cut compile time a little.
#[tokio::main] is a macro that turns your async main into a normal one. It roughly expands to this:
fn main() {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
// your async main body
})
}
It builds a runtime and blocks the main thread until your async code finishes. "Multi-thread" matters: by default, Tokio starts one worker thread per CPU core and spreads tasks across them. That's a real difference from Node, and we'll come back to it.
Doing things one after another, or at the same time
Here's a pretend API call that takes some milliseconds:
use std::time::{Duration, Instant};
use tokio::time::sleep;
async fn fetch(name: &str, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("{name} ({ms}ms)")
}
tokio::time::sleep is the async version of sleeping. It's the closest thing to await new Promise(r => setTimeout(r, ms)). The task steps aside, and the runtime wakes it when the time is up.
Awaiting three of these in a row takes as long as all three added together:
let user = fetch("user", 300).await;
let posts = fetch("posts", 500).await;
let likes = fetch("likes", 200).await;
one after another: user (300ms), posts (500ms), likes (200ms) in 1.0s
That's correct when each step needs the result of the one before. When they're independent, use tokio::join!, which is the Rust version of Promise.all:
let (user, posts, likes) =
tokio::join!(fetch("user", 300), fetch("posts", 500), fetch("likes", 200));
join!: user (300ms), posts (500ms), likes (200ms) in 0.5s
Half a second, the time of the slowest one. join! takes the futures, polls all of them, and returns a tuple of results when they're all done. Because futures are lazy, building them with fetch(...) costs nothing, and the work only starts inside join!.
tokio::try_join! is the version for futures that return Result. It stops at the first error, like Promise.all does with the first rejection:
async fn check(name: &str, ok: bool) -> Result<&str, String> {
sleep(Duration::from_millis(100)).await;
if ok { Ok(name) } else { Err(format!("{name} is down")) }
}
let result = tokio::try_join!(check("db", true), check("cache", false), check("queue", true));
try_join!: Err("cache is down") in 0.1s
When try_join! returns early, the other futures are dropped, which cancels them. That's another difference from JavaScript. When one promise in Promise.all rejects, the others keep running in the background, and their results are thrown away. In Rust, dropping a future stops it. Nothing keeps running unless something is still polling it.
Concurrency on one task
join! runs its futures concurrently, but all on the same task. It switches between them whenever one is waiting. That's great for waiting on I/O, which is what web code mostly does. It doesn't use extra CPU cores. For that, you need separate tasks.
Spawning tasks
tokio::spawn hands a future to the runtime to run as its own task, in the background, possibly on another thread. It's like starting a promise and not awaiting it yet, except you get back a JoinHandle that you can await later:
async fn resize(id: u32) -> String {
sleep(Duration::from_millis(100 * u64::from(id))).await;
format!("image-{id}.webp")
}
let handle = tokio::spawn(resize(3));
println!("spawned, doing other work meanwhile");
let file = handle.await.unwrap();
spawned, doing other work meanwhile
task finished: image-3.webp after 0.3s
Unlike a plain future, a spawned task starts running right away, whether or not you await the handle. That's the closest Rust gets to the eager behaviour of a JavaScript promise.
Why .unwrap() after the await? Because awaiting a JoinHandle gives a Result. If the task panicked, you get an error instead of your value:
let crashing = tokio::spawn(async {
let items: Vec<u32> = Vec::new();
items[0]
});
match crashing.await {
Ok(n) => println!("got {n}"),
Err(e) => println!("task failed: panicked={}", e.is_panic()),
}
println!("main is still running");
thread 'tokio-rt-worker' (1189) panicked at src/bin/spawn.rs:30:14:
index out of bounds: the len is 0 but the index is 0
task failed: panicked=true
main is still running
The panic was contained in that one task. This is the mechanism behind what I mentioned in part 5: when an Axum handler panics, the task serving that connection dies, and the server keeps going.
Many tasks at once
For a batch of tasks, JoinSet collects them and hands back results as each one finishes:
use tokio::task::JoinSet;
let mut set = JoinSet::new();
for id in [4, 1, 3, 2] {
set.spawn(resize(id));
}
while let Some(result) = set.join_next().await {
println!(" done: {}", result.unwrap());
}
done: image-1.webp
done: image-2.webp
done: image-3.webp
done: image-4.webp
all four in 0.4s
They were spawned in the order 4, 1, 3, 2, and came back in the order they finished. Total time is the slowest task. If you need results in the original order, keep the JoinHandles in a Vec and await them one by one, which is what wordfreq does at the end of this part.
Spawned tasks must own their data
Here's the error you'll hit within your first hour of Tokio:
let name = String::from("ana");
let handle = tokio::spawn(async {
println!("hello {name}");
});
error[E0373]: async block may outlive the current function, but it borrows `name`, which is owned by the current function
--> src/bin/e_borrow.rs:4:31
|
4 | let handle = tokio::spawn(async {
| ^^^^^ may outlive borrowed value `name`
5 | println!("hello {name}");
| ---- `name` is borrowed here
|
= note: async blocks are not executed immediately and must either take a reference or ownership of outside variables they use
help: to force the async block to take ownership of `name` (and any other referenced variables), use the `move` keyword
|
4 | let handle = tokio::spawn(async move {
| ++++
It's the same problem as returning a reference to a local variable in part 3, and the same fix as move closures in part 7. A spawned task can outlive the function that spawned it. The runtime has no idea when you'll await the handle, or whether you will at all. So the task can't borrow anything from the function's stack. It has to own what it uses. async move moves name into the task.
In the signature of tokio::spawn, this shows up as a 'static bound: the future must not hold any borrowed references that could expire. In practice, that means you'll write async move on almost every spawn, and clone things before moving them in when you still need them outside.
Timeouts and races
Every network call in a web server should have a timeout, so one slow dependency can't tie up your server forever. tokio::time::timeout wraps any future:
use tokio::time::timeout;
async fn slow_api() -> &'static str {
sleep(Duration::from_millis(800)).await;
"slow answer"
}
match timeout(Duration::from_millis(300), slow_api()).await {
Ok(answer) => println!("api said {answer}"),
Err(_) => println!("api timed out after 300ms"),
}
api timed out after 300ms
It returns Ok with the value if the future finished in time, and Err if it didn't. When it times out, the inner future is dropped, so the slow call is cancelled, not left running. In JavaScript, you'd build this out of Promise.race and setTimeout, plus an AbortController to actually stop the request.
tokio::select! is the general tool: wait on several futures and take whichever finishes first. It's Promise.race with a branch for each outcome:
async fn fast_cache() -> &'static str {
sleep(Duration::from_millis(50)).await;
"cached answer"
}
tokio::select! {
answer = slow_api() => println!("api won: {answer}"),
answer = fast_cache() => println!("cache won: {answer}"),
}
cache won: cached answer
The loser is dropped. select! gets really useful in loops. Here's a ticker that runs every 100ms until a deadline:
let mut ticks = tokio::time::interval(Duration::from_millis(100));
let deadline = sleep(Duration::from_millis(350));
tokio::pin!(deadline);
let mut count = 0;
loop {
tokio::select! {
_ = ticks.tick() => {
count += 1;
println!("tick {count}");
}
_ = &mut deadline => {
println!("deadline reached");
break;
}
}
}
tick 1
tick 2
tick 3
tick 4
deadline reached
Four ticks, because an interval's first tick fires immediately, then at 100, 200 and 300 milliseconds. tokio::pin! is needed because we poll the same deadline future again on every turn of the loop, instead of making a new one. Pinning is a deep topic I'm going to skip. The practical rule: if you select! on the same future across loop iterations, pin it first and use &mut, and the compiler will tell you when you've forgotten.
This exact pattern, "wait for work or a shutdown signal, whichever comes first", is how servers shut down gracefully, and we'll use it in part 15.
Channels: sending work between tasks
Tasks often need to talk to each other. A common pattern in web servers is a background worker: request handlers drop jobs on a queue and return immediately, and a worker task processes them. In Tokio, the queue is a channel.
use tokio::sync::{mpsc, oneshot};
enum Job {
Email { to: String },
Report { id: u32, reply: oneshot::Sender<usize> },
}
let (tx, mut rx) = mpsc::channel::<Job>(16);
let worker = tokio::spawn(async move {
while let Some(job) = rx.recv().await {
match job {
Job::Email { to } => {
tokio::time::sleep(Duration::from_millis(50)).await;
println!("worker: sent email to {to}");
}
Job::Report { id, reply } => {
println!("worker: building report {id}");
let _ = reply.send(42 * id as usize);
}
}
}
println!("worker: channel closed, stopping");
});
for to in ["ana@example.com", "bo@example.com"] {
tx.send(Job::Email { to: to.to_string() }).await.unwrap();
}
let (reply_tx, reply_rx) = oneshot::channel();
tx.send(Job::Report { id: 2, reply: reply_tx }).await.unwrap();
println!("main: report has {} rows", reply_rx.await.unwrap());
drop(tx);
worker.await.unwrap();
worker: sent email to ana@example.com
worker: sent email to bo@example.com
worker: building report 2
main: report has 84 rows
worker: channel closed, stopping
There's a lot packed in here, so let's take it apart.
mpsc means "multiple producer, single consumer". mpsc::channel(16) returns a sender tx and a receiver rx. You can clone tx as many times as you like and hand a copy to every request handler. There's only one rx, owned by the worker. The 16 is the buffer size: if 16 jobs are waiting, send waits until there's room. That's backpressure, and it stops a flood of requests from building an infinitely long queue in memory.
The job type is an enum from part 4, so the worker can handle different kinds of work with a match. Because channels are typed, you can't accidentally send something the worker doesn't understand.
oneshot is a channel for exactly one value. Putting a oneshot::Sender inside the job is how you get an answer back: the worker sends the result, and whoever sent the job awaits the receiver. It's the Rust version of resolving a promise from somewhere else.
rx.recv() returns None when every sender has been dropped. That's how the worker knows to stop: drop(tx) closes the channel, the while let loop ends, and the worker exits cleanly. No special shutdown message needed.
Sharing state between tasks
Channels are one way for tasks to cooperate. The other is shared state: a cache, a counter, a connection pool. In JavaScript, every request handler can touch the same object, because there's only one thread and no two handlers ever run at the same instant. In Tokio, two tasks can be running on two threads at literally the same time. If both could change the same HashMap without coordination, you'd have a data race, and the compiler won't allow it.
You need two things. Arc (atomically reference-counted pointer) lets several tasks own the same value. Cloning an Arc doesn't copy the data, it just bumps a counter, and the data is freed when the last clone is dropped. And Mutex makes sure only one task changes the data at a time.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
let hits = Arc::new(Mutex::new(HashMap::<String, u32>::new()));
let mut set = JoinSet::new();
for i in 0..100 {
let hits = Arc::clone(&hits);
set.spawn(async move {
let path = if i % 3 == 0 { "/about" } else { "/" };
let mut map = hits.lock().unwrap();
*map.entry(path.to_string()).or_insert(0) += 1;
});
}
set.join_all().await;
hits: [("/", 66), ("/about", 34)]
Arc strong count: 1
A hundred tasks, spread across worker threads, all updating the same map, and the total is exactly 100. Each task gets its own clone of the Arc (moved in with async move), locks the mutex, updates the map, and the lock is released when map goes out of scope at the end of the block. After every task finished, their clones were dropped, so the count is back to 1.
.lock().unwrap() deserves a word. lock returns a Result because a mutex becomes "poisoned" if a thread panics while holding it, as a signal that the data might be half updated. Most code unwraps here, on the reasoning that if something already panicked mid-update, crashing loudly is the right response.
This Arc pattern is exactly how Axum shares state with handlers, which is the subject of part 11.
Don't hold a lock across an await
Here's a mistake the compiler catches for you:
tokio::spawn(async move {
let mut n = c.lock().unwrap();
tokio::time::sleep(Duration::from_millis(10)).await;
*n += 1;
})
error: future cannot be sent between threads safely
--> src/bin/e_send.rs:8:5
|
8 | / tokio::spawn(async move {
9 | | let mut n = c.lock().unwrap();
10 | | tokio::time::sleep(Duration::from_millis(10)).await;
11 | | *n += 1;
12 | | })
| |______^ future created by async block is not `Send`
|
= help: within `{async block@src/bin/e_send.rs:8:18: 8:28}`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, i32>`
note: future is not `Send` as this value is used across an await
--> src/bin/e_send.rs:10:55
|
9 | let mut n = c.lock().unwrap();
| ----- has type `std::sync::MutexGuard<'_, i32>` which is not `Send`
10 | tokio::time::sleep(Duration::from_millis(10)).await;
| ^^^^^ await occurs here, with `mut n` maybe used later
Send is a marker trait meaning "safe to move to another thread". Tokio's multi-threaded runtime can pause a task at an .await and resume it on a different thread. The standard library's mutex guard must be released on the same thread that took it, so it isn't Send, and a future holding one across an .await isn't Send either. tokio::spawn requires Send, so the code doesn't compile.
The error is long, but the important line is "this value is used across an await". It names the value and points at the await. There's a good reason behind this rule beyond threads, too: holding a lock while you wait on a timer or a database call means every other task that wants the lock waits too.
There are two fixes. Usually, the right one is to restructure so the lock is released before the await: do the locked work in its own small block or function, and await afterwards. If you really do need to hold a lock across an await, Tokio has its own tokio::sync::Mutex, whose guard is Send. The Tokio docs recommend the standard library mutex in most cases, and the async one only when you hold the lock across awaits, because the async mutex is slower.
For data that's read often and written rarely, like configuration, there's RwLock, which allows many readers or one writer:
use tokio::sync::RwLock;
let config = Arc::new(RwLock::new(String::from("v1")));
let reader = {
let config = Arc::clone(&config);
tokio::spawn(async move { config.read().await.clone() })
};
println!("reader saw {}", reader.await.unwrap());
*config.write().await = String::from("v2");
println!("now {}", config.read().await);
reader saw v1
now v2
Don't block the runtime
This one bites Node developers too, so it may feel familiar. Async only works if tasks step aside when they wait. A task that does something slow without awaiting, like heavy computation or a blocking call to the file system or a C library, holds its thread the whole time. Nothing else scheduled on that thread can run.
To make it easy to see, here's a runtime with only one thread, flavor = "current_thread", a background ticker that prints every 100ms, and a slow function that blocks for 300ms. Password hashing is the realistic version of this, and we'll meet it in part 13.
fn expensive_hash(input: &str) -> u64 {
std::thread::sleep(Duration::from_millis(300));
input.bytes().map(u64::from).sum()
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
let start = Instant::now();
let ticks = ticker(start);
tokio::task::yield_now().await;
let hash = expensive_hash("password");
println!("hash done at {:.1}s: {hash}", start.elapsed().as_secs_f64());
ticks.await.unwrap();
}
--- blocking inside async
tick at 0.0s
hash done at 0.3s: 883
tick at 0.3s
tick at 0.4s
The ticker got one tick in, then the hash blocked the only thread for 300ms, and the next tick came at 0.3s instead of 0.1s. In a web server, that gap is every other request stuck waiting.
The fix is spawn_blocking, which runs a function on a separate pool of threads meant for blocking work, and gives you a handle you can await:
let hash = tokio::task::spawn_blocking(|| expensive_hash("password"))
.await
.unwrap();
--- with spawn_blocking
tick at 0.0s
tick at 0.1s
tick at 0.2s
hash done at 0.3s: 883
Now the ticker keeps its rhythm while the hash runs elsewhere.
On the default multi-threaded runtime, one blocking task won't freeze everything, since there are other worker threads. But it still takes one of them out of action, and enough blocking calls at once will starve the server. A widely quoted rule of thumb from the Tokio maintainers: code should reach an .await at least every 10 to 100 microseconds. Anything that runs longer without awaiting belongs in spawn_blocking. And watch for synchronous standard library calls, like std::fs::read_to_string or std::thread::sleep, inside async code. Use the Tokio versions (tokio::fs, tokio::time::sleep) instead.
A tiny HTTP server from scratch
To see why we'll want a web framework, here's an HTTP server built with nothing but Tokio's TCP listener:
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:3000").await?;
println!("listening on http://127.0.0.1:3000");
let mut visitors = 0;
loop {
let (mut socket, _addr) = listener.accept().await?;
visitors += 1;
let n = visitors;
tokio::spawn(async move {
let mut buf = [0u8; 1024];
let len = socket.read(&mut buf).await.unwrap_or(0);
let request = String::from_utf8_lossy(&buf[..len]);
let first_line = request.lines().next().unwrap_or("");
println!("request {n}: {first_line}");
let body = format!("hello from tokio, you are visitor {n}\n");
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
let _ = socket.write_all(response.as_bytes()).await;
});
}
}
The shape is every async server ever: loop forever, accept a connection, spawn a task to handle it, go back to accepting. Each connection gets its own task, so a slow client doesn't hold up anyone else.
Hitting it with curl:
curl http://127.0.0.1:3000/
curl http://127.0.0.1:3000/users?page=2
curl -i http://127.0.0.1:3000/about
hello from tokio, you are visitor 1
hello from tokio, you are visitor 2
HTTP/1.1 200 OK
content-type: text/plain
content-length: 36
connection: close
hello from tokio, you are visitor 3
And the server's log:
listening on http://127.0.0.1:3000
request 1: GET / HTTP/1.1
request 2: GET /users?page=2 HTTP/1.1
request 3: GET /about HTTP/1.1
It works, and it's about 30 lines. But look at everything it doesn't do. It reads at most 1024 bytes, so a large request gets cut off. It doesn't parse headers, methods or paths, so every URL gets the same answer. It doesn't handle request bodies, keep-alive, chunked encoding or HTTP/2. It closes the connection after each response. visitors is only safe because it lives in the accept loop and is copied into each task, so tasks can't update a shared count. And there's no routing, JSON, error handling or timeouts.
That's what the layers above give you. Hyper handles the HTTP protocol correctly. Axum, built on Hyper and Tokio, gives you routing, extractors for paths, queries and JSON bodies, shared state and middleware. You'll still recognise this loop underneath when we call axum::serve in the next part.
Async Rust and JavaScript side by side
| JavaScript | Rust with Tokio |
|---|---|
async function f() |
async fn f() |
await p |
fut.await |
| A promise starts running when created | A future does nothing until awaited or spawned |
| An un-awaited promise still runs | An un-awaited future never runs, with a warning |
| Event loop is built in | Runtime is a library, set up by #[tokio::main] |
| One thread runs your code | Tasks can run on many threads at once |
Promise.all([a, b]) |
tokio::join!(a, b) |
Promise.all with rejection |
tokio::try_join!(a, b) |
Promise.race([a, b]) |
tokio::select! |
setTimeout plus Promise.race for timeouts |
tokio::time::timeout(dur, fut) |
await new Promise(r => setTimeout(r, ms)) |
tokio::time::sleep(dur).await |
setInterval |
tokio::time::interval |
| Fire and forget a promise | tokio::spawn(fut) |
| Losing promises keep running | Dropped futures are cancelled |
| Worker threads for CPU-heavy work | spawn_blocking |
| Shared objects, no locking needed | Arc plus Mutex or RwLock |
EventEmitter, queues |
mpsc, oneshot, broadcast channels |
Back to wordfreq
wordfreq gets a small change: it now takes any number of files and reads them all at the same time.
The argument becomes a Vec, which clap turns into "one or more paths":
/// The files to read
#[arg(required = true)]
paths: Vec<PathBuf>,
A function that reads every file concurrently, each in its own task, and returns the contents in the original order:
/// Read every file at the same time and return their contents in order.
async fn read_all(paths: &[PathBuf]) -> anyhow::Result<Vec<String>> {
let handles: Vec<_> = paths
.iter()
.cloned()
.map(|path| {
tokio::spawn(async move {
tokio::fs::read_to_string(&path)
.await
.with_context(|| format!("could not read {}", path.display()))
})
})
.collect();
let mut texts = Vec::with_capacity(handles.len());
for handle in handles {
texts.push(handle.await??);
}
Ok(texts)
}
A few things from this part show up here. .cloned() gives each task its own PathBuf, because spawned tasks must own their data. The iterator chain spawns every task first, so they all start before we wait on any of them. Since spawned tasks start running immediately, the reads happen at the same time even though we then await the handles one by one, and awaiting in order keeps the output stable.
handle.await?? has two question marks because there are two things that can fail. Awaiting the handle gives a Result that's Err if the task panicked. Inside that is our own Result from reading the file. The first ? handles the panic case (anyhow converts Tokio's JoinError like any other error), and the second handles the read error.
main becomes async, and joins the texts together:
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
let text = read_all(&cli.paths).await?.join("\n");
// ... the rest is unchanged
}
For Tokio itself, wordfreq only needs a few features, so I added it with exactly those:
cargo add tokio --features rt-multi-thread,macros,fs
Running it on two files, with a new more.txt about Tokio:
cargo run -q -- notes.txt more.txt --skip-common
6 lines, 45 words, 23 unique
longest word: compiler (8 chars)
7.5 words per line
1. cargo 4 ####
2. compiler 3 ###
3. rust 3 ###
4. runs 2 ##
5. tasks 2 ##
A missing file still gives a clear error, thanks to the context we attached inside the task:
Error: could not read nope.txt
Caused by:
No such file or directory (os error 2)
And forgetting the files entirely is handled by clap:
error: the following required arguments were not provided:
<PATHS>...
Usage: wordfreq <PATHS>...
All 11 tests still pass and clippy is clean.
I want to be honest about this change. For two small text files, the async version isn't measurably faster, and the program is more complicated than a loop over std::fs::read_to_string. Tokio's own docs say file system access isn't where async shines, and tokio::fs actually runs each file operation on the blocking thread pool behind the scenes, because most operating systems don't offer true async file reads. Async pays off when you're waiting on the network, with many slow operations in flight at once. That's exactly what a web server does, which is why we're here. For wordfreq, take it as practice with the patterns.
Exercises
- Change
read_allto use aJoinSetinstead of aVecof handles. What happens to the order of the texts? How could you keep the order anyway? (Hint: spawn tasks that return the index along with the text.) - Add a
--timeout-msoption to wordfreq that wraps each file read intokio::time::timeout. What should the error message say when a read times out? - Extend the TCP server so
GET /andGET /aboutreturn different bodies, and everything else returns404 Not Found. You'll have to parse the first line yourself. Notice how quickly this gets tedious. - Make the visitor count in the TCP server shared, so each task reads and increments it itself, using
Arcand anAtomicUsizefromstd::sync::atomic. Why is an atomic simpler than aMutexhere? - Write a "rate limiter" worker: a task that owns a
HashMapof IP to request count, receives(ip, oneshot::Sender<bool>)messages on anmpscchannel, and repliestrueif that IP has made fewer than 5 requests. Notice you don't need aMutexat all, because only one task touches the map.
Next up: your first Axum server
That's every piece we need. You can write Rust that models data, handles errors, organises code into crates, uses traits and iterators, and now runs concurrent async code on Tokio.
In part 10 we start the project for the rest of the series: a JSON API built with Axum. We'll set up routes, read path and query parameters, accept and return JSON with serde, and see how Axum's extractors turn the raw HTTP from the server above into typed Rust values, with the compiler checking that your handlers make sense before you ever send a request.