Async I/O via Tokio in Axum
Why Axum's async I/O model with Tokio enables high-concurrency web servers and how to write non-blocking handlers correctly.
A web server spends most of its time waiting. It waits for a client to send a request, waits for a database to answer, waits for another service to respond. If the server uses a dedicated operating system thread for every connection, each waiting thread still consumes memory and CPU scheduling time. That limits how many clients the server can handle at once.
Axum avoids that problem by building on Tokio, an asynchronous runtime for Rust. This page explains what async I/O means in practice, how Tokio makes it efficient, and how you write code that takes advantage of it in an Axum application.
The Problem with Blocking I/O
Before async I/O, a typical multi-threaded server worked like this: when a new connection arrived, the server created a new thread and dedicated it to that connection. The thread would then perform a blocking read, waiting for the client to send data. While it waited, that thread did nothing useful, but it still occupied memory and appeared to the OS scheduler as a runnable unit.
A server handling 10,000 simultaneous connections would need 10,000 threads. Each thread has a default stack size, often 8 MB on Linux. That is 80 GB of memory just for stacks, not counting any data. The operating system also has to switch between those threads, causing context switching overhead.
In Rust, you can see blocking I/O with the standard library:
use std::io::{Read, Write};
use std::net::TcpListener;
fn main() {
let listener = TcpListener::bind("0.0.0.0:3000").unwrap();
for stream in listener.incoming() {
let mut stream = stream.unwrap();
std::thread::spawn(move || {
let mut buffer = [0; 1024];
loop {
let n = stream.read(&mut buffer).unwrap();
if n == 0 {
break;
}
let response = b"HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nHello, World!";
stream.write_all(response).unwrap();
}
});
}
}
This code creates one OS thread per connection. The read call blocks that thread until the client sends data. If the client never sends anything, the thread sits there forever. This works for a small number of connections, but it cannot scale to thousands of simultaneous clients on commodity hardware.
The point is that the server does not need a dedicated thread for each connection. It only needs to do work when data actually arrives. The rest of the time, the connection just needs to be remembered.
How Tokio Turns Waiting into Tasks
Tokio replaces the "one thread per connection" model with a small pool of worker threads, each of which runs many lightweight tasks. A task in Tokio is a future - a value that represents a computation that may not be finished yet. When you call .await on a future, the current task yields control back to the runtime if the future is not ready.
Behind the scenes, Tokio registers interest in the underlying non-blocking socket with the operating system's event notification mechanism (like epoll on Linux or kqueue on macOS). When data arrives, the OS tells Tokio, which then wakes up the task that was waiting for that socket and schedules it to run on a worker thread.
The result is that a few worker threads can handle tens of thousands of connections. A connection that is waiting for data does not consume a thread - it consumes only a small amount of memory to store its state and a registration in the event system.
Tokio's default multi-threaded runtime has one worker thread per CPU core. You typically do not need to change that.
Threads vs tasks:
A common beginner mistake is to think of a Tokio task as a thread. A task is much lighter: it is a stackless future, so it has no stack of its own at all - its state lives in the future value itself, sized by whatever locals the future holds across .await points. A thread, by contrast, has a fixed stack allocated by the OS (often 8 MB) and requires a system call to create. Tokio schedules many stackless tasks onto a few threads.
Your First Async Axum Handler
Axum handlers are ordinary async Rust functions. When you use #[tokio::main], you are telling Tokio to set up a runtime and run your main function inside it. The axum::serve function then runs an asynchronous accept loop: it waits for incoming connections, handles them, and goes back to waiting - without blocking a thread.
Here is the smallest Axum server that demonstrates async I/O:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn handler() -> &'static str {
"Hello, async world!"
}
When you run this and send a request with curl, you see the greeting. But the important part is what happens with many simultaneous requests. Each incoming request is turned into a Tokio task. The handler is an async function, so it can await other async operations without blocking the worker thread.
Suppose the handler performs an async sleep - for example, simulating a slow database call. Here is the difference between blocking sleep and async sleep:
use axum::{routing::get, Router};
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/blocking", get(blocking_handler))
.route("/async", get(async_handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn blocking_handler() -> &'static str {
std::thread::sleep(Duration::from_secs(5));
"slept 5 seconds using a blocking thread sleep"
}
async fn async_handler() -> &'static str {
sleep(Duration::from_secs(5)).await;
"slept 5 seconds using an async sleep"
}
If you hit /blocking in one terminal and then /async in another, you will notice a dramatic difference. The blocking handler calls std::thread::sleep, which blocks the entire worker thread for five seconds. If the runtime only has one worker thread, no other request can be processed during that time. If it has multiple worker threads, that one thread is unavailable, reducing total capacity.
The async handler calls tokio::time::sleep, which returns a future that completes after five seconds. The .await on that future causes the current task to yield. The worker thread is now free to poll other tasks, including tasks for incoming requests. After five seconds, the timer fires, and Tokio resumes the original task.
Async sleep is cooperative:
If you open two terminals and send curl localhost:3000/blocking and immediately curl localhost:3000/async, both responses take about five seconds - the difference is not the timing but what happens during those five seconds. The async handler's worker thread is free to serve other requests while it waits; the blocking handler's thread is stuck until the sleep finishes. With the default multi-thread runtime, a third request to a fast endpoint still answers (another worker picks it up), but every blocking handler removes one worker from the pool, so enough of them will stall the whole server.
Running Multiple Async Operations in One Handler
A handler often needs to do several independent things - call two external APIs, read two files, or query two databases. Because these are async operations, you can run them concurrently with tokio::join! or tokio::try_join!.
use axum::{routing::get, Router};
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn fetch_data_a() -> String {
sleep(Duration::from_secs(2)).await;
"data from A".to_string()
}
async fn fetch_data_b() -> String {
sleep(Duration::from_secs(3)).await;
"data from B".to_string()
}
async fn handler() -> String {
let (a, b) = tokio::join!(fetch_data_a(), fetch_data_b());
format!("{a} and {b}")
}
Both fetch_data_a and fetch_data_b run concurrently. The handler takes about 3 seconds total (the longer of the two) instead of 5 seconds if you awaited them one after another. This demonstrates that async I/O allows overlapping waits.
If you need to run many dynamic tasks, use tokio::spawn and a JoinSet:
use axum::{routing::get, Router};
use tokio::task::JoinSet;
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn handler() -> String {
let mut set = JoinSet::new();
for i in 0..10 {
set.spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(100 * i)).await;
format!("task {i} done")
});
}
let mut results = Vec::new();
while let Some(res) = set.join_next().await {
results.push(res.unwrap());
}
results.join(", ")
}
Each spawned task runs concurrently. The JoinSet collects their results as they finish. This is useful when you need to make many independent HTTP calls or database queries.
The Danger of Blocking the Async Runtime
Async I/O only works if every task cooperates by not blocking its worker thread. Blocking operations include:
std::thread::sleepstd::sync::Mutexlock when the lock is contended for a long timestd::fs::read_to_stringfor regular files (not async)- Heavy CPU computation in a tight loop
- Synchronous network calls using
std::netinside a handler
When a task performs such an operation, it blocks the worker thread running it. The thread cannot poll other tasks until the blocking call finishes. If all worker threads are blocked, the entire runtime stops making progress.
Blocking the runtime can freeze your entire server:
Suppose you have a multi-threaded runtime with 4 worker threads. If 4 requests simultaneously hit a handler that calls std::thread::sleep(Duration::from_secs(60)), all 4 threads are blocked for a minute. No other request can be processed, even if it only needs a millisecond. This is effectively a denial of service caused by your own code.
To avoid this, follow these rules:
- For async-aware operations (network, timers, some file I/O), use the Tokio equivalent (
tokio::net,tokio::fs,tokio::time). - For CPU-bound work or blocking libraries, use
tokio::task::spawn_blockingto move the work onto a separate thread pool reserved for blocking tasks. - Use
tokio::sync::Mutexinstead ofstd::sync::Mutexwhen the lock might be held across.awaitpoints. Astd::sync::MutexGuardheld across an.awaitblocks the worker thread for as long as the task is suspended, which can stall every other task on that thread;tokio::sync::Mutexyields instead of blocking.
Here is an example of moving a blocking operation into spawn_blocking:
use axum::{routing::get, Router};
use tokio::task;
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
fn expensive_calculation() -> u64 {
// Simulate CPU-bound work that should not run on the async worker threads.
std::thread::sleep(std::time::Duration::from_secs(3));
42
}
async fn handler() -> String {
let result = task::spawn_blocking(expensive_calculation)
.await
.unwrap();
format!("calculated {result}")
}
The spawn_blocking function runs the closure on a dedicated blocking thread pool (separate from the async worker threads). While the computation runs, the async worker thread is free to handle other requests. After the computation finishes, the result is sent back to the async task.
Do not use std::sync::Mutex across an await point:
If you hold a std::sync::MutexGuard and then call .await, the guard remains locked while the task is suspended, and the worker thread is blocked for that whole time. Other tasks trying to acquire the same mutex will block their worker threads, causing the same freeze problem. Use tokio::sync::Mutex if you need to lock across an await, or restructure your code to lock only for short synchronous sections.
What axum::serve Does Under the Hood
When you call axum::serve(listener, app).await, Axum passes your Router to Hyper, which is the HTTP implementation that actually handles connections. Hyper uses Tokio's async networking types - tokio::net::TcpListener and tokio::net::TcpStream - to accept connections and read/write data without blocking.
The accept loop works like this, simplified:
TcpListener::accept()returns a future that completes when a new connection arrives.- The runtime wakes the task waiting on that future.
- Hyper takes the new
TcpStreamand wraps it with an HTTP protocol implementation. - For each request, Hyper calls your Axum service (the
Router) and produces a response. - The entire pipeline - parsing the request, running your handler, serializing the response - runs as a series of async operations that can yield at any point where they wait for I/O.
Because every wait point uses .await, the worker thread is free to process other connections in the meantime.
The #[tokio::main] macro expands to something like:
fn main() {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
// your async main body here
})
}
This sets up a multi-threaded runtime, a timer system, and an I/O driver, then runs your async main function to completion.
Common Misconceptions About Async I/O
"Async is faster for everything." Async I/O shines when a server has many concurrent connections that spend most of their time waiting on I/O. It does not make CPU-bound work faster. For CPU-heavy tasks, you still need to use threads or processes, and you should offload them with spawn_blocking.
"I can use any blocking library." If a library is synchronous and performs I/O (like a database driver that uses std::net), calling it inside an async handler will block the runtime. You must either find an async version of the library or wrap the call in spawn_blocking.
"Tokio tasks are like OS threads." They are much smaller and cheaper, but they cannot do blocking I/O safely. The runtime expects tasks to yield quickly. A task that loops forever without yielding will starve other tasks on the same worker thread.
"All file I/O is non-blocking." On Linux, regular file reads and writes are not truly async at the OS level. Tokio's tokio::fs provides async wrappers that use a blocking thread pool internally. So using tokio::fs::read_to_string is still better than std::fs::read_to_string because it does not block the async worker threads, but the actual read may happen on a separate thread.
Spawning, Cancelling, and Racing Tasks
tokio::spawn returns a JoinHandle. Two facts about it surprise beginners, so learn them now rather than by debugging a leak:
- Dropping a
JoinHandledoes not cancel the task. The task keeps running, detached - its return value is simply discarded. A spawned task only stops when it finishes, when the runtime shuts down, or when you cancel it explicitly. - Only
handle.abort()cancels it, and even that is cooperative: the task is cancelled at its next.awaitpoint, when its future is dropped. Code between two.awaitpoints runs to completion, and a task that never yields cannot be stopped this way. Awaiting the handle afterabort()gives you aJoinErrorwhoseis_cancelled()is true.
async fn cancel_example() {
let handle = tokio::spawn(async {
tokio::time::sleep(std::time::Duration::from_secs(60)).await;
"done"
});
// This does NOT stop the task - it keeps running, detached.
// drop(handle);
// This does: cancel at the next `.await`, then observe the cancellation.
handle.abort();
let result = handle.await;
assert!(result.unwrap_err().is_cancelled());
}
If you need cancellation on drop, wrap the handle in tokio_util::task::AbortOnDropHandle, or keep an AbortHandle (handle.abort_handle()) that can cancel the task without owning the JoinHandle. Note the contrast with JoinSet: dropping a JoinSet does abort all of its tasks immediately. And spawn_blocking tasks are different again - abort() has no effect on one that has already started running, because blocking code has no .await point to cancel at; use a shared Arc<AtomicBool> flag for those.
For racing two futures - for example, a request against a timeout - use tokio::select!. The losing branch is dropped, which is itself a form of cancellation:
use std::time::Duration;
use tokio::time::timeout;
async fn fetch_with_timeout() -> Result<String, &'static str> {
// `timeout` is `select!` in a box: it drops the inner future on deadline.
match timeout(Duration::from_secs(2), slow_operation()).await {
Ok(value) => Ok(value),
Err(_) => Err("timed out"),
}
}
async fn slow_operation() -> String {
tokio::time::sleep(Duration::from_secs(10)).await;
"slow result".to_string()
}
// Or write the race out explicitly:
async fn race_example() -> String {
tokio::select! {
value = slow_operation() => value,
_ = tokio::time::sleep(Duration::from_secs(2)) => {
"gave up after 2 seconds".to_string()
}
}
}
Graceful shutdown uses the same idea, but do not race the bare serve future against a signal: dropping axum::serve(listener, app) mid-flight abandons in-flight connections. Instead, call .with_graceful_shutdown(signal) on the Serve future - it stops accepting new connections once the signal completes and lets in-flight requests finish.
When Async I/O Is a Core Advantage for Axum
Axum is designed for high-concurrency HTTP services. By building on Tokio, it inherits a production-grade, battle-tested async runtime. This means:
- You can handle many simultaneous connections with a fraction of the memory a thread-per-connection server would need.
- You can compose async operations naturally: call a database, call another API, read a file, and await all of them without blocking.
- You get built-in support for timeouts, graceful shutdown, and backpressure through Tokio and Hyper.
- You can share the same async runtime with other Rust services, such as Tonic (gRPC), because they all use Tokio.
A common scenario: a REST API that acts as a backend for a mobile app. Thousands of phones may be connected at once, many waiting for data. With Axum and Tokio, the server can handle all of them using a few threads and very little per-connection memory.
Runtime lock-in:
Axum is not runtime-agnostic. It works only with Tokio. The official documentation states that runtime and transport layer independence is not a goal. For most teams this is fine, because Tokio is the de facto standard for async Rust. If you must use a different runtime, Axum is not the right choice.
Summary
Async I/O via Tokio is the engine that lets Axum handle many connections without many threads. The key insight is not that async code runs faster per request, but that it can run many requests concurrently by overlapping their I/O waits.
When you write an Axum handler, you are writing a small piece of async code that Tokio schedules on a shared thread pool. The runtime waits for events, wakes up tasks that can proceed, and lets other tasks run while one task is waiting. This cooperative model is what makes Axum suitable for high-concurrency web services.
To use it correctly, you must never block the async worker threads. Use async versions of I/O operations, offload CPU-heavy work with spawn_blocking, and choose tokio::sync::Mutex when locks cross .await boundaries. If you follow those rules, your Axum server will scale gracefully to thousands of simultaneous clients.