Learn Tokio · 2/14

Getting Started: Your First Tokio Project

7 min read

Welcome to the engine room, Rustacean. If you made it here, you likely know the basics of Rust, but now you want your code to do more than one thing at a time without eating all your RAM.

You are about to enter the world of Asynchronous Programming. In the Rust ecosystem, Tokio is the absolute titan—the standard runtime that powers most of the industry's high-performance network services.

Fun Fact: Tokio is named after the city Tokyo, but spelled with an 'i' because... well, naming things in programming is arguably harder than cache invalidation. It downloads millions of times a month, powering everything from databases (like Redis clones) to web frameworks (like Axum).


1. Setting Up the Tokio Environment and Dependencies 📦

Before we write code, we need to prepare our workshop. Rust’s standard library (std) is synchronous by default. It doesn't ship with an async runtime because Rust aims to be minimal. You have to opt-in.

The Problem

You want to write async code, but Rust doesn't have a built-in scheduler to run it. If you try to write an async function without a runtime, nothing happens. It's like buying a Ferrari engine but not putting it in a car—it sits there looking cool, but it won't go anywhere.

The Solution

We bring in Tokio as a dependency to act as that car/chassis.

Step-by-Step Setup

  1. Create a new project:
    Open your terminal and create a fresh binary project.

    bash
    cargo new my_first_tokio
    cd my_first_tokio
  2. Add Tokio to Cargo.toml:
    You can do this manually, but the industry standard way (to ensure you get the latest version) is using cargo add.

    Run this command:

    bash
    cargo add tokio --features full

    Wait, what is --features full?
    Tokio is modular. By default, it includes almost nothing to keep binary sizes small. The full feature flag enables:

    • Multi-threaded runtime (Work Stealing scheduler)
    • I/O drivers (Network, File system)
    • Time drivers (Sleep, Interval)
    • Macros (The magic we are about to use)

    Your Cargo.toml should now look something like this:

    toml
    [dependencies]
    tokio = { version = "1.36.0", features = ["full"] }

    (Note: The version number might be higher when you read this, that is fine).


2. The #[tokio::main] Macro: Bootstrapping the Runtime 🏗️

Now, open src/main.rs. You probably see this:

rust
fn main() {
    println!("Hello, world!");
}

If you try to change fn main to async fn main, the Rust compiler will yell at you. The operating system expects a synchronous function to start a program. It doesn't know how to await a Future.

The Definition

#[tokio::main] is a procedural macro attribute. It transforms your code just before compilation.

How it Solves the Problem

It takes your async main function and wraps it in a synchronous runtime initialization code. It effectively bridges the gap between the OS (synchronous) and your code (asynchronous).

Under the Hood (What really happens)

When you write this:

rust
#[tokio::main]
async fn main() {
    println!("Hello Tokio!");
}

The macro rewrites it into something that looks like this (simplified):

rust
fn main() {
    // 1. Build the runtime
    let rt = tokio::runtime::Runtime::new().unwrap();

    // 2. Block the current thread until the async body finishes
    rt.block_on(async {
        println!("Hello Tokio!");
    });
}

This starts the "Work Stealing" scheduler, sets up the thread pool, and executes your code.


3. Your First Async Program: "Hello Tokio!" 💻

Let's write a program that actually does something "async". Printing text is too fast to notice the difference. Let's make it wait.

The Code

Update your src/main.rs:

rust
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    println!("1. Start: The journey begins...");

    // Spawn a background task
    let handle = tokio::spawn(async {
        println!("2. Background: I am running in a separate task!");
        sleep(Duration::from_secs(2)).await;
        println!("4. Background: I am done waiting.");
    });

    println!("3. Main: I am not blocked! I'm doing other work.");

    // Wait for the background task to finish
    handle.await.unwrap();
    
    println!("5. Finish: All done.");
}

Key Concepts Explanation

async fn

This defines a function that returns a Future. A Future is a promise that a value will be produced eventually. When you call an async function, it doesn't run immediately—it returns a task that can be run.

.await

This is the magic syntax.

  • Definition: It suspends the current function execution until the future is ready.
  • Industry Note: In synchronous code (like std::thread::sleep), the entire thread halts. The CPU core sits idle. In Async Rust (tokio::time::sleep), .await tells Tokio: "I'm waiting on a timer. Go use this CPU thread to run some other code while I wait."

Run it!

bash
cargo run

Expected Output:
The order is usually:

  1. Start...
  2. Main: I am not blocked...
  3. Background: I am running...
  4. (2 second pause)
  5. Background: I am done waiting.
  6. Finish: All done.

