Skip to content
Derar Sattouf

Building Production Rust Web Services with Axum and Tokio in 2026

Updated Backend & databases

Building Production Rust Web Services with Axum and Tokio in 2026

Rust has moved from "interesting for hot paths" to a mainstream choice for server-side work. Axum, built on Tokio, Hyper, and Tower, is the framework most teams land on because it adds very little magic: handlers are ordinary async functions, middleware is the same Tower ecosystem used across the Rust network stack, and state is explicit.

The code targets Axum 0.8 APIs. As of November 2026 the versions in use are axum 0.8.x, tokio 1.5x, sqlx 0.9, tower-http 0.7 and thiserror 2; check the crate docs for exact signatures when you upgrade.

Keep handlers thin, push logic into a service layer, and share state through a single AppState that is Clone (usually an Arc inside). Use one error enum implementing IntoResponse so every failure maps to a consistent status code and JSON body. Use SQLx (0.9 as of late 2026) with compile-time checked queries, or at least query macros in CI, with a connection pool sized deliberately.

Add timeouts, request limits, tracing, and graceful shutdown from day one. They're cheap now and painful later. And test handlers by calling the Router directly with tower::ServiceExt::oneshot, with no sockets required.

Project layout

A flat main.rs stops scaling at about 500 lines. A layout that works well:

my-service/
├── Cargo.toml
├── migrations/
├── src/
│   ├── main.rs          # wiring only: config, pool, router, serve
│   ├── config.rs        # typed env config
│   ├── state.rs         # AppState
│   ├── error.rs         # AppError + IntoResponse
│   ├── routes/
│   │   ├── mod.rs       # assembles the Router
│   │   ├── health.rs
│   │   └── users.rs
│   ├── services/        # business logic, no HTTP types
│   │   └── users.rs
│   └── db/              # queries
│       └── users.rs
└── tests/
    └── api.rs

The rule: HTTP types (Json, StatusCode) never leak below routes/. Services take plain Rust types and return Result<T, AppError>. That keeps business logic unit-testable.

Cargo.toml essentials

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["timeout", "limit"] }
tower-http = { version = "0.7", features = ["trace", "timeout", "request-id", "cors", "limit", "compression-gzip", "catch-panic"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "tls-rustls", "postgres", "uuid", "time", "migrate"] }
thiserror = "2"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
uuid = { version = "1", features = ["v4", "serde"] }
anyhow = "1"

[profile.release]
lto = "thin"
codegen-units = 1
panic = "abort"
strip = true

Typed configuration and shared state

Parse configuration once, fail fast on startup:

// config.rs
use std::net::SocketAddr;

#[derive(Clone)]
pub struct Config {
    pub bind: SocketAddr,
    pub database_url: String,
    pub db_max_connections: u32,
}

impl Config {
    pub fn from_env() -> anyhow::Result<Self> {
        Ok(Self {
            bind: std::env::var("BIND").unwrap_or_else(|_| "0.0.0.0:8080".into()).parse()?,
            database_url: std::env::var("DATABASE_URL")?,
            db_max_connections: std::env::var("DB_MAX_CONNECTIONS")
                .ok().and_then(|v| v.parse().ok()).unwrap_or(10),
        })
    }
}
// state.rs
use sqlx::PgPool;

#[derive(Clone)]
pub struct AppState {
    pub db: PgPool, // PgPool is already an Arc internally
}

One error type to rule them all

Scattered unwrap() and ad-hoc status codes are the top source of inconsistency in Rust services. Define an error enum with thiserror and implement IntoResponse:

// error.rs
use axum::{http::StatusCode, response::{IntoResponse, Response}, Json};
use serde_json::json;

#[derive(Debug, thiserror::Error)]
pub enum AppError {
    #[error("not found")]
    NotFound,
    #[error("validation failed: {0}")]
    Validation(String),
    #[error("conflict: {0}")]
    Conflict(String),
    #[error(transparent)]
    Database(#[from] sqlx::Error),
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, code, message) = match &self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "not_found", self.to_string()),
            AppError::Validation(m) => (StatusCode::UNPROCESSABLE_ENTITY, "validation", m.clone()),
            AppError::Conflict(m) => (StatusCode::CONFLICT, "conflict", m.clone()),
            AppError::Database(sqlx::Error::RowNotFound) => {
                (StatusCode::NOT_FOUND, "not_found", "not found".into())
            }
            AppError::Database(_) | AppError::Internal(_) => {
                // Log the details, never leak them.
                tracing::error!(error = ?self, "internal error");
                (StatusCode::INTERNAL_SERVER_ERROR, "internal", "internal error".into())
            }
        };
        (status, Json(json!({ "error": { "code": code, "message": message } }))).into_response()
    }
}

pub type Result<T> = std::result::Result<T, AppError>;

Two principles here: errors are logged with full detail server-side, and clients only get a stable code and a safe message.

Handlers, extractors, and validation

// routes/users.rs
use axum::{extract::{Path, State}, http::StatusCode, routing::{get, post}, Json, Router};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{error::{AppError, Result}, state::AppState};

#[derive(Serialize, sqlx::FromRow)]
pub struct User { id: Uuid, email: String, name: String }

#[derive(Deserialize)]
pub struct CreateUser { email: String, name: String }

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/users", post(create))
        .route("/users/{id}", get(fetch))
}

async fn create(State(s): State<AppState>, Json(body): Json<CreateUser>) -> Result<(StatusCode, Json<User>)> {
    if !body.email.contains('@') {
        return Err(AppError::Validation("email is invalid".into()));
    }
    let user = sqlx::query_as::<_, User>(
        "INSERT INTO users (id, email, name) VALUES ($1, $2, $3) RETURNING id, email, name",
    )
    .bind(Uuid::new_v4())
    .bind(&body.email)
    .bind(&body.name)
    .fetch_one(&s.db)
    .await
    .map_err(|e| match e {
        sqlx::Error::Database(d) if d.is_unique_violation() => AppError::Conflict("email already exists".into()),
        other => other.into(),
    })?;
    Ok((StatusCode::CREATED, Json(user)))
}

async fn fetch(State(s): State<AppState>, Path(id): Path<Uuid>) -> Result<Json<User>> {
    let user = sqlx::query_as::<_, User>("SELECT id, email, name FROM users WHERE id = $1")
        .bind(id).fetch_one(&s.db).await?;
    Ok(Json(user))
}

Notes:

  • Axum 0.8 uses /{id} path syntax (older versions used /:id). Check your version.
  • For richer validation, add the validator crate or a newtype per field (Email::parse) so invalid states are unrepresentable. The newtype approach is the more idiomatic Rust answer.
  • Prefer Json rejections to be customized so malformed bodies also return your error shape.

Middleware stack with Tower

Cross-cutting concerns belong in layers. Order matters: layers added later wrap earlier ones.

// routes/mod.rs
use std::time::Duration;
use axum::{http::StatusCode, routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{
    compression::CompressionLayer, limit::RequestBodyLimitLayer,
    request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer},
    timeout::TimeoutLayer, trace::TraceLayer,
};
use crate::state::AppState;

pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/healthz", get(|| async { "ok" }))
        .merge(users::router())
        .layer(
            ServiceBuilder::new()
                .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
                .layer(TraceLayer::new_for_http())
                .layer(PropagateRequestIdLayer::x_request_id())
                .layer(TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, Duration::from_secs(10)))
                .layer(RequestBodyLimitLayer::new(1024 * 1024))
                .layer(CompressionLayer::new()),
        )
        .with_state(state)
}

What each protects against:

LayerFailure it prevents
Request IDUn-debuggable logs across services
TraceMissing latency and status metrics
TimeoutSlow clients and stuck downstream calls tying up tasks
Body limitMemory exhaustion from giant uploads
CompressionWasted bandwidth for JSON-heavy APIs

Add concurrency limits (tower::limit::ConcurrencyLimitLayer) in front of expensive endpoints, and rate limiting at the edge (reverse proxy or API gateway) rather than in-process unless you need per-user quotas.

Database access with SQLx

Pool sizing is the most commonly misconfigured setting. A good starting heuristic: max_connections per instance = (database max connections minus headroom) divided by instance count, and rarely above 20-30 per instance. More connections do not mean more throughput; Postgres degrades with too many active backends.

// main.rs
use sqlx::postgres::PgPoolOptions;
use std::time::Duration;

let db = PgPoolOptions::new()
    .max_connections(cfg.db_max_connections)
    .acquire_timeout(Duration::from_secs(3))
    .idle_timeout(Duration::from_secs(300))
    .connect(&cfg.database_url)
    .await?;

