Learning objectives
After reading this article you will be able to:
- Write an Axum or Actix Web API that reads PORT and listens on 0.0.0.0
- Build in release mode without running the server out of memory
- Shut down gracefully and keep threads and memory in check
Rust compiles to a native binary with no garbage collector and no runtime to install on the server, and frameworks like Axum and Actix Web serve a lot of traffic on little memory. What breaks a first deploy is rarely the route code. It's the port, the listen address, a build that runs the machine out of memory, or a process that dies mid-request when the stop signal arrives.
This guide builds the same API in both frameworks, compiles it in release mode, handles shutdown and lists the most common errors. For the big picture of shipping any backend, see how to host an API; if you're still picking a language, see the best backend language.
What do you need before you start?#
- Rust installed through rustup, on the stable channel.
rustup updatebrings the latest compiler and cargo. - A project:
cargo new my-apicreatesCargo.tomlandsrc/main.rs. Add dependencies withcargo add, which writes the latest version of each crate intoCargo.toml. Cargo.lockin version control.cargo newtracks it by default, and for an application it makes the server build the exact versions you tested.- Somewhere to run it: a Linux VPS, a container or a hosting platform.
How do you write the API with Axum?#
Add Axum, Tokio (the async runtime) and serde_json:
cargo add axum serde_json
cargo add tokio --features fullThis src/main.rs reads the port from the environment, exposes a health endpoint and a route with a parameter, and shuts down cleanly on SIGTERM or Ctrl+C:
use std::{env, net::SocketAddr};
use axum::{Json, Router, extract::Path, routing::get};
use serde_json::{Value, json};
use tokio::{net::TcpListener, signal};
#[tokio::main]
async fn main() {
let port: u16 = env::var("PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(8080);
let app = Router::new()
.route("/health", get(health))
.route("/users/{id}", get(user));
let addr = SocketAddr::from(([0, 0, 0, 0], port));
let listener = TcpListener::bind(addr).await.expect("failed to bind the port");
println!("listening on {addr}");
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.expect("server error");
println!("shut down");
}
async fn health() -> Json<Value> {
Json(json!({ "status": "ok" }))
}
async fn user(Path(id): Path<String>) -> Json<Value> {
Json(json!({ "id": id }))
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c().await.expect("failed to install the Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install the SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
println!("signal received, shutting down");
}Test it on another port, the way the environment would run it:
PORT=9090 cargo run
curl -i http://localhost:9090/health0.0.0.0andPORT: listening on127.0.0.1only accepts connections from inside the same machine or container, so the host's proxy never reaches the process. The port comes from the environment; 8080 is just the local default. The reasoning is in EADDRINUSE, PORT and 0.0.0.0.- Shutdown: once
shutdown_signalcompletes,with_graceful_shutdownstops accepting new connections and waits for in-flight requests. It waits with no deadline; the official Axum example adds a tower-httpTimeoutLayerso no request can hang forever.
Routes use {id} because Axum changed its parameter syntax from /:id to /{id}. Older tutorials still use colons, and the current router panics when it registers a route like that:
Path segments must not start with `:`. For capture groups, use `{capture}`. If you meant to literally match a segment starting with a colon, call `without_v07_checks` on the router.What if you use Actix Web?#
cargo add actix-web serde_jsonuse std::env;
use actix_web::{App, HttpResponse, HttpServer, Responder, get, web};
use serde_json::json;
#[get("/health")]
async fn health() -> impl Responder {
HttpResponse::Ok().json(json!({ "status": "ok" }))
}
#[get("/users/{id}")]
async fn user(path: web::Path<String>) -> impl Responder {
HttpResponse::Ok().json(json!({ "id": path.into_inner() }))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let port: u16 = env::var("PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(8080);
let workers: usize = env::var("WORKERS")
.ok()
.and_then(|w| w.parse().ok())
.unwrap_or(2);
println!("listening on 0.0.0.0:{port} with {workers} workers");
HttpServer::new(|| App::new().service(health).service(user))
.bind(("0.0.0.0", port))?
.workers(workers)
.shutdown_timeout(20)
.run()
.await
}Actix Web handles signals for you: SIGTERM starts a graceful shutdown, while SIGINT and SIGQUIT force the workers to stop. In-flight requests get 30 seconds to finish by default, and the example's shutdown_timeout(20) lowers that. The deadline has to be shorter than the time the environment waits before sending SIGKILL.
Worker count is what trips people up in containers. By default, Actix starts one worker per CPU the system reports, and each worker builds its own copy of the App. Set the number explicitly, as the example does with the WORKERS variable.
How do you build in release mode?#
Plain cargo build produces an unoptimized debug binary that is much slower. For production:
cargo build --release --locked
./target/release/my-api--releaseuses the release profile (opt-level = 3, no debug info) and writes the binary totarget/release/, named after the package.--lockedmakes cargo fail ifCargo.lockwould need to change, instead of resolving new versions at build time.
You can tune the profile in Cargo.toml:
[profile.release]
strip = true
lto = "thin"strip = true removes symbols for a smaller binary. LTO and codegen-units = 1 can produce faster code at the cost of a longer build; measure before you adopt them.
Why does the build die from lack of memory?#
Compiling large crates in parallel can take far more RAM than the finished binary uses at runtime. On a small server or container, the system kills rustc, and cargo prints:
error: could not compile `serde` (lib)
Caused by:
process didn't exit successfully: `rustc --crate-name serde ...` (signal: 9, SIGKILL: kill)A SIGKILL with no compile error before it is the classic out-of-memory symptom (see exit code 137 and other exit codes). You have three ways out: more RAM during the build; fewer compiler processes at once with CARGO_BUILD_JOBS=1 (or cargo build -j 1), which is slower but lowers the peak; or building on another machine, such as CI, and shipping only the binary.
If you build off the server, target the same operating system and architecture: a binary built on macOS or Windows won't run on Linux, and differences in glibc version between Linux distributions can also keep it from running.
How much memory and CPU does a Rust API use?#
With no garbage collector, a Rust process's memory follows what it allocates and frees. It tends to stay flat under steady load and grows with concurrent connections, buffers and any caches you keep in memory. Measure the peak under real traffic before you size the machine; how to size RAM and CPU walks through the method.
Thread count is the sneaky part. Tokio's multi-threaded runtime starts one worker thread per core, and Actix one worker per CPU, both based on the parallelism the system reports. The Rust docs warn that on Linux, available_parallelism can overcount when a cgroup quota applies and can't be read. In a container with little CPU on a big host, you can end up with more threads than the quota allows. Pin the numbers: TOKIO_WORKER_THREADS=2 tunes Tokio without code changes, and in the Actix example the WORKERS variable does the same.
How do you check the deploy and fix common errors?#
- Logs: look for
listening on 0.0.0.0:...with the environment's port. If you see127.0.0.1, outside traffic can't get in. - Health endpoint:
curl -i https://your-domain/healthshould return200and{"status":"ok"}. - Shutdown: restart the app and check that Axum logs
signal received, shutting downfollowed byshut down. Without the second line, the process was killed before it finished.
The errors you'll see most:
| Symptom | Cause | Fix |
|---|---|---|
kind: AddrInUse (Address already in use) when binding |
Another process, or an old instance of the API, holds the port | Stop the old process or use the port from PORT |
| The log says it started, but outside connections are refused | The server listens on 127.0.0.1 |
Listen on 0.0.0.0 |
Panic with Path segments must not start with |
The route uses Axum's old syntax | Change /:id to /{id} |
(signal: 9, SIGKILL: kill) during the build |
Not enough memory to compile | More RAM, CARGO_BUILD_JOBS=1 or build on another machine |
| The app vanishes with no error after running for a while | The process was killed for using too much memory | Measure the peak and add RAM; see out of memory errors |
| Requests cut off on every deploy | Graceful shutdown is missing, or its deadline is longer than the time until SIGKILL |
Handle SIGTERM and use a shorter deadline |
Before opening it to the public, go through the API production checklist.
How to do this on Square Cloud#
On Square Cloud, you don't have to compile on your machine: upload the source code with Cargo.toml and Cargo.lock, and cargo downloads the crates and compiles in release mode on the server, using your Cargo.toml as is. Axum, Actix and Tonic are among the frameworks the runtime page lists. You can deploy with a ZIP in the dashboard, the CLI, GitHub or the VS Code extension, and the squarecloud.app file is optional: the dashboard generates it on deploy. With the CLI, squarecloud.ignore (.gitignore syntax) decides what stays out of the upload: a target/ line leaves out your local build folder, and a !Cargo.lock line makes sure the lockfile goes along.
The platform sets the PORT variable, and both examples already read it and listen on 0.0.0.0. Only port 80 receives traffic, published over HTTPS on a *.squareweb.app subdomain; a custom domain is available from the Standard plan. The proxy doesn't cut long-lived connections, so WebSocket and SSE go through.
A web app uses at least 512 MB of the plan's RAM pool, and the plan's vCPU is the ceiling for each environment. Variables such as TOKIO_WORKER_THREADS and WORKERS live in the app's settings and apply on the next restart. If the process exits with an error, auto restart (on by default when you deploy from the dashboard) brings it back; if it runs out of memory, it stops and doesn't come back on its own: add RAM and start it again. Hobby starts at R$12.49 a month, with 1 GB.
Cubic's vulnerability scanning checks crates.io crates against OSV.dev, from the lockfiles at the project root and from what the app installed. See the details of Rust hosting.
API hosting
APIs in always-on containers, with no cold starts
FAQs
Axum or Actix Web: which one should I use for a Rust API in production?
Both are production-ready, and the deploy is the same: a binary listening on a port. Axum runs on Tokio and the tower ecosystem; Actix Web ships its own server with workers and handles stop signals for you.
Do I need Rust installed on the server?
Only if you compile there. A release binary doesn't need the compiler to run, but it must be built for the server's operating system and architecture.
Why does my Rust build get killed with SIGKILL?
It's almost always memory: compiling many crates in parallel takes far more RAM than the running binary. Add memory, cut parallel jobs with CARGO_BUILD_JOBS=1, or compile on another machine.
How much memory does a Rust API use?
It depends on what it keeps in memory and how many connections it serves at once. With no garbage collector, usage tends to stay flat under steady load; measure the peak under real traffic before sizing the machine.
More in APIs
See all 36 articles- How to host an APIHosting an API means running its HTTP server around the clock at a public address with HTTPS. Step-by-step with Node.js and Python, testing and common errors.
- How to host a Node.js appTo host a Node.js app, prepare package.json, read the port and secrets from the environment, pick an LTS version and run it with node. Step-by-step guide.
- How much does it cost to host an API?Hosting a small API costs a few to a few dozen dollars a month. See what goes into the bill (compute, database, bandwidth, requests, logs) and how to estimate it.
- CORS error (blocked by CORS policy): cause and fixA CORS error means the API did not allow your page's origin. Learn the causes, how to fix it in Express and FastAPI, and how to test the preflight with curl.