Note: "Main" and "Background" output order might swap slightly depending on how the scheduler picks them up, which is normal in concurrent programming!


4. Understanding the Event Loop Conceptually 🔄

Why did we go through all this trouble? Why not just spawn a new OS thread for every task?

The Problem with Threads

OS threads are expensive.

  1. Memory: Each thread consumes a stack (usually 2MB). 10,000 threads = ~20GB of RAM just for stacks!
  2. Context Switching: Stopping one thread and starting another takes CPU time. Doing this thousands of times a second kills performance.

The Solution: The Event Loop

Tokio uses Non-blocking I/O and an Event Loop.

Definition

An Event Loop is a programming construct that waits for and dispatches events or messages in a program. It works by making a request to some internal or external event provider (which generally blocks the request until an event has arrived), and then calls the relevant event handler ("dispatches the event").

How it works (The Analogy)

Imagine a restaurant kitchen 🍳:

  • Synchronous (OS Threads): You hire 1 waiter for 1 customer. If the customer is thinking about their order for 5 minutes, that waiter stands there doing absolutely nothing. If you have 100 customers, you need 100 waiters. The kitchen is crowded.
  • Asynchronous (Tokio): You have 1 waiter (The Thread). The waiter takes an order (Task) and gives it to the chef. While the chef cooks, the waiter goes to the next table to take another order. When the food is ready (Event), the waiter brings it back. One waiter serves 100 tables efficiently.

Under the Hood: epoll / kqueue / IOCP

Tokio doesn't constantly ask "Is the data ready?". That would be inefficient (busy waiting).

Instead, it registers interest with the Operating System.

  1. Your code says: "Read this file."
  2. Tokio tells OS: "Tell me when this file has data."
  3. Tokio puts your task to sleep (removes it from CPU).
  4. Tokio runs other tasks.
  5. OS Interrupt: "Data is ready!"
  6. Tokio wakes up your task and continues exactly where it left off.

⚠️ Industry Warning: The Golden Rule

Never block the thread in async code.

Since Tokio uses a small number of threads (usually equal to CPU cores) to handle thousands of tasks, if you run a heavy computation or use std::thread::sleep inside an async function, you literally stop the "waiter." No one else gets served.

Bad Practice:

rust
// DO NOT DO THIS
fn bad_task() {
    std::thread::sleep(std::time::Duration::from_secs(10)); // Freezes the whole runtime!
}

Good Practice:

rust
// DO THIS
async fn good_task() {
    tokio::time::sleep(std::time::Duration::from_secs(10)).await; // Yields control
}

Summary Checklist ✅

  1. Created a project with cargo new.
  2. Added tokio with features = ["full"].
  3. Used #[tokio::main] to start the runtime.
  4. Wrote async functions and used .await to yield control.
  5. Understood that .await allows the Event Loop to swap tasks efficiently.

You have successfully initialized the reactor core. In the next sections, we will dive into Spawning, Channels, and handling Shared State.

References & Further Reading 📚

Challenge

Challenge: Concurrent Task Simulator

You are tasked with building a small simulation of a concurrent process manager using Tokio. Your program must spawn multiple asynchronous tasks that run in parallel, and the main function must wait for all of them to complete.

Requirements:

  1. Create an async function named process_task.

    • It must accept two arguments: a task identifier (id of type u32) and a processing time in milliseconds (duration_ms of type u64).
    • Inside the function, it should simulate work by pausing execution for duration_ms using the appropriate non-blocking Tokio timer function.
    • After the pause, the function shall return a String with the format: "Task <id> finished.", where <id> is the task identifier.
  2. Implement the main function.

    • It must be configured as the entry point for a Tokio runtime using the necessary attribute macro.
    • Define a collection of three tasks to be processed with the following parameters: (id: 1, duration: 1000), (id: 2, duration: 500), (id: 3, duration: 750).
    • Iterate through this collection, and for each task, use tokio::spawn to start its execution in a new asynchronous task.
    • Store the JoinHandle returned by each tokio::spawn call.
    • After all tasks have been spawned, wait for all of them to complete by awaiting their handles.

Expected result

Your code should successfully compile and demonstrate the correct use of Tokio's core components.

  • The main function must be decorated with the #[tokio::main] attribute.
  • An async fn process_task(id: u32, duration_ms: u64) -> String must be implemented.
  • The process_task function must use tokio::time::sleep and not std::thread::sleep.
  • The main function must correctly use tokio::spawn in a loop to start three concurrent tasks.
  • The main function must collect the JoinHandle from each spawned task and await each one to ensure completion before the program exits.
rust

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.