Rust Playbook

Course › Week 4 · Async and plugging into Laravel › Day 6 · lesson 27 of 42 · 1 h 5 min reading + 2–3 h practice

Build the Laravel worker

An artisan command sends a batch to Rust, Rust processes it concurrently and writes results in one transaction.

tokiosqlxProcess

On this page
  1. The task
  2. The design
  3. The tables, as Laravel creates them
  4. Step 1: errors and their exit codes
  5. Step 2: config and the job
  6. Step 3: the database
  7. Step 4: the analysis API client
  8. Step 5: the run
  9. Step 6: main.rs
  10. Run the tests
  11. Run it: the four outcomes
  12. And when the setup is wrong
  13. The Laravel side
  14. Deploy
  15. What changed, and what did not
  16. Practice
  17. Remember

This week’s tool is the one the course was planned around: Rust doing one heavy job inside a Laravel system, with Laravel still in charge of the queue, the retries and the users. It joins every lesson of the week, async, reqwest, sqlx, config and logging, and the process protocol, into one binary of about 400 lines.

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 Process lesson, the PHP side is syntax-checked but not executed on this machine.

#dataThursday 10:15

Sara · dataThe nightly analysis job takes 3 hours now. For each evaluation it loads the answers, sends the comments to the analysis API, and saves the counts, one evaluation at a time, because each call waits about 100 ms and PHP waits with it.

Omar · backendKeep the queue, the retries and the dashboard in Laravel. Give me a binary that takes a batch of ids, does the waiting in parallel, and either saves the whole batch or nothing. And it must tell the job apart: “API down, try later” is not the same as “these 3 evaluations have no answers”.

The design

One job, start to finish:

StepWhereLesson
Pick pending evaluations, split into batches of 200, queue one job eachLaravel: artisan command
Send {"evaluation_ids": […]} on stdinLaravel: queued jobProcess
Check the config, load every answer of the batch in two queriesRustsqlx, config
Call the analysis API for each evaluation, 8 at a time, with retriesRustreqwest
Save every result in one transactionRustsqlx
Print the result as JSON; exit 0, 1, 2 or 3RustProcess
Retry the job, or requeue only the retryable ids, or fail itLaravel: queued job

Two queries for the whole batch, not two per evaluation: where evaluation_id = any($1) with the list of ids bound as one Postgres array. The 3-hour job was mostly waiting; this one waits for 8 calls at a time.

worker/
worker/
├── Cargo.toml
└── src/
    ├── main.rs       (logging, stdin → run → stdout, exit codes)
    ├── lib.rs
    ├── error.rs      (WorkerError and its exit code)
    ├── config.rs     (DATABASE_URL, ANALYSIS_URL, WORKER_CONCURRENCY)
    ├── job.rs        (Job in, Output out)
    ├── db.rs         (load answers, save results in one transaction)
    ├── analysis.rs   (the analysis API client, with retries)
    └── process.rs    (the run: group, analyse concurrently, decide, save)

The tables, as Laravel creates them

database/migrations/2026_11_02_000000_create_evaluations_tables.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('evaluations', function (Blueprint $table) {
            $table->id();
            $table->string('school');
            $table->string('status', 20)->default('pending');   // pending → analysed
            $table->integer('average_tenths')->nullable();
            $table->integer('positive')->nullable();
            $table->integer('negative')->nullable();
            $table->integer('neutral')->nullable();
            $table->timestamp('analysed_at')->nullable();
            $table->timestamps();
        });

        Schema::create('answers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('evaluation_id')->constrained();
            $table->string('question', 20);
            $table->smallInteger('score');                     // smallint: i16 in Rust
            $table->text('comment')->nullable();
        });
    }
};

The sample data: five evaluations. 1042, 1043 and 1045 have answers with comments, one of them in Arabic; 1044 has no answers; 1046 has one answer without a comment.

Step 1: errors and their exit codes

Every way the run can stop, in one enum, as in csv2json. The one new idea is exit_code(): the error decides its own exit code, so main cannot map one wrongly. Only BadJob is 2 (“do not retry”); everything else is 1 (“may work later”).

AnalysisUnavailable is the answer to Omar’s second question, and step 6 explains when it is used.

src/error.rsnew file
use thiserror::Error;

/// Everything that stops a run. One evaluation that cannot be analysed is not an error:
/// it is reported in the output's "failed" list.
#[derive(Debug, Error)]
pub enum WorkerError {
    #[error("{0} is not set")]
    MissingConfig(&'static str),

    #[error("{name} must be a whole number from 1 to 64, got '{value}'")]
    BadConfig { name: &'static str, value: String },

    #[error("the job on stdin is not valid: {0}")]
    BadJob(serde_json::Error),

    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),

    #[error("the analysis API is unavailable, nothing was written: {0}")]
    AnalysisUnavailable(String),

    #[error("cannot save the results, nothing was written: {0}")]
    Save(sqlx::Error),

    #[error("cannot build the HTTP client: {0}")]
    Http(#[from] reqwest::Error),

    #[error("cannot write the result: {0}")]
    Output(#[from] std::io::Error),
}

impl WorkerError {
    /// 2 for a job Laravel should not retry; 1 for everything that may work later.
    pub fn exit_code(&self) -> u8 {
        match self {
            WorkerError::BadJob(_) => 2,
            _ => 1,
        }
    }
}

Step 2: config and the job

The Config of the config lesson, without .env: Laravel starts the process with its own environment, so the values can sit in Laravel’s .env next to everything else. ANALYSIS_URL is required: there is no sensible default for a production API.

src/config.rsnew file
use std::env;

use crate::error::WorkerError;

/// Everything the worker needs from its environment, checked once at startup.
/// Laravel passes its own environment to the process, so these can live in Laravel's .env.
pub struct Config {
    pub database_url: String,
    pub analysis_url: String,
    pub concurrency: usize,
}

impl Config {
    pub fn from_env() -> Result<Config, WorkerError> {
        let database_url = required("DATABASE_URL")?;
        let analysis_url = required("ANALYSIS_URL")?;
        let concurrency = match env::var("WORKER_CONCURRENCY") {
            Err(_) => 8,
            Ok(value) => match value.trim().parse::<usize>() {
                Ok(n) if (1..=64).contains(&n) => n,
                _ => {
                    return Err(WorkerError::BadConfig {
                        name: "WORKER_CONCURRENCY",
                        value,
                    });
                }
            },
        };
        Ok(Config {
            database_url,
            analysis_url,
            concurrency,
        })
    }
}

fn required(name: &'static str) -> Result<String, WorkerError> {
    match env::var(name) {
        Ok(value) if !value.trim().is_empty() => Ok(value),
        _ => Err(WorkerError::MissingConfig(name)),
    }
}

The job and the output. Ids are i64 because they are Postgres bigints. Each Failed entry says whether it is retryable, so Laravel can send those evaluations again without resending the rest.

src/job.rsnew file
use serde::{Deserialize, Serialize};

/// What Laravel sends on stdin.
#[derive(Deserialize)]
pub struct Job {
    pub evaluation_ids: Vec<i64>,
}

/// What Laravel reads from stdout: one JSON document.
#[derive(Debug, Default, Serialize)]
pub struct Output {
    pub analysed: Vec<Analysed>,
    pub failed: Vec<Failed>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Analysed {
    pub id: i64,
    pub average_tenths: i32,
    pub positive: i32,
    pub negative: i32,
    pub neutral: i32,
}

#[derive(Debug, PartialEq, Serialize)]
pub struct Failed {
    pub id: i64,
    pub reason: String,
    /// True when sending this evaluation again later may work (the analysis API was down).
    pub retryable: bool,
}

Step 3: the database

load runs two queries for the whole batch. = any($1) with a bound &[i64] is how Postgres takes a list: sqlx sends the slice as one array parameter, so 200 ids are still one query and still safe from injection.

save is section 6 of the sqlx lesson: one transaction, one update per result, commit at the end. If any update fails, ? returns before the commit and every earlier update in the batch is rolled back.

src/db.rsnew file
use sqlx::PgPool;

use crate::job::Analysed;

/// One answer, as Laravel stored it.
#[derive(sqlx::FromRow)]
pub struct Answer {
    pub evaluation_id: i64,
    pub score: i16,
    pub comment: Option<String>,
}

/// 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 in one transaction: all of them, or none.
pub async fn save(pool: &PgPool, results: &[Analysed]) -> 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?;
    }
    tx.commit().await
}

score is i16 because the column is a smallint. updated_at is set by hand, because Eloquent is not here to do it.

Step 4: the analysis API client

The retry loop from the reqwest lesson, with one change: a failure is a Failure struct, a reason and a retryable flag, instead of a plain String. Retryable means “the API was unreachable or overloaded after three attempts”; a 404 or a body that does not decode will not get better by asking again.

#[derive(Clone)] on Analyser: each concurrent task gets its own copy, and the copies share one connection pool inside reqwest’s Client.

src/analysis.rsnew file
use std::time::Duration;

use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use tokio::time::sleep;
use tracing::warn;

/// The sentiment counts the analysis API returns for one evaluation's comments.
#[derive(Debug, Deserialize)]
pub struct Sentiment {
    pub positive: i32,
    pub negative: i32,
    pub neutral: i32,
}

#[derive(Serialize)]
struct Request<'a> {
    evaluation_id: i64,
    comments: &'a [&'a str],
}

