Why We Used Rust, Axum, and SQLx FOR UPDATE Locking to Hit 8,420 RPS at 3.82ms P95 Latency
Shafikul Islam
Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

The Tail-Latency Problem Under Heavy Order Contention
When thousands of buyers hit a checkout endpoint at the same time, average latency is a vanity metric. What actually breaks checkout conversion is P95 and P99 tail latency.
In garbage-collected runtimes, sudden 10x bursts in concurrent order validation and inventory locking often trigger stop-the-world GC pauses right when database row locks are held. Even a 45ms GC pause inside an active transaction increases lock hold time, causing a queue buildup across every waiting connection in the pool.
When we architected our high-throughput e-commerce order engine, our goal was not just a high peak request rate. Our goal was flat, predictable P95 latency under heavy write contention.
We built the core checkout service in Rust using Axum 0.7, Tokio, and SQLx backed by PostgreSQL 16. Under verified load testing, the service sustained 8,420 requests per second (RPS) at 3.82ms P95 latency with zero inventory over-selling.
1. Compile-Time Verified SQL with SQLx and Pessimistic Row Locking
ORM layers often hide expensive query patterns behind innocent-looking method calls. We used SQLx so every SQL query is type-checked directly against the live PostgreSQL schema at compile time. If a column type or nullability constraint changes in a migration, the Rust binary refuses to compile.
To prevent race conditions when two concurrent orders attempt to reserve the same SKU, we used explicit SELECT ... FOR UPDATE row-level locking scoped to the exact inventory row inside a short-lived transaction:
use sqlx::{Postgres, Transaction};
use uuid::Uuid;
pub async fn reserve_inventory_sku(
tx: &mut Transaction<'_, Postgres>,
sku_id: Uuid,
requested_qty: i32,
) -> Result<i32, AppError> {
let row = sqlx::query!(
r#"
SELECT available_qty
FROM inventory_items
WHERE id = $1
FOR UPDATE
"#,
sku_id
)
.fetch_optional(&mut **tx)
.await?
.ok_or(AppError::SkuNotFound)?;
if row.available_qty < requested_qty {
return Err(AppError::InsufficientInventory {
available: row.available_qty,
requested: requested_qty,
});
}
let updated = sqlx::query!(
r#"
UPDATE inventory_items
SET available_qty = available_qty - $2,
updated_at = NOW()
WHERE id = $1
RETURNING available_qty
"#,
sku_id,
requested_qty
)
.fetch_one(&mut **tx)
.await?;
Ok(updated.available_qty)
}
Why Deterministic Lock Ordering Matters
If a cart contains multiple SKUs (for example, SKU B and SKU A), locking them in the order the client sent them can immediately cause a PostgreSQL deadlock when another user checks out with SKU A and SKU B in reverse order.
Before opening the transaction, we sort all SKU UUIDs in ascending lexicographical order in memory. Every concurrent worker acquires row locks in the exact same sequence, reducing deadlock errors to 0.00%.
2. Keeping Transactions Sub-Millisecond
A pessimistic FOR UPDATE lock is only fast if the transaction holding it does zero network I/O outside the database.
We enforced three strict rules on the checkout hot path:
- Zero external HTTP calls inside a database transaction: Payment gateway intent creation and webhook signing happen outside the SQL transaction boundary using idempotency keys.
- Bounded connection pool sizing: We tuned the SQLx Postgres pool to match physical CPU cores rather than setting an arbitrary high connection limit that causes PostgreSQL context-switching thrash.
- Zero heap allocations on validation paths: Request payloads are validated using borrowed slices where possible before touching the database pool.
use axum::{extract::State, Json};
use std::sync::Arc;
pub async fn create_order_handler(
State(state): State<Arc<AppState>>,
Json(mut payload): Json<CreateOrderRequest>,
) -> Result<Json<OrderResponse>, AppError> {
payload.items.sort_by_key(|item| item.sku_id);
let mut tx = state.db_pool.begin().await?;
for item in &payload.items {
reserve_inventory_sku(&mut tx, item.sku_id, item.quantity).await?;
}
let order_id = insert_order_record(&mut tx, &payload).await?;
tx.commit().await?;
Ok(Json(OrderResponse {
order_id,
status: "RESERVED",
}))
}
3. Fast CI Builds with Cargo-Chef Multi-Stage Containers
One common complaint about Rust in production is slow Docker build times in CI/CD pipelines. Recompiling the entire crate dependency tree on every commit wastes 12 to 18 minutes per deploy.
We solved this using cargo-chef in a multi-stage Dockerfile so third-party crates are compiled and cached in a dedicated layer that only invalidates when Cargo.toml or Cargo.lock changes:
FROM lukemathwalker/cargo-chef:latest-rust-1.80 AS chef
WORKDIR /app
FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
RUN cargo build --release --bin ecommerce-core
FROM debian:bookworm-slim AS runtime
WORKDIR /app
COPY --from=builder /app/target/release/ecommerce-core /usr/local/bin/ecommerce-core
ENTRYPOINT ["/usr/local/bin/ecommerce-core"]
Verified Production Benchmark Results
Under sustained load testing against the containerized Axum + SQLx service and PostgreSQL 16:
- Sustained Throughput: 8,420 requests per second (RPS)
- P95 Latency: 3.82ms
- Inventory Over-Selling: 0.00% across concurrent multi-item cart checkouts
- Runtime Memory Footprint: Under 42 MB RSS under full load
You do not need Rust for every internal admin CRUD service. When a single hot path governs revenue, inventory integrity, and tail latency under burst load, combining Axum, SQLx compile-time checks, and sorted pessimistic locking delivers predictable performance without over-provisioning cloud hardware.