Rust Playbook

Course › Week 6 · Laravel Rust › Day 6 · lesson 41 of 42 · 15 min reading + 2–3 h practice

Build the service on Laravel Rust

The Week 5 analysis service again: the queue takes over the background work, the retry rule stays yours.

Laravel RustqueuesHTTP client

On this page
  1. The task
  2. The design
  3. Step 1: the results’ tables
  4. Step 2: the models
  5. Step 3: a POST that is safe to retry
  6. Step 4: the job, all or nothing
  7. Run it
  8. The Laravel side
  9. Plain axum or Laravel Rust?
  10. Practice
  11. Remember

The Week 5 build day wrote an analysis service in plain axum. This one builds the same service inside the nordic Laravel Rust application, from the pieces of this week: typed input, models, the API key and the HTTP client, and the queue. Then it compares what each version had to write by hand.

The application already accepts a batch, pushes a job and analyses it. Four things are missing before Laravel can rely on it, and they are the steps below.

#dashboardMonday 10:05

Omar · backendWe’re moving the analysis service into the nordic app, so it shares the models and the queue with everything else. Same contract as the old service, please: my Http client and the poll job must not notice.

Omar · backendThat means a retried POST with the same reference returns the same batch, and the status shows which evaluations failed and whether sending them again can work. Partial results are worse than none.

The design

RequirementWeek 5, axumHere
Answer at once, work latertokio::spawn and a semaphoreA queued job (queues)
A retried POST returns the same batchon conflict do nothing, then a selectfirst_or_create, step 3
Survive a deploy mid-batchResume queued and running batches at startupThe job stays in the jobs table
Failures per evaluationA table and a Failed structA table and a model, step 2
All results or noneOne sqlx transactiondb::transaction, step 4
The API down: retry laterExit code 1 for the queueFail the attempt; tries and backoff

The last column is shorter mostly where the framework already owns the problem: the queue, the transaction, the 422 body, the key check. The retry rule and the all-or-nothing rule are still decisions in your code; no framework knows them for you.

Step 1: the results’ tables

The batch gets its counts and an error column, and the failures get their own table, in one new migration:

database/migrations/2026_12_08_000000_add_results_to_analysis_batches_table.rsnew file
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .alter("analysis_batches", |table| {
            table.integer("analysed").default(0);
            table.integer("failed").default(0);
            table.string("error").nullable();
        })
        .await?;

    tx.schema()
        .create("analysis_batch_failures", |table| {
            table.id();
            table.foreign_id("analysis_batch_id").constrained().cascade_on_delete();
            table.big_integer("evaluation_id");
            table.string("reason");
            table.boolean("retryable");
        })
        .await
}

Step 2: the models

BatchFailure would be read from batch_failures by the naming rule, so #[model(table = …)] names the real table. #[serde(skip)] keeps the two ids out of the JSON: Laravel reads evaluation_id, reason and retryable, the fields of the Week 5 contract.

src/models/batch_failure.rsnew file
use laravel::model::{BelongsTo, model};

use crate::models::AnalysisBatch;

/// An evaluation of a batch that was not analysed, and whether sending it again may work.
#[model(table = "analysis_batch_failures")]
pub struct BatchFailure {
    #[serde(skip)]
    pub id: i64,
    #[serde(skip)]
    pub analysis_batch_id: i64,
    pub evaluation_id: i64,
    pub reason: String,
    pub retryable: bool,

    #[belongs_to]
    pub analysis_batch: BelongsTo<AnalysisBatch>,
}

The batch gets the new columns and a #[has_many] for its failures:

