Web Development · Nov 18, 2026 · 12 min read

Axum 0.7 Tutorial: Building Secure Production APIs in Rust

Step-by-step guide to creating production-ready REST APIs with Axum 0.7, SQLx 0.8, tracing, rate limiting via Tower, and Docker deployment. Includes concrete code for middleware, database patterns, er

Axum 0.7 Tutorial: Building Secure Production APIs in Rust

Why Choose Axum for Production APIs in 2024

Axum 0.7 is built on Tokio for async runtime and Tower for middleware composition. It provides extractors for JSON, query parameters, path segments, and state while staying lightweight. The framework compiles to a single binary with no external runtime required.

Compared to Actix-web, Axum reuses the broader Tower ecosystem, allowing the same middleware for both HTTP and gRPC services. Compared to Rocket, Axum offers finer control over execution model and easier integration with async database drivers. The 0.7 release improved macro support for route nesting and added better defaults for error handling.

This tutorial builds a task management API with user-scoped data. Every component includes the exact crate versions, configuration values, and code required to run it. The completed service supports listing, creating, updating, and deleting tasks with proper authentication, input validation, structured logging, rate limiting, and database connection pooling.

Project Setup and Dependency Management

Initialize the project and pin exact versions to avoid supply-chain surprises:

cargo new task-api --bin
cd task-api

The Cargo.toml file contains these dependencies with features enabled only where needed:

[package]
name = "task-api"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = { version = "0.7.5", features = ["json", "query", "macros", "matched-path"] }
tokio = { version = "1.38.0", features = ["full"] }
sqlx = { version = "0.8.0", features = ["runtime-tokio", "tls-rustls", "postgres", "chrono", "uuid", "migrate"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "json", "fmt"] }
tower = { version = "0.4.13", features = ["limit", "util"] }
tower-http = { version = "0.5.2", features = ["trace", "cors", "limit", "timeout", "set-header"] }
serde = { version = "1.0.203", features = ["derive"] }
chrono = { version = "0.4.38", features = ["serde"] }
uuid = { version = "1.8.0", features = ["v4", "serde"] }
jsonwebtoken = "9.3.0"
thiserror = "1.0.61"
dotenvy = "0.15.7"
validator = { version = "0.18", features = ["derive"] }

SQLx 0.8 enables compile-time query checking via the query! macro. Tower-http 0.5 supplies production-ready middleware. Validator 0.18 adds struct-level validation rules. Run cargo update once to lock the exact dependency tree in Cargo.lock.

Application Structure and Configuration

Organize source code to keep the router, handlers, models, and middleware separate:

  • src/main.rs: initializes tracing, loads configuration, creates the router, and starts the server with graceful shutdown.
  • src/config.rs: reads environment variables and constructs typed configuration structs.
  • src/error.rs: defines AppError and converts it to HTTP responses.
  • src/models/task.rs: contains Task, CreateTask, and UpdateTask structs.
  • src/handlers/task.rs: all route handlers for the task resource.
  • src/middleware/auth.rs: JWT validation and user ID extraction.
  • migrations/20240701_create_tasks.sql: SQL migration files executed by SQLx.

In config.rs use a builder pattern to validate required environment variables at startup:

pub struct Config {
    pub database_url: String,
    pub jwt_secret: String,
    pub host: String,
    pub port: u16,
}

impl Config {
    pub fn from_env() -> Result<Self, String> {
        dotenvy::dotenv().ok();
        Ok(Config {
            database_url: std::env::var("DATABASE_URL").map_err(|_| "DATABASE_URL missing")?,
            jwt_secret: std::env::var("JWT_SECRET").map_err(|_| "JWT_SECRET missing")?,
            host: std::env::var("HOST").unwrap_or("0.0.0.0".to_string()),
            port: std::env::var("PORT").unwrap_or("3000".to_string()).parse().unwrap(),
        })
    }
}

This approach fails fast on missing configuration instead of allowing the application to start in a broken state.

