Course › Week 5 · Axum microservice › Day 6 · lesson 34 of 42 · 1 h 40 min reading + 2–3 h practice
Build the service
POST a batch, poll its status, and Laravel calls it with Http.
On this page
- The task
- The design
- The tables, as Laravel creates them
- Step 1: config
- Step 2: errors
- Step 3: the database
- Step 4: one batch in the background
- Step 5: work after the response
- Step 6: the routes
- Step 7: lib.rs and main.rs
- Run the tests
- Run it: one click
- When things go wrong
- The Laravel side
- The worker or the service?
- Practice
- Remember
This week’s tool turns the Week 4 worker into a service. The analysis code stays the same; what changes is how Laravel reaches it: over HTTP, with an answer in milliseconds, instead of a process that runs for minutes.
It joins every lesson of the week: routing, validated JSON, shared state, errors as responses and middleware. The one new idea is in step 5: work that goes on after the response has been sent.
The Rust side was built and run here for real, against Postgres 16 and the Laravel-style API on 127.0.0.1:8000. As in the worker lesson, the PHP side is syntax-checked but not executed on this machine.
#dashboardMonday 11:20
Sara · productSchools keep asking for an Analyse now button. Right now they wait for the nightly run at 02:00 to see the results of an evaluation they closed in the morning.
Omar · backendI can’t start the worker from a web request: a big batch takes minutes and the request dies at 30 seconds. I need a small HTTP service. I post the ids, get a batch id back at once, and a queued job polls until it’s done.
Omar · backendTwo things I care about. Our Http client retries on timeouts, so a retried POST must not start a second batch. And a deploy must not lose a batch that was half-way through.
The design
One click, start to finish:
| Step | Where | Lesson |
|---|---|---|
| The button posts the evaluation ids | Laravel: controller | |
POST /batches with a unique reference and the ids, and an API key | Laravel: Http facade | Middleware |
Validate, store the batch as queued, answer 202 with its id | Rust: handler | JSON, state |
| Analyse it in the background, at most two batches at a time | Rust: a spawned task | Step 5 |
| Save every result, every failure and the batch’s status in one transaction | Rust | The worker |
GET /batches/{id} every 5 seconds until it is done or failed | Laravel: queued job | Routing |
Retries. The reference is unique in the database. A retried POST with the same reference finds the batch already there and gets it back with 200, instead of creating a second one. That is how Stripe’s idempotency keys work, and the errors lesson showed why the database, not the code, has to be the judge.
Deploys. A batch’s status is written before the work starts. When the service starts, it picks up every batch still queued or running and runs it again. Because the results are saved in one transaction, a batch cut off half-way saved nothing, so running it again from the start is safe.
analysis-service/
├── Cargo.toml
└── src/
├── main.rs (logging, startup, resuming batches, serving, shutdown)
├── lib.rs (AppState, and the modules)
├── config.rs (DATABASE_URL, ANALYSIS_URL, SERVICE_API_KEY, …)
├── error.rs (AppError for requests, StartError for startup)
├── db.rs (batches, failures, answers, the one save transaction)
├── analysis.rs (the analysis API client: the worker’s file)
├── process.rs (one batch in the background)
└── routes.rs (the router, the API key check, the handlers)
lib.rs and main.rs are split as in the worker. Here it pays off in the checkpoint: the tests call the router from lib.rs without starting a server.
The tables, as Laravel creates them
evaluations and answers are the worker’s. The two new tables belong to the service, but the migration lives in Laravel, which owns the schema:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('analysis_batches', function (Blueprint $table) {
$table->id();
$table->string('reference', 100)->unique(); // the retry key
$table->string('status', 20)->default('queued'); // queued → running → done | failed
$table->integer('total');
$table->integer('analysed')->default(0);
$table->integer('failed')->default(0);
$table->string('error')->nullable();
$table->timestamps();
});
// A Postgres bigint[]: the batch's ids, sorted and without duplicates.
DB::statement('alter table analysis_batches add column evaluation_ids bigint[] not null');
Schema::create('analysis_batch_failures', function (Blueprint $table) {
$table->id();
$table->foreignId('batch_id')->constrained('analysis_batches');
$table->unsignedBigInteger('evaluation_id');
$table->string('reason');
$table->boolean('retryable');
});
}
};
Laravel’s schema builder has no array column, hence the one DB::statement. The sample data is the worker’s: five evaluations, of which 1044 has no answers.
Step 1: config
The worker’s Config, plus the address to listen on and the API key. A short key is refused at startup: the service will not run with a key like secret. The analysis concurrency keeps the worker’s rule, 1 to 64.
ConfigError is its own small enum this time, because two different error types use it: StartError in step 2 wraps it.
use std::env;
use thiserror::Error;
/// Everything the service needs from its environment, checked once at startup.
pub struct Config {
pub address: String,
pub database_url: String,
pub analysis_url: String,
pub api_key: String,
pub concurrency: usize,
}
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("{0} is not set")]
Missing(&'static str),
#[error("{name} {rule}")]
Invalid {
name: &'static str,
rule: &'static str,
},
}
impl Config {
pub fn from_env() -> Result<Config, ConfigError> {
let api_key = required("SERVICE_API_KEY")?;
if api_key.len() < 16 {
return Err(ConfigError::Invalid {
name: "SERVICE_API_KEY",
rule: "must be at least 16 characters",
});
}
let concurrency = match env::var("ANALYSIS_CONCURRENCY") {
Err(_) => 8,
Ok(value) => match value.trim().parse::<usize>() {
Ok(n) if (1..=64).contains(&n) => n,
_ => {
return Err(ConfigError::Invalid {
name: "ANALYSIS_CONCURRENCY",
rule: "must be a whole number from 1 to 64",
});
}
},
};
Ok(Config {
address: env::var("SERVICE_ADDRESS").unwrap_or_else(|_| String::from("127.0.0.1:3000")),
database_url: required("DATABASE_URL")?,
analysis_url: required("ANALYSIS_URL")?,
api_key,
concurrency,
})
}
}
fn required(name: &'static str) -> Result<String, ConfigError> {
match env::var(name) {
Ok(value) if !value.trim().is_empty() => Ok(value),
_ => Err(ConfigError::Missing(name)),
}
}
Step 2: errors
AppError is the errors lesson’s type with everything the week added: Unauthenticated for the key check, Invalid for validation (the 422 body from the JSON lesson), and Rejected for a body axum could not read. #[from] writes the From impls for those two, so ? works on them in a handler.
StartError is the other side: everything that stops the service from starting. main logs it in one line and exits with 1, so systemd or Docker reports a failed start instead of a crash.
use axum::Json;
use axum::extract::rejection::JsonRejection;
use axum::http::header::RETRY_AFTER;
use axum::http::{HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use serde::Serialize;
use std::collections::BTreeMap;
use thiserror::Error;
use tracing::error;
use validator::ValidationErrors;
use crate::config::ConfigError;
/// Every way a request can fail, and the response each one becomes.
#[derive(Debug, Error)]
pub enum AppError {
#[error("Unauthenticated.")]
Unauthenticated,
#[error("{0} not found.")]
NotFound(&'static str),
#[error("{0}")]
Conflict(&'static str),
#[error("{0}")]
Rejected(#[from] JsonRejection),
#[error("The given data was invalid.")]
Invalid(#[from] ValidationErrors),
#[error("The service is temporarily unavailable. Try again shortly.")]
Unavailable,
#[error("internal error: {0}")]
Internal(String),
}
#[derive(Serialize)]
struct Message {
message: String,
}
/// The body Laravel sends with a 422: the first message, and every message per field.
#[derive(Serialize)]
struct Invalid {
message: String,
errors: BTreeMap<String, Vec<String>>,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::Unauthenticated => StatusCode::UNAUTHORIZED,
AppError::NotFound(_) => StatusCode::NOT_FOUND,
AppError::Conflict(_) => StatusCode::CONFLICT,
AppError::Rejected(rejection) => rejection.status(),
AppError::Invalid(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
AppError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
let mut response = match self {
AppError::Invalid(errors) => (status, Json(invalid(&errors))).into_response(),
AppError::Rejected(rejection) => (
status,
Json(Message {
message: rejection.body_text(),
}),
)
.into_response(),
// The detail goes to the log for us, never to the client.
AppError::Internal(detail) => {
error!(%detail, "request failed");
(
status,
Json(Message {
message: String::from("Server Error"),
}),
)
.into_response()
}
other => (
status,
Json(Message {
message: other.to_string(),
}),
)
.into_response(),
};
if status == StatusCode::SERVICE_UNAVAILABLE {
response
.headers_mut()
.insert(RETRY_AFTER, HeaderValue::from_static("5"));
}
response
}
}
fn invalid(errors: &ValidationErrors) -> Invalid {
let mut fields: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (field, list) in errors.field_errors() {
let messages = list
.iter()
.map(|e| {
e.message
.as_deref()
.unwrap_or("The value is invalid.")
.to_string()
})
.collect();
fields.insert(field.to_string(), messages);
}
let message = fields
.values()
.next()
.and_then(|messages| messages.first())
.cloned()
.unwrap_or_else(|| String::from("The given data was invalid."));
Invalid {
message,
errors: fields,
}
}
/// So that ? works on any sqlx call in a handler.
impl From<sqlx::Error> for AppError {
fn from(error: sqlx::Error) -> AppError {
match error {
sqlx::Error::PoolTimedOut => AppError::Unavailable,
other => AppError::Internal(other.to_string()),
}
}
}
/// Everything that stops the service from starting.
#[derive(Debug, Error)]
pub enum StartError {
#[error("configuration: {0}")]
Config(#[from] ConfigError),
#[error("database: {0}")]
Database(#[from] sqlx::Error),
#[error("HTTP client: {0}")]
Http(#[from] reqwest::Error),
#[error("network: {0}")]
Io(#[from] std::io::Error),
}
Rejected keeps axum’s own status (400, 415 or 422), from rejection.status(), and only changes the body to JSON, so Laravel can read every error the same way.
Step 3: the database
create_batch is the retry rule in SQL. on conflict (reference) do nothing inserts the batch, or does nothing if the reference is taken; returning then gives back a row only when it inserted. No row means a retry, so the existing batch is read and returned with false. Two requests with the same reference at the same moment cannot both insert: the unique index decides.
finish is the worker’s save, grown: the results, the failures and the batch’s done status are written in one transaction. Either Laravel sees done with every result saved, or it sees no change at all.
use serde::Serialize;
use sqlx::PgPool;
/// A batch as Laravel sees it when it polls.
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct Batch {
pub id: i64,
pub reference: String,
pub status: String,
pub total: i32,
pub analysed: i32,
pub failed: i32,
pub error: Option<String>,
#[serde(skip)]
pub evaluation_ids: Vec<i64>,
/// Loaded by failures(), not by the batch query.
#[sqlx(skip)]
pub failures: Vec<Failed>,
}
/// An evaluation of the batch that was not analysed, and whether sending it again may work.
#[derive(Debug, PartialEq, Serialize, sqlx::FromRow)]
pub struct Failed {
pub evaluation_id: i64,
pub reason: String,
pub retryable: bool,
}
/// One answer, as Laravel stored it.
#[derive(sqlx::FromRow)]
pub struct Answer {
pub evaluation_id: i64,
pub score: i16,
pub comment: Option<String>,
}
/// The result for one evaluation, ready to be written.
#[derive(Debug, PartialEq)]
pub struct Analysed {
pub id: i64,
pub average_tenths: i32,
pub positive: i32,
pub negative: i32,
pub neutral: i32,
}
/// Creates the batch, or returns the one that already has this reference, and whether it is new.
pub async fn create_batch(
pool: &PgPool,
reference: &str,
ids: &[i64],
) -> Result<(Batch, bool), sqlx::Error> {
let total = i32::try_from(ids.len()).unwrap_or(i32::MAX);
let created: Option<Batch> = sqlx::query_as(
"insert into analysis_batches (reference, evaluation_ids, total, created_at, updated_at)
values ($1, $2, $3, now(), now())
on conflict (reference) do nothing
returning id, reference, status, total, analysed, failed, error, evaluation_ids",
)
.bind(reference)
.bind(ids)
.bind(total)
.fetch_optional(pool)
.await?;
if let Some(batch) = created {
return Ok((batch, true));
}
let existing: Batch = sqlx::query_as(
"select id, reference, status, total, analysed, failed, error, evaluation_ids
from analysis_batches where reference = $1",
)
.bind(reference)
.fetch_one(pool)
.await?;
Ok((existing, false))
}
pub async fn find_batch(pool: &PgPool, id: i64) -> Result<Option<Batch>, sqlx::Error> {
sqlx::query_as(
"select id, reference, status, total, analysed, failed, error, evaluation_ids
from analysis_batches where id = $1",
)
.bind(id)
.fetch_optional(pool)
.await
}
/// The batch's failed evaluations, in id order.
pub async fn failures(pool: &PgPool, batch_id: i64) -> Result<Vec<Failed>, sqlx::Error> {
sqlx::query_as(
"select evaluation_id, reason, retryable from analysis_batch_failures
where batch_id = $1 order by evaluation_id",
)
.bind(batch_id)
.fetch_all(pool)
.await
}
/// Batches a previous run of the service accepted and did not finish.
pub async fn unfinished(pool: &PgPool) -> Result<Vec<i64>, sqlx::Error> {
sqlx::query_scalar(
"select id from analysis_batches where status in ('queued', 'running') order by id",
)
.fetch_all(pool)
.await
}
/// Marks the batch as running and returns its evaluation ids.
pub async fn start(pool: &PgPool, batch_id: i64) -> Result<Vec<i64>, sqlx::Error> {
sqlx::query_scalar(
"update analysis_batches set status = 'running', updated_at = now()
where id = $1 returning evaluation_ids",
)
.bind(batch_id)
.fetch_one(pool)
.await
}
/// The ids among ids that exist, and all their answers.
pub async fn load(pool: &PgPool, ids: &[i64]) -> Result<(Vec<i64>, Vec<Answer>), sqlx::Error> {
let known: Vec<i64> = sqlx::query_scalar("select id from evaluations where id = any($1)")
.bind(ids)
.fetch_all(pool)
.await?;
let answers: Vec<Answer> = sqlx::query_as(
"select evaluation_id, score, comment from answers
where evaluation_id = any($1) order by evaluation_id, id",
)
.bind(ids)
.fetch_all(pool)
.await?;
Ok((known, answers))
}
/// Writes every result, every failure and the batch's counts in one transaction: all of it, or none.
pub async fn finish(
pool: &PgPool,
batch_id: i64,
results: &[Analysed],
failed: &[Failed],
) -> Result<(), sqlx::Error> {
let mut tx = pool.begin().await?;
for r in results {
sqlx::query(
"update evaluations
set status = 'analysed', average_tenths = $2, positive = $3, negative = $4,
neutral = $5, analysed_at = now(), updated_at = now()
where id = $1",
)
.bind(r.id)
.bind(r.average_tenths)
.bind(r.positive)
.bind(r.negative)
.bind(r.neutral)
.execute(&mut *tx)
.await?;
}
for f in failed {
sqlx::query(
"insert into analysis_batch_failures (batch_id, evaluation_id, reason, retryable)
values ($1, $2, $3, $4)",
)
.bind(batch_id)
.bind(f.evaluation_id)
.bind(&f.reason)
.bind(f.retryable)
.execute(&mut *tx)
.await?;
}
let analysed = i32::try_from(results.len()).unwrap_or(i32::MAX);
let failed = i32::try_from(failed.len()).unwrap_or(i32::MAX);
sqlx::query(
"update analysis_batches
set status = 'done', analysed = $2, failed = $3, updated_at = now()
where id = $1",
)
.bind(batch_id)
.bind(analysed)
.bind(failed)
.execute(&mut *tx)
.await?;
tx.commit().await
}
/// Records why a batch stopped. message is shown to Laravel, so it holds no internal detail.
pub async fn fail(pool: &PgPool, batch_id: i64, message: &str) -> Result<(), sqlx::Error> {
sqlx::query(
"update analysis_batches set status = 'failed', error = $2, updated_at = now() where id = $1",
)
.bind(batch_id)
.bind(message)
.execute(pool)
.await?;
Ok(())
}
#[sqlx(skip)] leaves failures out of the row mapping, so the same struct can hold what a second query loads. #[serde(skip)] leaves evaluation_ids out of the JSON: Laravel already has them, and a batch of 500 ids would make every poll 500 numbers longer.
analysis.rs is not shown: it is the worker’s file, with only the user agent changed to analysis-service/0.1. Step 4 of the worker explains it.
Step 4: one batch in the background
analyse is the worker’s run, line for line, with two changes. It reads the batch’s ids from the database instead of stdin. And failures carry their evaluation_id and go into the batch, so Laravel can send the retryable ones again.
run is the part that is new. It is what the handler will spawn, so it returns nothing: there is no caller waiting for an answer. Every outcome therefore has to end somewhere you can see it, in the log and in the batch’s status. A failed batch gets a short message for Laravel; the detail is only in the log.
use futures::stream::{self, StreamExt};
use thiserror::Error;
use tracing::{error, info};
use crate::AppState;
use crate::analysis::{Failure, Sentiment};
use crate::db::{self, Analysed, Answer, Failed};
/// Why a whole batch stopped. One evaluation that cannot be analysed is not one of these:
/// it is counted in the batch's "failed".
#[derive(Debug, Error)]
enum BatchError {
#[error("database error: {0}")]
Database(#[from] sqlx::Error),
#[error("the analysis API is unavailable: {0}")]
AnalysisUnavailable(String),
}
impl BatchError {
/// What Laravel reads in the batch's "error". The detail stays in the log.
fn public_message(&self) -> &'static str {
match self {
BatchError::Database(_) => "The service could not read or save the batch.",
BatchError::AnalysisUnavailable(_) => {
"The analysis API is unavailable. Nothing was saved."
}
}
}
}
/// Runs one batch in the background. Every outcome ends in the log and in the batch's status.
pub async fn run(state: AppState, batch_id: i64) {
// Wait for a free slot: at most BATCHES_AT_ONCE batches call the analysis API at a time.
let Ok(_slot) = state.slots.acquire().await else {
error!(batch_id, "the batch queue is closed");
return;
};
match analyse(&state, batch_id).await {
Ok((analysed, failed)) => info!(batch_id, analysed, failed, "batch done"),
Err(e) => {
error!(batch_id, error = %e, "batch failed");
if let Err(save) = db::fail(&state.pool, batch_id, e.public_message()).await {
error!(batch_id, error = %save, "cannot record the failure");
}
}
}
}
async fn analyse(state: &AppState, batch_id: i64) -> Result<(usize, usize), BatchError> {
let ids = db::start(&state.pool, batch_id).await?;
let (known, answers) = db::load(&state.pool, &ids).await?;
let (todo, mut failed) = group(&ids, &known, answers);
info!(
batch_id,
evaluations = todo.len(),
skipped = failed.len(),
"batch started"
);
let outcomes: Vec<(i64, i32, Result<Sentiment, Failure>)> = stream::iter(todo)
.map(|(id, answers)| async move {
let comments: Vec<&str> = answers
.iter()
.filter_map(|a| a.comment.as_deref())
.collect();
let average = average_tenths(&answers);
(id, average, state.analyser.analyse(id, &comments).await)
})
.buffer_unordered(state.config.concurrency)
.collect()
.await;
let mut analysed: Vec<Analysed> = Vec::new();
for (id, average_tenths, outcome) in outcomes {
match outcome {
Ok(s) => analysed.push(Analysed {
id,
average_tenths,
positive: s.positive,
negative: s.negative,
neutral: s.neutral,
}),
Err(f) => failed.push(Failed {
evaluation_id: id,
reason: f.reason,
retryable: f.retryable,
}),
}
}
// Nothing analysed and every failure temporary: the API is down, and the batch failed as a whole.
if analysed.is_empty() && !failed.is_empty() && failed.iter().all(|f| f.retryable) {
return Err(BatchError::AnalysisUnavailable(failed[0].reason.clone()));
}
failed.sort_by_key(|f| f.evaluation_id);
db::finish(&state.pool, batch_id, &analysed, &failed).await?;
Ok((analysed.len(), failed.len()))
}
/// Splits the batch's ids into evaluations to analyse, with their answers, and ones that cannot be.
/// ids is sorted; answers comes ordered by evaluation id.
pub fn group(
ids: &[i64],
known: &[i64],
answers: Vec<Answer>,
) -> (Vec<(i64, Vec<Answer>)>, Vec<Failed>) {
let mut todo: Vec<(i64, Vec<Answer>)> = ids.iter().map(|&id| (id, Vec::new())).collect();
for answer in answers {
if let Ok(i) = todo.binary_search_by_key(&answer.evaluation_id, |(id, _)| *id) {
todo[i].1.push(answer);
}
}
let mut failed: Vec<Failed> = Vec::new();
todo.retain(|(id, answers)| {
let reason = if !known.contains(id) {
"no such evaluation"
} else if answers.is_empty() {
"no answers"
} else {
return true;
};
failed.push(Failed {
evaluation_id: *id,
reason: reason.to_string(),
retryable: false,
});
false
});
(todo, failed)
}
/// The average score × 10, in whole numbers: [5, 4, 4] → 43. answers is never empty here.
pub fn average_tenths(answers: &[Answer]) -> i32 {
let sum: i32 = answers.iter().map(|a| i32::from(a.score)).sum();
let count = i32::try_from(answers.len()).unwrap_or(i32::MAX);
sum * 10 / count.max(1)
}
#[cfg(test)]
mod tests {
use super::*;
fn answer(evaluation_id: i64, score: i16, comment: Option<&str>) -> Answer {
Answer {
evaluation_id,
score,
comment: comment.map(String::from),
}
}
#[test]
fn averages_in_tenths() {
let answers = [answer(1, 5, None), answer(1, 4, None), answer(1, 4, None)];
assert_eq!(average_tenths(&answers), 43);
}
#[test]
fn groups_answers_and_reports_what_cannot_be_analysed() {
let ids = [1042, 1043, 1044, 9999];
let known = [1042, 1043, 1044];
let answers = vec![
answer(1042, 5, Some("Clear")),
answer(1042, 4, None),
answer(1043, 3, Some("Too fast")),
];
let (todo, failed) = group(&ids, &known, answers);
let grouped: Vec<(i64, usize)> = todo.iter().map(|(id, a)| (*id, a.len())).collect();
assert_eq!(grouped, [(1042, 2), (1043, 1)]);
assert_eq!(
failed,
[
Failed {
evaluation_id: 1044,
reason: String::from("no answers"),
retryable: false,
},
Failed {
evaluation_id: 9999,
reason: String::from("no such evaluation"),
retryable: false,
},
]
);
}
}
Step 5: work after the response
tokio::spawn from the async lesson starts a task that runs on its own. The handler spawns process::run and returns 202 at once; the task carries on after the response has been sent. This is dispatch() without a queue: the work runs inside the service’s own process.
Without a limit, ten clicks would start ten batches, each with 8 calls in flight: 80 calls at once to an analysis API that agreed to 8 or 16. tokio::sync::Semaphore is the limit: it holds a number of slots, and acquire().await waits until one is free. With BATCHES_AT_ONCE = 2, a third batch stays queued until one of the first two finishes and its _slot is dropped.
pub async fn run(state: AppState, batch_id: i64) {
// Wait for a free slot: at most BATCHES_AT_ONCE batches call the analysis API at a time.
let Ok(_slot) = state.slots.acquire().await else {
error!(batch_id, "the batch queue is closed");
return;
};
acquire fails only if the semaphore has been closed, which this service never does; the let … else still handles it, because no failure goes unlogged. The _slot name keeps the permit alive until the end of the function. A plain _ would drop it at once and the limit would do nothing.
Step 6: the routes
app builds the whole router, middleware included, so main and the tests get the same thing. The key check is the middleware lesson’s, with the constant-time comparison from its practice part; it returns AppError::Unauthenticated, so its 401 has the same shape as every other error.
store does the three things Omar asked for, in order. It validates the body, sorts the ids and drops duplicates, so [1043, 1042] and [1042, 1043, 1042] are the same batch. It creates the batch, or finds the one with this reference: a match is a retry and gets 200; the same reference with other ids is a bug in the caller and gets 409. Only a new batch is spawned, and gets 202.
use std::time::Duration;
use axum::extract::rejection::JsonRejection;
use axum::extract::{Path, Request, State};
use axum::http::header::LOCATION;
use axum::http::{HeaderMap, StatusCode};
use axum::middleware::{self, Next};
use axum::response::Response;
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Deserialize;
use subtle::ConstantTimeEq;
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;
use validator::Validate;
use crate::AppState;
use crate::db::{self, Batch};
use crate::error::AppError;
use crate::process;
/// Every route of the service, with its middleware. main.rs serves it; the tests call it directly.
pub fn app(state: AppState) -> Router {
Router::new()
.route("/batches", post(store))
.route("/batches/{id}", get(show))
.route_layer(middleware::from_fn_with_state(
state.clone(),
require_api_key,
))
.route("/health", get(health))
.layer(TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(8),
))
.layer(TraceLayer::new_for_http())
.with_state(state)
}
async fn require_api_key(
State(state): State<AppState>,
headers: HeaderMap,
request: Request,
next: Next,
) -> Result<Response, AppError> {
let sent = headers
.get("x-api-key")
.map(|key| key.as_bytes())
.unwrap_or_default();
if bool::from(sent.ct_eq(state.config.api_key.as_bytes())) {
Ok(next.run(request).await)
} else {
Err(AppError::Unauthenticated)
}
}
async fn health() -> &'static str {
"ok"
}
#[derive(Deserialize, Validate)]
struct NewBatch {
#[validate(length(
min = 1,
max = 100,
message = "The reference field must be 1 to 100 characters."
))]
reference: String,
#[validate(length(min = 1, max = 500, message = "Send between 1 and 500 evaluation ids."))]
evaluation_ids: Vec<i64>,
}
type Created = (
StatusCode,
[(axum::http::HeaderName, String); 1],
Json<Batch>,
);
/// 202 for a new batch; 200 with the same batch when Laravel retries with the same reference.
async fn store(
State(state): State<AppState>,
body: Result<Json<NewBatch>, JsonRejection>,
) -> Result<Created, AppError> {
let Json(batch) = body?;
batch.validate()?;
let mut ids = batch.evaluation_ids;
ids.sort_unstable();
ids.dedup();
let (mut found, created) = db::create_batch(&state.pool, &batch.reference, &ids).await?;
if !created && found.evaluation_ids != ids {
return Err(AppError::Conflict(
"This reference was already used for other evaluations.",
));
}
let location = [(LOCATION, format!("/batches/{}", found.id))];
if !created {
found.failures = db::failures(&state.pool, found.id).await?;
return Ok((StatusCode::OK, location, Json(found)));
}
tokio::spawn(process::run(state, found.id));
Ok((StatusCode::ACCEPTED, location, Json(found)))
}
async fn show(State(state): State<AppState>, Path(id): Path<i64>) -> Result<Json<Batch>, AppError> {
let mut batch = db::find_batch(&state.pool, id)
.await?
.ok_or(AppError::NotFound("Batch"))?;
batch.failures = db::failures(&state.pool, id).await?;
Ok(Json(batch))
}
body: Result<Json<NewBatch>, JsonRejection> asks axum for the result of reading the body instead of letting it answer on its own; body? then turns a rejection into an AppError through #[from]. It does the job of the JSON lesson’s ValidatedJson with less code, at the cost of two lines in each handler.
Location: /batches/1 tells the client where to poll, the HTTP way to answer a 202. process::run(state, …) moves state into the task: the handler does not use it afterwards, so nothing needs to be cloned.
Step 7: lib.rs and main.rs
AppState holds four handles: the pool, the analysis client, the config behind an Arc (the state lesson), and the semaphore, also behind an Arc so that every clone shares the same slots.
//! analysis-service: Laravel posts a batch of evaluations; the service analyses it in the background
//! and Laravel polls for the result.
pub mod analysis;
pub mod config;
pub mod db;
pub mod error;
pub mod process;
pub mod routes;
use std::sync::Arc;
use sqlx::PgPool;
use tokio::sync::Semaphore;
use crate::analysis::Analyser;
use crate::config::Config;
pub use routes::app;
/// How many batches call the analysis API at the same time. More wait their turn as "queued".
pub const BATCHES_AT_ONCE: usize = 2;
/// What every handler and every background batch shares. Cheap to clone: every field is a handle.
#[derive(Clone)]
pub struct AppState {
pub pool: PgPool,
pub analyser: Analyser,
pub config: Arc<Config>,
pub slots: Arc<Semaphore>,
}
main only sets up logging and turns the result of serve into an exit code. serve does the startup, in an order chosen so that a bad setup fails before anything is accepted: config, database (connect, not connect_lazy, because resuming needs the database right away), the analysis client, resuming, then listening.
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;
use analysis_service::analysis::Analyser;
use analysis_service::config::Config;
use analysis_service::error::StartError;
use analysis_service::{AppState, BATCHES_AT_ONCE, app, db, process};
use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener;
use tokio::signal::unix::{SignalKind, signal};
use tokio::sync::Semaphore;
use tracing::{error, info};
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> ExitCode {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
)
.with_writer(std::io::stderr)
.with_ansi(false)
.without_time()
.init();
match serve().await {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
error!(error = %e, "cannot run the service");
ExitCode::FAILURE
}
}
}
async fn serve() -> Result<(), StartError> {
let config = Config::from_env()?;
let pool = PgPoolOptions::new()
.max_connections(10)
.acquire_timeout(Duration::from_secs(3))
.connect(&config.database_url)
.await?;
let state = AppState {
pool,
analyser: Analyser::new(&config.analysis_url)?,
slots: Arc::new(Semaphore::new(BATCHES_AT_ONCE)),
config: Arc::new(config),
};
// Batches a previous run accepted but did not finish, cut off by a deploy or a crash.
for batch_id in db::unfinished(&state.pool).await? {
info!(batch_id, "resuming batch");
tokio::spawn(process::run(state.clone(), batch_id));
}
let listener = TcpListener::bind(&state.config.address).await?;
info!(address = %state.config.address, "listening");
axum::serve(listener, app(state))
.with_graceful_shutdown(shutdown_signal())
.await?;
info!("stopped");
Ok(())
}
/// Finishes on Ctrl-C (SIGINT) or on SIGTERM from a deploy.
async fn shutdown_signal() {
let mut terminate = match signal(SignalKind::terminate()) {
Ok(stream) => stream,
Err(e) => {
error!(error = %e, "cannot listen for SIGTERM");
return;
}
};
tokio::select! {
_ = tokio::signal::ctrl_c() => info!("SIGINT received"),
_ = terminate.recv() => info!("SIGTERM received"),
}
}
with_graceful_shutdown waits for requests in progress, but not for spawned tasks: a batch that is still running when the server stops is cut off. Nothing of it was saved, its status is still running, and the next start resumes it. The service is built so that a cut-off batch is a normal event, not a special case.
Run the tests
running 2 tests
test process::tests::averages_in_tenths ... ok
test process::tests::groups_answers_and_reports_what_cannot_be_analysed ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sThe worker’s two tests, for group and average_tenths, still pass. The checkpoint adds tests for the HTTP side.
Run it: one click
The service started on the five pending evaluations, then the requests the Laravel side will send:
HTTP/1.1 202 Accepted
content-type: application/json
location: /batches/1
content-length: 116
{"id":1,"reference":"dashboard-7f3e","status":"queued","total":5,"analysed":0,"failed":0,"error":null,"failures":[]}1 s later:
HTTP/1.1 200 OK
content-type: application/json
content-length: 247
{"id":1,"reference":"dashboard-7f3e","status":"done","total":5,"analysed":3,"failed":2,"error":null,"failures":[{"evaluation_id":1044,"reason":"no answers","retryable":false},{"evaluation_id":9999,"reason":"no such evaluation","retryable":false}]}HTTP/1.1 200 OK
content-type: application/json
location: /batches/1
content-length: 247
{"id":1,"reference":"dashboard-7f3e","status":"done","total":5,"analysed":3,"failed":2,"error":null,"failures":[{"evaluation_id":1044,"reason":"no answers","retryable":false},{"evaluation_id":9999,"reason":"no such evaluation","retryable":false}]}HTTP/1.1 409 Conflict
content-type: application/json
content-length: 68
{"message":"This reference was already used for other evaluations."}HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 188
{"message":"Send between 1 and 500 evaluation ids.","errors":{"evaluation_ids":["Send between 1 and 500 evaluation ids."],"reference":["The reference field must be 1 to 100 characters."]}}HTTP/1.1 404 Not Found
content-type: application/json
content-length: 30
{"message":"Batch not found."} INFO analysis_service: listening address=127.0.0.1:3000
INFO analysis_service::process: batch started batch_id=1 evaluations=3 skipped=2
INFO analysis_service::process: batch done batch_id=1 analysed=3 failed=2
INFO analysis_service: SIGINT received
INFO analysis_service: stoppedThe POST answers 202 with the batch queued: the 6 ids were cut to 5 (1045 was sent twice) and nothing has been analysed yet. A second later the batch is done: three evaluations analysed and saved, and the two that can never be, with retryable: false.
Then a retry of the same request, the one Laravel’s Http::retry sends after a timeout, gets the same batch back with 200; no second batch was started, as the log shows. The same reference with other ids is a 409, an empty batch a 422 in Laravel’s shape, and an unknown batch a 404.
When things go wrong
The analysis API is down
HTTP/1.1 202 Accepted
content-type: application/json
location: /batches/1
content-length: 116
{"id":1,"reference":"dashboard-91c2","status":"queued","total":2,"analysed":0,"failed":0,"error":null,"failures":[]}1.5 s later:
HTTP/1.1 200 OK
content-type: application/json
content-length: 165
{"id":1,"reference":"dashboard-91c2","status":"failed","total":2,"analysed":0,"failed":0,"error":"The analysis API is unavailable. Nothing was saved.","failures":[]} INFO analysis_service: listening address=127.0.0.1:3000
INFO analysis_service::process: batch started batch_id=1 evaluations=2 skipped=0
WARN analysis_service::analysis: retrying evaluation_id=1045 attempt=1 reason=analysis API unreachable: error sending request for url (http://127.0.0.1:8999/api/analyse)
WARN analysis_service::analysis: retrying evaluation_id=1046 attempt=1 reason=analysis API unreachable: error sending request for url (http://127.0.0.1:8999/api/analyse)
WARN analysis_service::analysis: retrying evaluation_id=1045 attempt=2 reason=analysis API unreachable: error sending request for url (http://127.0.0.1:8999/api/analyse)
WARN analysis_service::analysis: retrying evaluation_id=1046 attempt=2 reason=analysis API unreachable: error sending request for url (http://127.0.0.1:8999/api/analyse)
ERROR analysis_service::process: batch failed batch_id=1 error=the analysis API is unavailable: analysis API unreachable: error sending request for url (http://127.0.0.1:8999/api/analyse)
INFO analysis_service: SIGINT received
INFO analysis_service: stoppedThree attempts per evaluation, then the batch is failed with a message Laravel can show, and nothing was saved. The log holds the URL and the error, which Laravel and the school never see.
A deploy cut a batch off
The database is reset with one batch left running, as a deploy leaves it when it stops the old process half-way through a batch:
1 s later:
HTTP/1.1 200 OK
content-type: application/json
content-length: 115
{"id":1,"reference":"nightly-cut-off","status":"done","total":2,"analysed":2,"failed":0,"error":null,"failures":[]} INFO analysis_service: resuming batch batch_id=1
INFO analysis_service: listening address=127.0.0.1:3000
INFO analysis_service::process: batch started batch_id=1 evaluations=2 skipped=0
INFO analysis_service::process: batch done batch_id=1 analysed=2 failed=0
INFO analysis_service: SIGINT received
INFO analysis_service: stoppedresuming batch is the first line of the log, before the service even listens. The batch ran again from the start and is done. Nobody had to notice it had been cut off.
The setup is wrong
ERROR analysis_service: cannot run the service error=configuration: SERVICE_API_KEY must be at least 16 characters
exit code 1One line and exit code 1, before the database is touched or the port is opened.
The Laravel side
The settings
'analysis' => [
'url' => env('ANALYSIS_SERVICE_URL', 'http://127.0.0.1:3000'),
'key' => env('ANALYSIS_SERVICE_KEY'), // the service's SERVICE_API_KEY
],
The client
One class talks to the service. retry repeats a request only when repeating can help (no connection, 408, 429, 503), and it is safe to repeat a POST here because of the reference. throw() turns every other error status into a RequestException:
<?php
namespace App\Services\Analysis;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;
final class AnalysisService
{
public function __construct(private readonly string $url, private readonly string $key)
{
}
/**
* @param list<int> $evaluationIds
*
* @throws ConnectionException the service could not be reached, even after the retries
* @throws RequestException the service refused the batch (401, 409, 422) or kept failing
*/
public function submit(string $reference, array $evaluationIds): AnalysisBatch
{
$response = $this->client()->post('/batches', [
'reference' => $reference,
'evaluation_ids' => array_values(array_map('intval', $evaluationIds)),
]);
return AnalysisBatch::fromArray($response->json());
}
/** @throws ConnectionException|RequestException */
public function status(int $batchId): AnalysisBatch
{
return AnalysisBatch::fromArray($this->client()->get("/batches/{$batchId}")->json());
}
private function client(): PendingRequest
{
return Http::baseUrl($this->url)
->withHeaders(['X-Api-Key' => $this->key])
->acceptJson()
->timeout(10)
->retry(3, 500, fn (Throwable $e): bool => $e instanceof ConnectionException
|| ($e instanceof RequestException && in_array($e->response->status(), [408, 429, 503], true)))
->throw();
}
}
Bind it once in AppServiceProvider::register(): $this->app->singleton(AnalysisService::class, fn () => new AnalysisService(config('services.analysis.url'), config('services.analysis.key')));. The service’s timeout layer answers at 8 seconds, below this client’s 10, so Laravel gets a 408 it can retry instead of a cut connection.
<?php
namespace App\Services\Analysis;
final readonly class AnalysisBatch
{
/**
* @param list<array{evaluation_id: int, reason: string, retryable: bool}> $failures
*/
public function __construct(
public int $id,
public string $reference,
public string $status,
public int $analysed,
public ?string $error,
public array $failures,
) {
}
/** @param array<string, mixed> $data */
public static function fromArray(array $data): self
{
return new self(
(int) $data['id'],
(string) $data['reference'],
(string) $data['status'],
(int) $data['analysed'],
isset($data['error']) ? (string) $data['error'] : null,
$data['failures'] ?? [],
);
}
public function finished(): bool
{
return in_array($this->status, ['done', 'failed'], true);
}
/** @return list<int> */
public function retryableIds(): array
{
$retryable = array_filter($this->failures, fn (array $f): bool => $f['retryable']);
return array_values(array_map(fn (array $f): int => (int) $f['evaluation_id'], $retryable));
}
}
The button
The controller sends the batch and answers the browser at once. A fresh reference per click, made before the request, is what makes retry safe: every retry of this click carries the same one.
<?php
namespace App\Http\Controllers;
use App\Jobs\WatchAnalysisBatch;
use App\Services\Analysis\AnalysisService;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
final class AnalyseNowController
{
public function __invoke(Request $request, AnalysisService $analysis): JsonResponse
{
$validated = $request->validate([
'evaluation_ids' => ['required', 'array', 'min:1', 'max:500'],
'evaluation_ids.*' => ['integer'],
]);
try {
$batch = $analysis->submit('dashboard-' . Str::uuid(), $validated['evaluation_ids']);
} catch (ConnectionException|RequestException $e) {
Log::error('analysis service refused or unreachable', ['error' => $e->getMessage()]);
return response()->json(['message' => 'Analysis is not available right now. Try again in a few minutes.'], 503);
}
WatchAnalysisBatch::dispatch($batch->id)->delay(now()->addSeconds(2));
return response()->json(['batch' => $batch->id, 'status' => $batch->status], 202);
}
}
The poll
A queued job asks for the status, and puts itself back on the queue for 5 seconds while the batch is not finished. retryUntil gives up after 30 minutes, however many polls that took. Retryable failures go into one new batch; its reference ends in -retry, so they are retried once and not forever:
<?php
namespace App\Jobs;
use App\Services\Analysis\AnalysisService;
use DateTimeInterface;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
final class WatchAnalysisBatch implements ShouldQueue
{
use Queueable;
public function __construct(public readonly int $batchId)
{
}
public function retryUntil(): DateTimeInterface
{
return now()->addMinutes(30);
}
public function handle(AnalysisService $analysis): void
{
$batch = $analysis->status($this->batchId);
if (! $batch->finished()) {
$this->release(5);
return;
}
if ($batch->status === 'failed') {
$this->fail($batch->error ?? 'the analysis batch failed');
return;
}
Log::info('analysis batch done', ['batch' => $batch->id, 'analysed' => $batch->analysed]);
$retry = $batch->retryableIds();
if ($retry !== [] && ! str_ends_with($batch->reference, '-retry')) {
$next = $analysis->submit($batch->reference . '-retry', $retry);
self::dispatch($next->id)->delay(now()->addMinutes(2));
}
}
}
An exception from status (the service down for a moment) fails this attempt, and the queue tries again with its backoff until retryUntil. A failed batch fails the job for good: retrying the poll cannot change the batch’s result.
The worker or the service?
| The worker (Week 4) | The service | |
|---|---|---|
| Laravel reaches it with | Process: a binary per batch | Http: one long-running server |
| Answer time | When the batch is done | At once: 202 and an id |
| Fits | The nightly run, from a queued job | A button, or another app |
| Retries | The queue retries the job | The reference makes a repeated POST safe |
| Runs on | The Laravel server, no new process to manage | Its own process: systemd, Docker or Forge daemon |
Both use the same analysis code, which is the point of having moved it into its own modules. Many teams keep both: the nightly run as a worker, the button as a service.
PracticeTwo extensions
Extension 1: more than one instance
Run two copies of the service behind a load balancer and both will resume the same cut-off batches at startup. Make the claim atomic: update analysis_batches set status = 'running' where id = $1 and status in ('queued', 'running') and (updated_at < now() - interval '5 minutes' or status = 'queued') returning evaluation_ids. A batch that another copy claimed a moment ago returns no row and is skipped. Decide what updated_at must mean for this to work while a long batch is still running.
Extension 2: cancel a batch
Add DELETE /batches/{id}: it sets a queued batch to cancelled and answers 200, and answers 409 for a batch that is already running or finished. Then make db::start claim only a batch that is still queued or running (where id = $1 and status in ('queued', 'running'), with fetch_optional), so a cancelled batch waiting for a slot is skipped when its turn comes. Add cancelled to finished() on the Laravel side.
Remember
- Answer 202 at once and do slow work in a spawned task that records every outcome, with a limit on how many run together.
- A client-chosen reference makes a POST safe to retry; resume unfinished work at startup.
Tomorrow: the Week 5 checkpoint. Tests that call the router without a server, for every answer the service can give.