/// Why one evaluation could not be analysed, and whether asking again later may work.
#[derive(Debug)]
pub struct Failure {
    pub reason: String,
    pub retryable: bool,
}

/// A client for the analysis API. Cheap to clone: clones share one connection pool.
#[derive(Clone)]
pub struct Analyser {
    client: Client,
    url: String,
}

impl Analyser {
    pub fn new(url: &str) -> Result<Analyser, reqwest::Error> {
        let client = Client::builder()
            .timeout(Duration::from_secs(10))
            .user_agent("evaluation-worker/0.1")
            .build()?;
        Ok(Analyser {
            client,
            url: url.to_string(),
        })
    }

    /// Up to three attempts; only timeouts, connection failures, 429 and 5xx are retried.
    pub async fn analyse(
        &self,
        evaluation_id: i64,
        comments: &[&str],
    ) -> Result<Sentiment, Failure> {
        let body = Request {
            evaluation_id,
            comments,
        };
        let mut delay = Duration::from_millis(200);
        let mut attempt: u32 = 1;
        loop {
            let retry = match self.client.post(&self.url).json(&body).send().await {
                Ok(response) if response.status().is_success() => {
                    return response.json::<Sentiment>().await.map_err(|e| Failure {
                        reason: format!("analysis API sent an unexpected body: {e}"),
                        retryable: false,
                    });
                }
                Ok(response) => {
                    let status = response.status();
                    if status != StatusCode::TOO_MANY_REQUESTS && !status.is_server_error() {
                        return Err(Failure {
                            reason: format!("analysis API answered {status}"),
                            retryable: false,
                        });
                    }
                    format!("analysis API answered {status}")
                }
                Err(e) if e.is_timeout() || e.is_connect() => {
                    format!("analysis API unreachable: {e}")
                }
                Err(e) => {
                    return Err(Failure {
                        reason: format!("analysis request failed: {e}"),
                        retryable: false,
                    });
                }
            };
            if attempt == 3 {
                return Err(Failure {
                    reason: retry,
                    retryable: true,
                });
            }
            warn!(evaluation_id, attempt, reason = %retry, "retrying");
            sleep(delay).await;
            delay *= 2;
            attempt += 1;
        }
    }
}

reason = %retry logs the String with its Display form, the % from the config lesson. The warning carries the evaluation id and the attempt, so the Laravel log shows which evaluation the API struggled with.

Step 5: the run

