How to Build a Rust Web Server with Axum
Build a typed Rust HTTP API with Axum 0.8: extractors, shared state, JSON errors, timeouts, tracing, graceful shutdown, and handler tests with tower.
On this page
Introduction
Axum is a web framework built on Tokio, Hyper, and Tower. Its defining feature is not a large API surface but the way it uses Rust’s type system: a handler is an async function whose arguments are extractors, and whose return type implements IntoResponse. If a handler compiles, the request parsing and response conversion are usually wired correctly.
That type safety is valuable, but it does not remove operational concerns. A server still needs a body limit, request timeouts, structured errors, shared state that does not deadlock, graceful shutdown, and tests that exercise the router rather than a single function. This tutorial builds a small JSON API with Axum 0.8, then adds those pieces. The examples assume Tokio 1.x and Rust 1.75 or newer.
Add dependencies and create the router
Start with a new binary crate. Axum 0.8 uses the matchit 0.8 route syntax, where path parameters are written with braces:
[package]
name = "axum-api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tower = "0.5"
tower-http = { version = "0.6", features = ["trace", "timeout"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
thiserror = "2"
A main.rs that constructs the router inline is hard to test. Put the router in a function:
use axum::{routing::{get, post}, Router};
pub fn app() -> Router {
Router::new()
.route("/health", get(health))
.route("/users/{id}", get(get_user))
}
async fn health() -> &'static str {
"OK"
}
GET /health and GET /users/{id} are method-aware because the route is registered with get. Axum returns 405 for a POST to a GET-only route, and 404 for an unknown path. Keep health checks free of dependencies; a health endpoint that queries the database is a readiness check, not a liveness check.
Use typed extractors
Extractors parse parts of the request. Path<u32> rejects a non-numeric id with a 400 before the handler runs. Json<T> buffers and deserializes a JSON body, and rejects malformed JSON or a wrong content type:
use axum::{extract::{Path, State}, Json};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Arc};
use tokio::sync::RwLock;
#[derive(Clone)]
pub struct AppState {
pub users: Arc<RwLock<HashMap<u32, User>>>,
}
#[derive(Clone, Serialize)]
pub struct User {
pub id: u32,
pub name: String,
}
#[derive(Deserialize)]
pub struct CreateUser {
pub name: String,
}
pub async fn get_user(
Path(id): Path<u32>,
State(state): State<AppState>,
) -> Result<Json<User>, AppError> {
let users = state.users.read().await;
let user = users.get(&id).cloned().ok_or(AppError::NotFound)?;
Ok(Json(user))
}
pub async fn create_user(
State(state): State<AppState>,
Json(input): Json<CreateUser>,
) -> Result<(axum::http::StatusCode, Json<User>), AppError> {
if input.name.trim().is_empty() {
return Err(AppError::Validation("name is required".into()));
}
let mut users = state.users.write().await;
let id = users.len() as u32 + 1;
let user = User { id, name: input.name };
users.insert(id, user.clone());
Ok((axum::http::StatusCode::CREATED, Json(user)))
}
Extractor order matters: the body-consuming extractor must be last. A Json extractor after another body extractor fails at runtime because the body can only be consumed once. Path, query, state, and header extractors can appear in any order before it.
Json has a default body limit of 2 MB in Axum. For a small API, lower it explicitly; for an upload endpoint, raise it only on that route. A global limit protects the process from a single oversized JSON body.
Share state without holding locks across await
State requires T: Clone. A database pool or an Arc<RwLock<_>> is already a cheap handle to clone, so deriving Clone on AppState is often enough. The in-memory example below makes the shared-state mechanics visible; a production service would replace the map with a database pool while keeping the same AppState shape:
let state = AppState {
users: Arc::new(RwLock::new(HashMap::new())),
};
let app = Router::new()
.route("/health", get(health))
.route("/users/{id}", get(get_user))
.route("/users", post(create_user))
.with_state(state);
If the state contains a Mutex, prefer tokio::sync::Mutex for locks held across .await. A std::sync::MutexGuard is not Send, so holding one across an await point will not compile in a spawned task, and blocking the async runtime while waiting for a lock hurts throughput. Better still, avoid shared mutable state: use a database, a channel, or a lock-free structure.
Handlers must be 'static and cannot borrow from the router. Clone the handles they need, and move owned values into background tasks. Do not capture a reference to local configuration in a spawned task unless it is wrapped in an Arc with a 'static lifetime.
Return typed errors
An error type implementing IntoResponse keeps handlers readable and responses consistent:
use axum::{http::StatusCode, response::{IntoResponse, Response}, Json};
use serde_json::json;
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("not found")]
NotFound,
#[error("invalid input: {0}")]
Validation(String),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
AppError::Validation(message) => (StatusCode::UNPROCESSABLE_ENTITY, message.clone()),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
The database error is logged but not returned to the client. Leaking SQL errors, table names, or connection strings helps an attacker and confuses users. Validation messages can be specific because they describe the caller’s input. Use a request id in logs so a user-facing “internal error” can be correlated with a detailed server log without exposing the detail in the response.
Add tracing, timeouts, and a body limit
Tower layers compose around the router. TraceLayer logs requests and responses, TimeoutLayer bounds handler time, and DefaultBodyLimit caps the body:
use std::time::Duration;
use axum::extract::DefaultBodyLimit;
use tower_http::{timeout::TimeoutLayer, trace::TraceLayer};
let app = Router::new()
.route("/health", get(health))
.route("/users/{id}", get(get_user))
.layer(DefaultBodyLimit::max(256 * 1024))
.layer(TimeoutLayer::new(Duration::from_secs(10)))
.layer(TraceLayer::new_for_http())
.with_state(state);
Layer order is significant: the outermost layer sees the request first and the response last. Put tracing outside the timeout so timed-out requests are still logged, and put the body limit before handlers that read the body. A timeout layer cancels the future it wraps, but a handler that blocks a runtime thread cannot be cancelled cooperatively; keep blocking work on spawn_blocking.
Initialize tracing once at startup:
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
Avoid logging request bodies, authorization headers, or query strings that may contain tokens. Log method, route, status, latency, and a request id.
Serve with graceful shutdown
Bind a TcpListener explicitly so startup errors are visible, then serve with a shutdown signal:
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
let state = AppState {
users: Arc::new(RwLock::new(HashMap::new())),
};
let app = build_app(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app)
.with_graceful_shutdown(async {
tokio::signal::ctrl_c().await.ok();
})
.await?;
Ok(())
}
In production, handle SIGTERM as well as Ctrl+C. On Unix, tokio::signal::unix::signal(SignalKind::terminate()) provides a stream. Graceful shutdown stops accepting new connections and waits for in-flight requests; pair it with an orchestrator termination grace period that is longer than the slowest expected request. Axum’s graceful shutdown does not wait forever; the platform will eventually kill the process.
Test the router, not just the handler
Use tower::ServiceExt::oneshot to send a request through the full router:
use axum::{body::Body, http::{Request, StatusCode}};
use http_body_util::BodyExt;
use tower::ServiceExt;
#[tokio::test]
async fn health_returns_ok() {
let response = app()
.oneshot(Request::builder().uri("/health").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&body[..], b"OK");
}
Add http-body-util and tower as dev dependencies if they are not already present. Test a missing user (404), an invalid path id (400), a malformed JSON body (400 or 422 depending on the extractor), and an oversized body (413). For stateful handlers, construct a test state with a temporary database or an in-memory repository; do not reach for the production pool in a unit test.
Common pitfalls
- Using the old
/:idroute syntax. Axum 0.8 expects/{id}. - Putting
Jsonbefore another body extractor. The body can only be consumed once. - Holding a
std::sync::MutexGuardacross.await. The handler will not compile or will block the runtime. - Leaking internal errors. Log details, return a stable message.
- No timeout or body limit. A slow or large request can exhaust resources.
- Blocking in async handlers. Use
spawn_blockingfor CPU-heavy or synchronous I/O work. - Assuming
with_stateis optional. A handler requiringState<T>fails at runtime if the router has no matching state.
Conclusion
Axum’s extractors and typed responses make the happy path compact, but a production server is defined by its layers and error boundaries. Use braces in routes for Axum 0.8, keep state cheap to clone, return Result with a proper IntoResponse error, cap bodies and time, and shut down on signals. Test through the router with oneshot so routing, extraction, and response conversion are all covered. Those choices turn compile-time safety into runtime reliability.
Sources: Axum documentation, Tower HTTP layers, Tokio graceful shutdown.
FAQ
- Why did the Axum path syntax change from /:id to /{id}?
- Axum 0.8 moved to the matchit 0.8 routing syntax, which uses braces for parameters. The old colon syntax was rejected or interpreted differently. Update each route and use {*rest} for a catch-all when upgrading.
- Do I need Arc for Axum state?
- Only when the state is expensive to clone or must be shared by identity. State must implement Clone; a small struct of handles such as a database pool already clones cheaply. Arc<AppState> is fine, but cloning an Arc on every request is not automatically better than deriving Clone on the state.
- How do I return a JSON error from an Axum handler?
- Return a Result from the handler and implement IntoResponse for your error type. Map domain errors to status codes and a stable JSON body there, and keep internal error details in logs rather than the response.
Report a problem with this articleOpens a pre-filled issue on GitHub.