Queued Jobs
Part 2 · Laravel Rust. Move slow or important work out of the request with queued jobs: Queueable, #[job], dispatching, drivers, Inject<T>, retries, chains and batches.
When a customer places an order at the Rusty Bean Café, the barista does not stop everything to type out a receipt while the customer stands there. They take the order, hand the customer a number, and a receipt gets handled in the background. A queue does exactly that for your website.
In this lesson you will learn what a queue is, how to write a job in Laravel Rust, how to dispatch it, and how retries, chains and batches fit in.
Note
Laravel Rust is in beta (announced December 1, 2026). The code here is adapted from the official Queues guide (opens in new tab). Check it for the latest details.
Why queues?
Some work is too slow to do while a visitor waits (sending an email, resizing a photo). Other work is too important to lose (charging a card, sending a receipt). In the last lesson, task::background handled the first kind. It does not retry, and a crash loses it.
A queue solves both problems:
- Your handler writes a small note, called a job, into a list and replies to the visitor straight away.
- A separate program, the queue worker, picks notes off the list one by one and does the work.
- If a job fails, the worker can try again later.
The note is stored somewhere safe, so even a server restart does not lose it.
Writing a job
A job is a struct that derives Queueable, paired with a #[job] block that holds its handle method. Here is a job that sends a receipt for an order. For now, it takes the order’s ID:
use laravel::queue::{Queueable, job};
use crate::models::Order;
#[derive(Queueable)]pub struct SendReceipt { pub order_id: i64,}
#[job]impl SendReceipt { async fn handle(self) -> laravel::Result<()> { let order = Order::find_or_fail(self.order_id).await?;
// Build and send the receipt for `order`... Ok(()) }}Step by step:
#[derive(Queueable)]turns the struct into something Laravel can save to a queue, so its fields must be plain data.#[job] impl SendReceiptmarks the block that holdshandle. You can put jobs in any module (such assrc/jobs/). Laravel discovers them automatically, so there is nothing to register.handleis the work. It consumesselfand returns()orlaravel::Result<()>.Order::find_or_failloads a fresh copy of the order when the job actually runs, which might be seconds later.
Models in jobs
Storing an ID and loading the row yourself is fine, but a job may also hold the model directly:
#[derive(Queueable)]pub struct SendReceipt { pub order: Order,}When you dispatch this job, Laravel saves only the model’s primary key (its id). Before handle runs, the worker reloads the row from the database, so the job always sees fresh data. If the row has been deleted in the meantime, the worker deletes the job instead of running it. Relationships are not saved, so load any that handle needs yourself.
Dispatching a job
To queue a job, create it and call .dispatch().await:
use crate::jobs::SendReceipt;
// inside your `store` handler, after saving the order:SendReceipt { order }.dispatch().await?;Awaiting dispatch pushes the job onto your default queue and returns right away. You can also choose where and when it runs:
SendReceipt { order } .dispatch() .on_connection("redis") .on_queue("receipts") .delay(10.minutes()) .await?;Tip
If you dispatch a job inside a database transaction, Laravel waits for the transaction to commit before pushing it. That way a worker can never pick up a job whose order is not saved yet.
Running the worker
Jobs do nothing until a worker is running. Start one with:
laravel queue:workThe worker prints each job as it finishes, with its outcome and duration. During development, laravel dev starts your web server, a queue worker and Vite together, according to the installation guide. If you forget the worker, jobs just pile up waiting.
Drivers: where the list lives
A connection is the place jobs are stored, and a queue is a named list on a connection. Laravel gives you one API over several drivers:
| Driver | Where jobs live |
|---|---|
database |
A jobs table (the default) |
redis |
Redis (needs the redis feature) |
sqs |
Amazon SQS (needs the sqs feature) |
cloud |
Laravel Cloud’s managed queues |
sync |
Runs immediately, no worker needed |
You pick one with the QUEUE_CONNECTION variable in .env. The database driver needs its tables, which new applications get from a create_jobs_table migration containing one line: laravel::queue::tables!();. Run laravel migrate before dispatching your first job. Per the guide, tests use the sync driver by default.
Services with Inject<T>
A job often needs a helper, such as a service that formats receipts. Add an Inject<T> parameter to handle and Laravel supplies it:
use laravel::container::Inject;use laravel::queue::job;
use crate::services::ReceiptPrinter;
#[job]impl SendReceipt { async fn handle(self, printer: Inject<ReceiptPrinter>) -> laravel::Result<()> { printer.print(&self.order).await?; Ok(()) }}ReceiptPrinter is a service you would write yourself, so treat this as illustrative. handle may also take config sections (Section<T>) and an &Attempt, which tells the job which attempt number it is on.
Retries, backoff and timeouts
By default a failing job is tried once. Ask for more with options on #[job]:
#[job( queue = "receipts", tries = 3, backoff = [10.seconds(), 1.minutes()], timeout = 2.minutes(),)]impl SendReceipt { // ...}With these options, a failing job waits 10 seconds before its second attempt and one minute before its third. After that it counts as permanently failed and is recorded in the failed_jobs table, where you can inspect and retry it.
Warning
Design jobs to be safe to run twice. If a job sends an email and then crashes before reporting success, the retry sends it again. Check “did I already do this?” first when it matters.
Chains and batches
Two more tools, briefly:
- A chain runs jobs one after another. Each starts only when the previous succeeded, and the rest are skipped if one fails.
- A batch runs a group of jobs in parallel and lets you run callbacks when they all finish.
use laravel::queue;
queue::chain(( PrepareOrder { order_id }, SendReceipt { order_id }, NotifyBarista { order_id },)).await?;The guide also covers job middleware, debounced jobs, pausing queues and a Batch API with then, catch and finally callbacks. We will not need them for the café.
Try it yourself
- Write a job
RestockReminder { item_id: i64 }that loads aMenuIteminhandle. - Dispatch it onto a queue named
"reminders", delayed by 1 hour.
Show solution
use laravel::queue::{Queueable, job};
use crate::models::MenuItem;
#[derive(Queueable)]pub struct RestockReminder { pub item_id: i64,}
#[job]impl RestockReminder { async fn handle(self) -> laravel::Result<()> { let item = MenuItem::find_or_fail(self.item_id).await?; // Remind the manager to restock `item`... Ok(()) }}RestockReminder { item_id: 7 } .dispatch() .on_queue("reminders") .delay(1.hours()) .await?;Recap
- A queue stores small notes (jobs) so a separate worker can do slow or important work outside the request.
- A job is a struct deriving
Queueableplus a#[job]block withhandle. .dispatch().awaitqueues it. Models in jobs are saved by primary key and reloaded fresh.- Drivers include
database,redis,sqs, Laravel Cloud, andsyncfor tests. tries,backoffandtimeoutadd retries. Chains and batches combine jobs.
What’s next
Queues are great for single tasks, but some processes last days. Next up: Durable Workflows.
0 of 35 lessons complete