src/models/analysis_batch.rschanged since lesson 38: +12 −1
use laravel::db::Json;use laravel::model::model;use laravel::model::{HasMany, model};use laravel::prelude::*;use laravel::time::Timestamp;use serde::{Deserialize, Serialize}; use crate::models::BatchFailure; /// Where a batch is: queued until a worker takes it, then done or failed.#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]#[serde(rename_all = "snake_case")]
11 unchanged linespub enum BatchStatus { Queued, Running, Done, Failed,} #[model]pub struct AnalysisBatch { pub id: i64, pub reference: String,
#[default] pub status: BatchStatus, pub evaluation_ids: Json<Vec<i64>>, #[default] pub analysed: i32, #[default] pub failed: i32, /// Why the whole batch failed, in words Laravel may show. The detail is in the log. pub error: Option<String>, pub created_at: Timestamp, pub updated_at: Timestamp, #[has_many] pub failures: HasMany<BatchFailure>,}
src/models/mod.rschanged since lesson 38: +2
mod analysis_batch;mod answer;mod batch_failure;mod evaluation;mod user; pub use analysis_batch::{AnalysisBatch, BatchStatus};pub use answer::Answer;pub use batch_failure::BatchFailure;pub use evaluation::{Evaluation, Status};pub use user::{User, UserFactory};

Step 3: a POST that is safe to retry

first_or_create(condition, create!(…)) looks for a batch with this reference and creates one if there is none, filling reference from the condition (the .. at the end of create! says so). .found_or_created() says which happened, so the handler can answer 202 for a new batch and 200 for a retry, and 409 when the reference came back with other ids.

The unique index on reference makes it safe at the same moment too: if two requests both miss and both insert, the database refuses the second insert, and Laravel catches that and returns the winning row as Found. The unique validation rule of the models lesson is gone; it could not do that.

One more case is handled here. If the first request stored the batch and then failed to push its job, Laravel retries, finds the batch still queued, and would wait forever. So a retry of a queued batch pushes the job again; step 4 makes a second job harmless. retry also gets the dispatch it was missing since the queues lesson: until now it only reset the status.

src/http/handlers/batches.rschanged since lesson 40: +52 −22
use laravel::db::Json as JsonColumn;use laravel::errors::Status;use laravel::model::{create, update};use laravel::model::{FoundOrCreated, create, update};use laravel::prelude::*; use crate::jobs::AnalyseBatch;use crate::models::{AnalysisBatch, BatchStatus}; /// A batch of evaluations to analyse, as Laravel posts it.#[laravel::input]#[validate(anyone)]pub struct NewBatch {    #[validate(required, max_length(100), unique(AnalysisBatch::reference))]    #[validate(required, max_length(100))]    reference: String,    #[validate(required, max_items(500), distinct, each(min_value(1)))]    #[validate(required, max_items(500), each(min_value(1)))]    evaluation_ids: Vec<i64>,} /// Stores the batch as queued and hands it to a queue worker.pub async fn store(Valid(batch): Valid<NewBatch>) -> laravel::Result<(StatusCode, Json<AnalysisBatch>)> {    let evaluation_ids = JsonColumn(batch.evaluation_ids);    let stored = create!(AnalysisBatch {        reference: batch.reference,        evaluation_ids    })    .await?;    AnalyseBatch { batch_id: stored.id }.dispatch().await?;    Ok((StatusCode::ACCEPTED, Json(stored)))} /// What can go wrong with a batch that is the caller's mistake, with the status each one answers.#[derive(Debug, thiserror::Error, Status)]pub enum BatchError {    #[error("Only a failed batch can be retried.")]    #[status(409)]    NotFailed,} /// Puts a failed batch back in the queue.     #[error("This reference was already used for other evaluations.")]    #[status(409)]    ReferenceTaken,} /// 202 and a new batch, or 200 and the same batch when Laravel retries with the same reference.pub async fn store(Valid(batch): Valid<NewBatch>) -> laravel::Result<(StatusCode, Json<AnalysisBatch>)> {    let mut ids = batch.evaluation_ids;    ids.sort_unstable();    ids.dedup();     // A clone, because the ids are compared with an existing batch's after the lookup.    let evaluation_ids = JsonColumn(ids.clone());    let found = AnalysisBatch::first_or_create(        AnalysisBatch::reference.eq(&batch.reference),        create!(AnalysisBatch { evaluation_ids, .. }),    )    .found_or_created()    .await?;     match found {        FoundOrCreated::Created(stored) => {            AnalyseBatch { batch_id: stored.id }.dispatch().await?;            Ok((StatusCode::ACCEPTED, Json(stored)))        }        FoundOrCreated::Found(existing) if *existing.evaluation_ids == ids => {            // Still queued: the first request may have stored the batch and failed to push its job.            // A second job is harmless, because the job skips a batch that is already finished.            if existing.status == BatchStatus::Queued {                AnalyseBatch { batch_id: existing.id }.dispatch().await?;            }            Ok((StatusCode::OK, Json(existing)))        }        FoundOrCreated::Found(_) => Err(BatchError::ReferenceTaken.into()),    }} /// Puts a failed batch back in the queue, with a job to run it.pub async fn retry(mut batch: AnalysisBatch) -> laravel::Result<Json<AnalysisBatch>> {    if batch.status != BatchStatus::Failed {        return Err(BatchError::NotFailed.into());    }    update!(batch {        status: BatchStatus::Queued        status: BatchStatus::Queued,        error: None::<String>    })    .await?;    AnalyseBatch { batch_id: batch.id }.dispatch().await?;    Ok(Json(batch))} /// A batch, for Laravel to poll.pub async fn show(batch: AnalysisBatch) -> Json<AnalysisBatch> {    Json(batch)/// A batch with its failures, for Laravel to poll.pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<AnalysisBatch>> {    let batch = AnalysisBatch::query()        .with(AnalysisBatch::failures)        .find_or_fail(id)        .await?;    Ok(Json(batch))}