sqlx::migrate!("./migrations").run(&db).await?;

Tips:

  • Use sqlx::query! / query_as! macros with cargo sqlx prepare so CI fails when SQL and schema drift apart.
  • Never hold a transaction across an .await that calls an external service. You will pin a connection while waiting on the network and exhaust the pool.
  • SQLx 0.9 requires query text to be a &'static str (or an explicit opt-in wrapper), which nudges you away from building SQL with format!.
  • Keep acquire_timeout short. A fast failure is better than a pile-up.

Observability: tracing first

tracing_subscriber::registry()
    .with(tracing_subscriber::EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| "info,tower_http=info,sqlx=warn".into()))
    .with(tracing_subscriber::fmt::layer().json())
    .init();

Use #[tracing::instrument(skip(state))] on service functions to get spans with arguments for free. Export traces with the OpenTelemetry layer (tracing-opentelemetry) so spans from Rust show up in the same backend as the rest of your fleet. Add metrics (request count, latency histograms, pool usage) via the metrics crate or OpenTelemetry meters.

Graceful shutdown

Container orchestrators send SIGTERM and then kill after a grace period. If you ignore SIGTERM, in-flight requests are dropped on every deploy.

async fn shutdown_signal() {
    use tokio::signal;
    let ctrl_c = async { signal::ctrl_c().await.expect("ctrl-c handler") };

    #[cfg(unix)]
    let term = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("sigterm handler").recv().await;
    };
    #[cfg(not(unix))]
    let term = std::future::pending::<()>();

    tokio::select! { _ = ctrl_c => {}, _ = term => {} }
    tracing::info!("shutdown signal received, draining");
}

// main
let listener = tokio::net::TcpListener::bind(cfg.bind).await?;
axum::serve(listener, app(state))
    .with_graceful_shutdown(shutdown_signal())
    .await?;

In Kubernetes also add a preStop sleep of a few seconds so the load balancer stops routing before the process begins draining.

Testing without a network

Because an Axum Router is a Tower Service, you can call it directly:

// tests/api.rs
use axum::{body::Body, http::{Request, StatusCode}};
use tower::ServiceExt; // for oneshot

#[sqlx::test(migrations = "./migrations")]
async fn create_user_returns_201(pool: sqlx::PgPool) {
    let app = my_service::routes::app(my_service::state::AppState { db: pool });

    let res = app.oneshot(
        Request::post("/users")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"email":"a@b.co","name":"A"}"#))
            .unwrap(),
    ).await.unwrap();

    assert_eq!(res.status(), StatusCode::CREATED);
}

#[sqlx::test] creates an isolated database per test and applies migrations, which makes tests fast, parallel, and free of shared-state flakiness.

Production checklist

  1. panic = "abort" only if you are certain no code relies on catch_unwind; otherwise handle panics with tower_http::catch_panic.
  2. All outbound calls (reqwest) have explicit timeouts. The default is effectively none.
  3. cargo clippy -- -D warnings, cargo fmt --check, cargo deny check, and cargo audit run in CI.
  4. Build with --locked and ship a minimal image (distroless or scratch with a statically linked musl build).
  5. Health endpoints: /healthz (process alive) and /readyz (database reachable).
  6. Dashboards for the four golden signals: latency, traffic, errors, saturation (pool wait time is a great saturation signal).
  7. Load test with a realistic mix before launch (oha, k6, or wrk2) and capture a flamegraph with cargo flamegraph if throughput misses target.

Authentication with a custom extractor

Extractors are Axum's best feature for cross-cutting request logic. An AuthUser extractor means a handler declares "I need a logged-in user" in its signature, and forgetting auth becomes a compile-time visible omission rather than a runtime surprise. In Axum 0.8, FromRequestParts no longer needs the async_trait macro.

// auth.rs
use axum::{extract::FromRequestParts, http::{header, request::Parts}};
use crate::error::AppError;

pub struct AuthUser {
    pub user_id: uuid::Uuid,
}

impl<S: Send + Sync> FromRequestParts<S> for AuthUser {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let header = parts
            .headers
            .get(header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
            .ok_or(AppError::Unauthorized)?;

        let token = header.strip_prefix("Bearer ").ok_or(AppError::Unauthorized)?;
        // Replace with real verification: signature, expiry, audience, issuer.
        let user_id = verify_token(token).map_err(|_| AppError::Unauthorized)?;
        Ok(AuthUser { user_id })
    }
}

fn verify_token(_token: &str) -> anyhow::Result<uuid::Uuid> {
    anyhow::bail!("wire up your JWT or session verification here")
}

Add an Unauthorized variant to AppError that maps to 401 with the same JSON body shape. Then a handler is simply async fn me(user: AuthUser) -> Json<...>. Do not hand-roll token verification; use a maintained library and review the pitfalls in OAuth and OIDC API security pitfalls.

Calling other services safely

Outbound HTTP is where most production incidents start. Build one shared client with explicit timeouts, and keep it in AppState:

use std::time::Duration;

pub fn http_client() -> reqwest::Result<reqwest::Client> {
    reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(2))
        .timeout(Duration::from_secs(5))
        .pool_idle_timeout(Duration::from_secs(60))
        .user_agent("my-service/1.0")
        .build()
}

Rules that prevent outages:

  1. Every call has a deadline, and the deadline is shorter than the inbound request timeout.
  2. Retry only idempotent calls, with exponential backoff and jitter, and a retry budget. See API rate limiting, idempotency and pagination.
  3. Do not hold a database connection or transaction while waiting on the network.
  4. Propagate the request ID so a single user action is traceable across services.

Background work and cancellation

Use tokio::spawn for fire-and-forget work only when losing it is acceptable. For anything that must complete, write a job to the database first (an outbox table) and process it from a worker. That pattern survives restarts; an in-memory task does not. The pattern is explained in event-driven architecture, outbox and idempotency, and for long multi-step flows see durable execution with Temporal.

Two Tokio facts matter in handlers:

  • Futures are cancelled when dropped. If a client disconnects, Axum may drop the handler future at an .await point. Code after that point never runs. Do not put "must happen" side effects in the middle of a handler after an await without a transaction or an outbox.
  • Never block the runtime. CPU-heavy work (hashing passwords, image resizing, large JSON transforms) should use tokio::task::spawn_blocking or a dedicated thread pool such as rayon, otherwise it starves other requests on the same worker thread.
use tokio::task;

async fn hash_password(pw: String) -> Result<String, AppError> {
    task::spawn_blocking(move || expensive_hash(&pw))
        .await
        .map_err(|e| AppError::Internal(e.into()))?
        .map_err(AppError::Internal)
}

fn expensive_hash(_pw: &str) -> anyhow::Result<String> {
    // call argon2 here
    Ok(String::new())
}

Pagination that scales

Offset pagination slows down as the offset grows. Use keyset (cursor) pagination for large lists:

#[derive(serde::Deserialize)]
pub struct Page {
    after: Option<uuid::Uuid>,
    limit: Option<i64>,
}

async fn list(State(s): State<AppState>, axum::extract::Query(p): axum::extract::Query<Page>) -> Result<Json<Vec<User>>> {
    let limit = p.limit.unwrap_or(50).clamp(1, 100);
    let rows = sqlx::query_as::<_, User>(
        "SELECT id, email, name FROM users WHERE ($1::uuid IS NULL OR id > $1) ORDER BY id LIMIT $2",
    )
    .bind(p.after)
    .bind(limit)
    .fetch_all(&s.db)
    .await?;
    Ok(Json(rows))
}

Always clamp user-supplied limits. Index the column you order by. For query diagnosis see Postgres query performance with EXPLAIN ANALYZE.

Shipping: a small container image

A multi-stage build keeps the runtime image tiny and uses dependency caching so rebuilds are fast:

# syntax=docker/dockerfile:1
FROM rust:1 AS build
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY migrations ./migrations
COPY src ./src
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/app/target \
    cargo build --release --locked && cp target/release/my-service /my-service

FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=build /my-service /my-service
USER nonroot
EXPOSE 8080
ENTRYPOINT ["/my-service"]

If you use sqlx::query! macros, build with SQLX_OFFLINE=true and commit the .sqlx directory generated by cargo sqlx prepare, so the build does not need a live database. Verify the exact offline workflow against the SQLx 0.9 docs. For container hardening see container security hardening and Docker: The Complete Course.

A CI pipeline that catches the common problems

