Building a high‑performance Rust backend means picking tools that let me write clear, type‑safe code while keeping latency low and throughput high. Axum gives me ergonomic routing built on Tokio, and SQLx provides compile‑time‑checked, fully async database queries, so together they let me craft scalable microservices without sacrificing developer productivity.
What makes Axum a good fit for a Rust backend?
Axum’s design follows the “tower” middleware philosophy, which means routing, extraction, and error handling are composable building blocks. I can declare routes with a single macro, and the compiler checks that request extractors match handler signatures, eliminating a whole class of runtime bugs. Because Axum sits on top of Tokio, it inherits the same event‑loop efficiency that powers the most demanding network services today.
The official documentation highlights that Axum “focuses on ergonomics and type safety” while staying “lightweight” https://github.com/tokio-rs/axum. In practice, that translates to less boilerplate than Actix‑web’s actor model and clearer async flow than Hyper alone. I find that the type system acts as a guardrail; if my handler expects a Json<User> but the client sends malformed JSON, the framework handles the parsing error before my logic even runs. This separation of concerns keeps my business logic pure and testable.
How does SQLx enable async database access?
SQLx is a pure‑Rust async driver that supports PostgreSQL, MySQL, SQLite, and MSSQL. Its most compelling feature is compile‑time query checking: I write raw SQL, run cargo sqlx prepare, and the compiler verifies column types against the database schema. This eliminates the “works on my machine” problem where a column rename in the database breaks the application only in production.
The runtime uses Tokio’s non‑blocking sockets, so each query runs without blocking the thread pool. I can also pool connections with sqlx::Pool, letting the service handle thousands of concurrent requests with a modest number of OS threads. By default, SQLx uses rustls for TLS, which is a pure Rust implementation that avoids linking against OpenSSL, simplifying cross-compilation for static binaries.
Verification note: The exact throughput gains from SQLx vs. other drivers depend on query complexity, connection pool size, and hardware; benchmarks should be run in the target environment.
Should I choose Axum + SQLx over Actix-web or Tonic?
Both Actix-web and Tonic are excellent, but the decision hinges on three practical dimensions: routing ergonomics, async DB integration, and ecosystem alignment. I often see teams default to Actix-web because it was the first high-performance Rust web framework, but the ecosystem has shifted toward the Tokio tower stack.
| Dimension | Axum + SQLx | Actix-web + SQLx | Tonic + SQLx (gRPC) |
|---|---|---|---|
| Routing syntax | Macro-based, declarative (router!) |
Builder pattern, more verbose | Service definition via protobuf |
| Compile-time SQL safety | Native support (query!) |
Same (SQLx works) | Same (SQLx works) |
| Primary protocol | HTTP (via hyper) | HTTP | gRPC only |
| Learning curve | Low for developers familiar with async/await | Moderate (actor model) | Higher (proto generation, streaming) |
| Community momentum | Rapid growth, Tokio ecosystem | Mature, but slower releases | Strong in microservice RPC world |
If my service is a classic REST/JSON API, Axum + SQLx wins on simplicity. For high‑throughput RPC between services, Tonic may be preferable, but it adds protobuf overhead and a steeper onboarding curve. I have written about the trade-offs of using Actix-web in Build High-Performance Backend APIs with Rust and Actix-Web, and for gRPC specifics, see Build High-Performance gRPC Services in Rust with Tonic. However, for general-purpose microservices, the Axum/Tokio stack offers the best balance of developer experience and performance.
Building a simple microservice: step-by-step example
Below is a minimal “todo” service that demonstrates routing, request extraction, and async DB calls. The project layout follows conventional Cargo conventions. I prefer keeping database logic in a separate module to keep the main router file clean.
my_todo_service/
├─ Cargo.toml
├─ src/
│ ├─ main.rs
│ └─ db.rs
└─ sqlx-data.json # generated by `cargo sqlx prepare`
Cargo.toml
[package]
name = "my_todo_service"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.7", features = ["json"] }
tokio = { version = "1.35", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls", "macros"] }
dotenvy = "0.15"
src/db.rs
use sqlx::{Pool, Postgres};
use sqlx::postgres::PgPoolOptions;
use std::env;
pub type DbPool = Pool<Postgres>;
pub async fn init_pool() -> DbPool {
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set in .env");
PgPoolOptions::new()
.max_connections(10)
.connect(&database_url)
.await
.expect("Failed to create DB pool")
}
src/main.rs
use axum::{
routing::{get, post},
Json, Router, extract::Extension,
response::IntoResponse,
http::StatusCode,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use dotenvy::dotenv;
use crate::db::{self, DbPool};
#[derive(Serialize, Deserialize)]
struct Todo {
id: i32,
title: String,
completed: bool,
}
#[tokio::main]
async fn main() {
dotenv().ok();
let pool = db::init_pool().await;
let app = Router::new()
.route("/todos", get(list_todos).post(create_todo))
.layer(Extension(pool));
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
println!("Listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn list_todos(Extension(pool): Extension<DbPool>) -> impl IntoResponse {
let rows = sqlx::query_as!(
Todo,
r#"SELECT id, title, completed FROM todos ORDER BY id DESC LIMIT 20"#
)
.fetch_all(&pool)
.await
.expect("Failed to fetch todos");
(StatusCode::OK, Json(rows))
}
async fn create_todo(
Json(payload): Json<Todo>,
Extension(pool): Extension<DbPool>,
) -> impl IntoResponse {
let rec = sqlx::query!(
r#"INSERT INTO todos (title, completed) VALUES ($1, $2) RETURNING id"#,
payload.title,
payload.completed
)
.fetch_one(&pool)
.await
.expect("Insert failed");
let created = Todo {
id: rec.id,
title: payload.title,
completed: payload.completed,
};
(StatusCode::CREATED, Json(created))
}
Running cargo run starts the service on port 3000. The sqlx::query! macro guarantees that the todos table has the columns we reference, and any mismatch will cause a compile‑time error. This tiny example already showcases the core benefits of a Rust backend built with Axum and SQLx. Note that I am using Extension to pass the database pool to handlers. This is a standard pattern in Axum that avoids passing the pool as a parameter to every function, keeping the handler signatures clean.
Deploying and scaling the service in production
Once the code is stable, I containerize it with Docker. The official Rust Docker image provides a multi‑stage build that yields a tiny binary. I always use a multi-stage build to keep the final image small and secure, stripping out the Rust toolchain and build dependencies.
# syntax=docker/dockerfile:1.4
FROM rust:1.78 as builder
WORKDIR /app
COPY . .
RUN apt-get update && apt-get install -y libssl-dev pkg-config
RUN cargo build --release
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates libssl3 && rm -rf /var/lib/apt/lists/*
COPY /app/target/release/my_todo_service /usr/local/bin/
EXPOSE 3000
CMD ["my_todo_service"]
I push the image to a registry and run it in Kubernetes. A typical deployment spec looks like this. I set resource limits to prevent noisy neighbors from starving the service, and I use a Secret for the database URL to avoid hardcoding credentials.
apiVersion: apps/v1
kind: Deployment
metadata:
name: todo-service
spec:
replicas: 3
selector:
matchLabels:
app: todo-service
template:
metadata:
labels:
app: todo-service
spec:
containers:
- name: app
image: ghcr.io/username/my_todo_service:latest
ports:
- containerPort: 3000
envFrom:
- secretRef:
name: todo-db-secret
resources:
limits:
cpu: "500m"
memory: "256Mi"
requests:
cpu: "250m"
memory: "128Mi"
---
apiVersion: v1
kind: Service
metadata:
name: todo-service
spec:
selector:
app: todo-service
ports:
- protocol: TCP
port: 80
targetPort: 3000
type: ClusterIP
Horizontal Pod Autoscaling (HPA) can be enabled based on CPU or request latency, letting the service scale automatically under load. Because Axum runs on Tokio’s work‑stealing scheduler, each pod can efficiently handle many concurrent connections with a modest CPU budget. I have found that Rust services often require fewer replicas than their Go or Node.js counterparts for the same QPS, which reduces infrastructure costs.
For observability, I instrument the app with tower-http’s TraceLayer and export metrics to Prometheus using axum-prometheus. The combination gives me request latency histograms and error counters without adding runtime overhead. I also recommend adding structured logging with tracing and tracing-subscriber to correlate requests across services. If you are managing complex container orchestration, tools like Arcane can simplify the workflow, as detailed in Arcane: Modern Docker Management for Enterprise Teams.
Frequently asked questions
How do I handle graceful shutdown with Axum?
Axum integrates with Tokio’s signal handling; wrapping the server in tokio::select! on ctrl_c() lets the process finish in‑flight requests before exiting. I typically set a timeout to allow long-running queries to complete.
Can I use SQLx with a connection pool across multiple services?
Yes. The pool is process‑local, but you can run a sidecar like pgbouncer to share connections across containers, reducing PostgreSQL overhead. This is especially important if you have many microservices connecting to the same database.
Does Axum support WebSockets out of the box?
Axum provides a ws extractor in the tower-http crate, allowing you to upgrade HTTP connections to WebSockets with a few lines of code. I have used this for real-time updates in dashboards without needing a separate WebSocket server.
What’s the best way to version my API?
Follow the pattern described in my earlier post on API versioning — prefix routes with /v1/, /v2/, and keep old versions alive behind a feature flag. See Mastering API Versioning for a deeper dive. This approach ensures backward compatibility while allowing you to deprecate old endpoints safely.
How does error handling differ from Actix-web?
Axum encourages returning a custom Result<T, impl IntoResponse> from handlers, letting you map any error type to an HTTP response via the IntoResponse trait. This is more explicit than Actix’s ResponseError trait hierarchy and makes it easier to test error paths.
Conclusion
Axum’s ergonomic routing, combined with SQLx’s async, compile‑time‑checked database access, gives me a Rust backend that is both fast and maintainable. By containerizing the service, leveraging Kubernetes autoscaling, and adding observability layers, I can ship production‑grade microservices that scale horizontally with minimal latency. If you’re ready to prototype your next API or need a seasoned engineer to design a full‑stack solution, feel free to get in touch.
Related reading:
Service offering:



