404human Experience Projects Writing Build logs Learning Books Progress
Rust · Zola
zsh · 404human@dev:~ Tab complete · ↑↓ history · type help

Rust Axum + Tokio + SQLx in production: real concurrency traps

Production patterns for Rust Axum, Tokio, and SQLx: pool starvation, cancellation safety, graceful shutdown, and exact bugs we hit across five Rust services.

Published
Read time
5 min read
Kind
guide
Topics

The Rust Axum + Tokio + SQLx stack is one of the fastest, lowest-footprint ways to ship a production backend API today: compile-time SQL verification, tiny memory usage, predictable tail latency, and zero garbage-collection pauses.

Yet every team moving to axum + tokio + sqlx hits the exact same four production traps—none of which the Rust compiler warns you about. Across our built Rust services (Colophon CMS, Service Monitor, Durable Runner, and Payment Sandbox), we ran straight into all four under real traffic and load tests.

Here is how the stack fits together, the production pitfalls that actually bite, and the exact patterns that fix them.

Why Axum + Tokio + SQLx works so well together

LayerCrateWhat it ownsKey production job
HTTP router & middlewareaxum + tower-httpRouting, extractors, request body limits, concurrency limitsReject oversized or slow requests before business logic runs
Async runtimetokioCooperative task scheduling, timers, sockets, CancellationTokenKeep worker threads non-blocking and cancel cleanly on deploy
Database & migrationssqlxAsync Postgres/SQLite pool, compile-time checked queries, PgListenerKeep transactions short, bound pool wait time, survive reconnects

Trap 1: Blocking Tokio worker threads (silent latency collapse)

Tokio runs a small fixed pool of OS worker threads (typically equal to CPU cores). Every handler cooperatively yields at .await. If a handler runs CPU-heavy work (bcrypt/Argon2 password hashing, image resizing, large JSON compression) or synchronous file I/O directly inside an async fn, that worker thread freezes for every other request scheduled on it.

Fix: Push CPU-bound or blocking work onto Tokio’s dedicated blocking pool with tokio::task::spawn_blocking, and bound concurrency with a tokio::sync::Semaphore so a login burst cannot spawn 1,000 Argon2 threads and OOM your VPS:

let permit = state.hash_semaphore.clone().acquire_owned().await?;
let verified = tokio::task::spawn_blocking(move || {
    let _permit = permit;
    verify_argon2_hash(&password, &stored_hash)
})
.await??;

Trap 2: SQLx pool starvation and silent PgListener gaps

Two database mistakes break Axum services under modest load:

  1. Holding a sqlx transaction across external network I/O. If you BEGIN a Postgres transaction, call Stripe or a webhook URL that hangs for 15 seconds, and only COMMIT afterward, 20 slow webhook calls immediately exhaust a 20-connection pool and take down every unrelated read endpoint. Always commit your DB state (using an outbox row) before making outbound HTTP calls—see transactional outbox in Rust + PostgreSQL.
  2. Assuming sqlx::PgListener::recv() never drops notifications. When Postgres drops an idle connection, PgListener automatically reconnects—and recv() hides the reconnect event while silently losing every NOTIFY sent during the disconnect window! Use try_recv() so Ok(None) explicitly signals a reconnect and triggers a state resync (full post-mortem).

Always configure explicit PgPoolOptions ceilings instead of defaults:

let pool = PgPoolOptions::new()
    .max_connections(20)
    .acquire_timeout(Duration::from_secs(3))
    .idle_timeout(Duration::from_secs(300))
    .max_lifetime(Duration::from_secs(1800))
    .connect(&database_url)
    .await?;

Trap 3: Async cache races & cancellation across .await

In Rust, an Axum handler future is dropped the instant the client closes the TCP connection (or a timeout middleware fires). Anything after an .await may never run—and anything cached after an .await can overwrite newer state.

We hit a concrete security version of this across two services: Request A missed an in-memory auth cache, queried the DB across .await, and while it waited, Request B revoked that token and evicted the cache. Request A then resumed and wrote the stale “valid” token straight back into the cache—resurrecting a revoked token (exact race & generation-counter fix).

Rule: Never trust read-through caches filled across .await without a monotonic invalidation epoch/generation check, and keep critical multi-step mutations inside a single atomic SQL transaction or spawned background task rather than tying their completion to a client socket staying open.

Trap 4: hyper keep-alive timeouts & SSE graceful shutdown

Two HTTP-layer bugs only appear behind real proxies (Caddy/Nginx/Cloudflare) and during live deploys:

  • header_read_timeout killing idle keep-alive sockets: Setting hyper’s header_read_timeout without accounting for persistent HTTP/1.1 keep-alive connections causes hyper to close idle pooled sockets out from under your reverse proxy, producing random 502 or k6 status 0 errors (full teardown).
  • Open SSE streams blocking graceful shutdown: axum::serve(...).with_graceful_shutdown(...) waits for every in-flight HTTP response—including 30-minute Server-Sent Events streams! Unless you cancel your SSE CancellationToken the moment draining starts, every deploy stalls until the hard shutdown timeout kills the process. Fixing that cut our live Colophon deploy failures from 3 / 407 probes over 12.9 s down to 0 / 411 probes (measured deploy results).

Baseline Tower / Axum middleware stack

Every public Axum router we ship starts with explicit bounds before route handlers run (see our full Rust Axum production checklist):

let app = Router::new()
    .route("/healthz", get(healthz))
    .route("/api/v1/items", post(create_item))
    .layer(DefaultBodyLimit::max(1024 * 1024))           // 1 MiB body cap
    .layer(TimeoutLayer::new(Duration::from_secs(15)))   // hard request cap
    .layer(ConcurrencyLimitLayer::new(256))              // backpressure
    .with_state(state);

Pair that with sqlx acquire_timeout, spawn_blocking for crypto/CPU work, and CancellationToken for SSE and background loops—and Rust Axum + Tokio + SQLx becomes remarkably calm even under million-request load runs.

Frequently asked questions

Is Rust Axum with Tokio and SQLx ready for production web APIs? Yes. Axum, Tokio, and SQLx form a mature, low-memory, compile-time-checked Rust backend stack. Most production incidents with the stack are not framework bugs—they come from missing HTTP/DB timeouts, blocking Tokio worker threads, unbounded connection pools, or ignoring cancellation safety.

How do you prevent SQLx connection pool starvation in Axum? Never hold a SQLx database connection or transaction across an external HTTP call, slow file upload, or open SSE stream. Set explicit acquire_timeout and max_connections bounds, run short queries, and release connections before doing network I/O.

What is Tokio cancellation safety in plain terms? In Tokio, dropping a future—such as when a client disconnects or a tokio::select! branch completes—stops that future at its current .await point. If your handler held partial in-memory state or wrote half of an operation across .await without rollback or atomic commit, cancellation can leave corrupt state behind.

Related reading