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.

Bash
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:

Rust
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:

Bash
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:

Rust
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:

Rust
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.