The idea in one sentence. A Rust future is a lazy state machine that runs only when a runtime polls it and gives its thread back only at an .await; tokio polls such tasks on a few worker threads, axum makes every request one of them, and the whole service or command-line tool ships as one compiled file.
Fig. 1 is tokio's multi-thread runtime as its documentation describes it (the "Multi threaded runtime" section of the tokio runtime docs), the runtime under this page's service, tokserve. The queue contents are illustrative; the numbers are this page's recorded runs (an Apple M1 Pro, 2026-10-05).
tokserve takes --workers). The runtime "maintains one global queue, and a local queue for each worker thread"; a local queue "can fit at most 256 tasks". Each block on a tray is a task: a future handed to the runtime..await..await on a socket or a timer the poll returns Pending; the task leaves the worker and waits with the I/O driver and the timers, which hold its waker. The worker polls its next task at once: nothing is blocked.net feature is built on mio, an "I/O event queue backed by epoll, kqueue, and IOCP" (mio; what epoll does is the OS Concurrency page). The waker puts the task back on a run queue, not always its old worker's: in this page's 4-worker run, task A started on thread 3 and resumed on thread 5 at 103.8 ms, because thread 3 was stuck (Fig. 2, last mode)..await (counting a large log, std::thread::sleep) keeps its worker until it ends; nothing preempts it, and the tasks queued behind it wait unless another worker steals them. With both of tokserve's 2 workers counting, /health p50 went from 0.44 ms to 10.7 ms (Experiment B, measured).spawn_blocking runs the closure on the blocking pool (separate threads, 512 at most by default) while the task awaits it, so the worker goes back to polling. Because a task can move between workers at any .await, tokio::spawn demands Send + 'static.You need Rust: the essentials (ownership, borrowing, Cargo). Result and ? are on Rust: enums, traits, errors and iterators; Arc, Send and Sync on Rust: lifetimes, smart pointers, threads and unsafe. If you know Python's asyncio (Python: concurrency, asyncio and the GIL), this page only says what differs.
tokio::spawn; may run on any worker threadspawn_blockingCargo.toml (release, size, LTO)Everything here is built from the root page's running program (count tokens per user in a JSONL chat log, Rosetta tab): one crate with the logic in src/lib.rs and two binaries, the CLI tokcount and the axum service tokserve. Every output is a real recording on an Apple M1 Pro (rustc 1.99.0, tokio 1.53.2, axum 0.8.9, clap 4.6.7), reproduced by src/rs/run_all.sh.
| You want | Python | Rust | What changes for you |
|---|---|---|---|
| Concurrency for I/O | asyncio | tokio | Futures do nothing until polled; a runtime with several threads; tasks must be Send. |
| An HTTP API | FastAPI on uvicorn | axum on tokio (hyper underneath) | Handlers are async functions; extractors play the role of FastAPI's typed parameters. |
| Middleware | ASGI middleware | tower / tower-http layers | Timeouts, body limits, tracing as reusable layers. |
| Logs and spans | logging, OpenTelemetry | tracing + tracing-subscriber | Structured fields and spans per request. |
| JSON in and out | json, pydantic | serde + serde_json | The struct is the schema; parsing checks types like pydantic does. |
| Parse arguments, subcommands, help | argparse, typer, click | clap (derive a struct) | Bad arguments are rejected before your code runs; usage errors exit 2. |
| Errors with context in an app | exceptions, tracebacks | anyhow (apps), thiserror (libraries) | Errors are values; ? passes them up, .context() adds the "while doing X". |
| Ship it | a wheel, a venv, a 47 MB (compressed) python:3.14-slim base image | one binary (cargo install, or a static Linux build in an empty image) | No interpreter to install; the image can be the binary plus nothing. |
measured on the laptop in normal use (load average 7 to 13 on 10 cores); medians of three short runs, spread in the measured section.
Three ideas to keep. (1) A Rust tool or service is one compiled file: that is most of why people write them. (2) Async Rust is lazy and cooperative: CPU work between awaits blocks every other request on that thread (measured below: /health p50 went from 0.44 ms to 10.7 ms). (3) The type system follows you into concurrency: tokio::spawn demands Send + 'static, so data races and dangling borrows across tasks are compile errors, not incidents.
Rust's standard library deliberately has no HTTP, no async runtime and no argument parser; the ecosystem settled on a small set of de facto standards instead. This project uses ten dependencies:
[package] name = "tok" version = "0.1.0" edition = "2024" description = "Part 3 of the Rust page: the root's token counter as a CLI (tokcount) and an HTTP service (tokserve)" publish = false [dependencies] anyhow = "1" axum = "0.8" clap = { version = "4", features = ["derive", "env"] } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" tokio = { version = "1", features = ["full"] } tower-http = { version = "0.6", features = ["trace", "timeout", "limit"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } [dev-dependencies] http-body-util = "0.1" tower = { version = "0.5", features = ["util"] }
features = [...] switches on optional parts of a crate at compile time (clap's derive macros, tokio's full runtime); fewer features means a faster build and a smaller binary. Cargo.lock pins every transitive version, like uv.lock. Cargo builds every file in src/bin/ as its own executable, and both link the same library: one implementation, two front ends, the shape of a Python package with two [project.scripts] entry points, except each compiles to a self-contained executable.
Versions resolved on 2026-10-05: tokio 1.53.2, axum 0.8.9, clap 4.6.7, serde 1.0.229, tracing 0.1.44, tower-http 0.6.11 (0.7.1 exists; this project pins 0.6). The async-std runtime you may meet in old tutorials is discontinued; its README says "use smol instead" (async-std).
A service spends most of its time waiting (network, database, model API). One OS thread per waiting request works up to a few thousand requests, then stack memory and thread switches dominate. Async lets one thread juggle many waiting operations: each runs until it would wait, hands the thread back, and is resumed when its data arrives. That is asyncio's idea too; Rust differs in three ways, each shown with a real run: futures are lazy, the runtime is a library you choose (usually on several threads), and cancellation is dropping.
An async fn does not run when you call it. It returns a future that runs only when something polls it, normally .await. The program builds hello("a") and awaits it, and builds hello("b") and drops it:
// A future is a value: calling an async fn runs nothing until something awaits (polls) it. async fn hello(tag: &str) -> u32 { println!(" {tag}: body runs"); 42 } #[tokio::main(flavor = "current_thread")] async fn main() { println!("1. calling hello(\"a\")"); let fut = hello("a"); // nothing printed: we only built a state machine println!("2. holding a future of {} bytes; its body has not run", std::mem::size_of_val(&fut)); let v = fut.await; // now the runtime polls it to completion println!("3. awaited it: {v}"); hello("b"); // never awaited: the compiler warns and the body never runs println!("4. end of main"); }
1. calling hello("a")
2. holding a future of 24 bytes; its body has not run
a: body runs
3. awaited it: 42
4. end of mainThe future for hello("a") is a 24-byte struct (the compiler turns the body into a state machine holding its locals), and nothing ran until .await. hello("b") never ran; the compiler warns about exactly that:
warning: unused implementer of `Future` that must be used
--> examples/a1_lazy.rs:14:5
|
14 | hello("b"); // never awaited: the compiler warns and the body never runs
| ^^^^^^^^^^
|
= note: futures do nothing unless you `.await` or poll them
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
Python behaves the same way (a coroutine object plus a "never awaited" RuntimeWarning, on the Python concurrency page). JavaScript does not: an async function runs its body at once, up to its first await (JavaScript: the event loop, promises and streams).
Every future implements one method, poll. The runtime calls it; it returns Poll::Ready(value) if done, or Poll::Pending after arranging for a waker to be called when it can make progress (a socket becomes readable, a timer fires). The runtime polls something else meanwhile and polls this future again only after its waker fires. A hand-written future that is ready on its third poll:
awaiting Countdown { left: 2 }
poll: Pending (2 left), asking to be woken
poll: Pending (1 left), asking to be woken
poll: Ready
result: done
// What .await does underneath: the runtime calls poll() until it returns Ready. // A hand-written future that is not ready the first two times it is polled. use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; struct Countdown { left: u32, } impl Future for Countdown { type Output = &'static str; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { if self.left == 0 { println!(" poll: Ready"); return Poll::Ready("done"); } println!(" poll: Pending ({} left), asking to be woken", self.left); self.left -= 1; // A real future (a socket, a timer) hands the waker to the OS event source. // Here we wake ourselves at once, so the runtime polls again. cx.waker().wake_by_ref(); Poll::Pending } } #[tokio::main(flavor = "current_thread")] async fn main() { println!("awaiting Countdown {{ left: 2 }}"); let r = Countdown { left: 2 }.await; println!("result: {r}"); }
Pin. The generated state machine can hold a reference to one of its own locals across an await (a buffer and a slice of it). If the future were moved in memory, that reference would dangle. poll therefore takes Pin<&mut Self>: a pointer that promises the future will not move again once polled. .await, tokio::spawn and Box::pin handle it for you; you meet Pin when storing futures in structs or writing poll by hand (std::pin docs).
You will almost never write poll; async fn generates it, with one state per .await point. Two consequences matter every day: code between two awaits runs without interruption (no other task runs on that thread meanwhile), and a future that is never polled again simply stops at its last await.
The standard library defines the Future trait but no runtime (the executor that polls futures, plus timers and non-blocking sockets). You add one; tokio is the de facto standard, and axum, reqwest and tonic are built on it. Forgetting it is the first error everyone meets:
async fn main() with no runtime attribute: compiles?
error[E0752]: `main` function is not allowed to be `async`
--> src/main.rs:2:1
|
2 | async fn main() {
| ^^^^^^^^^^^^^^^ `main` function is not allowed to be `async`
For more information about this error, try `rustc --explain E0752`.
error: could not compile `errs` (bin "errs") due to 1 previous error#[tokio::main] rewrites main into "build a runtime, then block_on the body". tokserve.rs spells that out so the number of threads is a flag:
// What #[tokio::main] writes for you, spelled out so the worker count is configurable. let mut rt = tokio::runtime::Builder::new_multi_thread(); if let Some(n) = args.workers { rt.worker_threads(n); } rt.enable_all().build()?.block_on(serve(args))
#[tokio::main(flavor = "current_thread")]. Used by the examples here so traces are easy to read.spawn_blocking; up to 512 by default.tokio::join!(a, b, c) polls several futures inside the current task: concurrency without new tasks. tokio::spawn(fut) hands a future to the runtime as an independent task (Python's create_task) that may run on any worker thread, in parallel with others, and returns a JoinHandle. A JoinSet owns a group of tasks (like asyncio.TaskGroup) and aborts them all if dropped. Twenty calls to a local server that answers after 100 ms (this page's own service, standing in for a model API):
sequential, 20 calls 2.058 s JoinSet, 20 at once 0.107 s "slept 100 ms" JoinSet, at most 5 0.415 s timeout after 0.253 s Elapsed
let t = Instant::now(); for _ in 0..20 { get(addr, "/slow?ms=100".into()).await; // one after another } println!("sequential, 20 calls {:6.3} s", t.elapsed().as_secs_f64()); let t = Instant::now(); let mut set = JoinSet::new(); // like asyncio.TaskGroup: owns its tasks, aborts them when dropped for _ in 0..20 { set.spawn(get(addr, "/slow?ms=100".into())); } let bodies = set.join_all().await; println!("JoinSet, 20 at once {:6.3} s {:?}", t.elapsed().as_secs_f64(), bodies[0]); let t = Instant::now(); let limit = Arc::new(Semaphore::new(5)); // at most 5 in flight let mut set = JoinSet::new(); for _ in 0..20 { let limit = limit.clone(); set.spawn(async move { let _permit = limit.acquire().await.unwrap(); // released when dropped get(addr, "/slow?ms=100".into()).await }); } set.join_all().await; println!("JoinSet, at most 5 {:6.3} s", t.elapsed().as_secs_f64()); let t = Instant::now(); let r = tokio::time::timeout(Duration::from_millis(250), get(addr, "/slow?ms=2000".into())).await; println!("timeout after {:6.3} s {}", t.elapsed().as_secs_f64(), if r.is_err() { "Elapsed" } else { "ok" });
20 sequential calls cost 20 × 100 ms; concurrent ones cost one round trip; a semaphore with 5 permits gives 4 waves of 100 ms, the polite way to call a rate-limited model API. asyncio gives the same numbers on the same machine (the Python page's fan-out): for waiting, the language does not matter, the overlap does. Rust differs where work is done between the waits: a multi-threaded runtime uses all cores, which one asyncio loop cannot.
Each row's total is measured (examples/a4_fanout.rs: 2.058 s, 0.107 s and 0.415 s); each thin bar is one call, drawn as an equal share of its row's time (derived, not timed one by one).
Cancelling a future in Rust means dropping it: it is never polled again, so the code after its pending .await never runs, and its locals are dropped (their Drop code runs). timeout and select! are both built on that. Four cases, with a guard that prints when it is dropped:
/// Prints when it is dropped, to show exactly when a future is cancelled. struct Guard(&'static str); impl Drop for Guard { fn drop(&mut self) { println!(" drop: {} cleaned up", self.0); } } async fn step(name: &'static str, ms: u64) -> &'static str { let _g = Guard(name); println!(" {name}: started, waiting {ms} ms"); sleep(Duration::from_millis(ms)).await; println!(" {name}: finished"); // never printed if the future is dropped first name } #[tokio::main(flavor = "current_thread")] async fn main() { let t = Instant::now(); println!("1. timeout(250 ms) around a 2000 ms call"); let r = timeout(Duration::from_millis(250), step("slow", 2000)).await; println!(" -> {r:?} after {} ms", t.elapsed().as_millis()); println!("2. select!: first to finish wins, the other is dropped"); let t = Instant::now(); tokio::select! { w = step("fast", 100) => println!(" -> winner {w} after {} ms", t.elapsed().as_millis()), w = step("lazy", 300) => println!(" -> winner {w}"), } println!("3. a spawned task keeps running on its own; abort() cancels it"); let h = tokio::spawn(step("background", 1000)); sleep(Duration::from_millis(50)).await; h.abort(); println!(" -> join: {:?}", h.await.map_err(|e| e.is_cancelled())); println!("4. dropping a JoinHandle does NOT cancel the task (it is detached)"); drop(tokio::spawn(step("detached", 100))); sleep(Duration::from_millis(150)).await; println!(" -> main done"); }
1. timeout(250 ms) around a 2000 ms call slow: started, waiting 2000 ms drop: slow cleaned up -> Err(Elapsed(())) after 253 ms 2. select!: first to finish wins, the other is dropped fast: started, waiting 100 ms lazy: started, waiting 300 ms fast: finished drop: fast cleaned up drop: lazy cleaned up -> winner fast after 103 ms 3. a spawned task keeps running on its own; abort() cancels it background: started, waiting 1000 ms drop: background cleaned up -> join: Err(true) 4. dropping a JoinHandle does NOT cancel the task (it is detached) detached: started, waiting 100 ms detached: finished drop: detached cleaned up -> main done
In case 2, "lazy" started before "fast" because select! "randomly picks a branch to check first" unless you write biased; (select! docs). In case 4, dropping a JoinHandle detaches a spawned task, it does not cancel it; only abort() (or dropping the JoinSet that owns it) does.
What this means in practice. Python cancels by raising CancelledError at the await, so cleanup goes in finally; Rust has no exception to catch, so cleanup goes in Drop (a guard). A future that has done half its work when dropped (read part of a message, taken an item off a queue) loses that half: cancel safety. tokio documents which of its methods are cancel safe; inside select! loops, use those, or keep state outside the future.
A worker thread polls one task at a time and gets the thread back only at an .await. A task that calls a blocking function (std::thread::sleep, a synchronous file read, a CPU-heavy loop) holds its worker the whole time, and every other task queued on that worker waits. Alice Ryhl (a tokio maintainer) gives the rule of thumb: "no more than 10 to 100 microseconds between each .await" (Async: What is blocking?). Three jobs, A, B and C, wait 100, 200 and 300 ms, run five ways:
Predict first: with B blocking for 200 ms on one thread, when does A finish, and when does C even start? Then pick a mode; each step of Fig. 2 is a stretch of the recorded events.
job("A", 100).await polls A, which reaches sleep(100 ms).await at 0.1 ms and returns Pending. B does not exist yet: the next line has not run, so the thread idles.tokio::join! polls A, B and C in turn inside one task; each reaches its sleep and returns Pending at 0.0 ms. Three timers run and the thread is free.std::thread::sleep(200 ms) at 0.0 ms: no .await, so it never returns Pending and nothing else can run on the one thread. C has not even started.spawn_blocking, whose closure sleeps on a pool thread, not on ours.Send.Every event is drawn at the time it happened (measured, examples/a2_trace.rs). In short: join overlaps the waits, a blocking B holds the one thread and makes A late, spawn_blocking moves B off it, and on 4 workers the blocking B hides. The same three jobs on asyncio and on Node are on the Python concurrency page and the JavaScript event loop page.
async fn job(name: &str, ms: u64) -> String { ev(name, "start", ""); ev(name, "await", &format!("sleep({ms} ms).await")); tokio::time::sleep(Duration::from_millis(ms)).await; // yields to the runtime ev(name, "resume", ""); ev(name, "done", ""); name.into() } async fn job_blocking(name: &str, ms: u64) -> String { ev(name, "start", ""); ev(name, "block", &format!("std::thread::sleep({ms} ms)")); std::thread::sleep(Duration::from_millis(ms)); // blocks the worker thread: nothing else runs on it ev(name, "done", ""); name.into() } async fn job_offload(name: &str, ms: u64) -> String { ev(name, "start", ""); ev(name, "await", &format!("spawn_blocking(sleep {ms} ms).await")); tokio::task::spawn_blocking(move || std::thread::sleep(Duration::from_millis(ms))).await.unwrap(); ev(name, "resume", ""); ev(name, "done", ""); name.into() }
sequential 609.4 ms order of events: A:start A:await A:resume A:done B:start B:await B:resume B:done C:start C:await C:resume C:done join 303.7 ms order of events: A:start A:await B:start B:await C:start C:await A:resume A:done B:resume B:done C:resume C:done join_blocking 511.2 ms order of events: A:start A:await B:start B:block B:done C:start C:await A:resume A:done C:resume C:done join_offload 305.5 ms order of events: A:start A:await B:start B:await C:start C:await A:resume A:done B:resume B:done C:resume C:done spawn_blocking_multi 303.8 ms order of events: A:start A:await B:start B:block C:start C:await A:resume A:done B:done C:resume C:done
/count_log (L) and three tiny /health (H); the two async workers take them in arrival order..await: H2 and H3 sit in the queue although each needs microseconds. Nothing preempts a running task.spawn_blocking and awaits it..await: the worker is free again within microseconds, so H1, H2 and H3 are answered at once.Before and after on the same six requests (Fig. 3; pick a mode above). The drawing is a schedule built from the measured cost of one 3.9 MB count (illustrative timing, measured ingredients); the numbers under it, and the table below, are measured: Experiment B, tokserve with 2 async workers, 6 connections posting a 3.9 MB log to /count_log (about 10 ms of counting each) while /health is probed at a steady 100 requests per second, open loop (latency counted from the scheduled send time, so a stall cannot hide), once with --inline and once with spawn_blocking.
The fixes, in order of preference: use the async version of the call (tokio::time::sleep, tokio::fs, an async database driver); for blocking calls you cannot avoid, tokio::task::spawn_blocking; for CPU-heavy parallel work, a CPU thread pool such as rayon (the spawn_blocking docs: "Specialized CPU-bound executors, such as rayon, may also be a good fit"); the PyO3 page uses rayon from Python (Rust: speeding up Python with PyO3 and maturin).
A spawned task can outlive the function that spawned it ('static: it may not borrow its locals) and can move to another worker thread at any .await (Send: everything it holds across an await must be safe to move between threads). Send and Sync themselves are taught on Rust: lifetimes, smart pointers, threads and unsafe; here are the three errors they produce in async code, with the compiler's real messages.
Vec without move: compiles?
error[E0373]: async block may outlive the current function, but it borrows `prompts`, which is owned by the current function
--> src/main.rs:5:26
|
5 | let h = tokio::spawn(async {
| ^^^^^ may outlive borrowed value `prompts`
6 | println!("{} prompts", prompts.len());
| ------- `prompts` is borrowed here
|
= note: async blocks are not executed immediately and must either take a reference or ownership of outside variables they use
help: to force the async block to take ownership of `prompts` (and any other referenced variables), use the `move` keyword
|
5 | let h = tokio::spawn(async move {
| ++++
For more information about this error, try `rustc --explain E0373`.
error: could not compile `errs` (bin "errs") due to 1 previous errorFix: async move gives the task ownership (clone first if the caller still needs the data; for large shared data, clone an Arc).
Rc (single-threaded reference counting) kept across an .await inside a spawned task: compiles?
error: future cannot be sent between threads safely
--> src/main.rs:8:13
|
8 | let h = tokio::spawn(async {
| _____________^
9 | | let cache = Rc::new(vec![1, 2, 3]);
10 | | tokio::time::sleep(Duration::from_millis(10)).await;
11 | | println!("{}", cache.len());
12 | | });
| |______^ future created by async block is not `Send`
|
= help: within `{async block@src/main.rs:8:26: 8:31}`, the trait `Send` is not implemented for `Rc<Vec<i32>>`
note: future is not `Send` as this value is used across an await
--> src/main.rs:10:55
|
9 | let cache = Rc::new(vec![1, 2, 3]);
| ----- has type `Rc<Vec<i32>>` which is not `Send`
10 | tokio::time::sleep(Duration::from_millis(10)).await;
| ^^^^^ await occurs here, with `cache` maybe used later
note: required by a bound in `tokio::spawn`
--> ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.53.2/src/task/spawn.rs:176:21
|
174 | pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
| ----- required by a bound in this function
175 | where
176 | F: Future + Send + 'static,
| ^^^^ required by this bound in `spawn`
error: could not compile `errs` (bin "errs") due to 1 previous errorThe note lines name the value (cache, an Rc), the await where it is still alive, and the bound it violates (F: Future + Send + 'static on tokio::spawn). Fix: Arc (atomic counting), or drop the value before the await.
std::sync::Mutex guard held across an .await: compiles?
error: future cannot be sent between threads safely
--> src/main.rs:11:9
|
11 | / tokio::spawn(async move {
12 | | let mut n = hits.lock().unwrap();
13 | | tokio::time::sleep(Duration::from_millis(10)).await; // still holding the lock
14 | | *n += 1;
15 | | })
| |__________^ future created by async block is not `Send`
|
= help: within `{async block@src/main.rs:11:22: 11:32}`, the trait `Send` is not implemented for `std::sync::MutexGuard<'_, u64>`
note: future is not `Send` as this value is used across an await
--> src/main.rs:13:59
|
12 | let mut n = hits.lock().unwrap();
| ----- has type `std::sync::MutexGuard<'_, u64>` which is not `Send`
13 | tokio::time::sleep(Duration::from_millis(10)).await; // still holding the lock
| ^^^^^ await occurs here, with `mut n` maybe used later
note: required by a bound in `tokio::spawn`
--> ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.53.2/src/task/spawn.rs:176:21
|
174 | pub fn spawn<F>(future: F) -> JoinHandle<F::Output>
| ----- required by a bound in this function
175 | where
176 | F: Future + Send + 'static,
| ^^^^ required by this bound in `spawn`
error: could not compile `errs` (bin "errs") due to 1 previous errorThis one would be a real bug even on one thread: the lock stays held while the task sleeps, so every other task that wants it blocks its worker. Fix: lock, update, unlock before awaiting (the fixed file prints 1), or use tokio::sync::Mutex, whose guard can be held across awaits, when you truly must.
How tokio compares with asyncio and the JavaScript event loop row by row (calling, runtime, threads, fan-out, cancellation, blocking, shared state) is the topic root's concurrency axis (Topic: programming-languages). Newer stable features you will see in code: async fn in traits (Rust 1.75, 2023-12-28) and async closures (Rust 1.85, 2025-02-20), both from the Rust release notes.
The token counter as a service: POST /count with {"text": "..."} returns {"tokens": n}; POST /count_log with a JSONL body returns the root program's report as JSON. axum is the tokio project's web framework, a thin typed layer over the hyper HTTP library; most of it maps one to one onto FastAPI. What a service must do whatever its language (request lifecycle, health endpoints, config, graceful shutdown) is Building a backend API; this section is how axum does it.
pub fn app(cfg: Config) -> Router { let timeout = cfg.request_timeout; let limit = cfg.max_body_bytes; let state = Arc::new(AppState { cfg, requests: AtomicU64::new(0), tokens_counted: AtomicU64::new(0) }); Router::new() .route("/health", get(|| async { "ok" })) .route("/count", post(count)) .route("/count_log", post(count_log)) .route("/slow", get(slow)) .route("/stats", get(stats)) .with_state(state) // Layers wrap every route; the last added is the outermost. // axum's own extractor limit (2 MB) is replaced by one configurable limit for every route. .layer(DefaultBodyLimit::disable()) .layer(RequestBodyLimitLayer::new(limit)) .layer(TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, timeout)) .layer(TraceLayer::new_for_http()) } /// POST /count {"text": "..."} -> {"tokens": n} async fn count(State(st): State<Arc<AppState>>, Json(req): Json<CountReq>) -> Result<Json<CountResp>, AppError> { st.requests.fetch_add(1, Ordering::Relaxed); if req.text.is_empty() { return Err(AppError::Empty); } let tokens = count_tokens(&req.text); st.tokens_counted.fetch_add(tokens, Ordering::Relaxed); Ok(Json(CountResp { tokens })) }
A handler is an async fn. Its parameters are extractors: Json<CountReq> parses the body into the struct (serde checks every field and type, like a pydantic model), State<...> hands over shared state, Query<T> parses the query string, axum::body::Bytes takes the raw body. The return type must implement IntoResponse: a String, a Json<T>, a status code, a tuple of those, or a Result of two of them. If an extractor fails, axum answers for you and the handler never runs:
A layer wraps the whole router in reusable behaviour; tower-http provides the common ones. The last .layer added is the outermost, so a request passes through tracing, then the timeout, then the body limit, then the route.
Fig. 4 replays six recorded requests to tokserve (curl -i, outputs in the closed block below): where each one stops, and who answers. Predict each status before its step.
.layer wraps everything added before it, so the last one, TraceLayer, is the outermost, then TimeoutLayer, then RequestBodyLimitLayer (axum's own DefaultBodyLimit is disabled), then the Router, which picks the handler by method and path. A request passes through every frame on the way in, its response through them again on the way out.POST /count with {"text":"x86_64 and v2.1"} passes every layer, the Json<CountReq> extractor parses the body, and count answers 200 OK with {"tokens":5}./count_log against a 1 MiB limit: RequestBodyLimitLayer reads the Content-Length and answers 413 Payload Too Large at once; "the underlying service will not be called" (tower-http limit docs), so the handler never runs.{"txt":"oops"} has no text field, so Json<CountReq> rejects it and the handler body never runs: 422 Unprocessable Entity, with axum's plain-text sentence "missing field `text`".content-type: application/json: the Json extractor refuses it, 415 Unsupported Media Type.{"text":""} parses, so count runs and returns AppError::Empty; its IntoResponse turns that into 400 Bad Request with {"error":"text is empty"}.GET /slow?ms=1500 with the default 1,000 ms request timeout: the handler is still waiting when the time is up, the request "will be aborted" (tower-http timeout docs: in Rust, its future is dropped, section 5's cancellation), and the layer answers 408 Request Timeout with an empty body.
$ curl -i -X POST localhost:3000/count -H 'content-type: application/json' -d '{"text":"x86_64 and v2.1"}'
HTTP/1.1 200 OK
content-type: application/json
content-length: 12
date: (removed)
{"tokens":5}
$ curl -i -X POST localhost:3000/count_log --data-binary @pl/chat20k.jsonl
HTTP/1.1 413 Payload Too Large
content-type: text/plain; charset=utf-8
content-length: 21
date: (removed)
length limit exceeded
$ curl -i -X POST localhost:3000/count -H 'content-type: application/json' -d '{"txt":"oops"}'
HTTP/1.1 422 Unprocessable Entity
content-type: text/plain; charset=utf-8
content-length: 98
date: (removed)
Failed to deserialize the JSON body into the target type: missing field `text` at line 1 column 14
$ curl -i -X POST localhost:3000/count -d '{"text":"hi"}'
HTTP/1.1 415 Unsupported Media Type
content-type: text/plain; charset=utf-8
content-length: 54
date: (removed)
Expected request with `Content-Type: application/json`
$ curl -i -X POST localhost:3000/count -H 'content-type: application/json' -d '{"text":""}'
HTTP/1.1 400 Bad Request
content-type: application/json
content-length: 25
date: (removed)
{"error":"text is empty"}
$ curl -i 'localhost:3000/slow?ms=1500'
HTTP/1.1 408 Request Timeout
content-length: 0
date: (removed)FastAPI answers the same typo with 422 and a structured JSON detail list (recorded from the FastAPI twin in code/py/app.py: {"detail":[{"type":"missing","loc":["body","text"],"msg":"Field required",...}]}); axum's default rejection is a plain-text sentence, so for JSON errors write your own extractor wrapper or map rejections in a layer. FastAPI's dependency injection corresponds to extractors and State; Starlette middleware to tower layers.
Watch for two body limits: axum's extractors refuse bodies over 2 MB by default (DefaultBodyLimit), independently of any tower layer. This project's first run of Experiment B was silently measuring fast 413 rejections because of it; DefaultBodyLimit::disable() plus one configured RequestBodyLimitLayer leaves a single limit to reason about.
For errors the handler decides, define an enum with thiserror (so each case maps to its own status) and implement IntoResponse once; #[from] tokio::task::JoinError lets ? turn a crashed background job into a 500.
/// Errors a handler can return. IntoResponse turns each into a status code and a JSON body. #[derive(Debug, thiserror::Error)] pub enum AppError { #[error("body is not valid UTF-8")] NotUtf8, #[error("text is empty")] Empty, #[error("worker failed: {0}")] Join(#[from] tokio::task::JoinError), } impl IntoResponse for AppError { fn into_response(self) -> Response { let status = match self { AppError::NotUtf8 | AppError::Empty => StatusCode::BAD_REQUEST, AppError::Join(_) => StatusCode::INTERNAL_SERVER_ERROR, }; (status, Json(serde_json::json!({ "error": self.to_string() }))).into_response() } }
A panic (a bug such as an out-of-bounds index) inside a handler does not take the server down: tokio catches it at the task boundary, that one connection is closed without a response, and other requests carry on (examples/b3_panic.rs, curl as the client; exit 52 is "empty reply from server"). To answer 500 instead, add tower-http's CatchPanicLayer.
thread 'tokio-rt-worker' (N) panicked at examples/b3_panic.rs:25:14: index out of bounds: the len is 0 but the index is 3 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace GET /boom -> HTTP 000 (curl exit 52) GET /health -> HTTP 200 (curl exit 0) thread 'tokio-rt-worker' (N) panicked at examples/b3_panic.rs:25:14: index out of bounds: the len is 0 but the index is 3 GET /boom -> HTTP 000 (curl exit 52) GET /health -> HTTP 200 (curl exit 0)
Every request is its own task, maybe on another thread, so shared state goes behind an Arc and anything mutable inside it must be thread-safe: here, two atomic counters. For a mutable map use a Mutex (held briefly, never across an await) or a concurrent map; a database pool is already shareable. Python's equivalent, a module-level dict, is per worker process under uvicorn --workers 4, so /stats on the FastAPI twin reports only the worker that answered; tokserve's counters are process-wide because its workers are threads (/stats after the requests on this page: {"requests":3,"tokens_counted":44703}).
Counting a 391 KB log is about a millisecond of CPU, a 3.9 MB one about ten times that: both far above the 10 to 100 µs budget between awaits, so the handler moves it to the blocking pool (the inline mode exists only for Experiment B above). The double ??: the first unwraps the JoinError (did the background job panic?), the second the counting's own Result.
/// POST /count_log with a JSONL body -> the root program's report as JSON. /// Counting a large body is CPU work: with offload on it runs on the blocking pool. async fn count_log(State(st): State<Arc<AppState>>, body: axum::body::Bytes) -> Result<Json<crate::Report>, AppError> { st.requests.fetch_add(1, Ordering::Relaxed); let work = move || -> Result<crate::Report, AppError> { let text = std::str::from_utf8(&body).map_err(|_| AppError::NotUtf8)?; let mut t = Tally::default(); t.add_text(text); Ok(t.report(5)) }; let report = if st.cfg.offload { tokio::task::spawn_blocking(work).await?? } else { work()? }; st.tokens_counted.fetch_add(report.tokens, Ordering::Relaxed); Ok(Json(report)) }
tracing records events (log lines with typed fields) inside spans (a named period of work, here one per request, opened by TraceLayer). The subscriber decides format and filter: RUST_LOG=info,tower_http=debug asks for info everywhere and per-request lines from tower-http. The same spans can be exported to OpenTelemetry; what to log and alert on is Observability.
INFO tokserve: starting cfg=Config { max_body_bytes: 1048576, request_timeout: 1s, offload: true }
INFO tokserve: listening on http://127.0.0.1:3000
DEBUG request{method=GET uri=/health version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/health version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=POST uri=/count version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/count version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
DEBUG request{method=POST uri=/count version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/count version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=422
DEBUG request{method=POST uri=/count version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/count version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=415
DEBUG request{method=POST uri=/count version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/count version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=400
DEBUG request{method=POST uri=/count_log version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/count_log version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=1 ms status=200
DEBUG request{method=GET uri=/slow?ms=1500 version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/slow?ms=1500 version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=1002 ms status=408
DEBUG request{method=POST uri=/count_log version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=POST uri=/count_log version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=413
DEBUG request{method=GET uri=/stats version=HTTP/1.1}: tower_http::trace::on_request: started processing request
DEBUG request{method=GET uri=/stats version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=200
INFO tokserve: SIGTERM received, draining
INFO tokserve: drained, byeSettings come from clap with env = "TOK_ADDR" on each flag, so the same binary takes flags on a laptop and environment variables in a container. On shutdown an orchestrator sends SIGTERM, waits a grace period, then SIGKILL (10 s by default for docker stop: docs; Kubernetes' 30 s and why to drain are on the backend API page). with_graceful_shutdown takes a future; when it resolves (here a select! over Ctrl-C and SIGTERM), axum stops accepting connections and waits for in-flight requests. Recorded: a slow request, then SIGTERM, then a new request:
[client] GET /slow?ms=800 (in the background)
[shell] kill -TERM <tokserve>
[client] new connection refused (curl exit 7)
[server] exited with code 0
[client] slow request: HTTP 200 after 0.803311 s
--- server log ---
INFO tokserve: starting cfg=Config { max_body_bytes: 1048576, request_timeout: 5s, offload: true }
INFO tokserve: listening on http://127.0.0.1:3000
DEBUG request{method=GET uri=/slow?ms=800 version=HTTP/1.1}: tower_http::trace::on_request: started processing request
INFO tokserve: SIGTERM received, draining
DEBUG request{method=GET uri=/slow?ms=800 version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=802 ms status=200
INFO tokserve: drained, bye
axum::serve(listener, app(cfg))
.with_graceful_shutdown(shutdown_signal())
.await?;
info!("drained, bye");
Ok(())
}
/// Resolves on Ctrl-C or SIGTERM (what `docker stop` and Kubernetes send).
/// After it resolves, axum stops accepting and waits for in-flight requests to finish.
async fn shutdown_signal() {
let ctrl_c = async { tokio::signal::ctrl_c().await.expect("ctrl-c handler") };
#[cfg(unix)]
let term = async {
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let term = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => info!("Ctrl-C received, draining"),
_ = term => info!("SIGTERM received, draining"),
}
}The slow request in flight when SIGTERM arrived completed with 200; the new connection was refused; the process exited 0 after draining. In production, also bound the drain below the grace period.
Serve the token counter over HTTP. Every flag can also come from the environment
Usage: tokserve [OPTIONS]
Options:
--addr <ADDR> Address to listen on [env: TOK_ADDR=] [default: 127.0.0.1:3000]
--max-body <MAX_BODY> Largest request body accepted, in bytes [env: TOK_MAX_BODY=] [default: 1048576]
--timeout-ms <TIMEOUT_MS> Per-request time limit, in milliseconds [env: TOK_TIMEOUT_MS=] [default: 1000]
--workers <WORKERS> Async worker threads (default: one per CPU core) [env: TOK_WORKERS=]
--inline Count large bodies inline on the async worker instead of the blocking pool
-h, --help Print help
-V, --version Print versionThe FastAPI twin (code/py/app.py) has the same routes and rules and returns byte-identical JSON; it uses the root page's reference token function and FastAPI's advice for blocking work (the log count runs in a worker thread). tokserve is axum 0.8.9 on tokio 1.53.2 (release build); the twin is FastAPI 0.142.2 on uvicorn 0.54.0 with uvloop and httptools, pydantic 2.13.5, CPython 3.14.8. Same load generator (oha 1.16.0, 2 threads), same machine (Apple M1 Pro, 10 cores, in normal use), four configurations (1 or 4 async worker threads for axum, 1 or 4 uvicorn worker processes for FastAPI), three rounds of 3 s per load in alternating order.
Predict first: on /count_log (391 KB of counting), how many times more requests per second does axum with 4 workers serve than FastAPI with 4? Then, in Fig. 5, switch to "/health" and to memory.
How to read it. For tiny requests both are fast in absolute terms, and a real service's time goes to its database or model call, not the framework: at a steady 1,000 requests per second every configuration answered /count with a median under half a millisecond. The gaps that matter are CPU work in Python (counting 391 KB costs about 14 ms in Python and 1.3 ms in Rust, and in one uvicorn worker the GIL lets only one count run at a time, even on worker threads) and memory per worker: Python scales across cores with processes, each holding its own interpreter and imports, where tokio scales with threads in one process. How to load-test properly (open against closed loop, coordinated omission) is Capacity planning and performance; the root page's Benchmark tab measures the same program as a batch job.
| Load | axum, 1 worker | axum, 4 | FastAPI, 1 | FastAPI, 4 |
|---|---|---|---|---|
| GET /health, 32 connections (req/s) | 52,031 | 78,284 | 15,476 | 48,552 |
| POST /count, 1 KB JSON (req/s) | 29,504 | 79,535 | 7,075 | 26,610 |
| POST /count_log, 391 KB (req/s) | 4,385 | 4,804 | 75 | 206 |
| /count_log at a steady 20/s: p50 latency (ms) | 1.5 | 1.3 | 14.1 | 14.7 |
| Memory idle, after start (MB) | 3.4 | 3.4 | 57 | 281 |
| Memory peak under the /count load (MB) | 27 | 27 | 61 | 281 |
bench.py records each run's status codes, because a benchmark can silently measure rejections (the 2 MB body limit above).Bars: median of three rounds; whiskers: lowest and highest round. measured; method and raw runs in src/rs/bench/.
Three levels, all run by one cargo test (test strategy in general is Testing and quality):
src/lib.rs, with no async and no HTTP: the token rules from the root page's spec, and malformed lines being counted rather than fatal.Router is a tower Service: call it with a request object and await the response with tower::ServiceExt::oneshot. No sockets, and it exercises extractors, layers and status codes. #[tokio::test] gives each test its own runtime.#[tokio::test] async fn count_without_a_network() { let req = Request::post("/count") .header("content-type", "application/json") .body(Body::from(r#"{"text":"x86_64 and v2.1"}"#)) .unwrap(); let resp = app(cfg()).oneshot(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let bytes = resp.into_body().collect().await.unwrap().to_bytes(); let body: CountResp = serde_json::from_slice(&bytes).unwrap(); assert_eq!(body.tokens, 5); // x86, 64, and, v2, 1 } #[tokio::test]
/// A real server on port 0 (the OS picks a free port), talked to over TCP. #[tokio::test] async fn real_server_over_tcp() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(async move { axum::serve(listener, app(cfg())).await.unwrap() }); use tokio::io::{AsyncReadExt, AsyncWriteExt}; let mut s = tokio::net::TcpStream::connect(addr).await.unwrap(); s.write_all(b"GET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").await.unwrap(); let mut raw = String::new(); s.read_to_string(&mut raw).await.unwrap(); assert!(raw.starts_with("HTTP/1.1 200 OK"), "{raw}"); assert!(raw.ends_with("\r\n\r\nok"), "{raw}"); }
running 2 tests test tests::tokens_follow_the_rules ... ok test tests::malformed_lines_are_counted_not_fatal ... ok test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s running 4 tests test missing_field_is_422 ... ok test count_without_a_network ... ok test real_server_over_tcp ... ok test slow_request_times_out ... ok test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.50s
The timeout test runs the real 500 ms timeout; for longer timers, tokio::time::pause() lets a test advance a fake clock instantly.
A command-line tool has to read arguments, validate them, print help, report errors on stderr, write results on stdout, and return an exit code a shell script can test. clap generates all of it from a struct. No async here: a CLI that reads files needs no runtime.
/// Count word-ish tokens per user in JSONL chat logs. #[derive(Parser)] #[command(name = "tokcount", version)] struct Cli { #[command(subcommand)] cmd: Cmd, } #[derive(Subcommand)] enum Cmd { /// Count tokens per user in one or more JSONL files ("-" reads stdin) Count { /// Input files; "-" means standard input #[arg(required = true)] files: Vec<PathBuf>, /// How many users to list #[arg(short = 'n', long, default_value_t = 5, value_parser = clap::value_parser!(u16).range(1..=1000))] top: u16, /// Print JSON instead of text #[arg(long)] json: bool, /// Exit with code 3 if any line is malformed #[arg(long)] strict: bool, }, /// Count tokens in a piece of text (an argument, or stdin when absent) Text { text: Option<String> }, }
Read it like a typed argparse declaration. #[derive(Parser)] is a derive macro: at compile time it writes the parsing code for this struct. Each field is an argument and its type decides parsing (Vec<PathBuf> takes one or more paths, bool is a flag, Option<String> is optional, u16 must parse as a number); the /// doc comments become the help text; an enum with #[derive(Subcommand)] gives one subcommand per variant, like git commit and git push. Against argparse (which also exits 2 on usage errors): the checks are generated from types (a u16 field cannot receive "abc"), the help is always in sync with the code, and an error prints one line where Python prints a traceback.
$ tokcount count --help
Count tokens per user in one or more JSONL files ("-" reads stdin)
Usage: tokcount count [OPTIONS] <FILES>...
Arguments:
<FILES>... Input files; "-" means standard input
Options:
-n, --top <TOP> How many users to list [default: 5]
--json Print JSON instead of text
--strict Exit with code 3 if any line is malformed
-h, --help Print help
[exit 0]Unix convention: exit 0 for success, non-zero for failure, and clap uses 2 for usage errors (its source defines USAGE_CODE = 2: clap_builder util), before any of your code runs. After parsing, main calls a run function that returns anyhow::Result, so every fallible step can use ?, and only main decides how an error looks and which code it returns (main is in the closed block below).
with_context(|| format!("cannot open {}", ...)) wraps the OS error in a sentence, and {e:#} prints the chain on one line: "cannot open nope.jsonl: No such file or directory (os error 2)". That is anyhow, an error type for applications that carries any error plus context; libraries define their own error enums with thiserror instead (the service's AppError above), so callers can match on them.
Fig. 6 replays eleven recorded sessions of tokcount: guess the exit code a shell script would see, then reveal it.
Exit codes used: 0 success; 1 our runtime error (anyhow, from main); 2 clap usage error; 3 our "dirty data" code from --strict; 101 a Rust panic. For pipes, the code shown is the left-hand program's (${pipestatus[1]} in zsh). All outputs are real recordings from src/rs/run_all.sh; the count matches the root page's reference output byte for byte.
Three conventions make a tool composable with |: results go to stdout, messages and progress to stderr, and - as a file name means stdin. The trap is the pipe: head exits after one line, the pipe closes, and the next write fails with EPIPE. Rust programs ignore the SIGPIPE signal that would silently kill a C program (the runtime sets it to ignored before main: unstable book, on-broken-pipe), so the error reaches println!, which panics: exit 101 and a panic message, in every Rust CLI that prints with println! in a loop (Python's print raises BrokenPipeError: the same bug, different name).
$ target/release/examples/b1_naive_print | head -1; echo "[left side exit ${pipestatus[1]}]"
line 1
thread 'main' (N) panicked at /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/std/src/io/stdio.rs:1168:9:
failed printing to stdout: Broken pipe (os error 32)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[left side exit 101]
[exit 0]
tokcount writes through a locked stdout handle (one lock for the whole output, also faster) and treats BrokenPipe as a normal end; and it prints progress on stderr only when a person is watching: io::stderr().is_terminal() is false in a pipe, a cron job or a CI log (the indicatif crate draws real progress bars the same way).
fn main() -> ExitCode { let cli = Cli::parse(); // bad arguments: clap prints usage and exits with code 2 match run(cli) { Ok(code) => code, Err(e) => { // {:#} prints the whole context chain on one line: "outer: inner: cause" eprintln!("error: {e:#}"); ExitCode::from(1) } } }
Cmd::Count { files, top, json, strict } => {
let mut tally = Tally::default();
for path in &files {
if path.as_os_str() == "-" {
feed(&mut tally, io::stdin().lock(), "stdin")?;
} else {
let f = File::open(path)
.with_context(|| format!("cannot open {}", path.display()))?;
feed(&mut tally, BufReader::new(f), &path.display().to_string())?;
}
}
let report = tally.report(top as usize);
let out = if json {
serde_json::to_string_pretty(&report)? + "\n"
} else {
report.to_text()
};
// Write through a locked handle and treat a closed pipe (`| head`) as success:
// println! would panic with "failed printing to stdout: Broken pipe".
let mut stdout = io::stdout().lock();
if let Err(e) = stdout.write_all(out.as_bytes()).and_then(|_| stdout.flush()) {
if e.kind() != io::ErrorKind::BrokenPipe {
return Err(e).context("writing stdout");
}
}
Ok(if strict && report.malformed > 0 { ExitCode::from(3) } else { ExitCode::SUCCESS })
}/// Read lines into the tally. Progress goes to stderr, and only when stderr is a terminal, /// so pipes and logs stay clean. fn feed(tally: &mut Tally, mut r: impl BufRead, name: &str) -> Result<()> { let show = io::stderr().is_terminal(); let mut line = String::new(); loop { line.clear(); let n = r.read_line(&mut line).with_context(|| format!("reading {name}"))?; if n == 0 { break; } tally.add_line(line.trim_end_matches(['\n', '\r'])); if show && tally.lines % 100_000 == 0 { eprint!("\r{name}: {} lines", tally.lines); } } if show && tally.lines >= 100_000 { eprintln!(); } Ok(()) }
std::env::args() is fine.Giving a Python tool to someone means giving them a Python, a virtual environment and the right wheels. A Rust tool is one executable with its dependencies compiled in. Three ways onto a machine: cargo install --path . (or cargo install <crate> from crates.io) builds in release mode into ~/.cargo/bin, like uv tool install but from source, so the user needs a Rust toolchain; copy the file from target/release/ to a machine with the same OS, CPU architecture and (on Linux) a compatible C library; or release prebuilt binaries per platform (GitHub releases, Homebrew, a container image), built by CI or cross-compiled. That last is how uv and ruff ship.
A profile is a named set of compiler settings in Cargo.toml. The same code built from scratch under each (wall-clock build times on a shared laptop: compare them, do not quote them):
| Profile | Settings | tokcount | tokserve | clean build | Trade-off |
|---|---|---|---|---|---|
dev | cargo build: no optimisation, debug info | 6.05 | 22.59 | 15 | fast edit-compile loop only |
release | --release: opt-level 3, 16 codegen units, no LTO | 1.18 | 3.79 | 20 | the default for shipping |
release-strip | + strip = true: symbol names removed | 0.93 | 2.84 | 21 | panics still print a message, but backtraces lose function names |
release-lto | + lto = "fat", codegen-units = 1: whole-program optimisation | 0.86 | 2.66 | 37 | slower builds, often a little faster and smaller |
release-small | + strip, panic = "abort", opt-level = "z": optimise for size | 0.49 | 1.19 | 24 | smallest; slower code, a panic kills the process without unwinding |
Sizes in MB (106 bytes) of the macOS arm64 executables; measured by src/rs/pkg.sh, load average 13 at the start. The release defaults (lto = false, 16 codegen units) are in the Cargo profiles reference.
# Size experiments (Packaging section): each profile builds the same code. [profile.release-lto] inherits = "release" lto = "fat" codegen-units = 1 [profile.release-small] inherits = "release" lto = "fat" codegen-units = 1 strip = true panic = "abort" opt-level = "z" [profile.release-strip] inherits = "release" strip = true
Debug builds are large and slow and never for measuring or shipping (cargo run builds without optimisation); release is a good default; stripping and LTO are cheap wins for distributed binaries; opt-level = "z" is for when size matters more than speed (embedded, WebAssembly, a CLI downloaded millions of times).
A dynamically linked binary loads shared libraries (the C library, at least) when it starts; a statically linked one contains everything. Rust links its own crates statically always; the question is only the C library. On macOS every binary links Apple's libSystem dynamically (tokserve also links libiconv, which ships with macOS), and Apple supports nothing else ("Apple does not support statically linked binaries on Mac OS X": QA1118); fine, libSystem is on every Mac. On Linux the usual target links glibc dynamically, so a binary built on a new distribution can fail on an old one; the *-unknown-linux-musl targets link musl statically: one file that runs on any Linux kernel of that architecture.
Cross-compiling means building for another OS or CPU. rustup target add downloads the standard library for the target; you also need a linker. For a pure-Rust crate (no C code, as here: no TLS library), the rust-lld linker that ships with rustup was enough on this Mac (the rustc docs show a cross gcc and do not promise this); crates with C dependencies need a real cross toolchain, which cargo-zigbuild (zig as the linker) and cross (builds in a container) provide. The static arm64 tokserve came out at 4582976 bytes, "statically linked".
$ cargo build --release --bin tokserve --target aarch64-unknown-linux-musl
Finished `release` profile [optimized] target(s) in 16.33s
$ file tokserve
ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), statically linked, not stripped
size: 4582976 bytes
$ cargo build --release --bin tokserve --target x86_64-unknown-linux-musl
Finished `release` profile [optimized] target(s) in 13.86s
$ file tokserve
ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), static-pie linked, not stripped
size: 4515056 bytes
$ file target/release/tokserve (the macOS build, for comparison)
Mach-O 64-bit executable arm64
$ otool -L target/release/tokserve
/usr/lib/libiconv.2.dylib (compatibility version 7.0.0, current version 7.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1319.0.0)A Rust service image needs the binary and, at most, a C library: compile in a full Rust image, copy only the binary into a minimal one (a multi-stage build). For a normally linked binary, Google's distroless cc-debian12 adds glibc and libgcc and no shell or package manager (its :nonroot tag runs unprivileged: GoogleContainerTools/distroless); for the static musl build, scratch, the empty image, is enough. How images, layers and isolation work is Containers and isolation.
| Image for this service | Base (compressed, linux/arm64) | + the service | Source |
|---|---|---|---|
FastAPI on python:3.14-slim | 47.1 MB | + fastapi, pydantic, uvicorn and deps | Docker Hub tag API |
tokserve on distroless/cc-debian12 | 9.0 MB | + 2.84 MB binary (glibc build) | gcr.io registry manifest |
tokserve on distroless/static-debian12 or scratch | 0.7 MB / 0 | + 4582976 bytes (static musl build, arm64, not stripped) | gcr.io registry manifest; measured binary |
docker build -t tokserve . && docker images tokserve.# Multi-stage build: compile in a full Rust image, ship only the binary. # Stage 1: the builder (about 1.5 GB of compilers and headers; thrown away). FROM rust:1.99-slim-bookworm AS build WORKDIR /src # Cache dependencies: build once with a dummy main so code edits do not refetch crates. COPY Cargo.toml Cargo.lock ./ RUN mkdir -p src/bin && echo 'fn main(){}' > src/bin/tokserve.rs && echo '' > src/lib.rs \ && cargo build --release --bin tokserve && rm -rf src COPY src ./src RUN touch src/lib.rs src/bin/tokserve.rs && cargo build --release --bin tokserve # Stage 2: distroless "cc" = glibc + libgcc + CA certs, no shell, no package manager, non-root user. FROM gcr.io/distroless/cc-debian12:nonroot COPY --from=build /src/target/release/tokserve /tokserve ENV TOK_ADDR=0.0.0.0:3000 EXPOSE 3000 ENTRYPOINT ["/tokserve"]
# The smallest image: a static musl binary in an empty image. # Build the binary first (on any machine): see ../../cross.sh, or in a builder stage with # rustup target add x86_64-unknown-linux-musl && cargo build --release --target x86_64-unknown-linux-musl FROM scratch COPY tokserve /tokserve ENV TOK_ADDR=0.0.0.0:3000 USER 65532:65532 EXPOSE 3000 ENTRYPOINT ["/tokserve"]
What else production needs (health endpoint, SIGTERM, logs on stdout, configuration from the environment, TLS in front) is the backend API page's; the Rust-specific part is matching the worker count to the CPUs the container is given (tokserve takes --workers or TOK_WORKERS), and TLS in-process, when wanted, with rustls. Load balancing and capacity: Capacity planning and performance.
The pattern above (a fast, small HTTP front end in Rust around heavy compute) is how Hugging Face built its servers. Text Generation Inference's router is a Rust crate on axum (its router/Cargo.toml lists axum = 0.7), with the model code in Python; its README now says "text-generation-inference is now in maintenance mode" (TGI). Text Embeddings Inference is mostly Rust (1.0 MB of Rust against 0.13 MB of Python by GitHub's language count, 2026-10-05: TEI). Model-side Rust libraries (candle, burn, ort, mistral.rs) and serving concepts (batching, KV cache) belong to Topic: inference-and-serving; GPU kernels in Rust to Topic: cuda-and-gpu-programming.
std::thread::sleep, std::fs, a synchronous HTTP client, a long CPU loop): it hides on a multi-threaded runtime until load arrives. Use the async API, spawn_blocking, or rayon..await does nothing; do not silence the "futures do nothing unless you .await or poll them" warning.Arc; tokio::sync::Mutex only when the lock must be held across an await.abort() or a JoinSet.BrokenPipe as success.is_terminal().--release.DefaultBodyLimit) and test the 413 path.with_graceful_shutdown to SIGTERM and Ctrl-C.Every output above is recorded by src/rs/run_all.sh on an Apple M1 Pro (macOS 27) on 2026-10-05; toolchain versions in src/rs/versions.txt, sources checked in src/rs/sources.md.
Links checked 2026-10-26. Times for outside sources are rough reading times.
Result, ?, error types, the traits that Future and IntoResponse are.'static, Arc, Send and Sync, the rules behind tokio::spawn's errors.epoll and kqueue, what tokio's I/O driver sits on.