Go to content
Web development

How Tokio Implements Async/Await in Rust

When you write async fn in Rust and run it under Tokio, the compiler and the runtime split the work between them. The compiler rewrites your function into a state machine: a value that records where execution paused and what local variables it needs to resume. Tokio then drives that state machine, deciding when to poll it, what runs while it waits, and how to wake it when the thing it’s waiting for becomes available.

Tokio is an event-driven, non-blocking I/O platform: the runtime most Rust projects use to run async code. It supplies the executor, the component that polls futures and runs tasks. It also supplies an I/O driver that watches sockets and files, timers, and synchronization primitives such as channels and mutexes that work with async.

To understand how the pieces fit together, keep three things in mind. The compiler turns each async function into a state machine. The executor polls those state machines and schedules which one runs next. The I/O driver asks the operating system to notify it when a socket becomes readable or writable, then wakes the task waiting on that I/O.

The key fact to understand before going deeper: async/await gives you concurrency, not parallelism. await pauses the current task until the operation finishes, and during that pause the executor runs other tasks. Two tasks interleave on one CPU core.

How async/await becomes a state machine

When you call an async fn, the body doesn’t run. The call returns a Future, a value that will eventually produce the function’s result. In Rust, a Future is a trait that defines a poll method. When something polls a future, the future returns Ready with the result, or Pending to say the result isn’t available yet, and the body starts running only on the first poll. The executor polls.

The compiler builds the state machine by turning every await point into a state. The future’s fields hold the local variables that must survive across each await. Tokio’s tasks compile into an enum-based state machine that avoids heap allocation for the task itself, so a mostly idle task costs very little memory. That’s why Rust async has the reputation of being cheap: waiting costs almost nothing.

await has a strict rule: you can only use it inside an async function or an async block. The rule exists because await needs a place to yield. When a future returns Pending, it also hands the executor a waker, a handle the runtime uses to notify it later. The waker is the bridge between "not done yet" and "done now, poll me again."

The executor and the work-stealing scheduler

Tokio’s executor is the loop that polls futures. The multi-threaded runtime, which is the default, runs one worker thread per CPU core and uses a work-stealing scheduler. Each worker keeps its own local queue of tasks; when a worker’s queue is empty, it steals tasks from other workers’ queues. Stealing is what keeps all cores busy when one worker ends up with a burst of tasks.

A worker looks for work in three places. It checks its local queue first, then a LIFO slot, then the global queue shared by all workers, and finally steals from another worker. The LIFO slot is an optimization: a freshly spawned task is often the one that will finish fast or spawn another task, so running it immediately improves cache locality.

Tokio keeps the local queues lock-free and wakes tasks in batches to cut scheduling overhead. The task data is split into a Header and a Trailer. The hot fields, those touched on every poll, sit in the Header, aligned to cache lines so separate threads writing to adjacent tasks don’t slow each other down through false sharing. False sharing happens when two CPU cores write to different variables that happen to share one cache line; each write forces the other core to reload the line even though the data is unrelated. For the queue mechanics in detail, the source of Tokio’s multi-threaded queue is the authoritative reference.

Wakers: how a paused task gets told to run again

A waker is the handle a future hands to the executor when it returns Pending. It’s a small structure: a data pointer and a vtable, a table of function pointers, which gives zero-cost dynamic dispatch. The vtable holds the functions the runtime needs, most importantly wake.

The wake path in Tokio is short. Calling waker.wake invokes the wake function in the vtable, which calls Task::wake on the underlying task, which enqueues that task back onto the scheduler. Once enqueued, a worker thread polls it again, and this time the operation that returned Pending should be Ready.

Who calls wake depends on what the task was waiting for. For I/O, the driver calls it when the event fires. For a timer, the timer wheel calls it when the time arrives. For a channel or a mutex, the sender or the releaser calls it. The design keeps the notification close to the cause: the thing that makes progress is the thing that wakes the waiter.