show now loads the failures with with, so the route takes the id as a plain parameter, {batch}:

src/routes/api.rschanged since lesson 40: +1 −1
25 unchanged linesuse laravel::prelude::*;use serde::Serialize;use serde_json::json; use crate::http::handlers::{batches, evaluations};use crate::http::middleware::require_api_key; /// What /api/status reports, for Laravel's health checks and for people.#[derive(Serialize)]struct Status { service: &'static str, laravel: &'static str,} pub fn routes(route: &mut Router) { route.get("/version", async || Json(json!({ "laravel": laravel::VERSION }))); route.get("/status", async || { Json(Status { service: "nordic", laravel: laravel::VERSION, }) }); route.get("/evaluations/pending", evaluations::pending); route.get("/evaluations/{evaluation}", evaluations::show); route.get("/evaluations/{evaluation}/answers", evaluations::with_answers);
route.get("/evaluations/{evaluation}/export/{format}", evaluations::export); route.middleware(require_api_key).group(|route| { route.post("/batches", batches::store); route.get("/batches/{analysis_batch}", batches::show); route.get("/batches/{batch}", batches::show); route.post("/batches/{analysis_batch}/retry", batches::retry); route.post("/evaluations/{evaluation}/analyse", evaluations::analyse); }); route.fallback(async || laravel::abort(404));}

Step 4: the job, all or nothing

The job first decides what can never work: ids with no evaluation, and evaluations without answers. Those are failures with retryable: false. The rest go to the analysis API, eight at a time. analyse_one always returns Ok, with the call’s own result inside, so one evaluation the API cannot analyse does not cancel the others, as the practice part of the queues lesson asked.

Then the decision of the Week 4 worker: nothing analysed and every failure temporary means the API is down, so the attempt fails, nothing is saved, and the queue tries again after the backoff. Otherwise everything is saved inside db::transaction: every model write in the closure joins the transaction, and an error anywhere rolls all of it back.

A job that finds its batch done or failed stops at once. That is what makes the second job from step 3, or a job a worker picked up twice, harmless.

