The Complete Guide to Async Runtimes: Tokio, io_uring and Event Loops
How async runtimes work from the kernel up: readiness and completion I/O, epoll, io_uring, reactors, executors, Tokio internals and how to choose.

Every network server faces the same arithmetic. A connection spends nearly all of its life waiting: for the next request, for a database reply, for a slow client to drain a response. A server that gives each connection a thread pays for a stack, a kernel scheduling entity and a context switch per waiting client, and it runs into limits long before the CPU is busy. An async runtime is the machinery that avoids that bill. It lets a small number of threads wait on a large number of operations at once and do work only when the kernel says something is ready. This guide explains that machinery from the bottom up, across the whole subject rather than one library: the I/O models the kernel offers, how epoll and io_uring differ, what a reactor and an executor are, how Tokio is built, how thread-per-core runtimes depart from it, and how to choose and debug. The code is for Rust 1.90, Tokio 1.x, Linux 6.x and C with glibc 2.41, and it is written, not run, with the output worked out from the code.
Waiting is the workload. A runtime is not a way to compute faster; it is a way to wait on ten thousand things with a few threads and wake exactly the right piece of code when one of them is done.
If any of the vocabulary is new, the cluster's beginner posts define it: what asynchronous I/O is, how to write a Tokio echo server and how a future is polled. This guide assumes you can read Rust and C at the level of those posts and moves quickly through the ideas they introduce.
Why threads stop being the answer
Threads per connection is the oldest server design and the easiest to write. The code is straight-line: accept, read, process, write, block wherever necessary. For a few hundred connections it is a fine choice, and it remains the right choice for many programs, a point the boundary section returns to. The costs scale with the number of connections, not with the amount of work. Each thread reserves stack address space, and while untouched pages cost no physical memory, thousands of threads still mean thousands of kernel objects that the scheduler must consider. A blocked thread holds no CPU, but waking and switching to it costs cache state. When ten thousand mostly idle connections are served by ten thousand threads, the machine spends its effort managing sleepers.
The alternative decouples waiting from threads. A thread asks the kernel to watch many file descriptors, sleeps in a single call until at least one needs attention, and then handles exactly the ones that do. One thread can serve thousands of idle sockets and spends its time on the active ones. This is the design that Node.js popularized for JavaScript, that nginx uses in C, and that Tokio provides in Rust. The cost moves from the kernel to your program structure: you can no longer block, and the control flow of a request is split across many wake-ups.
The kernel's I/O models
Three models matter, and all later design choices follow from which one a runtime builds on.
Blocking I/O. read does not return until data is available. Simple, and it ties up a thread per wait.
Non-blocking I/O with readiness notification. The descriptor is put in non-blocking mode, so read returns immediately with EAGAIN when there is nothing to read. A separate call, such as select, poll or epoll_wait, tells you which descriptors are ready for an operation. You then perform the operation yourself, and it succeeds without blocking. The kernel tells you that you may act.
Completion-based asynchronous I/O. You submit an operation, with the buffer, to the kernel, and the kernel performs it and tells you when it has finished. The kernel does the work. Windows has had this for decades as I/O completion ports, and Linux's io_uring, which arrived in kernel 5.1, is its modern form there.
The difference between the last two is the center of this guide. Readiness is a hint about the future: by the time you act, another thread may have consumed the data. Completion reports a fact about the past: your bytes are in your buffer. Readiness needs two system calls per operation (wait, then read), completion can batch many operations into one. Completion needs the buffer to remain valid and untouched while the kernel owns it, which constrains API design, as we will see.
Readiness in practice: epoll
On Linux, epoll is the readiness interface. The epoll(7) manual describes three calls. epoll_create1 makes an epoll instance, a kernel object that holds a set of watched descriptors. epoll_ctl adds, modifies or removes a descriptor with an interest mask such as EPOLLIN for readable. epoll_wait sleeps until a watched descriptor is ready and fills an array of events.
Here is a complete single-threaded echo server on epoll, which is what every readiness-based runtime does at its core:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <sys/socket.h>
static void set_nonblocking(int fd)
{
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
}
int main(void)
{
int lfd = socket(AF_INET, SOCK_STREAM, 0);
int one = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
struct sockaddr_in addr = { .sin_family = AF_INET,
.sin_port = htons(7878),
.sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
bind(lfd, (struct sockaddr *)&addr, sizeof addr);
listen(lfd, 128);
set_nonblocking(lfd);
int ep = epoll_create1(0);
struct epoll_event ev = { .events = EPOLLIN, .data.fd = lfd };
epoll_ctl(ep, EPOLL_CTL_ADD, lfd, &ev);
struct epoll_event events[64];
for (;;) {
int n = epoll_wait(ep, events, 64, -1);
for (int i = 0; i < n; i++) {
int fd = events[i].data.fd;
if (fd == lfd) {
int cfd;
while ((cfd = accept(lfd, NULL, NULL)) >= 0) {
set_nonblocking(cfd);
struct epoll_event cev = { .events = EPOLLIN, .data.fd = cfd };
epoll_ctl(ep, EPOLL_CTL_ADD, cfd, &cev);
}
} else {
char buf[1024];
ssize_t r;
while ((r = read(fd, buf, sizeof buf)) > 0)
write(fd, buf, r); /* a real server handles a short write */
if (r == 0 || (r < 0 && errno != EAGAIN)) {
epoll_ctl(ep, EPOLL_CTL_DEL, fd, NULL);
close(fd);
}
}
}
}
}Compile with gcc -O2 -o epoll_echo epoll_echo.c, start it, and from another terminal run printf 'hello' | nc -q1 127.0.0.1 7878:
helloEverything a runtime does is here in miniature. There is one loop and one sleeping point, epoll_wait. The listening socket is ready when a connection waits to be accepted. Client sockets are ready when bytes arrive. The loops that call accept and read until they fail with EAGAIN are required for edge-triggered use, and harmless for the default level-triggered mode used here, where epoll_wait reports a descriptor as long as it stays ready. Real servers need what this lacks: a write queue for when write returns a short count, timers, and a way to structure per-connection logic that is not a hand-written state machine. An async runtime supplies exactly those.
Two other readiness interfaces exist for context: select and poll take the whole watched set on every call and scan it linearly, which is why epoll replaced them for large sets, and BSD and macOS use kqueue, which also covers files, signals and timers in one interface.
Anatomy of an event loop
Every async runtime, in any language, has the same four parts.
A reactor (or I/O driver): owns the readiness or completion mechanism and sleeps in it. When events arrive, it translates them into "this task can make progress".
A timer facility: sleeps and timeouts need a deadline queue, and the reactor's wait call takes a timeout equal to the nearest deadline, so one sleeping point covers both.
An executor (or scheduler): holds a queue of runnable tasks and runs them one at a time, each until it cannot make progress.
Tasks: units of work that can suspend. In Rust they are futures, in Node callbacks and promises, in Python coroutines, in Go goroutines.
The main loop is always some form of: run every runnable task; compute the nearest timer deadline; sleep in the reactor until an event or that deadline; turn events into runnable tasks; repeat. The only real difference between runtimes is how tasks are represented and whether the loop runs on one thread or several.
Rust's model: futures and wakers
Rust standardizes the task representation without standardizing the runtime. A task is a value implementing Future, whose poll method either finishes (Ready) or reports Pending after registering a Waker. An async fn compiles into a state machine implementing this trait, and .await is the point where that state machine hands control back when a sub-future is Pending. Futures are lazy: creating one does nothing until an executor polls it.
The bridge to the kernel is the waker. When a leaf future, say reading a socket, finds that the read would block, it stores the waker it was given under the descriptor's token and returns Pending. The reactor, on seeing the descriptor ready, looks up the waker and calls wake, which puts the task back on the run queue. The posts on implementing a future by hand and on how wakers connect to epoll walk through this with code; the one rule worth repeating here is that **returning Pending without registering a waker hangs the task forever**, because nothing will ever poll it again.
This design has an important consequence. Rust's async is poll-based, so a future is a passive state machine that is driven from outside, and the executor decides when to poll. The language has no built-in scheduler, I/O or timer. That is why a choice of runtime exists at all, and why libraries must be written against a runtime's I/O traits to be portable.
Tokio: the standard runtime
Tokio is the dominant Rust runtime and the one most libraries target. Its parts map directly to the anatomy above.
The I/O driver is built on mio, a thin portable layer over epoll, kqueue and IOCP. Each registered socket gets a token and a small structure holding readiness bits and waker slots. The time driver keeps a hierarchical timer wheel and feeds the nearest deadline into the I/O driver's wait. The scheduler comes in two flavors: a current-thread scheduler that runs everything on the thread that called block_on, and a multi-threaded scheduler with a worker per core, per-worker queues and work stealing, described in the post on Tokio's scheduler. A separate blocking pool of threads runs spawn_blocking closures and filesystem operations. Whichever worker finds itself with nothing to do drives the I/O driver, so there is no dedicated reactor thread.
A complete program ties the pieces together. This one starts a server and three clients in one process, so the whole interaction is visible and its output is deterministic:
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
async fn echo_server(listener: TcpListener) {
loop {
let (mut socket, _) = listener.accept().await.unwrap();
tokio::spawn(async move {
let mut buf = [0u8; 256];
loop {
match socket.read(&mut buf).await {
Ok(0) | Err(_) => return,
Ok(n) => {
if socket.write_all(&buf[..n]).await.is_err() {
return;
}
}
}
}
});
}
}
async fn client(addr: std::net::SocketAddr, id: u32) -> String {
let mut stream = TcpStream::connect(addr).await.unwrap();
let msg = format!("hello {id}");
stream.write_all(msg.as_bytes()).await.unwrap();
let mut reply = vec![0u8; msg.len()];
stream.read_exact(&mut reply).await.unwrap();
format!("client {id} got: {}", String::from_utf8(reply).unwrap())
}
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(echo_server(listener));
let handles: Vec<_> = (0..3).map(|id| tokio::spawn(client(addr, id))).collect();
for h in handles {
println!("{}", h.await.unwrap());
}
}client 0 got: hello 0
client 1 got: hello 1
client 2 got: hello 2Port 0 asks the kernel for a free port, which local_addr reads back, so the example cannot collide with another program. The three clients run concurrently as separate tasks, but the program awaits their handles in order, so the printed order is fixed even though completion order may vary. Three tasks, one accept loop and up to three connection tasks run on the worker threads, and every socket operation suspends its task instead of blocking a thread. The task count here is tiny; nothing changes in structure at ten thousand.
Composition: join, select and channels
Real programs run many operations at once and combine their results. Tokio's primitives follow a few patterns. tokio::join! polls several futures concurrently in one task and returns all results. tokio::select! waits for the first of several futures to complete and drops the others, which makes it both a race and a cancellation mechanism. tokio::spawn creates an independent task that runs without being awaited. Channels (mpsc, oneshot, broadcast, watch) connect tasks, and the post on Tokio channels shows which one fits which pattern.
Cancellation deserves emphasis because it is unlike threads. Dropping a future cancels it at its current .await, running destructors and executing nothing further. A function that does two writes with an await between them can be cancelled between them. Designing for this, with the cancel-safety notes in Tokio's documentation as the reference, is a core skill of async Rust, and it is the subject of the post on select! and CancellationToken. A graceful shutdown ties cancellation, tracking and timeouts together and gets its own post.
The cardinal rule: do not block the loop
Because tasks share threads, any code that holds a worker thread without reaching an .await delays every other task on that thread. Blocking calls, long computation, a lock held while waiting, a synchronous database driver, a large std::fs read: all of them. The symptom is latency that depends on what else is running, with low CPU use and timers firing late.
The remedies, in order of preference: use an async version of the operation; move blocking calls to the blocking pool with spawn_blocking; move heavy computation to a dedicated thread pool such as Rayon and await the result over a channel; and break long loops with explicit yields. The posts on spawn_blocking and on finding tasks that block the executor give code for each, including a watchdog that proves a runtime is stalled and a wrapper that names the offending task. Tokio's own cooperative budget limits how long a task can keep winning ready results from Tokio resources, but it cannot interrupt code that never touches one.
Completion-based I/O: io_uring
io_uring changes the kernel interface rather than the kernel's work. Introduced in Linux 5.1 by Jens Axboe and documented in the io_uring(7) manual and the liburing project, it gives a process two ring buffers shared with the kernel: a submission queue (SQ) where you write requests, and a completion queue (CQ) where the kernel writes results. Because the rings live in shared memory, queuing a request needs no system call; one io_uring_enter call, or none at all in the polling modes, tells the kernel to process everything queued. Each submission queue entry (SQE) describes an operation such as read, write, accept, send, receive, connect, open, close or timeout, with its arguments and a user-chosen user_data word. Each completion queue entry (CQE) returns the user_data and a res value, a byte count or a negative errno.
Compared with epoll, three differences stand out. A read is one request and one completion, not a wait followed by a read, which halves the system call count for simple cases. Many operations can be submitted in one call, which amortizes the system call overhead across a batch. And files work: regular file reads are not readiness-pollable, so epoll-based runtimes emulate asynchronous file I/O with a thread pool, whereas io_uring can submit file operations like any other.
A minimal complete program using liburing reads from a pipe, to show the submit and reap cycle:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <liburing.h>
int main(void)
{
struct io_uring ring;
io_uring_queue_init(8, &ring, 0);
int fds[2];
pipe(fds);
write(fds[1], "from the kernel", 15);
char buf[32] = {0};
struct io_uring_sqe *sqe = io_uring_get_sqe(&ring);
io_uring_prep_read(sqe, fds[0], buf, sizeof buf - 1, 0);
io_uring_sqe_set_data(sqe, buf);
io_uring_submit(&ring);
struct io_uring_cqe *cqe;
io_uring_wait_cqe(&ring, &cqe);
printf("completion: res=%d data='%s' user_data_is_buf=%d\n",
cqe->res, buf, io_uring_cqe_get_data(cqe) == (void *)buf);
io_uring_cqe_seen(&ring, cqe);
io_uring_queue_exit(&ring);
return 0;
}Build with gcc -O2 -o uring_read uring_read.c -luring.
completion: res=15 data='from the kernel' user_data_is_buf=1The res field is 15, the number of bytes read, and the buffer was filled by the kernel before the completion was posted. The user_data we attached came back unchanged, which is how a runtime finds the task to resume. The post on building an async runtime with C++20 coroutines turns exactly this cycle into an awaitable.
Using io_uring from Rust
Tokio does not use io_uring, since its driver is readiness-based and its I/O traits (AsyncRead and AsyncWrite) borrow buffers. Borrowing is incompatible with completion I/O in a subtle way. When you await a read into &mut buf and the future is dropped, as select! does to the losing branch, the borrow ends and the buffer can be freed or reused, while the kernel may still be about to write into it. Completion-based runtimes avoid the bug by taking ownership of the buffer: read(buf) consumes a Vec<u8> and returns it with the result, so the runtime can keep it alive until the kernel is finished, even if the caller gave up.
Several runtimes exist, each with its own traits: tokio-uring offers a Tokio-compatible runtime for io_uring with ownership-passing I/O; monoio and glommio are thread-per-core designs, covered in the post on thread-per-core runtimes; Seastar does the same in C++. The practical consequence is an ecosystem split. A library written against tokio::io::AsyncRead cannot be used unchanged with an ownership-based runtime, and the reverse holds. This is the biggest non-performance cost of choosing io_uring, and it is why the default remains Tokio.
Readiness versus completion
| Property | Readiness (epoll, kqueue) | Completion (io_uring, IOCP) |
|---|---|---|
| What the kernel tells you | "you may perform the operation now" | "the operation has finished" |
| System calls per read | wait, then read | submit and complete, batchable |
| Buffer ownership | borrowed during your own read | owned by the kernel until completion |
| Regular files | not pollable; thread pool needed | submitted like any operation |
| Cancellation | drop the future, no kernel state | must cancel the in-flight request |
| Ecosystem | very large (Tokio) | smaller, runtime-specific traits |
| Platform | every OS | Linux 5.1 and later for io_uring, Windows IOCP |
The table captures the trade. Completion saves system calls and handles files uniformly, at the cost of an ownership-based API, a smaller ecosystem and kernel-version dependence. There is also a security dimension: io_uring exposes a large kernel surface, and some container runtimes and hardened systems restrict or disable it through seccomp filters or sysctls, so check that your deployment target allows it before building on it.
Thread models: shared queue, stealing, thread per core
Where tasks run is a separate decision from how I/O is done. Three models cover the landscape.
Single thread. One loop, no parallelism. Node.js and a Tokio current-thread runtime work this way. There are no data races on task state, tasks can hold Rc and RefCell in Rust, and one blocked task stalls everything. It uses one core, so you scale by running several processes.
Multi-threaded with work stealing. A pool of workers with per-worker queues, where idle workers steal from busy ones. This is Tokio's default, Go's scheduler and .NET's thread pool. It balances uneven work automatically and uses all cores, at the cost of requiring tasks to be Send and shared state to be synchronized.
Thread per core. One single-threaded loop per core, each owning a slice of the connections and data, and communicating by message passing. Seastar, Glommio and Monoio work this way. It removes locks and atomics from the hot path and keeps data in one core's cache, and it moves load balancing to the programmer. It suits workloads that partition cleanly.
None is universally best. Work stealing is the forgiving default because it tolerates uneven work, and thread-per-core wins only when the workload partitions evenly and coordination is the measured bottleneck.
Event loops elsewhere
Seeing the same design in other ecosystems clarifies what is essential. libuv, the loop under Node.js, uses epoll on Linux and IOCP on Windows, runs callbacks on one thread, and uses a thread pool for file system calls and DNS, the same hybrid Tokio has. Python's asyncio exposes the loop and its low-level transports and protocols, as the post on asyncio transports shows, and runs coroutines on it; it also supports uvloop, a libuv-based drop-in. Go hides the loop entirely: the runtime's network poller parks goroutines on epoll and resumes them, so ordinary blocking-looking code yields the same effect, with a preemptive scheduler. Java's Netty is an event-loop framework over NIO, and recent Java versions add virtual threads that give blocking-style code the same economics. Erlang gives each process its own mailbox and runs them on preemptive schedulers. The pattern is constant: few threads, a readiness or completion mechanism, tasks that suspend. Languages differ in whether the suspension is explicit in the source (await), implicit (Go, virtual threads) or built into the process model (Erlang).
The disagreement worth naming is whether explicit await is good. Its supporters point to visible suspension points, which make cancellation and interleaving reasoning possible and cost nothing at run time. Its critics point to function coloring, where async code can only be called from async code, splitting every library in two. Go and Java's virtual threads choose the opposite trade, hiding suspension. Rust chose explicit, because it has no runtime to hide it in and needs the compiler to produce state machines it can size.
Reasoning about performance without a stopwatch
Benchmarks of runtimes are easy to misread, and this guide offers none. The mechanisms are what you can reason about. System calls cost: each epoll_wait and read crosses into the kernel, and io_uring's batching and shared rings exist to reduce those crossings. Wake-ups cost: each time a thread sleeps and is woken, the kernel scheduler and the CPU's caches pay, which is why runtimes limit how many workers search for work at once and why the LIFO slot keeps communicating tasks on one core. Synchronization costs: atomics and locks on shared queues make cache lines move between cores, which thread-per-core designs avoid. Allocation costs: each spawned task usually allocates, and large futures are expensive to move; the tokio-console post shows a lint for large futures. Copying costs: a read into a user buffer and a write from it moves each byte twice, and zero-copy facilities such as splice and sendfile avoid it.
The method that follows: find the bottleneck with a profiler or perf stat before changing runtime; check whether the program is waiting (low CPU, high latency) or computing (high CPU); and compare designs on your workload with realistic concurrency and skew. A runtime swap that does not address the measured bottleneck changes nothing.
Debugging and observability
Async programs fail differently from threaded ones. A stuck task has no thread to inspect, so the tools must understand tasks. tokio-console shows each task's busy, scheduled and idle times and warns about long polls, self-wakes and lost wakers. Runtime metrics, some stable and some behind tokio_unstable, expose queue depths and per-worker busy time. A watchdog task that measures how late its own timer fires is the simplest proof that something is blocking the workers. tracing spans attached to tasks give request-level context across awaits. For the system view, strace -f and perf trace show which system calls a worker spends time in, which finds blocking calls that CPU profiles miss. The lost wake-up is the characteristic bug of hand-written futures and reactors, and its signature is a task idle forever while its data is ready.
Choosing a runtime and a model
| Situation | Choose |
|---|---|
| General network service in Rust, broad library needs | Tokio multi-threaded |
Tool, test or embedded context, !Send data | Tokio current-thread, or a LocalSet |
| Many-core server, partitionable load, coordination-bound | thread-per-core (Glommio, Monoio) |
| Heavy file I/O on Linux, willing to own the ecosystem cost | io_uring runtime |
| Existing C or C++ codebase with an event library | libuv, libevent or Seastar |
| Python service with high connection counts | asyncio, possibly with uvloop |
| Few connections, simple logic | plain threads |
Timeouts, deadlines and retries
Every operation that waits on another party needs a deadline, because the other party can fail without telling you. In Tokio the tool is tokio::time::timeout(duration, future), which races the future against a timer and returns Err(Elapsed) if the timer wins, dropping the future. The same cancellation rule applies: whatever the future had half done stays half done. A deadline belongs at every network boundary: connect, each read of a response, and the whole request. Compose them by computing one overall deadline with tokio::time::Instant and using timeout_at for each step, so a slow first step leaves less time for the rest.
Retries need the opposite care. Retrying an operation that already partly succeeded duplicates its effects, so retry only idempotent operations or attach an identifier the server can deduplicate. Back off between attempts with a growing, randomized delay, and cap the total number of attempts. A retry loop with no cap and no delay turns a brief outage of a dependency into a self-inflicted overload of it, which is why backpressure and deadlines matter as much as the happy path.
Backpressure and bounded queues
An async program that accepts work faster than it can process it builds a queue somewhere, and the only question is where. An unbounded channel puts it in memory, where it grows until the process is killed. A bounded channel makes send wait when the queue is full, which pushes the delay back to the producer, and if the producer is a socket reader it stops reading, so the kernel's receive buffer fills and TCP closes its window, slowing the remote sender. This chain of waiting, from the slowest stage back to the original source, is backpressure, and it works only if every stage between them is bounded. One unbounded queue anywhere breaks the chain at that point.
Where waiting is not acceptable, shed load deliberately: reject new connections beyond a limit with a counting Semaphore, answer with a fast error when a queue is nearly full, or drop low-priority work. Tokio's Semaphore is the standard tool for limiting concurrency, such as the number of simultaneous outbound requests or open connections, and its owned permits release automatically when dropped, so a task that panics or is cancelled returns its permit.
Structured concurrency and task lifetimes
A spawned task is detached by default: dropping its JoinHandle does not cancel it. That makes it easy to leak tasks that outlive the work that started them, keep resources alive and continue after the caller has given up. Structured concurrency is the discipline of making sure child tasks end before their parent scope does. In Tokio the main tools are JoinSet, which owns a group of tasks, lets you await them as they complete and aborts any that remain when the set is dropped, and TaskTracker with a CancellationToken, as in the graceful shutdown post. Prefer join! and select! over spawn when the work is tied to the current function, since futures polled inline are dropped with their owner. Spawn only when a task must outlive the call.
Streams, framing and protocol state
Network protocols arrive as byte streams, so servers need framing: deciding where one message ends and the next begins. Length prefixes, delimiters such as newlines, and self-describing formats are the three common answers. In Tokio the tokio-util crate's Framed adapters turn an AsyncRead and AsyncWrite into a Stream and Sink of messages through a Decoder and an Encoder, which keeps the buffer management and the partial-read logic in one tested place. The decoder returns Ok(None) when it needs more bytes and Ok(Some(message)) when a full frame is available, and it must tolerate being called with a partial frame, many frames or the tail of a frame, exactly as the asyncio data_received example in the cluster does by hand.
Protocol state, such as "waiting for the handshake" or "authenticated", fits naturally into the structure of an async fn: the position in the function is the state, which is the main readability advantage of async over callbacks. A connection handler written as straight-line code, handshake then loop of requests, reads like the protocol specification. When states are numerous, interleaved or driven by timers, a state machine type with explicit states can be clearer, and Erlang's gen_statem is the model for it.
Security and resource limits
An async server is exposed to clients that behave badly on purpose. Each connection costs memory for its task and buffers, so cap the number of connections and the size of each message before allocating for it. Put a deadline on the time a client may take to send a request, since a slow-loris client that sends one byte a minute holds a connection and a task indefinitely at almost no cost to itself. Limit nesting and sizes in parsers, and do not trust a length prefix to allocate memory, because a four-byte prefix can claim four gigabytes. Run decompression and parsing of untrusted input with output limits. None of this is specific to async, but async makes it easy to hold a hundred thousand connections open, which makes the limits matter more.
Migrating between models
Programs rarely start in their final model. A common path starts with blocking threads, adds a thread pool, and moves the hot connection-handling path to Tokio when idle connections dominate. Keep the boundary clean when you do: put the async code behind a small interface with owned data crossing it, use channels between the async side and blocking workers, and migrate one component at a time. The reverse move, from async to threads, is also legitimate when the complexity is not paying for itself, and it is easier when the async code has been kept to the edges.
Moving from a readiness runtime to an io_uring runtime is a larger change because the I/O traits differ. Isolate socket and file access behind your own small traits first, so that application logic is written against read_some(buf) -> (result, buf) style interfaces. Then the runtime is an implementation detail, and a benchmark of your own workload on both settles the question with evidence, not guesses.
Boundaries: when async is the wrong tool
Async is a specialist tool, and these cases argue against it. CPU-bound work gains nothing: a runtime schedules waiting, not computing, and a data-parallel computation belongs on Rayon or plain threads. Programs with few connections pay async's complexity, function coloring, Send bounds and harder stack traces, for no benefit; a thread per connection serves a few hundred connections well. Code that must call blocking libraries heavily ends up wrapping most of it in spawn_blocking, so the async layer adds only overhead. Hard real-time systems need bounded latency that cooperative scheduling cannot promise; an RTOS or dedicated threads with priorities is the answer. Teams new to the model should expect a learning curve in cancellation and ownership that threads do not have. And latency-critical single-hot-key workloads do not parallelize however the loop is built.
For these readers the right path is simpler: use threads and a thread pool, and revisit async if connection counts or idle waits grow until threads become the measured problem.
A reading path through the cluster
The beginner posts introduce asynchronous I/O, the Tokio echo server and spawn_blocking. The intermediate posts cover cancellation, channels, bridging sync and async code, the Send bound, runtime flavors and shutdown, plus asyncio's protocols. The advanced posts implement a future and an executor by hand, explain Tokio's work stealing, build a C++20 coroutine runtime on io_uring and use tokio-console. The expert posts find blocking tasks, compare thread-per-core runtimes, trace wakers down to epoll and build a stackful event loop with ucontext. Read them in that order, and write the small executor yourself at least once: it removes the mystery faster than any description.
Operating an async service
Running an async service in production adds a few habits. Expose runtime metrics alongside application metrics, so a graph of queue depth or busy time sits next to request latency and the two can be correlated. Set the worker thread count deliberately when the process runs in a container with a CPU quota, because the runtime may see the host's core count and start more workers than the quota allows, which causes throttling that looks like random latency. Pin file descriptor limits above the maximum connection count you intend to hold, since running out of descriptors makes accept fail in ways that surface far from the cause. And rehearse shutdown: send the termination signal under load in a staging environment and check that in-flight requests finish and no connection is cut mid-response.
Treat every dependency of the event loop as a potential blocker. A logging library that writes synchronously to a slow disk, a metrics client that flushes inline, a DNS lookup that uses the blocking resolver, a TLS library that does heavy certificate work on the calling thread: each of these can stall a worker. The remedy is the same each time, but you have to look for them, which is the argument for keeping the watchdog task from the post on finding blocking tasks permanently enabled.


