Blocking vs Non-Blocking I/O
Understand the difference between blocking and non-blocking I/O, why it matters for backend services, and how Rust's async ecosystem solves the scalability problem without threads blocking each other.
Blocking vs Non-Blocking I/O
When a computer program needs to talk to the outside world - reading a file, sending a network request, querying a database - it performs what programmers call I/O (Input/Output). I/O is any operation where the program waits for data to come in or go out. The way a program waits for that I/O to finish determines whether it is blocking or non-blocking. These two styles form the foundation of how modern web servers handle thousands of connections at once.
Before we dive into the details, we need to understand a simple fact: I/O is slow compared to CPU work. Reading one byte from a hard drive or receiving a packet over the internet might take milliseconds, while the CPU can execute millions of instructions in that same time. If a program stops everything just to wait for one slow I/O operation, most of its power goes to waste.
What Blocking I/O Actually Means
Blocking I/O is the default and simplest way to handle I/O in most programming languages. When your program calls a blocking function - for example, read_from_file() - the program blocks there. It pauses completely at that line of code, doing nothing else, until the read operation finishes and returns the data.
Think of blocking I/O like standing in line at a bank. You walk up to the teller, ask for something, and then stand there doing nothing while the teller processes your request. You cannot check your phone, write a note, or help the next person. You are blocked until the teller finishes.
In code, a blocking operation looks like this:
use std::fs;
fn main() {
println!("Starting to read file...");
let contents = fs::read_to_string("data.txt").unwrap(); // blocks here
println!("File contents: {}", contents);
println!("This runs only after the file is fully read.");
}
When this program runs, the line with fs::read_to_string causes the entire program to stop. The CPU is idle while the operating system fetches the file from disk. Only after the file is completely read does the program print the contents and continue to the next line. This is fine for a small script that does one thing, but it becomes a serious problem for a server that must handle many clients at the same time.
Imagine a web server built with blocking I/O. Each incoming connection is handled by reading the request (blocking), processing it, and sending a response (blocking). If one client has a slow internet connection, the server might block for several seconds while trying to read that client's request. During that time, the server is stuck and cannot accept new connections - unless you start a separate thread for each connection.
A Blocking Server Example (Thread Per Connection)
Here is a simplified version of a blocking TCP server in Rust. It accepts a connection, reads some bytes, and echoes them back. Notice that every operation blocks the current thread.
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
fn handle_client(mut stream: TcpStream) {
let mut buffer = [0; 1024];
loop {
// This read blocks until data arrives from the client
match stream.read(&mut buffer) {
Ok(0) => break, // client closed connection
Ok(n) => {
// This write can also block if the client is slow to receive
stream.write_all(&buffer[0..n]).unwrap();
}
Err(e) => {
eprintln!("Error: {}", e);
break;
}
}
}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
println!("Server listening on 8080");
for incoming in listener.incoming() {
match incoming {
Ok(stream) => {
// Spawn a new thread for each client
thread::spawn(|| {
handle_client(stream);
});
}
Err(e) => eprintln!("Connection failed: {}", e),
}
}
}
This works, but it has a hidden cost. Each thread consumes memory and operating system resources. If you have 10,000 clients, you have 10,000 threads. Most of those threads will spend almost all their time blocked, waiting for I/O, while still taking up memory and causing the OS to spend time switching between them. The server becomes slow and may run out of memory.
Threads Do Not Solve the Scalability Problem:
Using one thread per connection works for a handful of clients, but it does not scale to thousands or tens of thousands. Each blocked thread still reserves a full OS thread, which means high memory usage and expensive context switching. The core problem remains: the server is blocked waiting for I/O even if you spawn many threads.
What Non-Blocking I/O Changes
Non-blocking I/O flips the model. Instead of calling a function and waiting for it to finish, you start the I/O operation and immediately get back a handle - a future in Rust - that represents the work that is still in progress. Your program can continue doing other things while the I/O happens in the background. Later, when the I/O completes, the future resolves with the result.
A useful mental model is ordering coffee at a busy café. In a blocking model, you walk up to the counter, order, and stand there staring at the barista until your coffee is ready. You cannot do anything else. In a non-blocking model, you order, get a buzzer, and go sit down. You can read a book, talk to a friend, or do other work. When your coffee is ready, the buzzer vibrates, and you go pick it up. The barista was able to serve many other customers while your coffee was being made.
In Rust, the async/await syntax makes writing non-blocking code look almost like blocking code, but underneath it works completely differently. The key is that awaiting a future yields control back to the async runtime instead of blocking the thread. The runtime can then run other tasks on the same thread.
How Futures and Async/Await Work
A future is a value that represents an operation that hasn't finished yet. In Rust, a type that implements the Future trait can be polled to check if it is ready. But you rarely poll futures manually; you use async functions and the .await keyword.
Here is a small async function that reads a file without blocking the entire program:
use tokio::fs;
async fn read_file_async() -> String {
// This call returns a future, but the await does not block the thread.
// Instead, the runtime suspends this task and runs other tasks.
let contents = fs::read_to_string("data.txt").await.unwrap();
contents
}
This function is not executed directly like a normal function. It returns a future that must be driven by an async runtime - like Tokio. When you call .await on fs::read_to_string, the runtime pauses this task, registers interest in the file operation, and immediately switches to running another task. When the file read completes, the runtime wakes this task up and continues from where it left off.
That is the core of non-blocking I/O in Rust: the thread never blocks. It is always either doing useful CPU work or switching to another task that can make progress.
Async Runtime Does the Heavy Lifting:
The magic that makes non-blocking I/O possible is an async runtime. It manages all the pending I/O operations, watches for them to complete, and schedules tasks to run when they are ready. Tokio is the most popular async runtime in the Rust ecosystem. You will learn about it in detail later, but for now, understand that async/await alone does not do anything - you need a runtime to execute futures.
A Non-Blocking Async Server Example
Now let's rewrite the earlier echo server using Tokio's non-blocking primitives. This version handles thousands of connections without spawning a thread per connection.
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
async fn handle_client(mut stream: TcpStream) {
let mut buffer = [0; 1024];
loop {
// This read does not block the thread. It yields control to the runtime.
match stream.read(&mut buffer).await {
Ok(0) => break,
Ok(n) => {
if let Err(e) = stream.write_all(&buffer[0..n]).await {
eprintln!("Write error: {}", e);
break;
}
}
Err(e) => {
eprintln!("Read error: {}", e);
break;
}
}
}
}
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();
println!("Server listening on 8080");
loop {
match listener.accept().await {
Ok((stream, _addr)) => {
// Spawn a lightweight async task, not an OS thread
tokio::spawn(async move {
handle_client(stream).await;
});
}
Err(e) => eprintln!("Accept error: {}", e),
}
}
}
The structure looks almost identical, but there are two crucial differences. First, every I/O call is awaited with .await, so the function yields control when it cannot make progress. Second, each client is handled by a task (spawned with tokio::spawn) rather than a separate OS thread. Tasks are extremely lightweight - they are just pieces of code that the runtime schedules on a small number of worker threads. Thousands of tasks can run concurrently on just a few threads because each task only uses the thread briefly before pausing at an .await point and letting another task run.
You Have Reached the Core Insight:
If you understand why the async version scales better than the thread-per-connection version, you understand the entire motivation for async programming. The thread never blocks; it always finds some task that can make progress. That is how a single process can serve tens of thousands of concurrent connections with only a handful of threads.
Blocking vs Non-Blocking: Side-by-Side Comparison
To make the contrast clear, let's compare the two approaches in a table-like mental picture.
| Feature | Blocking I/O | Non-Blocking I/O |
|---|---|---|
| How it waits | Stops the thread until the operation finishes | Returns a future, thread is free to do other work |
| Concurrency model | One OS thread per connection (or serial processing) | Many tasks multiplexed on few threads |
| Resource usage | High memory per thread, heavy context switching | Low memory per task, efficient scheduling |
| Code complexity | Simple, straightforward | Slightly more complex due to async/await, but manageable |
| Typical use case | CPU-bound tasks, short scripts, simple CLI tools | Network servers, high-concurrency backend services |
| Rust ecosystem | Standard library (std::net, std::fs) | Tokio, async-std, smol, etc. |
Blocking I/O is not bad. It is perfectly fine for many situations. A command-line tool that reads a config file and exits is better off using blocking I/O because there is no concurrency to manage and the simplicity is a benefit. But a web server that must handle thousands of simultaneous clients absolutely needs non-blocking I/O.
What Happens When You Mix Them Up
The most common mistake beginners make is calling a blocking function inside an async task. This can silently destroy the performance of your entire server. Here is an example:
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
// This is a blocking sleep from std::thread. It blocks the current OS thread.
std::thread::sleep(std::time::Duration::from_secs(5));
println!("Task finished");
});
handle.await.unwrap();
}
This code compiles and runs, but inside the async task, std::thread::sleep blocks the thread that the Tokio runtime is using. While that thread is blocked, no other task can run on it. If the runtime has only a few worker threads, one blocked task can stall the entire server.
Never Block the Async Executor:
Calling std::thread::sleep, std::fs::read_to_string, or any other blocking function inside an async task blocks the underlying OS thread. That thread cannot be used by the async runtime to run other tasks. If you need to perform a blocking operation from async code, use tokio::task::spawn_blocking to offload it to a separate thread pool that is designed for blocking work.
The correct way to wait in an async task is to use a non-blocking equivalent, such as tokio::time::sleep:
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
// This sleep does not block the thread. It yields to the runtime.
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
println!("Task finished");
});
handle.await.unwrap();
}
This version allows other tasks to run during those five seconds.
A close cousin of this mistake is a long CPU-bound loop inside an async task - for example, crunching a large dataset with no .await points anywhere in it. The runtime cannot interrupt a task that never yields, so one busy handler can starve every other task on that worker thread, even though nothing is "blocking" in the I/O sense. The fix is the same: move the heavy computation to tokio::task::spawn_blocking, or break the work into chunks with an .await point between them. If a task has no .await, the runtime has no chance to schedule anything else on that thread.
Why Rust Chose the Async Model
Rust does not have a built-in runtime for non-blocking I/O in the standard library. Instead, the language provides the async/await syntax and the Future trait, while external crates like Tokio provide the actual runtime and non-blocking I/O primitives. This design keeps the standard library small and portable while allowing different runtimes to compete and specialize.
For backend services, Tokio is the de facto standard. Axum is built directly on Tokio, which means every handler in Axum is an async function and every I/O operation inside a handler should be non-blocking. Understanding blocking vs non-blocking I/O is therefore essential before you start writing Axum applications.
A Practical Exercise to Test Your Understanding
Imagine you are building a REST API endpoint that must:
- Parse a JSON request body.
- Query a database for user information.
- Call an external weather API.
- Return the combined result.
If you write this endpoint using blocking libraries (like the synchronous rusqlite for database and reqwest::blocking for HTTP), each step blocks the current thread. Under load, the server becomes unresponsive because all threads are stuck waiting for I/O. If you instead use async libraries (sqlx for database, reqwest for HTTP), each .await point yields control, allowing the runtime to process other requests while waiting.
The choice of blocking vs non-blocking is not just theoretical - it determines whether your server handles a handful of requests at a time or thousands of them at once.
Summary
The difference between blocking and non-blocking I/O boils down to what happens while an I/O operation is in progress. Blocking I/O stops the thread, wasting CPU cycles and limiting concurrency. Non-blocking I/O lets the thread switch to another task, maximizing utilization and allowing many tasks to share a few threads. Rust's async/await syntax makes non-blocking code almost as readable as blocking code, but it requires an async runtime like Tokio to actually run.
The most important takeaway: in an async context, never call a blocking function. If you need to run blocking code, use spawn_blocking. This single rule will save you from countless performance bugs as you start building async web services with Axum. With this foundation, you are ready to understand what an async runtime is and why Tokio is the heart of the Rust async ecosystem.