src/jobs/analyse_batch.rschanged since lesson 40: +107 −22
use laravel::config::Section;use laravel::model::update;use laravel::db;use laravel::model::{create, update};use laravel::queue::{Queueable, job};use laravel::task; use crate::analysis::{self, Sentiment};use crate::config::services::Analysis;use crate::models::{AnalysisBatch, BatchStatus, Evaluation, Status};use crate::models::{AnalysisBatch, BatchFailure, BatchStatus, Evaluation, Status}; /// Analyses every evaluation of one batch. Only the id is queued; the job reads the batch when it runs.#[derive(Queueable)]pub struct AnalyseBatch {    pub batch_id: i64,} /// How many calls to the analysis API one batch makes at the same time.const CONCURRENCY: usize = 8; /// An evaluation that could not be analysed, before it is saved.struct Failure {    evaluation_id: i64,    reason: String,    retryable: bool,} #[job(name = "batches.analyse", tries = 3, backoff = [5.seconds(), 30.seconds()], timeout = 5.minutes())]impl AnalyseBatch {    async fn handle(self, analysis: Section<Analysis>) -> laravel::Result<()> {        let mut batch = AnalysisBatch::find_or_fail(self.batch_id).await?;        // A second job for the same batch (see the store handler) finds it finished and stops.        if matches!(batch.status, BatchStatus::Done | BatchStatus::Failed) {            return Ok(());        }        update!(batch {            status: BatchStatus::Running        })        .await?;         let evaluations = Evaluation::query()            .filter(Evaluation::id.is_in(batch.evaluation_ids.iter().copied()))            .with(Evaluation::answers)            .get()            .await?;        let results = task::map(evaluations, CONCURRENCY, async |evaluation| {            analyse_one(&analysis, evaluation).await        })        .await?;         for (mut evaluation, sentiment) in results {            update!(evaluation {                status: Status::Analysed,                positive: sentiment.positive,                negative: sentiment.negative,                neutral: sentiment.neutral,         // What can never be analysed, whatever the API says: unknown ids and evaluations without answers.        let mut failures: Vec<Failure> = Vec::new();        for &id in batch.evaluation_ids.iter() {            if !evaluations.iter().any(|e| e.id == id) {                failures.push(Failure {                    evaluation_id: id,                    reason: "no such evaluation".into(),                    retryable: false,                });            }        }        let (with_answers, without): (Vec<Evaluation>, Vec<Evaluation>) =            evaluations.into_iter().partition(|e| !e.answers.is_empty());        for e in &without {            failures.push(Failure {                evaluation_id: e.id,                reason: "no answers".into(),                retryable: false,            });        }         let outcomes = task::map(with_answers, CONCURRENCY, async |e| analyse_one(&analysis, e).await).await?;        let mut analysed: Vec<(Evaluation, Sentiment)> = Vec::new();        for outcome in outcomes {            match outcome {                Ok(pair) => analysed.push(pair),                Err((evaluation_id, error)) => {                    tracing::warn!(batch = batch.id, evaluation_id, %error, "evaluation not analysed");                    failures.push(Failure {                        evaluation_id,                        reason: "the analysis API did not answer".into(),                        retryable: true,                    });                }            }        }         // Nothing analysed and every failure temporary: the API is down. Fail the attempt, so the queue        // tries again later, and save nothing.        if analysed.is_empty() && !failures.is_empty() && failures.iter().all(|f| f.retryable) {            return Err(laravel::Error::msg(format!(                "batch {}: the analysis API is unavailable",                batch.id            )));        }         // Every result, every failure and the batch's counts, all or nothing.        let (analysed_count, failed_count) = (count(analysed.len()), count(failures.len()));        failures.sort_by_key(|f| f.evaluation_id);        db::transaction(async |_tx| {            for (mut evaluation, sentiment) in analysed {                update!(evaluation {                    status: Status::Analysed,                    positive: sentiment.positive,                    negative: sentiment.negative,                    neutral: sentiment.neutral,                })                .await?;            }            for f in failures {                create!(BatchFailure {                    analysis_batch: &batch,                    evaluation_id: f.evaluation_id,                    reason: f.reason,                    retryable: f.retryable,                })                .await?;            }            update!(batch {                status: BatchStatus::Done,                analysed: analysed_count,                failed: failed_count            })            .await?;        }        update!(batch {            status: BatchStatus::Done            Ok(())        })        .await?;        Ok(())    }     /// Runs once every attempt has failed: the batch must not stay "running" forever.    async fn failed(self, _error: &laravel::Error) -> laravel::Result<()> {        let mut batch = AnalysisBatch::find_or_fail(self.batch_id).await?;        let error = "The analysis API is unavailable. Nothing was saved.";        update!(batch {            status: BatchStatus::Failed            status: BatchStatus::Failed,            error        })        .await?;        Ok(())    }} /// One evaluation and what the analysis API said about it.async fn analyse_one(analysis: &Analysis, evaluation: Evaluation) -> laravel::Result<(Evaluation, Sentiment)> {    let sentiment = analysis::analyse(analysis, &evaluation).await?;    Ok((evaluation, sentiment))}/// One evaluation and what the analysis API said, or the evaluation's id and the error.type Outcome = Result<(Evaluation, Sentiment), (i64, laravel::Error)>; /// Always Ok: a call that fails is a failure of its evaluation, not of the batch, so task::map/// must not stop the other calls for it.async fn analyse_one(analysis: &Analysis, evaluation: Evaluation) -> laravel::Result<Outcome> {    Ok(match analysis::analyse(analysis, &evaluation).await {        Ok(sentiment) => Ok((evaluation, sentiment)),        Err(error) => Err((evaluation.id, error)),    })} /// A count for an integer column. A batch has at most 500 evaluations, so this never saturates.fn count(n: usize) -> i32 {    i32::try_from(n).unwrap_or(i32::MAX)}