group is plain synchronous code, so it is tested without a database: it puts each answer under its evaluation, and moves the ids that cannot be analysed (“no such evaluation”, “no answers”) into the failed list. binary_search_by_key finds an id in the sorted list in a few steps instead of scanning it for every answer.

retain keeps the items for which the closure returns true and drops the rest. Here the closure also records why an item is dropped, then returns false: one pass decides both lists.

src/process.rsnew file
use std::time::Duration;

use futures::stream::{self, StreamExt};
use sqlx::postgres::PgPoolOptions;
use tracing::info;

use crate::analysis::{Analyser, Failure, Sentiment};
use crate::config::Config;
use crate::db::{self, Answer};
use crate::error::WorkerError;
use crate::job::{Analysed, Failed, Job, Output};

/// Runs one job: load, analyse concurrently, save everything in one transaction.
pub async fn run(job: &Job, config: &Config) -> Result<Output, WorkerError> {
    let mut ids = job.evaluation_ids.clone(); // sorted and deduplicated below; the job stays as sent
    ids.sort_unstable();
    ids.dedup();

    let pool = PgPoolOptions::new()
        .max_connections(5)
        .acquire_timeout(Duration::from_secs(5))
        .connect(&config.database_url)
        .await?;
    let (known, answers) = db::load(&pool, &ids).await?;
    let (todo, mut failed) = group(&ids, &known, answers);
    info!(evaluations = todo.len(), skipped = failed.len(), "loaded");

    let analyser = Analyser::new(&config.analysis_url)?;
    let outcomes: Vec<(i64, i32, Result<Sentiment, Failure>)> = stream::iter(todo)
        .map(|(id, answers)| {
            let analyser = analyser.clone();
            async move {
                let comments: Vec<&str> = answers
                    .iter()
                    .filter_map(|a| a.comment.as_deref())
                    .collect();
                let average = average_tenths(&answers);
                (id, average, analyser.analyse(id, &comments).await)
            }
        })
        .buffer_unordered(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 {
                id,
                reason: f.reason,
                retryable: f.retryable,
            }),
        }
    }
    analysed.sort_by_key(|a| a.id);
    failed.sort_by_key(|f| f.id);

    // Nothing analysed and every failure temporary: the API is down. That is not "partly done",
    // it is a failed run that Laravel should retry as a whole, later.
    if analysed.is_empty() && !failed.is_empty() && failed.iter().all(|f| f.retryable) {
        return Err(WorkerError::AnalysisUnavailable(failed[0].reason.clone()));
    }

    db::save(&pool, &analysed)
        .await
        .map_err(WorkerError::Save)?;
    info!(saved = analysed.len(), failed = failed.len(), "done");
    Ok(Output { analysed, failed })
}

/// Splits the job'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 {
            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 {
                    id: 1044,
                    reason: String::from("no answers"),
                    retryable: false,
                },
                Failed {
                    id: 9999,
                    reason: String::from("no such evaluation"),
                    retryable: false,
                },
            ]
        );
    }
}

The concurrent part is the stream from the reqwest lesson: buffer_unordered(config.concurrency) keeps 8 analysis calls in flight. Each task owns its evaluation’s answers (async move), borrows the comments out of them, and returns the id, the average and the outcome together, so nothing has to be matched up afterwards.

Then the decision Omar asked for, just before saving: nothing analysed and every failure retryable means the API is down, so the run fails as a whole and saves nothing. Anything else is saved, and the failures are listed.

Step 6: main.rs

Logging goes to stderr without colour codes or timestamps: Laravel captures stderr and writes it to its own log, which adds the timestamp. Then the three outcomes become exit codes in one match.

src/lib.rsnew file
//! worker: analyse a batch of evaluations for Laravel.
//! Job on stdin, result on stdout, logs on stderr, and an exit code that says what happened.

pub mod analysis;
pub mod config;
pub mod db;
pub mod error;
pub mod job;
pub mod process;
src/main.rsnew file
use std::io::{self, Write};
use std::process::ExitCode;

