Rust Playbook

Course › Week 6 · Laravel Rust › Day 5 · lesson 40 of 42 · 25 min reading + 45 min practice

Queues and tasks

Jobs with #[job], retries and backoff, release and fail, and concurrent work with laravel::task.

Queueable#[job]queue:worklaravel::task

On this page
  1. 1. One function for the call
  2. 2. A job
  3. 3. Dispatching, and the worker
  4. 4. Retries, backoff and the failed hook
  5. 5. Workers in production
  6. The same job in PHP Laravel
  7. Practice
  8. Remember

In the Week 5 service, work after the response was a tokio::spawn with a semaphore, and the service had to resume batches a deploy cut off. Laravel Rust has queues, the same as PHP Laravel: a job is pushed to a table, a worker process takes it, and a job that fails is tried again later. A deploy that stops the worker leaves the job in the table.

This lesson moves the analysis of a batch into a job. The POST /api/batches from the models lesson answers 202 and pushes the job; a worker analyses the batch.

1. One function for the call

The analyse route of the previous lesson called the analysis API inside the handler. The job will make the same call, so it moves into a module of its own, src/analysis.rs, as a function that takes the settings and an evaluation with its answers loaded:

src/analysis.rsnew file
//! The call to the analysis API, shared by the analyse route and the batch job.

use laravel::http::client::{self, Backoff};
use laravel::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::config::services::Analysis;
use crate::models::Evaluation;

/// What the analysis API answers for one evaluation.
#[derive(Deserialize, Serialize)]
pub struct Sentiment {
    pub evaluation_id: i64,
    pub positive: i32,
    pub negative: i32,
    pub neutral: i32,
}

/// Sends an evaluation's comments to the analysis API. The evaluation must have its answers loaded.
pub async fn analyse(analysis: &Analysis, evaluation: &Evaluation) -> laravel::Result<Sentiment> {
    let comments: Vec<&str> = evaluation.answers.iter().filter_map(|a| a.comment.as_deref()).collect();

    let sentiment: Sentiment = client::post(&analysis.url)
        .json(json!({ "evaluation_id": evaluation.id, "comments": comments }))
        .timeout(analysis.timeout)
        .retry(3, Backoff::exponential(200.milliseconds()))
        .await
        .with_context(|| format!("evaluation {} could not be analysed", evaluation.id))?
        .json()?;
    Ok(sentiment)
}

The handler keeps loading the evaluation and calls the function. Its answer is the same as before:

src/http/handlers/evaluations.rschanged since lesson 39: +3 −22
use laravel::config::Section;use laravel::http::client::{self, Backoff};use laravel::prelude::*;use serde::{Deserialize, Serialize};use serde_json::json;  use crate::analysis::{self, Sentiment};use crate::config::services::Analysis;use crate::models::{Evaluation, Status}; 
45 unchanged lines/// The formats an evaluation can be exported in. Any other value in the URI is a 404.#[derive(Clone, Copy, Deserialize, Serialize)]#[serde(rename_all = "lowercase")]pub enum Format { Csv, Xlsx,} #[derive(Serialize)]pub struct Export { evaluation: i64, format: Format, url: String,} pub async fn export(Params((id, format)): Params<(i64, Format)>) -> Json<Export> { let extension = match format { Format::Csv => "csv", Format::Xlsx => "xlsx", }; Json(Export { evaluation: id, format, url: format!("/exports/evaluation-{id}.{extension}"), })} /// One evaluation, found by the {evaluation} in the URI. An unknown id is a 404 before this runs.pub async fn show(evaluation: Evaluation) -> Json<Evaluation> { Json(evaluation)} /// Every evaluation still waiting for the analysis, oldest first.pub async fn pending() -> laravel::Result<Json<Vec<Evaluation>>> { let evaluations = Evaluation::query() .filter(Evaluation::status.eq(Status::Pending)) .order_by(Evaluation::id) .get() .await?; Ok(Json(evaluations))} /// One evaluation with its answers, in two queries whatever the number of answers.pub async fn with_answers(Params(id): Params<i64>) -> laravel::Result<Json<Evaluation>> { let evaluation = Evaluation::query().with(Evaluation::answers).find_or_fail(id).await?;
Ok(Json(evaluation))} /// What the analysis API answers for one evaluation.#[derive(Deserialize, Serialize)]pub struct Sentiment { evaluation_id: i64, positive: i32, negative: i32, neutral: i32,} /// Sends an evaluation's comments to the analysis API and answers with its result.pub async fn analyse(analysis: Section<Analysis>, Params(id): Params<i64>) -> laravel::Result<Json<Sentiment>> { let evaluation = Evaluation::query().with(Evaluation::answers).find_or_fail(id).await?; let comments: Vec<&str> = evaluation.answers.iter().filter_map(|a| a.comment.as_deref()).collect(); let sentiment: Sentiment = client::post(&analysis.url) .json(json!({ "evaluation_id": evaluation.id, "comments": comments })) .timeout(analysis.timeout) .retry(3, Backoff::exponential(200.milliseconds())) .await .with_context(|| format!("evaluation {id} could not be analysed"))? .json()?; Ok(Json(sentiment)) Ok(Json(analysis::analyse(&analysis, &evaluation).await?))}