Tracing and Observability Setup

Structured logging provides context for every request. Initialize once at startup:

fn init_tracing() {
    let env_filter = tracing_subscriber::EnvFilter::from_default_env()
        .add_directive("task_api=info".parse().unwrap())
        .add_directive("tower_http=debug".parse().unwrap());

    tracing_subscriber::registry()
        .with(env_filter)
        .with(tracing_subscriber::fmt::layer().json())
        .init();
}

Attach a custom span to record business-level fields:

let request_id = Uuid::new_v4();
tracing::info_span!("request", %request_id, path = %matched_path);

The TraceLayer from tower-http records method, path, status code, latency in milliseconds, and request size. Combine it with OpenTelemetry later by swapping the subscriber. This setup produces logs that can be ingested by vector, fluent-bit, or directly by cloud logging services without additional parsers.

Database Layer with SQLx

Create a connection pool tuned for production workloads:

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(20)
        .min_connections(5)
        .acquire_timeout(Duration::from_secs(5))
        .idle_timeout(Duration::from_secs(300))
        .max_lifetime(Duration::from_secs(1800))
        .connect(database_url)
        .await
}

The Task model uses derive macros for both SQLx and Serde:

#[derive(sqlx::FromRow, Serialize, Deserialize, Debug)]
pub struct Task {
    pub id: Uuid,
    pub title: String,
    pub description: Option<String>,
    pub completed: bool,
    pub created_at: DateTime<Utc>,
    pub user_id: Uuid,
}

#[derive(Deserialize, Validate)]
pub struct CreateTask {
    #[validate(length(min = 3, max = 120))]
    pub title: String,
    #[validate(length(max = 500))]
    pub description: Option<String>,
}

SQLx migrations create the table with a composite index on (user_id, created_at DESC) to speed up user-specific listing queries. The query! macro verifies queries against the database at compile time, catching column name or type mismatches before deployment.

Centralized Error Handling

The AppError enum maps internal failures to appropriate HTTP responses:

#[derive(thiserror::Error, Debug)]
pub enum AppError {
    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),
    #[error("authentication failed")]
    Unauthorized,
    #[error("resource not found")]
    NotFound,
    #[error("validation error: {0}")]
    Validation(String),
    #[error("rate limit exceeded")]
    RateLimitExceeded,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, error_message) = match self {
            AppError::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal server error"),
            AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
            AppError::NotFound => (StatusCode::NOT_FOUND, "not found"),
            AppError::Validation(msg) => (StatusCode::BAD_REQUEST, Box::leak(msg.into_boxed_str())),
            AppError::RateLimitExceeded => (StatusCode::TOO_MANY_REQUESTS, "rate limit exceeded"),
        };
        (status, Json(json!({"error": error_message}))).into_response()
    }
}

Handlers return Result<T, AppError>. This removes duplicated status code logic and ensures every error path returns consistent JSON.

Building the Router with Axum 0.7

Compose the router with nested routes and multiple middleware layers:

pub fn create_router(state: AppState) -> Router {
    let task_routes = Router::new()
        .route("/", get(list_tasks).post(create_task))
        .route("/:id", get(get_task).put(update_task).delete(delete_task))
        .route_layer(middleware::from_fn(auth_middleware));

    Router::new()
        .nest("/tasks", task_routes)
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CorsLayer::new().allow_origin("https://yourfrontend.com".parse().unwrap()))
                .layer(RequestLimitLayer::new(100, Duration::from_secs(60)))
                .layer(TimeoutLayer::new(Duration::from_secs(10)))
                .layer(SetResponseHeaderLayer::if_not_present(
                    header::STRICT_TRANSPORT_SECURITY,
                    HeaderValue::from_static("max-age=31536000; includeSubDomains"),
                ))
        )
        .with_state(state)
}

The nest method groups protected routes. The ServiceBuilder applies middleware in declared order. TimeoutLayer prevents requests from hanging longer than 10 seconds.

