Axum
Axum is a Tokio-first web framework built on hyper and Tower. You declare a Router, attach handlers, and extract typed inputs from the request.
Detailed Explanation
Axum's unit of routing is Router::new().route("/health", get(health)). A handler is an async function whose arguments implement FromRequest or FromRequestParts — extractors — and whose return type implements IntoResponse. async fn health() -> &'static str { "ok" } is a complete handler. async fn user(Path(id): Path<u64>) -> Json<User> pulls the id from the path and serialises a body.
State is explicit. Router::with_state(app_state) and an extractor State<AppState> (often Arc<...> inside) replace globals. You do not use lazy statics for a database pool. Layers are Tower middleware: tracing, CORS, timeouts, compression. Because Axum is Tower, you can attach the same layers you would attach to a raw hyper service.
Axum does not include an ORM or a template engine. You pick SQLx or SeaORM, and a template crate if you need HTML. That thinness is the appeal. The cost is that a full app is a pile of well-chosen crates, not one batteries-included framework.
Handlers should be cheap at the signature. Heavy work belongs in functions the handler calls. Returning Result<impl IntoResponse, AppError> plus an IntoResponse for AppError is the usual error story. Do not unwrap a database call in a handler; map it to a 500.
When you reach for Axum: a new Tokio service, especially if you already use Tower. When you reach for Actix: you have an Actix codebase or need its actor ecosystem. When you reach for hyper alone: a proxy or a very custom server.
Version your public JSON independently of your handler signatures. Extractors and IntoResponse are an internal convenience. A breaking change to User is a breaking change to every client, whether or not the route path stayed the same. Put DTOs in a module and keep domain types off the wire if they will grow fields that clients should not see.
Code Examples
async fn health() -> &'static str {
"ok"
}
#[tokio::main]
async fn main() {
// axum::Router::new().route("/health", axum::routing::get(health));
println!("{}", health().await); // prints: ok
}Common Gotchas
Extractors run in order and can reject the request
A failed `Json<T>` is a 400 before your handler body runs. Check extractor error responses when debugging "handler never hit".
Do not put a `std` mutex hold across `.await` in a handler
Use Tokio's mutex or finish the lock first. You will stall a worker.
`State` must be `Clone`
Wrap the pool in `Arc`. Cloning the extractor clones the `Arc`, not the pool.
`unwrap` in a handler is a 500 you did not design
Implement `IntoResponse` for your error type.