The new module is declared in lib.rs, with the others:

src/lib.rschanged since the new application: +1
pub mod analysis;mod app;pub mod config;mod console;
10 unchanged linespub mod events;pub mod http;pub mod listeners;pub mod models;pub mod routes;#[path = "../database/seeders/mod.rs"]pub mod seeders;pub mod testing; pub use app::{configure, create};

2. A job

The job will store what the analysis API answers, so evaluations gets three columns, in a new migration as always:

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

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .alter("evaluations", |table| {
            table.integer("positive").nullable();
            table.integer("negative").nullable();
            table.integer("neutral").nullable();
        })
        .await
}
src/models/evaluation.rschanged since lesson 38: +3
19 unchanged linesuse laravel::model::{HasMany, model};use laravel::prelude::*;use laravel::time::Timestamp;use serde::{Deserialize, Serialize}; use crate::models::Answer; /// Where an evaluation is in the analysis.#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]#[serde(rename_all = "snake_case")]pub enum Status { Pending, Analysed,} #[model]pub struct Evaluation { pub id: i64, pub school: String,
#[default] pub status: Status, pub average_tenths: Option<i32>, pub positive: Option<i32>, pub negative: Option<i32>, pub neutral: Option<i32>, pub created_at: Timestamp, pub updated_at: Timestamp, #[has_many] pub answers: HasMany<Answer>,}

A job is a struct that derives Queueable, and an impl marked #[job] with a handle method: the handle() of a PHP job class. The struct is what goes in the queue, serialised, so it carries plain data: the batch’s id, not a database connection. handle takes self and, like a handler, any services it needs, here the Analysis section.

task::map(evaluations, CONCURRENCY, …) runs the closure for every evaluation, at most eight at a time, and returns the results in the input’s order. It is the buffer_unordered of the reqwest lesson, with the order kept. If one call fails, the others are cancelled and the error is returned.

name = "batches.analyse" is the name stored with each queued job. Without it the name is the type’s path, app::jobs::AnalyseBatch, and moving the struct to another module would break the jobs already waiting.

src/jobs/analyse_batch.rsnew file
use laravel::config::Section;
use laravel::model::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};

/// 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;

#[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?;
        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,
            })
            .await?;
        }
        update!(batch {
            status: BatchStatus::Done
        })
        .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?;
        update!(batch {
            status: BatchStatus::Failed
        })
        .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))
}

A jobs module with the job, declared in lib.rs. Nothing else registers it: Laravel finds every #[job] by itself.

src/jobs/mod.rsnew file
mod analyse_batch;

pub use analyse_batch::AnalyseBatch;
src/lib.rschanged since the version above: +1
pub mod analysis;mod app;pub mod config;mod console;pub mod events;pub mod http;pub mod jobs;pub mod listeners;pub mod models;pub mod routes;#[path = "../database/seeders/mod.rs"]pub mod seeders;pub mod testing; pub use app::{configure, create};

3. Dispatching, and the worker

AnalyseBatch { batch_id: stored.id }.dispatch().await? pushes the job, the AnalyseBatch::dispatch($batch->id) of PHP. The handler gets a show too, for Laravel to poll the batch.

src/http/handlers/batches.rschanged since lesson 39: +8 −1
use laravel::db::Json as JsonColumn;use laravel::errors::Status;use laravel::model::{create, update};use laravel::prelude::*; use crate::jobs::AnalyseBatch;use crate::models::{AnalysisBatch, BatchStatus}; /// A batch of evaluations to analyse, as Laravel posts it.
6 unchanged lines#[laravel::input]#[validate(anyone)]pub struct NewBatch { #[validate(required, max_length(100), unique(AnalysisBatch::reference))] reference: String, #[validate(required, max_items(500), distinct, each(min_value(1)))]
evaluation_ids: Vec<i64>,} /// Stores the batch as queued. The queue lesson gives it to a worker./// 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)))}
16 unchanged lines/// 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.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 })
.await?; Ok(Json(batch))} /// A batch, for Laravel to poll.pub async fn show(batch: AnalysisBatch) -> Json<AnalysisBatch> { Json(batch)}

