Building Fast REST APIs with Axum and Tokio in Rust on Ubuntu
This deep-dive covers axum tokio rest api rust with actionable analysis, practical implications, and expert insights.
Why Axum + Tokio Is the Go-To Stack for Linux Microservices
When you need predictable low-millisecond tail latency without garbage-collection pauses or bloated container images, Rust's axum framework on top of the tokio async runtime delivers standout efficiency. A compiled release binary runs directly under systemd with single-digit megabytes of RAM and saturates multi-core Linux servers effortlessly.
Step 1: Install Rust and Initialize the Project on Ubuntu
Install the build linker and the official Rust toolchain via rustup:
sudo apt update
sudo apt install -y build-essential pkg-config libssl-dev curl
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source "$HOME/.cargo/env"
cargo new axum-tasks-api && cd axum-tasks-api
Add the core crates in Cargo.toml:
[package]
name = "axum-tasks-api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tower-http = { version = "0.6", features = ["trace", "cors", "compression-gzip", "timeout"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
Step 2: Build Typed Handlers, Shared State, and Clean Error Responses
Replace src/main.rs with a complete, thread-safe REST API featuring structured logging, request timeouts, JSON validation, custom error mapping, and graceful SIGTERM shutdown:
use axum::{
extract::{Path, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
net::SocketAddr,
sync::{Arc, RwLock},
time::Duration,
};
use tokio::signal;
use tower_http::{
compression::CompressionLayer,
timeout::TimeoutLayer,
trace::TraceLayer,
};
#[derive(Clone, Serialize)]
struct Task {
id: u64,
title: String,
done: bool,
}
#[derive(Deserialize)]
struct CreateTask {
title: String,
}
struct AppState {
next_id: RwLock<u64>,
tasks: RwLock<HashMap<u64, Task>>,
}
enum AppError {
BadRequest(String),
NotFound(String),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg),
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
};
(status, Json(serde_json::json!({ "error": message }))).into_response()
}
}
async fn health() -> &'static str {
"ok"
}
async fn list_tasks(State(state): State<Arc<AppState>>) -> Json<Vec<Task>> {
let map = state.tasks.read().expect("lock poisoned");
Json(map.values().cloned().collect())
}
async fn create_task(
State(state): State<Arc<AppState>>,
Json(payload): Json<CreateTask>,
) -> Result<(StatusCode, Json<Task>), AppError> {
let title = payload.title.trim();
if title.is_empty() || title.len() > 140 {
return Err(AppError::BadRequest("title must be 1 to 140 characters".into()));
}
let mut id_guard = state.next_id.write().expect("lock poisoned");
*id_guard += 1;
let id = *id_guard;
let task = Task {
id,
title: title.to_string(),
done: false,
};
state.tasks.write().expect("lock poisoned").insert(id, task.clone());
Ok((StatusCode::CREATED, Json(task)))
}
async fn get_task(
State(state): State<Arc<AppState>>,
Path(id): Path<u64>,
) -> Result<Json<Task>, AppError> {
let map = state.tasks.read().expect("lock poisoned");
map.get(&id)
.cloned()
.map(Json)
.ok_or_else(|| AppError::NotFound(format!("task {id} not found")))
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c().await.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
tracing::info!("Shutdown signal received, draining in-flight requests");
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_env_filter("axum_tasks_api=info,tower_http=info")
.init();
let state = Arc::new(AppState {
next_id: RwLock::new(0),
tasks: RwLock::new(HashMap::new()),
});
let app = Router::new()
.route("/health", get(health))
.route("/api/tasks", get(list_tasks).post(create_task))
.route("/api/tasks/:id", get(get_task))
.with_state(state)
.layer(CompressionLayer::new())
.layer(TimeoutLayer::new(Duration::from_secs(10)))
.layer(TraceLayer::new_for_http());
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::info!("Listening on http://{addr}");
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
Step 3: Compile in Release Mode and Test Endpoints
Build an optimized release binary and exercise the API with curl:
cargo build --release
./target/release/axum-tasks-api &
curl -s http://127.0.0.1:3000/health
curl -s -X POST http://127.0.0.1:3000/api/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Deploy Axum behind Nginx"}' | jq .
curl -s http://127.0.0.1:3000/api/tasks | jq .
Step 4: Deploy as a Hardened Systemd Service
Copy the single release binary to /usr/local/bin/axum-tasks-api and run it as an unprivileged systemd unit:
# /etc/systemd/system/axum-tasks.service
[Unit]
Description=Axum Tasks REST API
After=network-online.target
[Service]
User=www-data
Group=www-data
ExecStart=/usr/local/bin/axum-tasks-api
Restart=on-failure
RestartSec=2
NoNewPrivileges=true
ProtectSystem=strict
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Summary
Axum paired with Tokio and Tower gives Linux backend engineers compile-time safety, structured error responses, graceful shutdowns, and single-binary deployments with negligible memory overhead. Swap the in-memory RwLock map for a sqlx::PgPool and you have a rock-solid production microservice ready for high traffic.
Was this technical analysis helpful?
Your feedback informs our benchmark updates and ongoing article audits.
FAQ
Frequently Asked Questions
Structured for search engines and AI answer systems (AEO/GEO).
Axum is maintained by the Tokio team, avoids procedural macros for routing, and composes natively with the Tower middleware ecosystem (tower-http). Both are very fast; Axum is widely favored for ergonomics and Tokio alignment.
Store your sqlx::PgPool or Arc<AppState> inside Router::with_state(state) and extract it in handlers using State(state): State<Arc<AppState>>.
A typical JSON REST API compiled with cargo build --release idles at 4 to 12 MB RSS, making it ideal for 512 MB or 1 GB Linux VPS instances.
Pass .with_graceful_shutdown(shutdown_signal()) to axum::serve(), listening for both SIGINT (Ctrl+C) and SIGTERM (systemd stop) so in-flight HTTP requests finish cleanly.
More answers in our FAQ hub.
Newsletter
Practical Linux & Applied AI Newsletter
Get new tested tutorials and benchmark comparisons delivered directly to your inbox. Zero spam.
Join Weekly guides readers getting our weekly digest.
- Practical Linux administration & terminal workflows
- Tested open-source AI setups & benchmarks
- Zero spam - unsubscribe anytime