Handler Implementation with Extractors

A list handler with pagination and filtering:

async fn list_tasks(
    State(state): State<AppState>,
    Extension(user_id): Extension<Uuid>,
    Query(params): Query<PaginationParams>,
) -> Result<Json<Vec<Task>>, AppError> {
    let tasks = sqlx::query_as!(
        Task,
        r#"SELECT * FROM tasks 
           WHERE user_id = $1 
           ORDER BY created_at DESC 
           LIMIT $2 OFFSET $3"#,
        user_id,
        params.limit.unwrap_or(20),
        params.offset.unwrap_or(0)
    )
    .fetch_all(&state.db)
    .await
    .map_err(AppError::Database)?;

    Ok(Json(tasks))
}

The PaginationParams struct uses validator to constrain limit between 1 and 100. Extractors run in sequence; Extension provides the user ID injected by the authentication middleware. Each handler stays under 30 lines, making behavior obvious.

Authentication Middleware with JWT

The middleware extracts the bearer token, validates signature and expiry, then inserts the subject claim into request extensions:

pub async fn auth_middleware(
    mut req: Request<Body>,
    next: Next,
) -> Result<Response, StatusCode> {
    let auth_header = req.headers()
        .get("authorization")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.strip_prefix("Bearer "));

    let token = match auth_header {
        Some(t) => t,
        None => return Err(StatusCode::UNAUTHORIZED),
    };

    let secret = std::env::var("JWT_SECRET").map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    let key = DecodingKey::from_secret(secret.as_bytes());
    let mut validation = Validation::default();
    validation.validate_exp = true;

    let token_data = decode::<Claims>(token, &key, &validation)
        .map_err(|_| StatusCode::UNAUTHORIZED)?;

    req.extensions_mut().insert(token_data.claims.sub);
    Ok(next.run(req).await)
}

Claims struct includes sub as UUID and exp. For production, add audience and issuer validation plus a refresh token endpoint that issues short-lived access tokens.

Input Validation with Validator Crate

Combine Serde with validator derive macros to reject invalid payloads early:

#[derive(Deserialize, Validate)]
pub struct UpdateTask {
    #[validate(length(min = 3, max = 120))]
    pub title: Option<String>,
    pub completed: Option<bool>,
}

async fn update_task(
    Path(id): Path<Uuid>,
    State(state): State<AppState>,
    Extension(user_id): Extension<Uuid>,
    Json(payload): Json<UpdateTask>,
) -> Result<Json<Task>, AppError> {
    payload.validate().map_err(|e| AppError::Validation(e.to_string()))?;
    // proceed with database update using optional updates via dynamic query or separate statements
    // ...
}

Early validation prevents unnecessary database round-trips and gives clients clear error messages listing all violated constraints.

Using Database Transactions for Data Consistency

For operations requiring atomicity, use SQLx transactions:

let mut tx = state.db.begin().await.map_err(AppError::Database)?;

sqlx::query!("UPDATE tasks SET completed = $1 WHERE id = $2 AND user_id = $3")
    .bind(new_completed)
    .bind(id)
    .bind(user_id)
    .execute(&mut *tx)
    .await?;

sqlx::query!("INSERT INTO task_events ...")
    .execute(&mut *tx)
    .await?;

tx.commit().await.map_err(AppError::Database)?;

Transactions ensure the task status and audit event are written together. Set isolation level to READ COMMITTED for most workloads to balance consistency and performance.

Testing the API Layers

Unit test a handler by constructing a test router and using oneshot:

#[tokio::test]
async fn test_list_tasks() {
    let pool = sqlx::PgPool::connect("postgres://...").await.unwrap();
    sqlx::migrate!().run(&pool).await.unwrap();
    
    let app = create_router(AppState { db: pool });
    
    let response = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/tasks")
                .header("authorization", "Bearer eyJ...")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
}

