Async Rust
local graph
Chapter 19 — Async Rust
Section titled “Chapter 19 — Async Rust”Festina lente. (Make haste slowly.)
Thread-based concurrency carries inherent costs. Each thread requires a stack, typically megabytes of memory. Context switches between threads involve the operating system, adding latency measured in microseconds. For applications handling thousands of concurrent connections (web servers, chat systems, real-time data feeds) these costs compound. A server spawning a thread per connection exhausts memory before reaching capacity. The model that works for a dozen workers breaks down at network scale.
Async programming offers a different trade-off. Instead of threads that block waiting for I/O, async code uses lightweight tasks that yield control when they would block. A single thread can multiplex thousands of tasks, switching between them at suspension points. The scheduler runs in userspace, with context switches measured in nanoseconds. Memory overhead drops to kilobytes per task. What was impossible with threads becomes routine with async.
This approach originated in cooperative multitasking systems and evolved through callback-based APIs, promises, and eventually the async/await syntax now common in JavaScript, C#, Python, and Rust. Rust’s implementation adds compile-time safety guarantees while achieving zero-cost abstraction: async code compiles to state machines as efficient as hand-written equivalents.
The Async/Await model
Rust’s async system centers on the Future trait. A future represents a value that may not exist yet, a computation that will eventually complete. Unlike Java’s Future which blocks when you call get (), Rust futures are lazy. Creating an async function produces a future, but nothing happens until something drives that future to completion.
The async keyword transforms a function into one that returns a future:
async fn fetch_data(url: &str) -> Result<String, Error> { // This body executes when the future is polled let response = make_request(url).await?; parse_response(response).await}Calling this function does not run its body; the async keyword makes the call return a future. The return type Result<String, Error> describes what the future will eventually produce. The .await operator suspends execution until an inner future completes, yielding control to the executor so other tasks can progress.
What distinguishes Rust’s approach is ownership integration. The future captures its state (local variables, partial computations) in a compiler-generated state machine. Unlike closures in garbage-collected languages, Rust futures have deterministic lifetimes. When a future is dropped, its resources release immediately. The borrow checker applies to async code, preventing data races and use-after-free just as it does in synchronous code.
A synchronous function blocks its thread while waiting:
fn sync_fetch(url: &str) -> Result<String, Error> { let response = blocking_request(url); // Thread waits here parse(response)}An async function suspends without blocking:
async fn async_fetch(url: &str) -> Result<String, Error> { let response = non_blocking_request(url).await; // Task yields here parse(response)}The synchronous version ties up its thread during the network request. The async version releases its thread at the .await point, allowing other tasks to run. When the response arrives, the executor resumes the task. The programming model looks sequential but executes concurrently.
Futures and executors
Section titled “Futures and executors”The Future trait defines how async computation works:
pub trait Future { type Output; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;}
pub enum Poll<T> { Ready(T), Pending,}When polled, a future either returns Ready(value) indicating completion, or Pending indicating more work remains. The Context provides a Waker that the future uses to signal when it should be polled again. The Pin ensures self-referential futures (common in async code) cannot be moved in memory, preventing dangling pointers.
This design enables efficient execution. An executor polls a future, which returns Pending and registers a waker with the underlying I/O system. The executor moves to other tasks. When data arrives, the I/O system invokes the waker. The executor schedules the future for another poll, which now returns Ready with the result. No thread blocks waiting; the executor always has work to do or sleeps waiting for wakeups.
The following diagram shows how an executor coordinates multiple tasks:
graph TD
subgraph EX["Executor"]
Q["Task Queue"] --> SC["Scheduler"]
end
subgraph AT["Active Tasks"]
T1["Task 1<br/>(reading file)"]
T2["Task 2<br/>(network request)"]
T3["Task 3<br/>(timer)"]
end
subgraph IO["I/O Subsystem"]
R["Event Loop /<br/>Reactor"]
end
SC -- poll --> T1
SC -- poll --> T2
SC -- poll --> T3
T1 -- "Pending +<br/>waker" --> R
T2 -- "Pending +<br/>waker" --> R
T3 -- "Pending +<br/>waker" --> R
R -- wake --> Q
[!visual-conversion] Executor polling tasks and reactor handling wakeups. Print diagram (PDF 502, printed p. 494) recreated in Mermaid; frames, nodes and edge labels verbatim.
Rust’s standard library provides the Future trait but no executor. Executors are runtime components, and Rust deliberately avoids mandating one. This separation allows different executors optimized for different scenarios: lightweight executors for embedded systems, work-stealing executors for CPU-bound parallelism, or full-featured async runtimes for network servers. The most prominent is Tokio.
Tokio essentials
Tokio provides a complete async runtime for Rust. It includes a multi-threaded executor, asynchronous I/O primitives, timers, synchronization tools, and utilities for building networked applications. When developers speak of “async Rust” in production contexts, they typically mean Tokio.
A minimal Tokio application:
use tokio;
#[tokio::main]async fn main() { println!("Starting async application"); let result = fetch_something().await; println!("Got: {}", result);}
async fn fetch_something() -> String { tokio::time::sleep(std::time::Duration::from_secs(1)).await; "data".to_string()}The #[tokio::main] macro transforms main into a synchronous
function that initializes the Tokio runtime and blocks on the async
body. Without this macro, you would initialize the runtime manually:
fn main() { let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async { println!("Running async code"); });}Spawning tasks creates concurrent execution within the runtime:
#[tokio::main]async fn main() { let handle1 = tokio::spawn(async { tokio::time::sleep(Duration::from_millis(100)).await; "first" });
let handle2 = tokio::spawn(async { tokio::time::sleep(Duration::from_millis(50)).await; "second" });
let (r1, r2) = tokio::join!(handle1, handle2); println!("Results: {:?}, {:?}", r1, r2);}tokio::spawn creates a new task that runs concurrently. Unlike thread spawning, this is cheap (microseconds, not milliseconds). The join! macro awaits multiple futures concurrently, completing when all finish. Both tasks run on the Tokio thread pool, and their execution interleaves at await points.
For I/O operations, Tokio provides async versions of standard library types:
use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::TcpStream;
async fn send_message(addr: &str, message: &[u8]) -> std::io::Result<Vec<u8>> { let mut stream = TcpStream::connect(addr).await?; stream.write_all(message).await?;
let mut buffer = vec![0u8; 1024]; let n = stream.read(&mut buffer).await?; buffer.truncate(n); Ok(buffer)}The API mirrors the synchronous standard library. TcpStream::connect returns a future that resolves to a connected stream. Read and write operations are async, yielding control while waiting for I/O completion. The code reads sequentially but executes without blocking threads.
Tokio’s channel implementations provide async-aware message passing:
use tokio::sync::mpsc;
#[tokio::main]async fn main() { let (tx, mut rx) = mpsc::channel(32);
tokio::spawn(async move { for i in 0..10 { tx.send(i).await.unwrap(); } });
while let Some(value) = rx.recv().await { println!("Received: {}", value); }}Unlike std::sync::mpsc, these channels suspend tasks when empty or full rather than blocking threads. The producer and consumer can run on the same thread without deadlocking because suspension releases the thread for other work.
Async traits
A recurring challenge in async Rust involves traits with async methods. The straightforward approach does not compile:
trait DataStore { async fn get(&self, key: &str) -> Option<String>; // Error}The issue is technical: async functions return anonymous future types, and trait methods must have known return types. The language team is addressing this, but until full support arrives (it is stabilizing gradually), workarounds exist.
The async-trait crate provides the most common solution:
use async_trait::async_trait;
#[async_trait]trait DataStore { async fn get(&self, key: &str) -> Option<String>; async fn set(&self, key: &str, value: String) -> Result<(), Error>;}
#[async_trait]impl DataStore for PostgresStore { async fn get(&self, key: &str) -> Option<String> { self.pool.query_one(key).await.ok() }
async fn set(&self, key: &str, value: String) -> Result<(), Error> { self.pool.execute(key, value).await }}The macro transforms async methods into methods returning
Pin<Box<dyn Future>>. This involves heap allocation and
dynamic dispatch, costs that matter in tight loops but are negligible for
I/O-bound operations where network latency dominates.
As of Rust 1.75, native async trait methods work in some contexts without the crate:
trait DataStore { fn get(&self, key: &str) -> impl Future<Output = Option<String>> + Send;}This approach avoids heap allocation but has limitations with complex lifetime relationships. The async-trait crate remains valuable for complex trait hierarchies and when broad ecosystem compatibility matters.
For performance-critical code, manual future types avoid the boxing overhead:
trait DataStore { type GetFuture<'a>: Future<Output = Option<String>> + Send + 'a where Self: 'a;
fn get(&self, key: &str) -> Self::GetFuture<'_>;}This generic associated type (GAT) approach requires more boilerplate but produces optimal code. I find async-trait sufficient for most applications, reserving manual approaches for frameworks and libraries where allocation counts.
Bridging sync and async code
Real applications mix synchronous and asynchronous code. Legacy libraries, CPU-intensive computations, and blocking system calls do not magically become async. Bridging these worlds requires care to avoid blocking the async executor.
Running async code from synchronous contexts uses block_on:
fn synchronous_function() -> String { let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(async { fetch_data().await })}This creates a runtime, runs the async block to completion, and returns the result synchronously. Creating a runtime is expensive; for repeated calls, reuse a runtime or use Handle::current() if already inside one:
fn sync_wrapper() -> String { let handle = tokio::runtime::Handle::current(); handle.block_on(async { fetch_data().await })}Running synchronous code from async contexts requires preventing thread blocking. tokio::task::spawn_blocking moves work to a dedicated thread pool:
async fn process_data(data: Vec<u8>) -> ProcessedData { let result = tokio::task::spawn_blocking(move || { // CPU-intensive or blocking work expensive_computation(&data) }).await.unwrap();
result}The blocking work runs on a separate thread pool sized for CPU-bound operations. The async task suspends until the blocking work completes. This pattern keeps the async executor responsive while accommodating code that cannot yield.
For file I/O, which blocks at the OS level, Tokio provides async file operations through tokio::fs:
use tokio::fs;
async fn read_config() -> std::io::Result<String> { fs::read_to_string("config.toml").await}Internally, this uses spawn_blocking because file I/O cannot be made truly asynchronous on most operating systems. The async interface maintains consistency with other Tokio APIs.
A common mistake is calling blocking code directly in async contexts:
async fn bad_example() { std::thread::sleep(Duration::from_secs(5)); // Blocks the executor thread let content = std::fs::read_to_string("file.txt").unwrap(); // Also blocks}These calls block the executor thread, preventing other tasks from running. During that five-second sleep, no other tasks on that thread can progress. In a single-threaded runtime, the entire application stalls. Use async equivalents (tokio::time::sleep, tokio::fs::read_to_string) or spawn_blocking for code that must block.
Complete example: async web scraper
The following example combines async concepts into a practical application that fetches multiple URLs concurrently:
use std::time::Duration;use tokio::time::timeout;
#[derive(Debug)]struct FetchResult { url: String, status: FetchStatus,}
#[derive(Debug)]enum FetchStatus { Success { size: usize, elapsed: Duration }, Timeout, Error(String),}
async fn fetch_url(client: &reqwest::Client, url: String) -> FetchResult { let start = std::time::Instant::now();
let result = timeout( Duration::from_secs(10), client.get(&url).send() ).await;
let status = match result { Ok(Ok(response)) => { match response.text().await { Ok(text) => FetchStatus::Success { size: text.len(), elapsed: start.elapsed(), }, Err(e) => FetchStatus::Error(e.to_string()), } } Ok(Err(e)) => FetchStatus::Error(e.to_string()), Err(_) => FetchStatus::Timeout, };
FetchResult { url, status }}
async fn scrape_urls(urls: Vec<String>) -> Vec<FetchResult> { let client = reqwest::Client::new(); let mut handles = Vec::new();
for url in urls { let client = client.clone(); handles.push(tokio::spawn(async move { fetch_url(&client, url).await })); } let mut results = Vec::new(); for handle in handles { if let Ok(result) = handle.await { results.push(result); } }
results}
#[tokio::main]async fn main() { let urls = vec![ "https://www.rust-lang.org".to_string(), "https://tokio.rs".to_string(), "https://docs.rs".to_string(), ];
println!("Fetching {} URLs concurrently...", urls.len()); let start = std::time::Instant::now();
let results = scrape_urls(urls).await;
for result in &results { match &result.status { FetchStatus::Success { size, elapsed } => { println!( "{}: {} bytes in {:?}", result.url, size, elapsed ); } FetchStatus::Timeout => { println!("{}: timed out", result.url); } FetchStatus::Error(e) => { println!("{}: error - {}", result.url, e); } } } println!( "Total time: {:?} (sequential would be ~{:?})", start.elapsed(), results.iter() .filter_map(|r| match &r.status { FetchStatus::Success { elapsed, .. } => Some(*elapsed), _ => None, }) .sum::<Duration>() );}The scraper spawns a task for each URL. All requests execute concurrently, bounded by connection limits rather than thread count. Timeouts prevent slow servers from blocking progress. The total time approximates the slowest request rather than the sum of all requests.
This pattern scales to thousands of URLs. The memory overhead per task is minimal. The executor efficiently multiplexes tasks across a small thread pool. What would require thread pools, careful resource management, and complex coordination in synchronous code becomes straightforward with async.
Async Essentials
Section titled “Async Essentials”Async programming enables high-concurrency applications through lightweight tasks that yield at suspension points rather than blocking threads. Rust’s implementation integrates with the ownership system, providing compile-time safety for async code.
Futures represent values that will exist later. The async keyword creates functions that return futures. The .await operator suspends execution, yielding control to the executor until the awaited future completes.
Tokio provides the most widely used async runtime. It offers multi-threaded execution, async I/O primitives, timers, and channels designed for async contexts. The #[tokio::main] macro sets up the runtime for async main functions.
Async traits require workarounds due to language limitations being addressed. The async-trait crate provides the most convenient solution through boxing, while manual approaches using generic associated types achieve zero overhead.
Bridging sync and async code requires care. block_on runs async code from synchronous contexts. spawn_blocking runs blocking code from async contexts without stalling the executor. Calling blocking functions directly in async code prevents other tasks from running.
The next chapter examines cancellation and graceful shutdown, challenges that become more complex in async systems where tasks can be cancelled at any await point.