The worker is the application’s own command, laravel queue:work. --stop-when-empty makes it exit when there is nothing left, which is what a page like this one needs; a real worker keeps running:

src/routes/api.rschanged since lesson 39: +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.post("/batches/{analysis_batch}/retry", batches::retry); route.post("/evaluations/{evaluation}/analyse", evaluations::analyse); }); route.fallback(async || laravel::abort(404));}
$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' -H 'content-type: application/json' -d '{"reference": "dashboard-7f3e", "evaluation_ids": [1, 2]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 202 Accepted
content-type: application/json
content-length: 164
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: b3dd4b4849df79026ab4aa1633457239

{"id":2,"reference":"dashboard-7f3e","status":"queued","evaluation_ids":[1,2],"created_at":"2026-12-02T01:47:09.235247Z","updated_at":"2026-12-02T01:47:09.235247Z"}
$ laravel queue:work --stop-when-empty
Processing jobs from `database:default`. Press Ctrl+C to stop.
batches.analyse  130.5ms
$ 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: 162
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: 31294a4f639d6cf5cbb50c3f2d397880

{"id":2,"reference":"dashboard-7f3e","status":"done","evaluation_ids":[1,2],"created_at":"2026-12-02T01:47:09.235247Z","updated_at":"2026-12-02T01:47:09.405071Z"}
$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' http://127.0.0.1:3000/api/evaluations/1
HTTP/1.1 200 OK
content-type: application/json
content-length: 201
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: 7ee8f4b621808734c2be67a16c91595f

{"id":1,"school":"Alexandria STEM","status":"analysed","average_tenths":null,"positive":1,"negative":0,"neutral":0,"created_at":"2026-12-02T01:47:08.981173Z","updated_at":"2026-12-02T01:47:09.401662Z"}
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
GET     200  /api/batches/2  2.5ms
GET     200  /api/evaluations/1  2.0ms
Stopping. Waiting up to 20s for the work in progress.

The POST answered at once with the batch queued. The worker ran the job in about 130 ms: two calls of 100 ms each, at the same time. The batch is done, and the evaluation holds its sentiment counts.

The application and the worker are two processes of one binary. The QUEUE_CONNECTION=database of the skeleton’s .env keeps jobs in the jobs table that the framework’s migration created; Redis and SQS are a Cargo feature and a line in .env away.

4. Retries, backoff and the failed hook

A job that returns an error is not retried by default. tries = 3 allows three attempts, and backoff = [5.seconds(), 30.seconds()] sets the wait before the second and the third, the $tries and $backoff of a PHP job. timeout = 5.minutes() cancels an attempt that runs longer, at its next .await.

After the last attempt, the worker calls the job’s failed method and records the job in failed_jobs. Here failed marks the batch failed, so Laravel, polling, sees the end instead of a batch that stays running. The same application, with the analysis API down:

$ curl -si -H 'x-api-key: 9f2c4e1ab7d05e38a1c6' -H 'content-type: application/json' -d '{"reference": "dashboard-91c2", "evaluation_ids": [1, 2]}' http://127.0.0.1:3000/api/batches
HTTP/1.1 202 Accepted
content-type: application/json
content-length: 164
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: 3ad0e9260b383ab0ae3a590a67c32aed

{"id":2,"reference":"dashboard-91c2","status":"queued","evaluation_ids":[1,2],"created_at":"2026-12-02T01:47:17.368571Z","updated_at":"2026-12-02T01:47:17.368571Z"}
$ laravel queue:work --stop-when-empty
Processing jobs from `database:default`. Press Ctrl+C to stop.
batches.analyse retrying  623.2ms
evaluation 1 could not be analysed: the HTTP request to http://127.0.0.1:8999/api/analyse failed: Connection refused (os error 111)
$ 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: 165
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: 086de1059aca711f04568ed968a7baed

{"id":2,"reference":"dashboard-91c2","status":"running","evaluation_ids":[1,2],"created_at":"2026-12-02T01:47:17.368571Z","updated_at":"2026-12-02T01:47:17.422789Z"}

5.5 s later:

$ laravel queue:work --stop-when-empty
Processing jobs from `database:default`. Press Ctrl+C to stop.
batches.analyse retrying  629.2ms
evaluation 1 could not be analysed: the HTTP request to http://127.0.0.1:8999/api/analyse failed: Connection refused (os error 111)

31 s later:

$ laravel queue:work --stop-when-empty
Processing jobs from `database:default`. Press Ctrl+C to stop.
batches.analyse failed  630.6ms
evaluation 1 could not be analysed: the HTTP request to http://127.0.0.1:8999/api/analyse failed: Connection refused (os error 111)
$ 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: 164
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: 85e96a75a9fbd4be67f8638ce8d2356c

{"id":2,"reference":"dashboard-91c2","status":"failed","evaluation_ids":[1,2],"created_at":"2026-12-02T01:47:17.368571Z","updated_at":"2026-12-02T01:47:55.974809Z"}
$ laravel queue:failed
ID                                    Queue             Job              Failed at
01a2346f-45fa-77ac-a53b-37f12e03bdf9  database:default  batches.analyse  2026-12-02 01:47:55
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  11.6ms
GET     200  /api/batches/2  2.9ms
GET     200  /api/batches/2  3.1ms

Each attempt took about 600 ms: the HTTP client’s own three tries with backoff, inside the job’s attempt. Between the attempts the batch shows running, because the first attempt set it and nothing reset it; a batch that is waiting for a retry is not finished, so Laravel keeps polling. After the third attempt, failed ran and the job is in queue:failed, from where laravel queue:retry can run it again once the API is back.

The first worker run exited while the job was still in the queue: a job waiting out its backoff is not available yet, so for --stop-when-empty the queue is empty. A worker without that flag picks it up the moment the wait is over.

5. Workers in production

A worker is a long-running process, kept alive by systemd, Supervisor, Docker or Laravel Cloud, as for php artisan queue:work:

terminal
laravel queue:work --concurrency=4   # four jobs at a time in one process
laravel queue:restart                # after a deploy: workers finish their job, then exit to be restarted

--concurrency runs several jobs in one process, which suits jobs that wait on the network, as this one does. A worker keeps running the binary it started with, so a deploy restarts the workers with queue:restart; each finishes the job in hand first.

This is what replaces Week 5’s resume on startup. A job a deploy interrupts was never removed from the jobs table, so a worker takes it again. What stays your job is the same as in PHP: a job that may run twice must be safe to run twice. This one is, because it writes the same counts each time.

The same job in PHP Laravel

app/Jobs/AnalyseBatch.php
<?php

namespace App\Jobs;

use App\Models\AnalysisBatch;
use App\Services\Analysis;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Concurrency;
use Throwable;

class AnalyseBatch implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;

    /** @var list<int> */
    public array $backoff = [5, 30];

    public int $timeout = 300;

    public function __construct(public int $batchId) {}

    public function handle(Analysis $analysis): void
    {
        $batch = AnalysisBatch::findOrFail($this->batchId);
        $batch->update(['status' => 'running']);

        // ... the analysis, one evaluation after another, unless you reach for Concurrency::run()

        $batch->update(['status' => 'done']);
    }

    public function failed(?Throwable $exception): void
    {
        AnalysisBatch::whereKey($this->batchId)->update(['status' => 'failed']);
    }
}

The same properties, the same failed hook. The real difference is inside handle: a PHP worker runs one request at a time, so eight calls at once need Http::pool or Concurrency::run() with child processes, while in Rust task::map makes them in one process, on one thread, while the others wait on the network.

PracticeThe queues and tasks guides

Read queues up to “Job middleware”, and the first two parts of tasks.

Exercise: one failure is not the batch’s

As written, one evaluation the API cannot analyse fails the whole batch. Change the closure so that it returns Ok with a Result inside (Ok(analyse_one(…).await)), save the evaluations that succeeded, and fail the job only when none did, as the Week 4 worker decided. The build day needs exactly this.

Remember

  • A job is a Queueable struct with a #[job] impl; give it a stable name, tries and backoff, and a failed hook that leaves no record half-done.
  • task::map(items, n, …) makes n calls at a time and keeps the order.

Tomorrow: the build day. The Week 5 service, rebuilt on Laravel Rust: a retried POST returns the same batch, every result is saved in one transaction, and Laravel calls it as before.