Rust Playbook

Course › Week 5 · Axum microservice › Day 3 · lesson 31 of 42 · 20 min reading + 45 min practice

Shared state

A database pool every handler can use, with State.

StateAppStatePgPool

On this page
  1. 1. AppState and State
  2. 2. Why cloning the state is cheap
  3. 3. Arc for settings
  4. 4. A counter every request can change
  5. In Laravel, the container does this
  6. Practice
  7. Remember

A Laravel controller reaches the database through a facade or an injected service; the container builds them once and hands them out. axum has no container. Instead, you build the things every handler needs once, in main, put them in one struct, and give it to the router. A handler that needs it asks for it with an extractor, like Path or Json.

The handlers today read the worker’s evaluations table from the real Postgres database, reset before each server starts.

1. AppState and State

AppState holds what handlers share: here the PgPool from the sqlx lesson. Router::with_state(state) gives it to every route, and State(state): State<AppState> takes it out in a handler. axum hands each request its own clone, which is why AppState derives Clone.

src/main.rs
use std::env;
use std::error::Error;

use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
use sqlx::PgPool;
use tokio::net::TcpListener;

#[derive(Clone)]
struct AppState {
    pool: PgPool,
}

#[derive(Serialize, sqlx::FromRow)]
struct Evaluation {
    id: i64,
    school: String,
    status: String,
    average_tenths: Option<i32>,
}

async fn show(
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<Evaluation>, StatusCode> {
    let found: Option<Evaluation> =
        sqlx::query_as("select id, school, status, average_tenths from evaluations where id = $1")
            .bind(id)
            .fetch_optional(&state.pool)
            .await
            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    found.map(Json).ok_or(StatusCode::NOT_FOUND)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
    let state = AppState { pool };

    let app = Router::new()
        .route("/evaluations/{id}", get(show))
        .with_state(state);

    let listener = TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}
$ curl -si http://127.0.0.1:3000/evaluations/1042
HTTP/1.1 200 OK
content-type: application/json
content-length: 78

{"id":1042,"school":"Alexandria STEM","status":"analysed","average_tenths":43}
$ curl -si http://127.0.0.1:3000/evaluations/1043
HTTP/1.1 200 OK
content-type: application/json
content-length: 85

{"id":1043,"school":"Cairo Language School","status":"pending","average_tenths":null}
$ curl -si http://127.0.0.1:3000/evaluations/9999
HTTP/1.1 404 Not Found
content-length: 0

found.map(Json) wraps the evaluation in Json if there is one: a function, Json, used where a closure is expected, as map(normalise) was in csv2json. Then ok_or turns None into the 404.

map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) throws the database error away, so nobody would ever know what went wrong. That is the errors lesson: an error type that logs the detail and answers 500.

average_tenths is null for the pending evaluation: an Option field serialises None as JSON null.

2. Why cloning the state is cheap

Cloning AppState for every request sounds expensive. It is not, because of what is inside. A PgPool is a handle: a pointer to the real pool, shared by every clone. The same is true of reqwest’s Client. Cloning one copies a pointer and adds one to a counter, the atomic reference count that Arc stands for (the rayon lesson).

In AppStateA clone copiesShared by all clones
PgPoola pointerthe connections
reqwest::Clienta pointerthe connection pool, the settings
Arc<Config>a pointerthe config struct
String, Vec<…> directlyall of it, every requestnothing

So the rule for AppState: handles and Arcs, not plain data. Settings that are read-only for the life of the server go in one Arc<Config>.

3. Arc for settings

Arc::new(config) puts the config on the heap once; each clone of the state shares it. Inside a handler, state.config.max_batch reads through the Arc without any special syntax.

src/main.rs
use std::env;
use std::error::Error;
use std::sync::Arc;

use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use tokio::net::TcpListener;

struct Config {
    max_page: i64,
}

#[derive(Clone)]
struct AppState {
    pool: PgPool,
    config: Arc<Config>,
}

#[derive(Serialize, sqlx::FromRow)]
struct Evaluation {
    id: i64,
    school: String,
    status: String,
    average_tenths: Option<i32>,
}

#[derive(Deserialize)]
struct Filters {
    status: Option<String>,
    limit: Option<i64>,
}

async fn index(
    State(state): State<AppState>,
    Query(filters): Query<Filters>,
) -> Result<Json<Vec<Evaluation>>, StatusCode> {
    let limit = filters.limit.unwrap_or(50).clamp(1, state.config.max_page);
    let rows: Vec<Evaluation> = sqlx::query_as(
        "select id, school, status, average_tenths from evaluations
         where ($1::text is null or status = $1) order by id limit $2",
    )
    .bind(filters.status)
    .bind(limit)
    .fetch_all(&state.pool)
    .await
    .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(Json(rows))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let state = AppState {
        pool: PgPool::connect(&env::var("DATABASE_URL")?).await?,
        config: Arc::new(Config { max_page: 2 }),
    };

    let app = Router::new()
        .route("/evaluations", get(index))
        .with_state(state);

    let listener = TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}
$ curl -si http://127.0.0.1:3000/evaluations
HTTP/1.1 200 OK
content-type: application/json
content-length: 166

[{"id":1042,"school":"Alexandria STEM","status":"analysed","average_tenths":43},{"id":1043,"school":"Cairo Language School","status":"pending","average_tenths":null}]
$ curl -si 'http://127.0.0.1:3000/evaluations?status=pending'
HTTP/1.1 200 OK
content-type: application/json
content-length: 164