name: ci
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_PASSWORD: postgres
        ports: ["5432:5432"]
        options: >-
          --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
    env:
      DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy, rustfmt
      - uses: Swatinem/rust-cache@v2
      - run: cargo fmt --check
      - run: cargo clippy --all-targets --locked -- -D warnings
      - run: cargo test --locked

Pin action versions to commit SHAs for supply-chain safety; see software supply chain with SLSA, Sigstore and SBOMs.

Troubleshooting table

SymptomLikely causeFix
Requests hang under load, then time outPool exhausted by long transactions or a slow external callShorten transactions, lower acquire_timeout, move network calls outside DB scope
PoolTimedOut errorsToo few connections or leaked connectionsCheck slow queries and pool size; look for held guards across awaits
Handler does not compile: "trait bound Handler not satisfied"A non-Send type held across an await, or wrong extractor orderEnable #[axum::debug_handler] for a readable error; the body extractor must be last
413 or truncated bodiesRequestBodyLimitLayer smaller than payloadRaise the limit on specific routes only
404 for /users/:id after upgradeAxum 0.8 changed path syntax to /{id}Update route strings
Deploys drop in-flight requestsNo graceful shutdown, or no preStop delayAdd with_graceful_shutdown and a preStop sleep
One endpoint freezes everythingBlocking CPU or sync I/O on the async runtimeUse spawn_blocking; check with tokio-console
Memory grows steadilyUnbounded channels or cachesUse bounded channels and capped caches
Build breaks after dependency updateSQLx 0.9 requires &'static str for query textUse string literals, or wrap dynamic SQL deliberately with the SQLx escape hatch (see changelog)

#[axum::debug_handler] is the single most useful macro when learning Axum. Put it on any handler that gives you a long type error.

Where this usually goes wrong

  1. Holding a MutexGuard across .await. Use tokio::sync::Mutex only when you must, and prefer message passing or Arc of immutable data.
  2. Using unwrap() and expect() in request paths. Panics abort the task, and with panic = "abort" the process.
  3. Building SQL with format!. Always use bound parameters. SQLx 0.9 makes dynamic query strings an explicit opt-in for exactly this reason.
  4. Returning internal error text to clients. Log it, return a stable code.
  5. Unbounded everything. Unbounded request bodies, channels, concurrency, query limits and caches all turn into outages eventually.
  6. No timeouts on outbound calls. The default for most clients is "wait forever".
  7. Sharing one huge AppState with mutable globals. Prefer immutable data plus pools; if you need mutable state, make it explicit and small.
  8. Pool size equal to CPU count times a big number. Size from the database capacity, not from the app server.
  9. Skipping load tests. Rust is fast, but your database and downstream services are the usual bottleneck.

When Rust is the wrong choice

A small CRUD app with a tight deadline and a team that knows Laravel, Django or Rails is a poor fit, because the productivity gap is real; see replacing Laravel with Rust: a migration guide and Rust vs Go vs Zig. The same goes for teams without Rust experience and no time to learn, since compile times, lifetimes and async errors have a learning curve. A glue service that mostly shells out to other tools may be simpler in a scripting language. And when your bottleneck is the database, a faster web layer will not help; fix queries first.

Rust shines for latency-sensitive services, high-throughput gateways, services with strict memory limits, and codebases where correctness guarantees pay for themselves.

Questions that come up

Axum, Actix Web or Rocket? Axum is built on the Tokio and Tower ecosystem, so middleware and tooling are shared with much of the Rust network stack, which is why many teams choose it. Actix Web is mature and very fast; evaluate both against your needs.

Should I use an ORM? SQLx is a query toolkit with compile-time checks, not an ORM. SeaORM and Diesel are alternatives if you want a higher-level API. Pick one approach and stay consistent.

How do I handle configuration and secrets? Read from environment variables at startup, validate once, and inject secrets via your orchestrator or secret manager. Never log them.

How many Tokio worker threads do I need? The default (one per CPU core) is right for most services. In containers with CPU limits, check that the runtime sees the limit, and measure before tuning.

Does panic = "abort" save much? It reduces binary size and removes unwinding overhead, but disables catch_unwind. Decide deliberately, as noted in the checklist.

How do I add OpenAPI docs? Crates such as utoipa generate OpenAPI from handler annotations; verify current Axum integration docs.

Sources and docs