Run it

The seeded evaluations: 1 has answers, 2 has none. The batch sends [2, 1, 1, 99]:

$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": [2, 1, 1, 99]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 202 Accepted
content-type: application/json
content-length: 204
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: aacd3677f64299431fc1d4f39b54a3be

{"id":2,"reference":"dashboard-7f3e","status":"queued","evaluation_ids":[1,2,99],"analysed":0,"failed":0,"error":null,"created_at":"2026-12-02T01:52:38.163546Z","updated_at":"2026-12-02T01:52:38.163546Z"}
$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": [2, 1, 1, 99]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 200 OK
content-type: application/json
content-length: 204
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 27235863e25ba57b2be39815b36b889c

{"id":2,"reference":"dashboard-7f3e","status":"queued","evaluation_ids":[1,2,99],"analysed":0,"failed":0,"error":null,"created_at":"2026-12-02T01:52:38.163546Z","updated_at":"2026-12-02T01:52:38.163546Z"}
$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": [1]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 409 Conflict
content-type: application/json
content-length: 68
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 8778bf118f3f59023ce40bcdb0ad5f68

{"message":"This reference was already used for other evaluations."}
$ laravel queue:work --stop-when-empty
Processing jobs from `database:default`. Press Ctrl+C to stop.
batches.analyse  128.7ms
batches.analyse  1.7ms
$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:3000/api/batches/2
HTTP/1.1 200 OK
content-type: application/json
content-length: 344
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 5d8c19cbd30b0e555050bf63434c0b2f

{"id":2,"reference":"dashboard-7f3e","status":"done","evaluation_ids":[1,2,99],"analysed":1,"failed":2,"error":null,"created_at":"2026-12-02T01:52:38.163546Z","updated_at":"2026-12-02T01:52:38.355974Z","failures":[{"evaluation_id":2,"reason":"no answers","retryable":false},{"evaluation_id":99,"reason":"no such evaluation","retryable":false}]}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
POST    202  /api/batches  13.7ms
POST    200  /api/batches  3.2ms
POST    409  /api/batches  2.7ms
GET     200  /api/batches/2  4.1ms
Stopping. Waiting up to 20s for the work in progress.

