Axum for Microservices Backends
Learn why Axum is an excellent choice for building microservices, with practical examples of structuring services, health checks, error handling, and shared middleware.
What Microservices Are and Why a Backend Framework Matters
A microservice architecture breaks a large application into many small, independent services. Each service owns one piece of business functionality, runs in its own process, and communicates with other services over the network. A typical e-commerce system might have a user service, a product service, an order service, and a payment service.
This style brings real benefits: teams can deploy services independently, scale only the parts that need scaling, and use different technologies for different services. But it also introduces hard problems. Every service must handle HTTP requests reliably, produce consistent error responses, expose health checks for orchestrators, log enough information for debugging across service boundaries, and stay lightweight so it starts fast and consumes little memory.
That is exactly where a backend framework like Axum shines. Axum gives you the tools to build each service cleanly without adding unnecessary weight. It stays out of your way while providing type safety, composable middleware, and predictable error handling.
Why Axum Fits Microservices Naturally
Axum was designed by the Tokio team with the philosophy of "small, well-typed pieces." That philosophy maps perfectly onto microservices. Here are the specific reasons Axum is a strong fit.
Modular and Composable Routing
Each microservice usually exposes a small number of endpoints. Axum's Router type lets you split routes by feature, nest them under a prefix, and merge them together. This keeps a service's code organized even as it grows.
Type-Safe Extractors Reduce Boilerplate
Microservices often have many small handlers that parse JSON, query parameters, and path variables. Axum's extractor system checks the types at compile time and validates the values at runtime. You write the shape of the data once as a Rust struct, and Axum handles the parsing and type checking. This removes entire classes of runtime errors and lets the compiler catch mistakes before deployment.
Tower Middleware for Cross-Cutting Concerns
Every microservice needs logging, timeouts, tracing, compression, and sometimes rate limiting. Axum does not invent a separate middleware system of its own; it uses Tower's Service and Layer traits, with only small helpers of its own on top. That means you can reuse battle-tested middleware from tower-http across all your services. You write a logging layer once and apply it to every service you build.
Async and Performance Without Tuning
Axum runs on Tokio, the most widely used async runtime in Rust. Async I/O lets a single service handle thousands of concurrent connections without spawning a thread per connection. You get this performance without having to tune thread pools or write unsafe code.
Small Footprint and Fast Startup
Microservices are often deployed in containers and scaled up and down quickly. A Rust binary compiled with Axum starts in milliseconds and uses a small amount of memory compared to frameworks in higher-level languages. That makes it cheap to run many instances and to handle sudden traffic spikes.
Macro-Free API Keeps Code Readable
Many Rust web frameworks use attribute macros to define routes, which can hide control flow and make code harder to read. Axum uses ordinary functions and method calls. A new developer can read an Axum service and understand exactly what it does without learning a DSL.
A Minimal Axum Microservice
Let's start with the smallest possible service. This one exposes a /health endpoint that returns a plain OK and a /users endpoint that returns a JSON list. In a real microservice, the health endpoint is used by the orchestrator to decide whether the service is alive, and the /users endpoint is the actual business functionality.
// main.rs
use axum::{
routing::get,
Router,
Json,
};
use serde_json::{json, Value};
#[tokio::main]
async fn main() {
// Build the router with two routes
let app = Router::new()
.route("/health", get(health_check))
.route("/users", get(list_users));
// Bind to a port and start serving
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Service listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
// Handler for /health
async fn health_check() -> &'static str {
"OK"
}
// Handler for /users - returns a JSON array
async fn list_users() -> Json<Value> {
Json(json!([
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]))
}
This code does a lot in a few lines. The Router::new() creates an empty router. The two .route() calls attach handler functions to specific paths and HTTP methods. The health_check handler returns a string, which Axum automatically converts into an HTTP response with status 200 and a plain text body. The list_users handler returns Json<Value>, which Axum serializes to JSON and sets the Content-Type header automatically.
The #[tokio::main] macro sets up the Tokio async runtime. TcpListener::bind creates a TCP listener on port 3000. axum::serve ties the listener and the router together and runs forever, accepting incoming connections and passing them to the router.
This is already a complete, deployable microservice. You could containerize it, deploy it to Kubernetes, and expose /health as a liveness probe.
Structuring a Microservice for Independent Deployment
As a service grows, you will add more routes. A single main.rs file with everything in it becomes unwieldy. Axum encourages splitting routes into modules using nested routers.
Splitting Routes by Feature
Suppose you are building a user service. It has user-related routes and also health and version endpoints. You can create a user_routes() function that returns a Router, then nest it under /users in the main router.
// main.rs
mod users;
use axum::{
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", get(health_check))
.nest("/users", users::routes());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn health_check() -> &'static str {
"OK"
}
// users.rs
use axum::{
routing::{get, post},
Router,
Json,
};
use serde_json::{json, Value};
pub fn routes() -> Router {
Router::new()
.route("/", get(list_users).post(create_user))
.route("/{id}", get(get_user).put(update_user).delete(delete_user))
}
async fn list_users() -> Json<Value> {
Json(json!([{"id": 1, "name": "Alice"}]))
}
async fn create_user() -> &'static str {
"User created"
}
async fn get_user(axum::extract::Path(id): axum::extract::Path<u64>) -> Json<Value> {
Json(json!({"id": id, "name": "Alice"}))
}
async fn update_user(axum::extract::Path(id): axum::extract::Path<u64>) -> String {
format!("User {id} updated")
}
async fn delete_user(axum::extract::Path(id): axum::extract::Path<u64>) -> String {
format!("User {id} deleted")
}
The key idea is that each feature or domain area gets its own module and its own Router. The main router just nests those routers under appropriate prefixes. This makes it easy to see the service's public API at a glance and to work on one feature without touching others.
Nested Routers vs Merged Routers
There are two common ways to combine routers: nesting and merging. The right choice depends on how you want to organize paths.
// main.rs
use axum::{routing::get, Router};
mod health;
mod users;
#[tokio::main]
async fn main() {
let app = Router::new()
.nest("/health", health::routes())
.nest("/users", users::routes());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
// health.rs
use axum::{routing::get, Router};
pub fn routes() -> Router {
Router::new().route("/", get(|| async { "OK" }))
}
// users.rs
use axum::{routing::get, Router};
pub fn routes() -> Router {
Router::new()
.route("/", get(|| async { "list users" }))
.route("/{id}", get(|axum::extract::Path(id): axum::extract::Path<u64>| async move {
format!("user {id}")
}))
}
With nesting, each subrouter defines paths relative to the prefix: route("/") in the users subrouter responds at /users, and route("/{id}") at /users/{id}. With merging, each subrouter defines full paths from the root. Nesting is often cleaner when you have a natural hierarchical prefix, while merging is useful when you want to combine routers that were built independently without a shared prefix.
Nesting / gives the bare prefix, not a trailing slash:
When you nest a router whose route is / under /users, the result responds at /users - with no trailing slash. A request to /users/ gets a 404. If you need both spellings, register the same handler at both paths or use merge with full paths instead of nest.
Health Checks and Readiness Endpoints
In a microservices deployment, an orchestrator like Kubernetes periodically hits a health endpoint to decide whether to send traffic to a service. If the health check fails, the orchestrator restarts the container. Your Axum service should expose a /health or /ready endpoint that returns a successful HTTP status when the service is ready to accept requests.
Without Probes, Kubernetes Cannot Tell a Hung Service from a Healthy One:
If you deploy an Axum service to Kubernetes and do not define a liveness or readiness probe, the orchestrator assumes a running container is ready - it has no way to know your service has hung or entered a broken state. Always include a /health route that returns 200 OK when the process is healthy, and point a probe at it, so the orchestrator can restart or deprioritise a pod that stops answering.
A simple health check can just return a static string. For a more informative check, you can return JSON with service name, version, and timestamp.
use axum::Json;
use serde_json::{json, Value};
use std::time::{SystemTime, UNIX_EPOCH};
async fn health_check() -> Json<Value> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
Json(json!({
"status": "ok",
"service": "user-service",
"version": env!("CARGO_PKG_VERSION"),
"timestamp": now
}))
}
The env!("CARGO_PKG_VERSION") macro reads the version from Cargo.toml at compile time, so every build embeds its own version string. This is extremely useful for debugging which version of a service is running in a cluster.
Correctly Responding Health Check:
If you run this service and send a request to http://localhost:3000/health, you should see a response like:
{"status":"ok","service":"user-service","version":"0.1.0","timestamp":1717000000}
This confirms your service is alive, identifies itself, and provides a version number. Orchestrators and monitoring tools can use this data.
Consistent Error Handling Across Services
In a microservices system, every service should return errors in the same shape. If one service returns {"error": "not found"} and another returns {"message": "Not found", "code": 404}, clients have to handle many different formats. A consistent error envelope makes the whole system easier to work with.
Axum lets you define a custom error type that implements IntoResponse. Every handler can return Result<T, ApiError> where T is the success response and ApiError is your unified error type.
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
#[derive(Debug)]
enum ApiError {
NotFound,
BadRequest(String),
Internal,
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, message) = match self {
ApiError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
ApiError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg),
ApiError::Internal => (StatusCode::INTERNAL_SERVER_ERROR, "internal error".to_string()),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
Now a handler can look like this:
async fn get_user(
axum::extract::Path(id): axum::extract::Path<u64>,
) -> Result<Json<serde_json::Value>, ApiError> {
// Imagine a database lookup here.
// For now, we only know how to handle id 1.
if id == 1 {
Ok(Json(json!({"id": 1, "name": "Alice"})))
} else {
Err(ApiError::NotFound)
}
}
The handler returns Ok with a JSON response for a successful case, or Err with a typed error. Axum converts the ApiError into an HTTP response using the IntoResponse implementation. This pattern keeps error handling predictable and consistent.
Never Leak Internal Error Details:
When mapping internal errors like database connection failures to an HTTP response, do not include the raw error message in the body. That can expose internal paths, SQL queries, or stack traces to attackers. Always log the real error server-side and return a generic message like "internal error" to the client.
Sharing Middleware Across Microservices
Every microservice has cross-cutting concerns: logging, request tracing, timeouts, compression, and maybe authentication. Since Axum uses Tower, you can define a middleware layer once and apply it to every service you build.
For example, you can create a reusable logging layer using tower_http::trace::TraceLayer. The layer can be applied to any Axum router.
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", get(|| async { "OK" }))
.route("/users", get(|| async { "[]" }))
// Attach the tracing middleware globally
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
TraceLayer::new_for_http() will automatically create spans for every request and log when the request starts and finishes. This is invaluable for debugging in a distributed system, especially when you add correlation IDs or trace IDs that propagate between services.
You can also add a timeout layer so that slow handlers don't tie up resources forever:
use std::time::Duration;
use axum::{http::StatusCode, routing::get, Router};
use tower_http::timeout::TimeoutLayer;
async fn slow_handler() -> &'static str {
tokio::time::sleep(Duration::from_secs(10)).await;
"finally done"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/slow", get(slow_handler))
.layer(TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(5),
));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Use the tower-http timeout here, not tower::timeout::TimeoutLayer: the tower one fails with a BoxError, and axum::serve requires the service error to be Infallible, so that combination does not compile without a HandleErrorLayer to convert the error. The tower-http layer answers with a 408 itself, so it composes directly.
The same layers work across all Axum services because they are just Tower layers. You can create a shared crate in your workspace that exports preconfigured middleware stacks.
Configuration and Environment Variables
Microservices are usually configured through environment variables. A service should read its port, database URL, and other settings from the environment so the same binary can run in development, staging, and production without recompilation.
Axum itself does not enforce a configuration method, but you can use std::env or a crate like dotenvy. Here is a simple pattern:
use std::env;
fn get_port() -> u16 {
env::var("PORT")
.unwrap_or_else(|_| "3000".to_string())
.parse()
.expect("PORT must be a valid u16")
}
Then bind to that port:
let port = get_port();
let addr = format!("0.0.0.0:{port}");
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
println!("Listening on {addr}");
This keeps the service flexible and follows the twelve-factor app methodology that is common in microservices.
Observability in Microservices
In a monolith, you can debug by reading a single log file. In a microservices system, a single user request may pass through five different services. You need structured logs and trace IDs to follow a request across service boundaries.
Axum has no built-in distributed tracing. Tracing comes from two opt-in pieces you add yourself: the tracing crate (a separate crate, not part of axum) for spans and events, and tower_http::trace::TraceLayer for one span per request. TraceLayer creates the span and logs request start/finish, but it does not by itself propagate a trace ID to downstream services - extracting an incoming traceparent header and passing it on in your outbound reqwest calls is your code's job, usually with an OpenTelemetry exporter if you want traces to leave the process. This is a vast topic, but the key point for this page is that Axum does not lock you into a particular observability stack. You can use any tracing subscriber and any log aggregator.
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() {
// Initialize tracing to print logs to stdout as JSON
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new("info"))
.with(tracing_subscriber::fmt::layer().json())
.init();
// Build router and add TraceLayer
let app = Router::new()
.route("/health", get(|| async { "OK" }))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
This setup produces structured JSON logs that tools like Loki, Elasticsearch, or Datadog can ingest.
Building a Microservice from Scratch
This section walks through creating a new Axum microservice step by step, including dependencies, code, and a quick test. It assumes you already have Rust and Cargo installed.
Step 1: Create a new binary project
Run these commands in your terminal to create a new Rust binary crate and add Axum and Tokio:
cargo new user-service
cd user-service
cargo add axum
cargo add tokio --features full
Step 2: Add a health endpoint and a business endpoint
Replace the contents of src/main.rs with this code:
use axum::{routing::get, Router, Json};
use serde_json::{json, Value};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", get(health_check))
.route("/users", get(list_users));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("user-service listening on 0.0.0.0:3000");
axum::serve(listener, app).await.unwrap();
}
async fn health_check() -> Json<Value> {
Json(json!({"status": "ok"}))
}
async fn list_users() -> Json<Value> {
Json(json!([{"id": 1, "name": "Alice"}]))
}
Step 3: Add a custom error type
Add this to the same file after the handler functions:
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
enum ApiError {
NotFound,
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let (status, message) = match self {
ApiError::NotFound => (StatusCode::NOT_FOUND, "not found"),
};
(status, Json(json!({"error": message}))).into_response()
}
}
Step 4: Run and test
Start the service with cargo run. In a second terminal, test the endpoints:
curl http://localhost:3000/health
# {"status":"ok"}
curl http://localhost:3000/users
# [{"id":1,"name":"Alice"}]
Service Works As Expected:
If you see the JSON responses above, you have successfully built and run a minimal Axum microservice. This service is ready to be containerized and deployed into a cluster.
Common Mistakes in Axum Microservices
Even with Axum's design, beginners make a few predictable mistakes when building microservices.
Sharing State Without Arc
Microservices often need shared state, like a database connection pool or a configuration object. Axum's State extractor requires the state type to implement Clone. If your state contains a database pool, cloning it directly may be expensive or impossible. The fix is to wrap the state in Arc.
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
// A stand-in for a database pool: it holds a connection and cannot be cloned.
struct DatabasePool {
connection_string: String,
}
impl DatabasePool {
fn new() -> Self {
Self { connection_string: "postgres://localhost/mydb".to_string() }
}
fn list_users(&self) -> &'static str {
"users"
}
}
struct AppState {
db: DatabasePool,
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState { db: DatabasePool::new() });
let app = Router::new()
.route("/users", get(list_users))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn list_users(State(state): State<Arc<AppState>>) -> String {
// Cloning the Arc is cheap: it only bumps a reference count.
// The pool itself is never cloned.
state.db.list_users().to_string()
}
Without Arc, this would not work at all: State requires the state type to be Clone, and a pool that owns a connection is not Clone. Wrapping it in Arc makes the state cheaply cloneable - cloning the Arc only bumps a reference count - while the pool itself is shared, never copied.
Use Arc for Shared State:
Wrap any large or non-trivial state in Arc before putting it in State. This makes per-request cloning cheap because it only increments a reference count.
Forgetting to Handle All Error Cases
If a handler returns Result<T, E>, you must ensure E implements IntoResponse. If it doesn't, the compiler will reject your code. Beginners sometimes use unwrap() or expect() inside handlers, which can panic. Under the default panic = "unwind" setting, a panic in a handler does not bring down the whole process: it unwinds and aborts only that request's task, and the server keeps serving other requests (the client whose request panicked gets no response, unless you added tower_http::catch_panic::CatchPanicLayer, which turns it into a 500). A panic only kills the process if it happens in main - or if the binary was built with panic = "abort". So a panic is still a bug to fix, but one bad request does not take the service down with it.
Always handle errors gracefully and return a proper HTTP error response. Use the Result type with a custom error enum as shown earlier.
Not Setting Timeouts on External Calls
Although Axum does not make external calls itself, your handlers will often use reqwest or hyper to call other services. If you do not set a timeout, a slow downstream service can tie up your handler's future indefinitely, leading to resource exhaustion. Always wrap external calls in a timeout: use tokio::time::timeout around the call, or set the timeout on the client itself (for example, reqwest::Client::builder().timeout(...)).
Overcomplicating Routing with Macros
Some frameworks encourage you to use macros to define routes. Axum's macro-free API is a feature, not a limitation. Resist the urge to add procedural macros for routing. Plain functions and method chains are easier to read, test, and refactor.
Graceful Shutdown and Service Discovery
Two standard microservice concerns the sections above only gesture at are shutting down cleanly and finding other services. Neither is built into Axum; both are small, explicit pieces you add.
Graceful shutdown is opt-in. axum::serve on its own runs until the process is killed. Add .with_graceful_shutdown(...) and it stops accepting new connections once the signal future completes, while in-flight requests finish:
use tokio::signal;
#[tokio::main]
async fn main() {
let app = Router::new().route("/health", get(|| async { "OK" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
async fn shutdown_signal() {
// Ctrl+C, or SIGTERM from Kubernetes / your orchestrator.
let ctrl_c = async {
signal::ctrl_c().await.expect("failed to listen for Ctrl+C");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to listen for SIGTERM")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
Pair this with two different health endpoints rather than one: a liveness probe (/health/live) that only answers "is this process alive?" and a readiness probe (/health/ready, or /ready) that also checks the things the service needs before it should receive traffic - database reachable, downstream services reachable, configuration loaded. Kubernetes restarts a pod whose liveness probe fails, but only removes a pod from load balancing when readiness fails; using one endpoint for both means a temporarily-unready dependency can get your pod restarted instead of just deprioritised.
Service discovery is not built into Axum either. There is no registry, no client-side load balancing, and no service-mesh integration in the framework. In practice a service finds its peers in one of three ways, and you pick per deployment: environment variables or config files with the peer's base URL (the simplest, and enough for a handful of services); DNS names provided by the platform (for example, Kubernetes Service names such as http://user-service:3000, resolved by the cluster DNS); or a registry such as Consul or etcd, queried at startup or watched for changes, with the discovered addresses fed into a shared reqwest::Client in application state. Whichever you choose, keep the lookup outside your handlers - resolve the peer address once at startup, store the client in State, and let handlers just call it.
Summary
Axum's design philosophy of small, well-typed, composable pieces makes it a natural fit for building microservices. Its macro-free routing keeps each service readable, its extractor system eliminates manual parsing, and its integration with Tower gives you a rich middleware ecosystem for logging, tracing, timeouts, and more. The same patterns work whether you are building one service or fifty.
If you are evaluating Axum for a new microservices project, start with a minimal service that exposes health and business endpoints, then layer on structured error handling, shared middleware, and observability. The compiler will guide you as you add features, and the result will be a lightweight, fast, and maintainable service.