Async Rust With Tokio: Build an Echo Server That Juggles a Thousand Clients
One waiter, forty tables, and nobody waits for their soup. That's async. Learn async Rust with Tokio by building a 30-line TCP echo server, then meet the one mistake that freezes the whole restaurant.
Ada Brackett
4 min read
Picture a restaurant with forty tables and one waiter. In a normal program, the waiter takes table one's order, walks to the kitchen, and stands there until the soup is ready. Thirty-nine tables watch. Someone at table twelve has started eating the menu.
[Cut to table twelve. A man is halfway through a laminated menu. "The specials are surprisingly chewy," he says.]
Async Rust with Tokio is the waiter who drops the order at the kitchen, takes four more orders, refills table seven's water, and comes back the moment the soup is ready. One waiter, forty tables, nobody eats the menu.
Today we build that waiter: a TCP echo server in about 30 lines that can juggle many clients at once.
Hire the waiter
Rust has async and .await in the language, but it doesn't ship the thing that actually runs async code. That's a runtime, and Tokio is the most widely used one.
cargo new echo
cd echo
cargo add tokio --features full
full switches on everything (networking, timers, the multi-threaded scheduler). It's perfect for learning. In real projects you'd pick just the features you need.
The echo server
src/main.rs:
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:7878").await?;
println!("listening on 127.0.0.1:7878");
loop {
let (mut socket, addr) = listener.accept().await?;
println!("{addr} sat down");
tokio::spawn(async move {
let mut buf = [0u8; 1024];
loop {
let n = match socket.read(&mut buf).await {
Ok(0) => return,
Ok(n) => n,
Err(_) => return,
};
if socket.write_all(&buf[..n]).await.is_err() {
return;
}
}
});
}
}
Run it with cargo run. Then, in two or three other terminals:
nc 127.0.0.1 7878
Type something and it comes straight back. Open several at once and they all echo independently. Close one and the others don't notice. One waiter, many tables.
What each piece does
#[tokio::main] starts the Tokio runtime and runs your async fn main on it. Under the hood it's a few lines of setup you never have to write.
.await is the waiter walking away from the kitchen. listener.accept().await means "wait for a new customer, and while we're waiting, let other work happen." Code reads top to bottom like normal code, but whenever it awaits, the runtime is free to go and serve someone else.
tokio::spawn(async move { ... }) hands each customer their own task: a lightweight unit of work, much cheaper than an operating system thread. You can have thousands of them. move moves the socket into the task, so the task owns it. That's the ownership rules from our first Rust post, doing their job again.
Ok(0) => return: reading zero bytes means the client hung up. The task ends, the socket is dropped, and the connection closes. Tidy.
The one mistake that freezes the restaurant
Add a pause to the echo, the wrong way:
std::thread::sleep(std::time::Duration::from_secs(5));
Put it just before write_all and connect a few clients. Things get sluggish, and with enough clients, everything grinds to a halt. Why? std::thread::sleep doesn't hand control back to Tokio. It blocks the worker thread itself, and with it every task that was going to run there. The waiter isn't waiting on the soup any more. He's fallen asleep standing up in the middle of the restaurant.
The async-friendly version:
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
This tells Tokio "wake me in five seconds, and go and serve other tables in the meantime." Same pause, no frozen restaurant.
The rule: inside async code, never do anything slow that doesn't .await. That means no blocking sleeps, no heavy file reads from std::fs in a hot loop, and no big CPU number-crunching. For work that has to block, Tokio gives you tokio::task::spawn_blocking, a side room where slow jobs can't hold up the floor.
Homework
- Make the server shout back: uppercase the bytes before writing with
buf[..n].to_ascii_uppercase(). - Count connected clients with an
Arc<AtomicUsize>shared between tasks, and print the count when each one joins and leaves. - The Tokio tutorial at tokio.rs builds a mini-Redis step by step. It's the best next stop.
The restaurant's open. Nobody's eating the menu. Table twelve has been given bread, and he's thrilled.
Cloud
More like this
Cloud
Build a Tiny JSON API With Axum: Rust on the Web in Fifteen Minutes
Your Rust programs have been talking to the terminal. Time they talked to the internet. Build a notes API with Axum, with routes, JSON in and out, shared state and proper 404s, in about 50 lines.
Cloud
Ollama Review: Running Local LLMs on Your Own Machine, No Cloud Required
What if your AI assistant lived in your basement instead of someone else's data centre? A review of Ollama: how to run local LLMs with it, what hardware you really need, the API that makes it useful, and where it falls short.
Cloud
Rust Iterators: Fire Your for Loops (They'll Be Fine, They Have Savings)
Your for loop has been doing three jobs at once and it's tired. Rust iterators split the work into map, filter and sum, cost nothing extra at run time, and are lazier than a cat in a sunbeam. A ten-minute lab.