The ids were sorted and the duplicate dropped, so the batch is [1, 2, 99]. The retry got the same batch with 200, and other ids for the same reference a 409. The worker ran two jobs: the batch’s, in about 130 ms, and the second one the retry pushed, which found the batch done and stopped in a couple of milliseconds. The status has one evaluation analysed and two failures, each with its reason and retryable: false, the body the Week 5 poll job reads.

Five requests at the same moment

curl’s -Z sends the same POST five times in parallel:

$ curl -s -Z --parallel-immediate -w '%{http_code}\n' -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' -H 'content-type: application/json' -d '{"reference": "race-1", "evaluation_ids": [1]}' -o /dev/null http://127.0.0.1:3000/api/batches -o /dev/null http://127.0.0.1:3000/api/batches -o /dev/null http://127.0.0.1:3000/api/batches -o /dev/null http://127.0.0.1:3000/api/batches -o /dev/null http://127.0.0.1:3000/api/batches
202
200
200
200
200
$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:3000/api/batches/2
HTTP/1.1 200 OK
content-type: application/json
content-length: 205
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: ed62bfe8971bfc7d2bbdbeff8eca02b1

{"id":2,"reference":"race-1","status":"queued","evaluation_ids":[1],"analysed":0,"failed":0,"error":null,"created_at":"2026-12-02T01:52:46.958352Z","updated_at":"2026-12-02T01:52:46.958352Z","failures":[]}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
POST    202  /api/batches  39.8ms
POST    200  /api/batches  36.9ms
POST    200  /api/batches  38.8ms
POST    200  /api/batches  41.4ms
POST    200  /api/batches  37.4ms
GET     200  /api/batches/2  4.2ms
Stopping. Waiting up to 20s for the work in progress.

One 202 and four 200s, and one batch: the unique index settled the race and first_or_create turned the losers’ failed inserts into the winner’s row.

The analysis API is down

