Async work and networking.
See what a future represents, how it is driven, and why cancellation matters.
The idea behind the syntax.
An async function returns a future: a value representing work that may complete later. Calling it does not run the whole operation to completion immediately. An executor polls futures, and .await marks a point where the current task may yield while waiting. This model is useful when many tasks spend time waiting on network or other I/O, but it is not a promise that CPU-heavy work becomes faster.
Threads and async are complementary. Threads can execute work in parallel; async tasks allow a runtime to interleave work when tasks cooperate at await points. Blocking a runtime thread with a long synchronous operation can prevent unrelated tasks from progressing. A network request also has more states than success or failure: connection, timeout, partial data, cancellation, and remote closure all affect what a caller can infer.
What Rust is checking.
A future can hold references to its own state across an await. Pinning provides a stable address when a future's implementation requires it; the details matter at framework boundaries even when high-level async code hides them. Dropping a future can cancel it before completion. If it has already performed a side effect, cancellation may leave external state changed, so a retry policy needs to account for that ambiguity.
The standard library has synchronous networking primitives; common async runtimes and network libraries are ecosystem crates. Read example signatures carefully: a future's Output type describes its eventual value, often a Result, while the runtime determines when it is polled. The examples below make the distinction between defining work, driving work, and observing its result visible.
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
async, await & Future
An async function returns a future: a state machine representing work that can make progress when polled. Calling it alone does not run the body to completion. await suspends the current future while another future is pending; it does not inherently spawn a thread. An executor such as Tokio polls ready tasks, while reactor infrastructure wakes work when I/O becomes ready. Use the cookbook’s Tokio/Axum projects to run async I/O. This standard-library example deliberately creates and drops a future to make laziness visible.
async fn compute() -> u32 {
println!("body ran");
42
}
fn main() {
let work = compute();
println!("future created");
drop(work);
println!("future dropped without polling");
}future created future dropped without polling
- Calling compute constructs a future.
- No executor polls the future here, so its body does not print.
- The server cookbook uses #[tokio::main] to supply a runtime.
The boundary: Blocking std I/O inside an async task can stall an executor worker. Use async APIs or a controlled spawn_blocking boundary.
Pin, cancellation & task lifetimes
Pin constrains movement of a value that must remain at a stable memory location. Some futures need this because their state can contain references related to their own storage. Box::pin safely creates an owned pinned allocation. Dropping a future cancels that future’s remaining work, but does not roll back side effects it already performed. Dropping a Tokio JoinHandle detaches the spawned task rather than cancelling it. Build cancellation-safe boundaries with explicit task ownership, timeouts, and cleanup rather than assuming everything stops together.
use std::{future::Future, pin::Pin};
async fn answer() -> u32 {
42
}
fn hold(_: Pin<Box<dyn Future<Output = u32>>>) {}
fn main() {
let work: Pin<Box<dyn Future<Output = u32>>> = Box::pin(answer());
hold(work);
println!("pinned future created, not executed");
}pinned future created, not executed
- Box::pin provides a stable owned location.
- The trait object erases the concrete future type.
- No polling happens in hold, so the future is dropped without executing.
The boundary: Cancellation is not a transaction rollback. Consider partially written files, sent messages, and committed database changes.
TCP, HTTP & WebSockets
TCP provides an ordered byte stream, not application message boundaries. HTTP defines request and response semantics over a transport. WebSocket begins with an HTTP upgrade and then supports bidirectional framed messages over a persistent connection. A single read may contain only part of an application message, so define framing or use a protocol library. The cookbook uses Axum for HTTP and WebSocket framing rather than inventing an HTTP parser. Bind local practice servers to loopback so their audience matches the exercise.
use std::net::SocketAddr;
fn main() {
let address: SocketAddr = "127.0.0.1:3000".parse().unwrap();
println!(
"loopback={}, port={}",
address.ip().is_loopback(),
address.port()
);
let payload = "hello";
println!("payload bytes={}", payload.len());
}loopback=true, port=3000 payload bytes=5
- SocketAddr separates address and port.
- Loopback restricts access to the local machine.
- A payload length is a byte count, not a TCP packet boundary.
The boundary: Do not assume one socket read equals one message or one complete HTTP request. Use framing and bounded message sizes.
Keep this model.
A future is a state machine for eventual work, driven by an executor. Await, cancellation, and external side effects define its real behavior.