Integration tests use a Dockerized PostgreSQL instance via testcontainers-rs or a dedicated test database with unique schema per test run. The compile-time query checks remain active during tests.

Docker Production Image

Use a multi-stage build to minimize final image size and attack surface:

FROM rust:1.76-bookworm as builder
WORKDIR /build
COPY . .
RUN cargo build --release

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /build/target/release/task-api /usr/local/bin/task-api
EXPOSE 3000
USER nobody
CMD ["task-api"]

Create a .dockerignore excluding target, git, and test data. The resulting image runs as non-root user. Set resource limits in your orchestrator: CPU 0.5 cores, memory 256 MiB per instance for typical workloads.

Performance and Scaling Considerations

Configure Tokio runtime with explicit thread count in main.rs:

#[tokio::main(worker_threads = 4)]
async fn main() {
    init_tracing();
    let config = Config::from_env().unwrap();
    let pool = create_pool(&config.database_url).await.unwrap();
    let app = create_router(AppState { db: pool });
    
    let listener = TcpListener::bind(format!("{}:{}", config.host, config.port))
        .await
        .unwrap();
    
    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await
        .unwrap();
}

Use spawn_blocking for any CPU-bound work such as cryptographic operations outside the async context. Connection pool parameters balance between database load and latency. Horizontal scaling works by running multiple identical containers; the shared PostgreSQL becomes the coordination point. Add read replicas for heavy read workloads by creating a second pool used only for SELECT queries.

Security Hardening Checklist

  • Validate all incoming payloads with the validator crate to reject oversized or malformed data before hitting business logic.
  • Apply CORS only to explicitly allowed origins instead of wildcard in production.
  • Use tower_http::trace with a filter that avoids logging Authorization headers or other secrets.
  • Set security response headers for Strict-Transport-Security, X-Content-Type-Options, and Referrer-Policy on every response.
  • Implement request size limits using tower_http::limit::RequestBodyLimitLayer to prevent memory exhaustion attacks.
  • Rotate JWT signing secrets and maintain a short expiry window of 15 minutes combined with refresh tokens stored in HttpOnly cookies.
  • Run cargo audit and cargo update in CI to catch known vulnerabilities in dependencies.
  • Apply seccomp and AppArmor profiles in Docker or Kubernetes to restrict system calls available to the container.

Observability Beyond Tracing

Add Prometheus metrics with the axum-prometheus crate. Register a metrics collector that tracks requests by route and status code. Export metrics on a separate /metrics endpoint protected by basic auth or network policies. Combine with Grafana to create dashboards showing error rates, latency histograms by endpoint, and database connection usage. Structured log fields contain trace IDs that link logs, metrics, and traces together in tools that support correlation.

When to Choose Axum Over Alternatives

Axum provides the best balance when your organization already uses Tokio elsewhere. Its middleware story is stronger than Rocket because any Tower service works unchanged. Actix-web can achieve marginally lower latency on raw JSON serialization workloads, but the difference narrows once database calls dominate execution time. Axum handlers are plain functions, easing local testing and IDE support. The framework's focus on HTTP primitives makes adding Server-Sent Events, WebSocket upgrade routes, or multipart form handling straightforward by composing additional extractors and response types.

Next Steps and Extensions

Extend the service with background processing by adding a separate worker binary that listens to a PostgreSQL notification channel or polls a job_queue table. Implement event sourcing by publishing structured events after each successful transaction using a Redis pub/sub or Kafka producer. Add response caching for list endpoints using the moka crate with time-based eviction and manual invalidation on writes. Configure graceful shutdown to finish in-flight requests and close database connections cleanly on SIGTERM. Integrate with an API gateway for centralized rate limiting and authentication when running multiple Rust services. These patterns maintain the same error handling, logging, and state management style established in the core router.

The architecture described compiles to a single static binary, starts in under 30 milliseconds, and scales horizontally with standard container orchestration. All code shown uses stable Rust features and production-tested patterns for authentication, data access, observability, and deployment.

Keep reading

Related Articles