$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' -H 'content-type: application/json' -d '{"reference": "dashboard-91c2", "evaluation_ids": [1]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 202 Accepted
content-type: application/json
content-length: 199
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: f75635319ab933f9327d8bb51002f48e

{"id":2,"reference":"dashboard-91c2","status":"queued","evaluation_ids":[1],"analysed":0,"failed":0,"error":null,"created_at":"2026-12-02T01:52:55.716422Z","updated_at":"2026-12-02T01:52:55.716422Z"}
$ laravel queue:work --stop-when-empty
Processing jobs from `database:default`. Press Ctrl+C to stop.
2026-12-02T01:52:56.385093Z  WARN job{id=01a23474-6fa6-706c-903a-0279b7f6bc62 job=batches.analyse connection="database" queue="default" attempt=1}: app::jobs::analyse_batch: evaluation not analysed batch=2 evaluation_id=1 error="evaluation 1 could not be analysed: the HTTP request to http://127.0.0.1:8999/api/analyse failed: Connection refused (os error 111)"
batches.analyse retrying  625.2ms
batch 2: the analysis API is unavailable

5.5 s later:

$ laravel queue:work --stop-when-empty
Processing jobs from `database:default`. Press Ctrl+C to stop.
2026-12-02T01:53:02.577209Z  WARN job{id=01a23474-6fa6-706c-903a-0279b7f6bc62 job=batches.analyse connection="database" queue="default" attempt=2}: app::jobs::analyse_batch: evaluation not analysed batch=2 evaluation_id=1 error="evaluation 1 could not be analysed: the HTTP request to http://127.0.0.1:8999/api/analyse failed: Connection refused (os error 111)"
batches.analyse retrying  623.3ms
batch 2: the analysis API is unavailable

31 s later:

$ laravel queue:work --stop-when-empty
Processing jobs from `database:default`. Press Ctrl+C to stop.
2026-12-02T01:53:34.272736Z  WARN job{id=01a23474-6fa6-706c-903a-0279b7f6bc62 job=batches.analyse connection="database" queue="default" attempt=3}: app::jobs::analyse_batch: evaluation not analysed batch=2 evaluation_id=1 error="evaluation 1 could not be analysed: the HTTP request to http://127.0.0.1:8999/api/analyse failed: Connection refused (os error 111)"
batches.analyse failed  629.0ms
batch 2: the analysis API is unavailable
$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:3000/api/batches/2
HTTP/1.1 200 OK
content-type: application/json
content-length: 262
vary: access-control-request-method, access-control-request-headers
access-control-allow-origin: *
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
x-request-id: 0be6d1d1abd8e385267db8ad2a3fde79

{"id":2,"reference":"dashboard-91c2","status":"failed","evaluation_ids":[1],"analysed":0,"failed":0,"error":"The analysis API is unavailable. Nothing was saved.","created_at":"2026-12-02T01:52:55.716422Z","updated_at":"2026-12-02T01:53:34.278324Z","failures":[]}
the server’s log (stderr), after Ctrl-C
Server running at `http://127.0.0.1:3000`. Press Ctrl+C to stop.
POST    202  /api/batches  16.7ms
GET     200  /api/batches/2  4.3ms
Stopping. Waiting up to 20s for the work in progress.

Three attempts, then failed with the message from the failed hook, and nothing saved: no sentiment, no failure rows. Once the API is back, POST /api/batches/2/retry queues it again.

The Laravel side

The PHP of the Week 5 build day works unchanged: the AnalysisService client, the Analyse now controller and the WatchAnalysisBatch poll job read id, reference, status, analysed, error and failures, and this service sends all of them, with the same statuses. Only the base URL moves under /api:

.env (part, of the PHP Laravel application)
ANALYSIS_SERVICE_URL=http://127.0.0.1:3000/api
ANALYSIS_SERVICE_KEY=9f2c4e1ab7d05e38a1c6   # the same value as SERVICE_API_KEY in the Rust app's .env

That is the contract test for a rewrite: the callers do not change. If the PHP side had needed edits, the service would have changed its API, and every other caller would need them too.

Plain axum or Laravel Rust?

Week 5: axumWeek 6: Laravel Rust
Code you writeEvery piece: errors, key check, state, spawn, resumeThe decisions: retry rule, all-or-nothing, failure reasons
Background workInside the server processA separate worker, retries and failed jobs included
Startup and binarySmall: only what it usesThe framework’s: sessions, Inertia, mail and more, compiled in
Stabilityaxum 0.8, sqlx 0.9: matureA 0.1 beta: APIs may change before 1.0
FitsOne small service that does one thingAn application: users, pages, queues, many routes

For a single-purpose service next to a PHP Laravel application, both work, and plain axum is the smaller, steadier choice today. When the Rust side grows into an application of its own, Laravel Rust saves you from rebuilding the framework by hand, as Week 5 started to.

PracticeTwo extensions

Extension 1: send the retryable ones again

Add POST /api/batches/{batch}/resend: a new batch, with the reference <old>-resend, holding only the failures with retryable: true. Use first_or_create again, so a retried resend is safe too.

Extension 2: a progress count

Let the job write analysed after every evaluation instead of at the end, outside the transaction, and decide what Laravel sees when a batch fails half-way. Then decide whether the all-or-nothing rule was worth more than the progress bar.

Remember

  • first_or_create(…).found_or_created() with a unique index makes a POST safe to retry, even at the same moment.
  • A job that can run twice must find out it already ran; save a batch in one db::transaction.

Tomorrow: the Week 6 checkpoint. Tests with #[laravel::test] against a fresh database, the HTTP client and the queue faked, for every answer the service gives.