Skip to content

Web API Services

Production Rust web APIs combine compile-time type safety with predictable latency and low memory use. Configure the HTTP framework, middleware limits, structured errors, database queries, telemetry, graceful shutdown, and container builds before deployment.

Crate stack

Select crates that integrate cleanly with the tokio async runtime and pure-Rust TLS (rustls).

Purpose Crate Notes
HTTP framework axum Default choice. Macro-free extractors and native tower middleware support.
High-throughput alternative actix-web Thread-per-core runtime for specialized low-tail-latency workloads.
Middleware tower and tower-http Timeouts, body size limits, CORS, compression, and HTTP trace layers.
Database access sqlx Async SQL with compile-time query checks and embedded migrations.
Telemetry tracing and tracing-subscriber Structured JSON logs and span-aware async diagnostics.
OpenAPI specification utoipa Derive OpenAPI schemas from Rust request and response structs.
Outbound HTTP client reqwest Use default-features = false with rustls (on 0.13+, plus ClientBuilder::tls_backend_rustls() if another dependency can enable native-tls) or rustls-tls (on 0.12, plus use_rustls_tls()), and share one Client across handlers.

Application structure and shared state

Separate the service into clear layers so you can check domain logic without an HTTP server.

  • routes or handlers: Parse HTTP requests, validate inputs, and map domain results to HTTP responses.
  • domain or services: Implement business rules with no dependency on HTTP types.
  • repositories: Send database queries and external service calls.

Bundle shared resources such as the database pool and reqwest::Client in an AppState struct. Pass AppState through the framework state extractor instead of global variables.

Middleware, limits, and graceful shutdown

Limit response creation time after headers are read, limit body size, and drain in-flight requests during deployments. TimeoutLayer bounds only the service response future after Hyper parses request headers—it does not protect against clients that send incomplete request headers or bound a streaming response body after headers are returned. Enforce header read timeouts at a reverse proxy.

use axum::{routing::get, Router};
use std::net::SocketAddr;
use std::time::Duration;
use tokio::signal;
use tower::ServiceBuilder;
use tower_http::{
compression::CompressionLayer,
limit::RequestBodyLimitLayer,
timeout::TimeoutLayer,
trace::TraceLayer,
};
async fn health() -> &'static str {
"ok"
}
async fn shutdown_signal() {
let ctrl_c = async {
let _ = signal::ctrl_c().await;
};
#[cfg(unix)]
let terminate = async {
if let Ok(mut sig) = signal::unix::signal(signal::unix::SignalKind::terminate()) {
sig.recv().await;
}
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
}
pub async fn serve(addr: SocketAddr) -> std::io::Result<()> {
let middleware = ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new())
.layer(TimeoutLayer::new(Duration::from_secs(30)))
.layer(RequestBodyLimitLayer::new(2 * 1024 * 1024));
let app = Router::new()
.route("/healthz", get(health))
.layer(middleware);
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
}

Add explicit liveness (/healthz) and readiness (/readyz) endpoints. Make the readiness endpoint check database connectivity with a short timeout.

Structured errors (RFC 9457)

Do not call unwrap or expect in request handlers. Return a centralized error enum that maps domain errors to RFC 9457 Problem Details (application/problem+json).

  • Include type, title, status, and detail fields in client error responses.
  • Record internal stack traces, SQL errors, and upstream failures in structured logs only. Never expose internal error strings to external callers.

Database queries and offline CI builds

Use sqlx::query! and sqlx::query_as! to check SQL syntax and column types at compile time.

  1. Set explicit max_connections, acquire_timeout, and idle_timeout values on the connection pool.
  2. Start cargo sqlx prepare --workspace -- --all-targets against a local database and commit the .sqlx/ metadata directory.
  3. Set SQLX_OFFLINE=true in CI and container builds so Cargo compiles without a live database connection.
  4. Keep database migrations in migrations/ and apply them in a controlled deployment step or startup hook.

Observability and security controls

  • Write structured JSON logs with tracing-subscriber in production. Configure log levels with RUST_LOG.
  • Propagate W3C Trace Context (traceparent) headers across incoming requests and outbound reqwest calls with tracing-opentelemetry.
  • Validate authentication tokens, authorization scopes, and request schemas on every protected route.
  • Configure strict CORS origins in tower_http::cors::CorsLayer. Do not allow wildcard origins with credentials.
  • Apply rate limits to authentication and write endpoints at the reverse proxy or middleware layer.
  • Redact secrets, authorization headers, and personal data from logs and traces.

Refer to Secure development lifecycle for threat models and security verification.

Testing web APIs

Test HTTP routers directly in memory without opening a network socket.

  • Call axum::Router directly in integration tests with tower::ServiceExt::oneshot.
  • Use ephemeral databases in CI (for example, test containers or per-test schemas) to check migrations and SQL queries.
  • Add tests for unauthorized access, malformed JSON, oversized request bodies, and invalid query parameters. Make sure that each test returns the expected HTTP status code without a panic. Refer to Never panic on untrusted input.
  • Generate and check the OpenAPI document in CI so API documentation stays in sync with route handlers.

Container packaging and deployment

Use multi-stage container builds with cargo-chef to cache dependency compilation separately from application source changes.

  • Copy only the compiled binary into a minimal runtime image such as Distroless or debian:bookworm-slim with ca-certificates.
  • Operate the container as a non-root user with a read-only root filesystem.
  • Pin base images by SHA-256 digest in the Dockerfile.
  • Scan container images with Trivy and publish a container SBOM and provenance attestation. Refer to Security scanning and Release automation.

Further reading