use tracing::error;
use tracing_subscriber::EnvFilter;
use worker::config::Config;
use worker::error::WorkerError;
use worker::job::{Job, Output};
use worker::process;

#[tokio::main]
async fn main() -> ExitCode {
    // Logs go to stderr as plain text: no colour codes, no timestamps (Laravel adds its own when it logs them).
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(io::stderr)
        .with_ansi(false)
        .without_time()
        .init();

    match run().await {
        Ok(output) if output.failed.is_empty() => ExitCode::SUCCESS,
        Ok(_) => ExitCode::from(3), // partly done: the result lists what failed
        Err(e) => {
            error!("{e}");
            ExitCode::from(e.exit_code())
        }
    }
}

async fn run() -> Result<Output, WorkerError> {
    let job: Job = serde_json::from_reader(io::stdin().lock()).map_err(WorkerError::BadJob)?;
    let config = Config::from_env()?;
    let output = process::run(&job, &config).await?;

    let mut stdout = io::stdout().lock();
    serde_json::to_writer(&mut stdout, &output).map_err(io::Error::from)?;
    writeln!(stdout)?;
    stdout.flush()?;
    Ok(output)
}

The job is read before the config is checked: a malformed job is reported as exit 2 even on a machine where the config is also wrong, so Laravel never retries a job that can never succeed.

Run the tests

$ cargo test
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.00s

The tests cover the logic that needs no network or database. The runs below cover the rest, against the real ones.

Run it: the four outcomes

Each run starts from the same five pending evaluations. DATABASE_URL and ANALYSIS_URL come from the environment, as Laravel would pass them.

job.json
{"evaluation_ids": [1042, 1043]}
$ cargo run < job.json
{"analysed":[{"id":1042,"average_tenths":43,"positive":1,"negative":1,"neutral":0},{"id":1043,"average_tenths":30,"positive":0,"negative":2,"neutral":0}],"failed":[]}
 INFO worker::process: loaded evaluations=2 skipped=0
 INFO worker::process: done saved=2 failed=0

Exit 0: both analysed and saved. The JSON is the only thing on stdout; the two log lines are on stderr.

job.json
{"evaluation_ids": [1042, 1043, 1044, 1045, 9999]}
$ cargo run < job.json
{"analysed":[{"id":1042,"average_tenths":43,"positive":1,"negative":1,"neutral":0},{"id":1043,"average_tenths":30,"positive":0,"negative":2,"neutral":0},{"id":1045,"average_tenths":50,"positive":2,"negative":0,"neutral":0}],"failed":[{"id":1044,"reason":"no answers","retryable":false},{"id":9999,"reason":"no such evaluation","retryable":false}]}
 INFO worker::process: loaded evaluations=3 skipped=2
 INFO worker::process: done saved=3 failed=2
exit code 3

Exit 3, partly done. Three evaluations were analysed and saved in one transaction. 1044 has no answers and 9999 does not exist, both retryable: false: sending them again would not help, so the PHP side reports them instead of retrying.