[{"id":1043,"school":"Cairo Language School","status":"pending","average_tenths":null},{"id":1044,"school":"Giza Primary","status":"pending","average_tenths":null}]
$ curl -si 'http://127.0.0.1:3000/evaluations?status=pending&limit=1'
HTTP/1.1 200 OK
content-type: application/json
content-length: 87

[{"id":1043,"school":"Cairo Language School","status":"pending","average_tenths":null}]

($1::text is null or status = $1): one query that filters only when a status is given. Binding None sends SQL NULL. max_page is 2 here so the cap is visible: the first request asked for the default 50 and got 2.

4. A counter every request can change

State shared by many requests at once can only be changed safely. For a number, an atomic integer is the simplest: fetch_add increments it as one indivisible step, so two requests adding at the same time both count. It goes in an Arc like the config, and needs no mut: atomics change through a shared reference by design.

src/main.rs
use std::error::Error;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use axum::extract::State;
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
use tokio::net::TcpListener;

#[derive(Clone)]
struct AppState {
    batches_received: Arc<AtomicU64>,
}

#[derive(Serialize)]
struct Stats {
    batches_received: u64,
}

async fn receive(State(state): State<AppState>) -> &'static str {
    state.batches_received.fetch_add(1, Ordering::Relaxed);
    "received"
}

async fn stats(State(state): State<AppState>) -> Json<Stats> {
    Json(Stats {
        batches_received: state.batches_received.load(Ordering::Relaxed),
    })
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let state = AppState {
        batches_received: Arc::new(AtomicU64::new(0)),
    };
    let app = Router::new()
        .route("/receive", get(receive))
        .route("/stats", get(stats))
        .with_state(state);

    let listener = TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}
$ curl -si http://127.0.0.1:3000/receive
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 8

received
$ curl -si http://127.0.0.1:3000/receive
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 8

received
$ curl -si http://127.0.0.1:3000/receive
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 8

received
$ curl -si http://127.0.0.1:3000/stats
HTTP/1.1 200 OK
content-type: application/json
content-length: 22

{"batches_received":3}

Ordering::Relaxed says the counter does not need to be in step with any other memory, which is true for a statistic. Read it as “just count”.

A counter in memory is lost on restart and is per server: two instances behind a load balancer each have their own. Anything that must survive, or be the same everywhere, goes in the database. That is why the service’s batches will live in a table, not in a HashMap in AppState.

In Laravel, the container does this

app/Providers/AppServiceProvider.php (part of register)
<?php

use App\Services\Analysis\AnalysisClient;

$this->app->singleton(AnalysisClient::class, fn () => new AnalysisClient(
    baseUrl: config('services.analysis.url'),
    timeout: (int) config('services.analysis.timeout', 10),
));

// …and any controller can then ask for it:
// public function show(AnalysisClient $client, int $id) { … }

Same idea, built once and handed out. The differences: Laravel’s container resolves anything by type at runtime, while axum’s state is one struct the compiler checks, so a handler asking for something that is not in it does not compile. And a PHP request starts from scratch each time, so “shared state” means the cache or the database; a Rust service keeps its pool and clients alive between requests, which is where much of its speed comes from.

PracticeThe axum State docs, and a status summary

Read the State extractor docs, including “Substates”.

Exercise: a status summary

Add GET /evaluations/summary returning {"pending": 2, "analysed": 1}: one group by status query into a Vec<(String, i64)>, collected into a BTreeMap<String, i64> for the response. Register the route before /evaluations/{id} and check whether the order matters in axum.

Show the solution
src/main.rs
use std::collections::BTreeMap;
use std::env;
use std::error::Error;

use axum::extract::State;
use axum::http::StatusCode;
use axum::routing::get;
use axum::{Json, Router};
use sqlx::PgPool;
use tokio::net::TcpListener;

#[derive(Clone)]
struct AppState {
    pool: PgPool,
}

async fn summary(State(state): State<AppState>) -> Result<Json<BTreeMap<String, i64>>, StatusCode> {
    let rows: Vec<(String, i64)> =
        sqlx::query_as("select status, count(*) from evaluations group by status")
            .fetch_all(&state.pool)
            .await
            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(Json(rows.into_iter().collect()))
}

async fn show() -> &'static str {
    "one evaluation"
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let state = AppState {
        pool: PgPool::connect(&env::var("DATABASE_URL")?).await?,
    };
    let app = Router::new()
        .route("/evaluations/{id}", get(show))
        .route("/evaluations/summary", get(summary))
        .with_state(state);

    let listener = TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}
$ curl -si http://127.0.0.1:3000/evaluations/summary
HTTP/1.1 200 OK
content-type: application/json
content-length: 26

{"analysed":1,"pending":2}
$ curl -si http://127.0.0.1:3000/evaluations/1042
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
content-length: 14

one evaluation

The routes are registered the “wrong” way round on purpose, and it does not matter: axum picks the most specific match, so the fixed path summary wins over {id}. In Laravel, the order of the route file decides, and /evaluations/{id} first would swallow summary.

Remember

  • Build what handlers share once in main, put it in a Clone state struct, and hand it to the router with with_state.
  • Share settings with Arc, counters with atomics; a PgPool is already a cheap handle.

Tomorrow: one AppError type that turns every failure into the right status and a JSON body, and logs what the client must not see.