Queues and jobs in Laravel Rust, for Laravel developers
Jobs, dispatching, retries with backoff, failure hooks, workers and testing, shown on a failed-payment recovery job and compared line by line with Laravel PHP.
- queues
- jobs
- background-work
On this page
Queued jobs in Laravel Rust do what they do in Laravel PHP: they take slow or unreliable work out of the request, run it on a worker, and retry it when it fails. The vocabulary is the same (connections, queues, tries, backoff, failed_jobs, queue:work). What changes is where the settings live and a few defaults that are worth knowing before they surprise you.
The job in this guide is for a subscription business whose card payments sometimes fail. When the payment provider reports a declined renewal, the app queues a job that tries the card again later, a few times, and flags the invoice for a human if it never goes through.
The job you’d write in Laravel PHP
class RetryFailedCharge implements ShouldQueue
{
use Queueable;
public $tries = 4;
public $timeout = 30;
public function __construct(public Invoice $invoice) {}
public function backoff(): array
{
return [3600, 21600, 86400]; // 1 hour, 6 hours, 1 day
}
public function handle(PaymentGateway $gateway): void
{
$gateway->charge($this->invoice);
$this->invoice->update(['paid' => true]);
}
public function failed(?Throwable $e): void
{
$this->invoice->update(['needs_review' => true]);
}
}
The same job in Laravel Rust
// src/jobs/retry_failed_charge.rs
use laravel::container::Inject;
use laravel::model::update;
use laravel::prelude::*;
use laravel::queue::{Queueable, job};
use crate::models::Invoice;
use crate::services::PaymentGateway;
#[derive(Queueable)]
pub struct RetryFailedCharge {
pub invoice: Invoice,
}
#[job(
queue = "billing",
tries = 4,
backoff = [1.hours(), 6.hours(), 24.hours()],
timeout = 30.seconds(),
fail_when_missing_models,
)]
impl RetryFailedCharge {
async fn handle(self, gateway: Inject<PaymentGateway>) -> laravel::Result<()> {
gateway.charge(&self.invoice).await?;
let mut invoice = self.invoice;
update!(invoice { paid: true }).await?;
Ok(())
}
async fn failed(self, _error: &laravel::Error) -> laravel::Result<()> {
let mut invoice = self.invoice;
update!(invoice { needs_review: true }).await?;
Ok(())
}
}
PaymentGateway stands for your own service that talks to the payment provider, registered in the service container. Each part of the PHP job has a counterpart:
The struct is the payload, the impl is the behaviour. The job derives Queueable, and #[job] marks the impl that holds handle. There’s no registration step: Laravel discovers jobs automatically.
Settings move into #[job(...)]. tries, backoff, timeout and the default queue are attributes instead of properties. Durations are written as spans (30.seconds(), 6.hours()) rather than integers of seconds. Because the settings belong to the job type, changing them also applies to jobs already waiting on the queue, once the new code is deployed.
Dependencies come in as arguments. handle can take Inject<T> for services, just as a PHP handle method gets type-hinted dependencies. It may also take &Attempt to see which attempt this is.
Models are stored by key. As in PHP, a model field is serialized as its primary key and reloaded fresh before handle runs. Relationships are not serialized, so load the ones you need inside the job.
Two defaults that differ from PHP
Tip: no retries unless you ask. A Laravel Rust job that returns an error is attempted once by default. Set
tries, orretry_forfor a time window, on every job that should try again.
Tip: a deleted model deletes the job. If the invoice row is gone by the time the worker picks the job up, Laravel Rust deletes the job without running it and logs it at
info. That’s the opposite of PHP’s default, where a missing model fails the job unless you opt in with$deleteWhenMissingModels. For a payment, a vanished invoice means something is wrong, so the example addsfail_when_missing_models. Note that in that case thefailedhook doesn’t run, since there’s no model to pass to it.
Dispatching
The payment provider’s webhook tells the app a renewal failed. The handler records it and queues the retry:
use laravel::db;
db::transaction(async |_tx| {
let mut invoice = Invoice::find_or_fail(invoice_id).await?;
let attempts = invoice.attempts_failed + 1;
update!(invoice { attempts_failed: attempts }).await?;
RetryFailedCharge { invoice }.dispatch().await?;
Ok(())
})
.await?;
dispatch() builds the dispatch, and .await pushes it. Inside a database transaction, Laravel holds the job until the transaction commits, and drops it if the transaction rolls back, so a worker never picks up a job whose rows aren’t visible yet. In PHP you’d reach for afterCommit(); here it’s the default.
Before the .await, you can pick a connection, a queue and a delay, as with PHP’s fluent dispatch:
RetryFailedCharge { invoice }
.dispatch()
.on_queue("billing-urgent")
.delay(15.minutes())
.await?;
dispatch_sync() runs the job immediately in the current process, like dispatchSync. To push many jobs in as few round trips as possible, pass them to queue::bulk.
Choosing a connection
QUEUE_CONNECTION picks the default, as in PHP:
| Driver | Notes |
|---|---|
database |
The default. Jobs live in a jobs table created by the starter’s migrations |
redis |
Needs the redis Cargo feature |
sqs |
Amazon SQS. Needs the sqs feature |
cloud |
Laravel Cloud’s managed queues. Also needs the sqs feature |
sync |
Runs jobs immediately. Used by default in tests |
discard |
Drops every job |
Running workers
laravel queue:work
laravel queue:work --queue=billing,default
laravel queue:work --concurrency=8
Listing queues gives priority, as in PHP. --concurrency is new: one worker process runs several jobs at once, which suits jobs that mostly wait on the network, like calling a payment API. Move CPU-heavy work into task::spawn_blocking so it doesn’t hold the others up.
Tip: restart workers on every deploy. A worker keeps running the binary it started with. Run
laravel queue:restartafter deploying (it needs a shared cache store such asdatabaseorredis), or let your process supervisor restart it. On Laravel Cloud’s managed queues, workers roll over on every deploy and scale with the queue on their own.
Timeouts work slightly differently from PHP. A job that runs past its timeout is cancelled at its next .await point, because that’s where Rust can stop a future. Blocking code with no .await can’t be interrupted, which is another reason to put it in spawn_blocking.
Failed jobs
The failed-job commands are the ones you know, without php artisan:
| Laravel PHP | Laravel Rust |
|---|---|
php artisan queue:failed |
laravel queue:failed |
php artisan queue:retry all |
laravel queue:retry all |
php artisan queue:forget {id} |
laravel queue:forget {id} |
php artisan queue:flush --hours=48 |
laravel queue:flush --hours=48 |
php artisan queue:clear redis --queue=emails |
laravel queue:clear redis --queue=emails |
On Laravel Cloud’s managed queues, failed jobs appear in the Cloud dashboard instead of the failed_jobs table.
Testing
In tests, jobs go to the sync connection, so a dispatched job runs straight away unless you fake the queue. To check that the webhook queues a retry without running it:
use laravel::queue;
use laravel::testing::prelude::*;
#[laravel::test]
async fn a_declined_renewal_queues_a_retry(app: Application) {
let queue = queue::fake();
app.post("/webhooks/payments")
.json(json!({ "type": "renewal.declined", "invoice_id": 1042 }))
.await
.assert_ok();
queue.assert_pushed_where::<RetryFailedCharge>(|job| job.invoice.id == 1042);
}
The fake also serializes and deserializes every job, so a job that can’t survive the trip fails the test, not production. To test the job on its own, run one attempt with app.job(RetryFailedCharge { invoice }) and assert on the outcome with assert_succeeded, assert_released_after or assert_failed.
Quick reference
| Laravel PHP | Laravel Rust |
|---|---|
implements ShouldQueue |
#[derive(Queueable)] and #[job] |
public $tries = 4; |
#[job(tries = 4)] |
backoff() returning seconds |
backoff = [1.hours(), 6.hours()] |
public $timeout = 30; |
timeout = 30.seconds() |
->afterCommit() |
The default inside db::transaction |
| Missing model fails the job | Missing model deletes the job; opt in with fail_when_missing_models |
Queue::fake() |
queue::fake() |