Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
RECIPE 01 / 8

A server with a pulse.

An Axum HTTP server with JSON health checks and graceful Ctrl+C shutdown.

BY NAVAN SAMI~25 MIN BUILDLOCAL PROJECT
Download this project ↓
Axum 0.8Tokio 1Serde 1

01 The shape of the build

Begin with a tiny service whose lifecycle you can observe. Axum routes requests to typed handlers, Tokio drives async I/O, and Serde converts the response into JSON. The service binds to loopback and waits for Ctrl+C before stopping acceptance and draining active work. A health endpoint only establishes that this process can answer; a real readiness check must reflect the dependencies your service needs.

  1. 1

    Define the health response as a typed serializable struct.

  2. 2

    Compose routes with Router and bind a Tokio listener.

  3. 3

    Attach a shutdown future instead of abruptly exiting the process.

  4. 4

    Start the service, request /health, then stop it with Ctrl+C.

02 Get it running

Install Rust stable and extract this project’s ZIP. Run these commands from the extracted signal-server folder. The full workbench keeps it under cookbook/signal-server.

terminal
cargo run
# In another terminal:
curl http://127.0.0.1:3000/health
WHAT YOU SHOULD SEE

GET / returns Build Lab / Rust. GET /health returns {"status":"ok","service":"signal-server"}. Ctrl+C prints shutdown requested and allows the server to stop.

First builds download dependencies. The included Cargo.lock files record the versions resolved during authoring. Use --locked with Cargo commands when you want to enforce those resolutions.

03 The complete source

Every source file below is also in the download. Start with the manifest, then follow the Rust entry point and any UI or test files.

Cargo.toml11 lines +
Cargo.toml
[package]
name = "signal-server"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal"] }
serde = { version = "1", features = ["derive"] }

[workspace]
src/main.rs36 lines +
src/main.rs
use axum::{Json, Router, routing::get};
use serde::Serialize;
#[derive(Serialize)]
struct Health {
    status: &'static str,
    service: &'static str,
}
async fn health() -> Json<Health> {
    Json(Health {
        status: "ok",
        service: "signal-server",
    })
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new()
        .route("/", get(|| async { "Build Lab / Rust" }))
        .route("/health", get(health));
    let address: std::net::SocketAddr = std::env::var("LAB_ADDRESS")
        .unwrap_or_else(|_| "127.0.0.1:3000".into())
        .parse()?;
    if !address.ip().is_loopback() {
        return Err("this recipe requires a loopback address".into());
    }
    let listener = tokio::net::TcpListener::bind(address).await?;
    println!("Signal server: http://{address}");
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            if let Err(error) = tokio::signal::ctrl_c().await {
                eprintln!("signal error: {error}");
            }
            println!("shutdown requested");
        })
        .await?;
    Ok(())
}

04 Check the behavior

  • □curl /health returns HTTP 200 and the expected JSON fields.
  • □An unknown route returns HTTP 404.
  • □Ctrl+C stops the process without leaving the port occupied.

05 Know what you are building on

Health is process liveness, not a database readiness check.

No authentication, TLS termination, persistence, or deployment supervisor is configured.

Graceful draining is not given a forced deadline here; long-lived connections would need one.

MAKE IT YOUR OWN

Choose one boundary to improve. Write down the new behavior, add a test that demonstrates it, then change the implementation. Keep the original working path intact.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.