job.json
{"evaluation_ids": [1042, 1046]}
$ cargo run < job.json
 INFO worker::process: loaded evaluations=2 skipped=0
 WARN worker::analysis: retrying evaluation_id=1042 attempt=1 reason=analysis API unreachable: error sending request for url (http://127.0.0.1:8999/api/analyse)
 WARN worker::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 worker::analysis: retrying evaluation_id=1042 attempt=2 reason=analysis API unreachable: error sending request for url (http://127.0.0.1:8999/api/analyse)
 WARN worker::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 worker: the analysis API is unavailable, nothing was written: analysis API unreachable: error sending request for url (http://127.0.0.1:8999/api/analyse)
exit code 1

Exit 1, with the analysis API unreachable (a wrong port). Each evaluation was tried three times, with 200 and 400 ms between attempts, then the run failed without saving anything. That is the “try later” Omar asked for: Laravel retries the whole job after its backoff.

job.json
{"evaluation_ids": "1042,1043"}
$ cargo run < job.json
ERROR worker: the job on stdin is not valid: invalid type: string "1042,1043", expected a sequence at line 1 column 30
exit code 2

Exit 2: the ids were sent as one string, the kind of bug a missing array_map('intval', …) causes. Nothing was touched, and Laravel will not retry it.

And when the setup is wrong

job.json
{"evaluation_ids": [1042]}
$ cargo run < job.json
ERROR worker: ANALYSIS_URL is not set
exit code 1

A missing setting: one sentence, before anything is read or written.

job.json
{"evaluation_ids": [1042]}
$ cargo run < job.json
ERROR worker: database error: pool timed out while waiting for an open connection
exit code 1

The database is down (a wrong port): exit 1 after the 5-second acquire timeout. Laravel retries later.

The Laravel side

The runner

The ScoreRunner of the Process lesson, for this protocol. It returns a typed result, and turns each exit code into exactly one decision:

app/Services/Worker/WorkerRunner.php
<?php

namespace App\Services\Worker;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use InvalidArgumentException;
use JsonException;

final class WorkerRunner
{
    public function __construct(private readonly string $binary, private readonly int $timeout = 600)
    {
    }

    /**
     * @param  list<int>  $evaluationIds
     *
     * @throws WorkerFailed  nothing was saved; retry the whole batch later
     * @throws InvalidArgumentException  the worker rejected the job; a bug on this side
     */
    public function analyse(array $evaluationIds): WorkerResult
    {
        $job = json_encode(['evaluation_ids' => array_map('intval', $evaluationIds)], JSON_THROW_ON_ERROR);

        $result = Process::input($job)->timeout($this->timeout)->run([$this->binary]);

        foreach (preg_split('/\R/', trim($result->errorOutput())) ?: [] as $line) {
            if ($line !== '') {
                Log::info('worker: ' . $line);
            }
        }

        return match ($result->exitCode()) {
            0, 3 => $this->parse($result->output()),
            2 => throw new InvalidArgumentException('the worker rejected the job; see the log'),
            default => throw new WorkerFailed('the worker exited with ' . $result->exitCode() . '; see the log'),
        };
    }

    /** @throws WorkerFailed */
    private function parse(string $stdout): WorkerResult
    {
        try {
            $data = json_decode($stdout, true, flags: JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
            throw new WorkerFailed('the worker wrote something that is not JSON', previous: $e);
        }

        $retry = [];
        $failed = [];
        foreach ($data['failed'] ?? [] as $row) {
            if ($row['retryable']) {
                $retry[] = (int) $row['id'];
            } else {
                $failed[(int) $row['id']] = (string) $row['reason'];
            }
        }

        return new WorkerResult(count($data['analysed'] ?? []), $retry, $failed);
    }
}

Each line of stderr becomes one Laravel log line, which gives the Rust logs Laravel’s timestamps and channels.

app/Services/Worker/WorkerResult.php
<?php

namespace App\Services\Worker;

final readonly class WorkerResult
{
    /**
     * @param  list<int>  $retry  evaluations to send again later
     * @param  array<int, string>  $failed  evaluation id => why it can never be analysed
     */
    public function __construct(public int $analysed, public array $retry, public array $failed)
    {
    }
}
app/Services/Worker/WorkerFailed.php
<?php

namespace App\Services\Worker;

use RuntimeException;

/** The worker did not finish, and saved nothing. Retrying later may succeed. */
final class WorkerFailed extends RuntimeException
{
}

The queued job

WorkerFailed is thrown on to the queue, which retries with backoff. A rejected job fails at once. Retryable ids from a partial run go into a new, delayed job, so the analysed ones are never sent twice:

app/Jobs/AnalyseEvaluations.php
<?php

namespace App\Jobs;

use App\Services\Worker\WorkerRunner;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;

final class AnalyseEvaluations implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    /** @var list<int> */
    public array $backoff = [60, 300, 900, 1800];

    public int $timeout = 660;   // longer than the runner's own process timeout

    /** @param  list<int>  $evaluationIds */
    public function __construct(public readonly array $evaluationIds)
    {
    }

    public function handle(WorkerRunner $worker): void
    {
        try {
            $result = $worker->analyse($this->evaluationIds);
        } catch (InvalidArgumentException $e) {
            $this->fail($e);

            return;
        }

        foreach ($result->failed as $id => $reason) {
            Log::warning('evaluation cannot be analysed', ['evaluation_id' => $id, 'reason' => $reason]);
        }
        if ($result->retry !== []) {
            self::dispatch($result->retry)->delay(now()->addMinutes(5));
        }
    }
}

$timeout = 660 on the job, longer than the 600-second process timeout: the process times out first, with a clean WorkerFailed, instead of the queue killing the PHP worker in the middle of it.

The artisan command

app/Console/Commands/AnalyseEvaluationsCommand.php
<?php

namespace App\Console\Commands;

use App\Jobs\AnalyseEvaluations;
use App\Models\Evaluation;
use Illuminate\Console\Command;

final class AnalyseEvaluationsCommand extends Command
{
    protected $signature = 'evaluations:analyse {--batch=200 : evaluations per worker run}';

    protected $description = 'Queue every pending evaluation for analysis by the Rust worker';

    public function handle(): int
    {
        $batch = (int) $this->option('batch');
        if ($batch < 1 || $batch > 1000) {
            $this->error('--batch must be from 1 to 1000');

            return self::INVALID;
        }

        $jobs = 0;
        Evaluation::query()
            ->where('status', 'pending')
            ->select('id')
            ->chunkById($batch, function ($evaluations) use (&$jobs) {
                AnalyseEvaluations::dispatch($evaluations->pluck('id')->all());
                $jobs++;
            });

        $this->info("Queued {$jobs} batches of up to {$batch} evaluations.");

        return self::SUCCESS;
    }
}

self::INVALID is Artisan’s exit code 2, the same meaning as clap’s. The command only queues; the work happens on the queue workers, where retries and timeouts are managed.

Deploy

terminal (in the deploy script)
cargo build --release --manifest-path worker/Cargo.toml
install -m 755 worker/target/release/worker bin/worker

# a smoke test: an empty job must be rejected with exit 2, proving the binary starts
echo '{}' | bin/worker; test $? -eq 2

And in Laravel’s .env: WORKER_BINARY, ANALYSIS_URL and DATABASE_URL (or DB_URL) next to the database settings it already has.

What changed, and what did not

BeforeAfter
Analysis callsOne at a time, in PHP8 at a time, in Rust
Queries per batch of 200400 (answers + save, per evaluation)2 to load, 1 transaction to save
When the API is downEach evaluation fails on its own, some savedNothing saved, the whole job retried later
Queue, retries, scheduling, dashboardLaravelLaravel

The time the job takes is mostly the analysis API’s: 1,000 evaluations at 100 ms each are 100 seconds one at a time and about 13 seconds 8 at a time. Raise WORKER_CONCURRENCY only as far as the API’s owner agrees to.

PracticeTwo extensions

Extension 1: skip what is already analysed

Two overlapping jobs can send the same evaluation twice. Make load return only evaluations whose status is still pending, and report the others as failed with "already analysed", retryable: false. Add a test for group with an id that is known but not pending.

Extension 2: lock while analysing

Better than skipping: claim the batch at the start, in its own short transaction, with update evaluations set status = 'analysing' where id = any($1) and status = 'pending' returning id. Only the returned ids are processed. Then decide what must happen to the analysing status when the run fails, so a crashed run does not leave evaluations stuck forever. (Hint: Laravel’s scheduler can reset rows that have been analysing for more than an hour.)

Remember

  • Load a batch in a few queries, wait for many calls at once, save in one transaction.
  • Tell “try again later” apart from “never possible”, and let Laravel own the retries.

Tomorrow is the Week 4 checkpoint: break the database in the middle of a save, and prove that nothing was half-written.