The I/O driver: epoll, kqueue, and IOCP

The I/O driver is Tokio’s bridge to the operating system’s event notification. Tokio uses the mio library underneath, which on Linux uses epoll, on macOS uses kqueue, and on Windows uses IOCP plus the AFD device. The driver registers the sockets it cares about, waits, and reacts when the OS reports readiness.

Each registered socket has a record called ScheduledIo that stores readiness bits, a tick counter, and a close flag in a single usize. Read and write each get one waker slot; extra waiters on the same operation go into an intrusive linked list. When a task polls a socket that isn’t ready, it returns Pending and the driver stores its waker; when the OS reports the socket ready, the driver wakes the task and the scheduler re-queues it.

The driver also manages timers. Tokio implements its timer with a hierarchical timing wheel, which gives O(1) insertion and deletion. A timing wheel is a ring of slots, each covering a slice of time, where a timer that fires far in the future goes into a wheel further out. This keeps the common case cheap: most timers are short-lived, and O(1) insert means you don’t pay for the size of the timer set.

Cooperative scheduling: the poll budget

Tokio runs tasks cooperatively, not preemptively. A task keeps running until it either hits an await that returns Pending or uses up its budget, which is 128 polls per task by default. When a task exhausts the budget, the scheduler suspends it and runs another task, so one long-running task can’t starve its worker thread.

This matters for your code directly. If a task spends a long time doing CPU work without reaching an await, it holds that worker thread. Alice Ryhl, a Tokio maintainer, recommends async code not go more than 10 to 100 microseconds without an await when you’re optimizing for response tail latency. The 128-poll budget is the safety net; the microsecond range is the practical target for services where the slowest request matters.

Where the async model breaks: blocking and CPU-bound work

The most common failure is doing blocking work inside an async task. A blocking call, like reading a file with std::fs, occupies the worker thread; enough of those clog the worker threads so nothing else on the runtime makes progress. Tokio provides spawn_blocking, which moves synchronous work to a dedicated thread pool for blocking tasks, keeping the async workers free.

A std::sync::Mutex is a common offender: locking it blocks the worker thread until another thread releases it. The deadlock patterns that std::sync::Mutex creates in async code deserve their own article.

There’s a subtler version when you mix Tokio with Rayon, a library for parallel data processing. If an async task calls a function that internally uses Rayon’s global thread pool and then waits for the result, the two runtimes can deadlock because Rayon’s global pool gets starved. Tokio’s worker sits stuck waiting on Rayon’s result while Rayon’s workers can’t get CPU to finish it. Keeping async runtime compatibility in mind when you pick libraries avoids this class of bug.

For CPU-bound work, the guidance is to not use the same runtime instance for both I/O and CPU-bound work; use separate runtime instances instead. The I/O runtime wants its worker threads free to answer sockets; a CPU-heavy task hogs a worker and raises I/O latency. InfluxDB IOx uses a dedicated executor: a separate multi-threaded Tokio runtime on its own thread at lower OS priority, running CPU-heavy tasks. The practical guide to CPU-bound work on Tokio covers the setup in more depth.

A related habit: don’t put await inside a loop if you want real concurrency. Awaiting each item in sequence makes each operation wait for the previous one; join_all or stream::iter(…).for_each_concurrent runs them concurrently.

Observing what the runtime is doing

Tokio provides tokio-console, a diagnostic tool that exposes live metrics over gRPC: active tasks, waker state, scheduling latency, and the split between work-stealing and work-sharing. When latency climbs and you suspect a task is stuck, tokio-console shows how many tasks sit in Pending state and how long they’ve been there. In one reported case, 70% of futures stayed in Pending for more than 5 ms during a traffic spike, which points directly at blocking work inside async tasks. That example is illustrative, but the diagnostic pattern is real: when most tasks sit in Pending for milliseconds, look at what’s actually holding them.

More in Web development Back to top ↑