Queues
- Introduction
- Configuration
- Creating jobs
- Dispatching jobs
- Retries and timeouts
- Inside a job
- Job middleware
- Job chains
- Job batches
- Running the worker
- Failed jobs
- Events
- Writing a driver
- Testing
Introduction
While building your web application, you may have work that takes too long to do while a user waits, such as transcoding an uploaded podcast or sending a batch of emails. Queues let you defer that work as a job, so your application responds right away while a separate queue worker process handles it in the background.
Laravel provides a unified queueing API across database, Redis, Amazon SQS, and Laravel Cloud managed queues. Each job is a struct with an async handle method that runs when a worker picks it up via laravel queue:work.
For lightweight work that does not need to survive a restart, task::background runs in the current process without a queue. To queue an event listener, use queued listeners.
Connections and queues
Before you dispatch a job, it's important to know the difference between connections and queues. A connection is a backend that keeps jobs, such as your database or a Redis server. A queue is a named list of jobs on a connection, and a connection may have any number of them.
When you dispatch a job without specifying a queue, it's pushed onto the connection's default queue. Using separate queues lets you prioritize work. For example, you may push urgent jobs onto a high queue and instruct your worker to process them first:
1laravel queue:work --queue=high,default1laravel queue:work --queue=high,default
Configuration
By default, Laravel uses the database queue connection and stores queued jobs in a jobs table on your default database connection. You can choose a different connection or customize the defaults through your environment variables:
| Variable | Sets | Default |
|---|---|---|
QUEUE_CONNECTION |
The default connection | database |
DB_QUEUE_CONNECTION, DB_QUEUE_TABLE, DB_QUEUE |
The database connection's database connection, table, and default queue |
The default database connection, jobs, and default |
REDIS_QUEUE_CONNECTION, REDIS_QUEUE |
The redis connection's Redis connection and default queue |
default and default |
DB_QUEUE_FAILED_CONNECTION, DB_QUEUE_FAILED_TABLE |
Where failed jobs are stored | The default database connection and failed_jobs |
The Amazon SQS and Laravel Cloud connections have their own environment variables.
Drivers
Laravel includes several built-in queue drivers:
| Driver | Behavior |
|---|---|
database |
Stores jobs in a table on one of your database connections |
redis |
Stores jobs in Redis. Requires the redis feature |
sqs |
Pushes jobs to Amazon SQS queues. Requires the sqs feature |
cloud |
Pushes jobs to Laravel Cloud's managed queues. Requires the sqs feature |
sync |
Runs each job immediately in the current process and returns any error from dispatch |
discard |
Discards dispatched jobs without running them |
The sync driver is useful during local development when you don't want to run a separate worker, and Laravel uses it by default in tests. To disable queued work entirely, set QUEUE_CONNECTION=discard.
The jobs table
The database driver stores queued jobs in a jobs table and moves permanently failed jobs to a failed_jobs table so you can inspect and retry them later. New applications create both tables, along with the job batch tables, in their create_jobs_table migration, which holds only the queue::tables! macro:
1// database/migrations/0001_01_01_000002_create_jobs_table.rs2laravel::queue::tables!();1// database/migrations/0001_01_01_000002_create_jobs_table.rs2laravel::queue::tables!();
Run your migrations before dispatching jobs:
1laravel migrate1laravel migrate
If you customize DB_QUEUE_TABLE or DB_QUEUE_FAILED_TABLE, replace the macro with the migration it stands for and change the table names to match:
1// database/migrations/0001_01_01_000002_create_jobs_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("jobs", |table| {7 table.id();8 table.string("queue").index();9 table.long_text("payload");10 table.integer("attempts").default(0);11 table.timestamp("reserved_at").nullable();12 table.timestamp("available_at");13 table.timestamp("created_at");14 })15 .await?;1617 tx.schema()18 .create("failed_jobs", |table| {19 table.id();20 table.string("job_id").length(36).unique();21 table.string("connection");22 table.string("queue");23 table.long_text("payload");24 table.long_text("error");25 table.timestamp("failed_at");2627 table.index(["connection", "queue", "failed_at"]);28 })29 .await?;3031 tx.schema()32 .create("job_batches", |table| {33 table.string("id").length(36).primary();34 table.string("name").nullable();35 table.integer("total_jobs");36 table.integer("pending_jobs");37 table.integer("failed_jobs");38 table.long_text("options");39 table.timestamp("created_at");40 table.timestamp("cancelled_at").nullable();41 table.timestamp("finished_at").nullable();42 })43 .await?;4445 tx.schema()46 .create("job_batch_jobs", |table| {47 table.string("batch_id").length(36);48 table.string("job_id").length(36);49 table.string("status").length(16);5051 table.primary(["batch_id", "job_id"]);52 })53 .await54}1// database/migrations/0001_01_01_000002_create_jobs_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("jobs", |table| {7 table.id();8 table.string("queue").index();9 table.long_text("payload");10 table.integer("attempts").default(0);11 table.timestamp("reserved_at").nullable();12 table.timestamp("available_at");13 table.timestamp("created_at");14 })15 .await?;1617 tx.schema()18 .create("failed_jobs", |table| {19 table.id();20 table.string("job_id").length(36).unique();21 table.string("connection");22 table.string("queue");23 table.long_text("payload");24 table.long_text("error");25 table.timestamp("failed_at");2627 table.index(["connection", "queue", "failed_at"]);28 })29 .await?;3031 tx.schema()32 .create("job_batches", |table| {33 table.string("id").length(36).primary();34 table.string("name").nullable();35 table.integer("total_jobs");36 table.integer("pending_jobs");37 table.integer("failed_jobs");38 table.long_text("options");39 table.timestamp("created_at");40 table.timestamp("cancelled_at").nullable();41 table.timestamp("finished_at").nullable();42 })43 .await?;4445 tx.schema()46 .create("job_batch_jobs", |table| {47 table.string("batch_id").length(36);48 table.string("job_id").length(36);49 table.string("status").length(16);5051 table.primary(["batch_id", "job_id"]);52 })53 .await54}
Permanently failed jobs are written to failed_jobs regardless of which queue driver you use, except on Laravel Cloud, where managed queues store failed jobs in the Laravel Cloud dashboard so you can inspect, retry, or delete them there instead. If you prefer to discard failed jobs instead of storing them, set queue.failed to FailedJobs::Discard in your queue configuration:
1use laravel::config::queue::FailedJobs;23queue.failed = FailedJobs::Discard;1use laravel::config::queue::FailedJobs;23queue.failed = FailedJobs::Discard;
Redis
To store queued jobs in Redis, enable Laravel's redis feature in Cargo.toml, configure a Redis connection, and set QUEUE_CONNECTION=redis:
1laravel-rust = { version = "0.1", features = ["database-postgres", "redis"] }1laravel-rust = { version = "0.1", features = ["database-postgres", "redis"] }
Store queued jobs in a separate Redis database from your cache, since flushing the cache clears every key in that database. By default, the default Redis connection uses database 0 and the cache connection uses database 1. If your REDIS_URL specifies a database number, both connections share it, so you should configure a dedicated Redis connection for queues. Because Laravel does not prefix queue keys, separate applications should use their own Redis servers.
Blocking
By default, an idle worker sleeps for --sleep seconds before polling for new jobs. With block_for, the worker instead blocks on Redis for up to that duration and claims a job the moment one is pushed. Configure block_for in your queue configuration:
1use laravel::config::queue::RedisQueue;23queue.add_connection("redis", RedisQueue::from_env(env).block_for(5.seconds()));1use laravel::config::queue::RedisQueue;23queue.add_connection("redis", RedisQueue::from_env(env).block_for(5.seconds()));
block_for is not supported on a Redis Cluster.
Amazon SQS
To use Amazon SQS for your queues, enable Laravel's sqs feature in Cargo.toml and set QUEUE_CONNECTION=sqs:
1laravel-rust = { version = "0.1", features = ["database-postgres", "sqs"] }1laravel-rust = { version = "0.1", features = ["database-postgres", "sqs"] }
You can configure the sqs connection using these environment variables:
| Variable | Description | Default |
|---|---|---|
AWS_DEFAULT_REGION |
The AWS region | The region resolved by the AWS SDK, such as AWS_REGION |
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN |
AWS credentials | Credentials resolved by the AWS SDK, such as a container's IAM role |
SQS_PREFIX |
Base URL for your queues, such as https://sqs.us-east-1.amazonaws.com/123456789012 |
Look up each queue's URL by name |
SQS_SUFFIX |
Suffix appended to every queue name, such as -production |
None |
SQS_QUEUE |
The connection's default queue | default |
AWS_ENDPOINT_URL_SQS |
Custom SQS endpoint, such as a local emulator | AWS's endpoint for the region |
SQS_OVERFLOW_ENABLED, SQS_OVERFLOW_STORE |
Stores payloads that exceed SQS limits in a cache store | Off, using the default cache store |
Each queue name maps directly to an SQS queue. With the prefix and suffix above, the emails queue resolves to https://sqs.us-east-1.amazonaws.com/123456789012/emails-production. Because Laravel does not create SQS queues automatically, create them in AWS first. To enable long polling so idle workers wait for new jobs efficiently, configure each queue's receive message wait time in AWS up to 20 seconds.
You may dispatch jobs with delays longer than SQS's 15-minute limit; Laravel holds them until they are due. Because failed jobs from SQS are written to the failed_jobs table, the sqs driver requires a database feature unless you discard failed jobs.
FIFO queues
Any queue name ending in .fifo is treated as an SQS FIFO queue, processing jobs within each message group one at a time in dispatch order. When SQS_SUFFIX is set, Laravel inserts it before .fifo, so orders.fifo becomes orders-production.fifo. Use on_group to assign a message group; jobs dispatched without one share a single group:
1use laravel::prelude::*;23pub async fn ship(Params(order_id): Params<i64>) -> laravel::Result<Redirect> {4 let order = Order::find_or_fail(order_id).await?;56 ShipOrder { order_id }7 .dispatch()8 .on_queue("orders.fifo")9 .on_group(format!("customer-{}", order.customer_id))10 .await?;1112 Ok(Redirect::back())13}1use laravel::prelude::*;23pub async fn ship(Params(order_id): Params<i64>) -> laravel::Result<Redirect> {4 let order = Order::find_or_fail(order_id).await?;56 ShipOrder { order_id }7 .dispatch()8 .on_queue("orders.fifo")9 .on_group(format!("customer-{}", order.customer_id))10 .await?;1112 Ok(Redirect::back())13}
SQS FIFO queues drop any job whose deduplication ID matches another job dispatched within the last five minutes. By default, Laravel generates a unique ID for each dispatch so duplicate dispatches run separately. To deduplicate jobs instead, pass your own deduplication_id:
1ShipOrder { order_id }2 .dispatch()3 .on_queue("orders.fifo")4 .deduplication_id(format!("ship-order-{order_id}"))5 .await?;1ShipOrder { order_id }2 .dispatch()3 .on_queue("orders.fifo")4 .deduplication_id(format!("ship-order-{order_id}"))5 .await?;
SQS FIFO queues do not support per-message delays, so dispatch delayed jobs to a standard queue.
Large payloads
SQS messages are limited to 1 MiB, and dispatching a larger job returns an error. To support larger payloads, set SQS_OVERFLOW_ENABLED=true. Oversized payloads are then stored in your cache store while the SQS message carries only the cache key. Set SQS_OVERFLOW_STORE to choose a specific store, or omit it to use your default store. Make sure you use a shared cache store such as database or redis so all workers can read the payload.
Laravel Cloud
On Laravel Cloud, managed queues provide fully managed, auto-scaling queue infrastructure with zero AWS setup. Because managed queues scale automatically to absorb sudden bursts of jobs, you don't need to provision SQS queues, manage IAM credentials, or size queue servers yourself. Applications with managed queues receive a preconfigured cloud connection automatically; enable the sqs feature and set QUEUE_CONNECTION=cloud to use it as your default connection.
Managed queues are backed by SQS, so they support all sqs driver features, including FIFO queues and large payloads. You can enable payload overflow from Laravel Cloud's queue settings or with CLOUD_QUEUE_OVERFLOW_ENABLED and CLOUD_QUEUE_OVERFLOW_STORE. The Laravel Cloud dashboard tracks each job's progress and stores permanently failed jobs instead of writing them to your failed_jobs table, allowing you to inspect, retry, or delete failed jobs directly from the dashboard.
Defining your own connections
When you need an additional connection, such as a reports connection that stores its jobs in a report_jobs table on the reporting database connection, create a src/config/queue.rs configuration file. Start from Queue::from_env to inherit the default connections and add your own. Multiple connections may share the same driver with different settings:
1// src/config/queue.rs2use laravel::config::queue::{DatabaseQueue, Queue};3use laravel::config::{self, Env};45#[config::section]6fn queue(env: &Env) -> Queue {7 let mut queue = Queue::from_env(env);89 queue.add_connection(10 "reports",11 DatabaseQueue::new()12 .connection("reporting")13 .table("report_jobs")14 .queue("reports"),15 );1617 queue18}1// src/config/queue.rs2use laravel::config::queue::{DatabaseQueue, Queue};3use laravel::config::{self, Env};45#[config::section]6fn queue(env: &Env) -> Queue {7 let mut queue = Queue::from_env(env);89 queue.add_connection(10 "reports",11 DatabaseQueue::new()12 .connection("reporting")13 .table("report_jobs")14 .queue("reports"),15 );1617 queue18}
Then add the file to src/config/mod.rs:
1mod queue;1mod queue;
You may then dispatch jobs to the connection by name, as Connections, queues, and delays shows.
Creating jobs
A job is a struct that derives Queueable, paired with a #[job] impl containing its handle method. You can place jobs in any module, such as src/jobs/; Laravel discovers them automatically, so there is nothing to register.
For example, consider a podcast publishing application that processes each uploaded episode before publishing it. This job receives a podcast's ID and loads the Podcast model when it runs:
1// src/jobs/process_podcast.rs2use laravel::queue::{Queueable, job};34use crate::models::Podcast;56#[derive(Queueable)]7pub struct ProcessPodcast {8 pub podcast_id: i64,9}1011#[job]12impl ProcessPodcast {13 async fn handle(self) -> laravel::Result<()> {14 let podcast = Podcast::find_or_fail(self.podcast_id).await?;1516 // Process the uploaded podcast...1718 Ok(())19 }20}1// src/jobs/process_podcast.rs2use laravel::queue::{Queueable, job};34use crate::models::Podcast;56#[derive(Queueable)]7pub struct ProcessPodcast {8 pub podcast_id: i64,9}1011#[job]12impl ProcessPodcast {13 async fn handle(self) -> laravel::Result<()> {14 let podcast = Podcast::find_or_fail(self.podcast_id).await?;1516 // Process the uploaded podcast...1718 Ok(())19 }20}
Because queued jobs are serialized until a worker executes them, a job should carry plain data or models rather than database connections or open file handles.
handle consumes self and returns () or laravel::Result<()>. Alongside self, it may accept services via Inject<T>, config sections via Section<T>, and the current &Attempt in any order:
1use laravel::container::Inject;2use laravel::queue::job;34use crate::models::Podcast;5use crate::services::AudioProcessor;67#[job]8impl ProcessPodcast {9 async fn handle(self, processor: Inject<AudioProcessor>) -> laravel::Result<()> {10 let podcast = Podcast::find_or_fail(self.podcast_id).await?;1112 processor.process(&podcast).await?;1314 Ok(())15 }16}1use laravel::container::Inject;2use laravel::queue::job;34use crate::models::Podcast;5use crate::services::AudioProcessor;67#[job]8impl ProcessPodcast {9 async fn handle(self, processor: Inject<AudioProcessor>) -> laravel::Result<()> {10 let podcast = Podcast::find_or_fail(self.podcast_id).await?;1112 processor.process(&podcast).await?;1314 Ok(())15 }16}
Each job executes in a fresh application context, so helpers like config, resolve, URL generation, and once all work, though there is no HTTP request or session. Laravel propagates any context values present at dispatch time, such as the active tenant, into the job's execution context.
Models in jobs
Instead of storing an ID and loading the record yourself, a job may store models directly as fields. When dispatched, Laravel serializes only each model's primary key. Before handle runs, the worker reloads the model from the database so your job always works with fresh data:
1// src/jobs/process_podcast.rs2use laravel::queue::{Queueable, job};34use crate::models::Podcast;56#[derive(Queueable)]7pub struct ProcessPodcast {8 pub podcast: Podcast,9}1011#[job]12impl ProcessPodcast {13 async fn handle(self) -> laravel::Result<()> {14 // Process self.podcast...1516 Ok(())17 }18}1// src/jobs/process_podcast.rs2use laravel::queue::{Queueable, job};34use crate::models::Podcast;56#[derive(Queueable)]7pub struct ProcessPodcast {8 pub podcast: Podcast,9}1011#[job]12impl ProcessPodcast {13 async fn handle(self) -> laravel::Result<()> {14 // Process self.podcast...1516 Ok(())17 }18}
Pass the model directly when dispatching, as in ProcessPodcast { podcast }.dispatch().await?. Option<Podcast> and Vec<Podcast> fields also store keys and reload the models when the job runs. Relationships are not serialized, so load any relationships handle needs, such as self.podcast.load(Podcast::episodes).await?.
If a model's row no longer exists when the job runs, the worker deletes the job without running it. For example, there's no reason to process a podcast that its author has since deleted, and retrying the job couldn't bring the record back anyway. The worker logs each job it deletes this way at the info level, naming the missing model and its keys, and the JobProcessed event for the job reports the MissingModels outcome. For a Vec<Podcast> field, the worker leaves out the deleted records and runs the job with the remaining models.
When the deleted job is part of a chain, the rest of the chain doesn't run, and the chain's catch callback isn't called, since no job failed. In a batch, the job and the rest of its chain count as skipped, so the batch can still finish and run its then callbacks.
If a deleted record means something went wrong, such as a payment job whose invoice should never disappear, or a chain that must undo its earlier steps in catch, add fail_when_missing_models to fail the job permanently with a MissingModels error instead:
1#[job(fail_when_missing_models)]2impl ChargeInvoice {3 // ...4}1#[job(fail_when_missing_models)]2impl ChargeInvoice {3 // ...4}
Even when using fail_when_missing_models, the failed job's failed hook does not run, since the worker can't load the job's models to pass to it.
Job names
Laravel records each job's name in the queue payload and resolves the job type by that name when a worker executes it. By default, the name is the type's module path, such as app::jobs::ProcessPodcast. If you rename or move the struct, jobs already sitting on the queue will fail to resolve. To keep a job's identifier stable across refactors, assign an explicit name:
1#[job(name = "podcasts.process")]2impl ProcessPodcast {3 // ...4}1#[job(name = "podcasts.process")]2impl ProcessPodcast {3 // ...4}
Jobs already on the queue retain the fields they were serialized with. When adding a new field, annotate it with #[serde(default)] so previously queued jobs still deserialize. When renaming a field, preserve the previous name with #[serde(alias = "...")]:
1#[derive(Queueable)]2pub struct TranscribeEpisode {3 #[serde(alias = "podcast_id")]4 pub episode_id: i64,5 #[serde(default)]6 pub include_timestamps: bool,7}1#[derive(Queueable)]2pub struct TranscribeEpisode {3 #[serde(alias = "podcast_id")]4 pub episode_id: i64,5 #[serde(default)]6 pub include_timestamps: bool,7}
If you add a new model field to a job struct, wrap it in Option or Vec when using #[serde(default)], since models themselves do not have a default value.
Dispatching jobs
Once you've defined a job, dispatch it by calling the dispatch method generated by #[job] and awaiting it. By default, awaiting pushes the job onto your default queue connection. This handler creates a podcast and queues it for background processing:
1use laravel::model::create;2use laravel::prelude::*;34use crate::jobs::ProcessPodcast;56#[laravel::input]7#[validate(anyone)]8pub struct NewPodcast {9 #[validate(required, max_length(255))]10 title: String,11}1213pub async fn store(Valid(form): Valid<NewPodcast>) -> laravel::Result<Redirect> {14 let podcast = create!(Podcast { title: &form.title }).await?;1516 ProcessPodcast { podcast }.dispatch().await?;1718 Ok(Redirect::to("/podcasts"))19}1use laravel::model::create;2use laravel::prelude::*;34use crate::jobs::ProcessPodcast;56#[laravel::input]7#[validate(anyone)]8pub struct NewPodcast {9 #[validate(required, max_length(255))]10 title: String,11}1213pub async fn store(Valid(form): Valid<NewPodcast>) -> laravel::Result<Redirect> {14 let podcast = create!(Podcast { title: &form.title }).await?;1516 ProcessPodcast { podcast }.dispatch().await?;1718 Ok(Redirect::to("/podcasts"))19}
Awaiting dispatch returns the job's JobId, matching the ID exposed by attempt.id() and the failed jobs commands. You may dispatch jobs from route handlers, console commands, scheduled tasks, event listeners, or other jobs.
Connections, queues, and delays
Before awaiting a dispatch, you can specify a connection, choose a queue, or delay when the job becomes available:
1ProcessPodcast { podcast }2 .dispatch()3 .on_connection("redis")4 .on_queue("podcasts")5 .delay(10.minutes())6 .await?;1ProcessPodcast { podcast }2 .dispatch()3 .on_connection("redis")4 .on_queue("podcasts")5 .delay(10.minutes())6 .await?;
delay accepts a duration span, a Timestamp, or a ZonedDateTime. The sync connection ignores delays and runs the job immediately.
To route every dispatch of a job to a specific queue by default, set the queue option on the job itself, such as #[job(queue = "podcasts")]. Calling on_queue at dispatch time overrides that default.
Database transactions
When you dispatch a job inside a database transaction, Laravel waits until the transaction commits before pushing the job onto the queue, and discards it if the transaction rolls back. This ensures a worker never attempts to process a job before its database records are visible:
1use laravel::db;2use laravel::model::create;34db::transaction(async |_tx| {5 let podcast = create!(Podcast { title: &form.title }).await?;67 ProcessPodcast { podcast }.dispatch().await?;89 Ok(())10})11.await?;1use laravel::db;2use laravel::model::create;34db::transaction(async |_tx| {5 let podcast = create!(Podcast { title: &form.title }).await?;67 ProcessPodcast { podcast }.dispatch().await?;89 Ok(())10})11.await?;
Inside the transaction, dispatch returns the JobId immediately and pushes the job once the transaction commits. If pushing to the queue fails after commit, db::transaction returns that error while the database changes remain committed, as described in after-commit work. In that case, retry dispatching the job rather than rerunning the transaction.
Events dispatched inside a transaction also wait until the transaction commits before running.
Synchronous dispatching
If you want to execute a job immediately within the current process instead of pushing it to a queue, call dispatch_sync:
1ProcessPodcast { podcast }.dispatch_sync().await?;1ProcessPodcast { podcast }.dispatch_sync().await?;
The job runs through its normal lifecycle, and dispatch_sync returns any error produced by handle. Unlike dispatch, it executes immediately even inside an open database transaction, so the job sees uncommitted writes from that transaction.
Dispatching jobs in bulk
To enqueue many jobs at once, pass them to queue::bulk. Laravel sends them in as few backend requests as possible rather than pushing each job individually:
1use laravel::queue;23let subscriber_ids = Subscriber::query()4 .filter(Subscriber::podcast_id.eq(podcast.id))5 .pluck(Subscriber::id)6 .await?;78let jobs = subscriber_ids.into_iter().map(|subscriber_id| NotifySubscriber {9 podcast_id: podcast.id,10 subscriber_id,11});1213queue::bulk(jobs).on_queue("notifications").await?;1use laravel::queue;23let subscriber_ids = Subscriber::query()4 .filter(Subscriber::podcast_id.eq(podcast.id))5 .pluck(Subscriber::id)6 .await?;78let jobs = subscriber_ids.into_iter().map(|subscriber_id| NotifySubscriber {9 podcast_id: podcast.id,10 subscriber_id,11});1213queue::bulk(jobs).on_queue("notifications").await?;
queue::bulk accepts a single job, an iterator of jobs of the same type, or a tuple of jobs of different types, returning their JobIds in order. If pushing fails partway through, earlier jobs in the batch may already be queued. When you need to track a group of jobs together or run callbacks once they complete, use a job batch instead.
Debounced jobs
When a job may be dispatched repeatedly in quick succession, you may only want the latest dispatch to execute. For example, if a post is edited three times in a few seconds, its search index only needs to be updated once. Configure debounce_for on #[job] and implement debounce_id to group dispatches that should supersede each other:
1use laravel::prelude::*;2use laravel::queue::{Queueable, job};34#[derive(Queueable)]5pub struct UpdateSearchIndex {6 pub post_id: i64,7}89#[job(debounce_for = 30.seconds())]10impl UpdateSearchIndex {11 fn debounce_id(&self) -> i64 {12 self.post_id13 }1415 async fn handle(self) -> laravel::Result<()> {16 // Update the post's search index...1718 Ok(())19 }20}1use laravel::prelude::*;2use laravel::queue::{Queueable, job};34#[derive(Queueable)]5pub struct UpdateSearchIndex {6 pub post_id: i64,7}89#[job(debounce_for = 30.seconds())]10impl UpdateSearchIndex {11 fn debounce_id(&self) -> i64 {12 self.post_id13 }1415 async fn handle(self) -> laravel::Result<()> {16 // Update the post's search index...1718 Ok(())19 }20}
Each dispatch waits 30 seconds before becoming eligible to run. When its turn arrives, the worker discards it if a newer dispatch for the same post is still pending. debounce_id may return any type implementing Display; omitting it causes every dispatch of that job type to supersede earlier ones.
If edits arrive continuously, each dispatch would reset the window indefinitely. To cap the total delay, set max_wait. Once the oldest pending dispatch reaches that age, the next dispatch runs immediately:
1#[job(debounce_for = 30.seconds(), max_wait = 2.minutes())]1#[job(debounce_for = 30.seconds(), max_wait = 2.minutes())]
Laravel tracks debounce state in your default cache store, so make sure you use a shared store such as database or redis. Because the sync connection executes jobs immediately, it does not debounce dispatches.
Retries and timeouts
By default, a job that returns an error or panics is attempted once and not retried. You can configure retries, backoff delays, and execution timeouts on #[job]:
1use laravel::prelude::*;2use laravel::queue::job;34#[job(5 queue = "podcasts",6 tries = 3,7 backoff = [10.seconds(), 1.minutes()],8 timeout = 2.minutes(),9)]10impl ProcessPodcast {11 // ...12}1use laravel::prelude::*;2use laravel::queue::job;34#[job(5 queue = "podcasts",6 tries = 3,7 backoff = [10.seconds(), 1.minutes()],8 timeout = 2.minutes(),9)]10impl ProcessPodcast {11 // ...12}
With these options, a failing job waits 10 seconds before its second attempt and one minute before its third before failing permanently. When backoff is a list, each entry sets the wait before the corresponding retry, and the final duration repeats for any subsequent retries.
| Option | Description | Default |
|---|---|---|
queue = "podcasts" |
Default queue when on_queue is not specified at dispatch |
The connection's default queue |
tries = 3 |
Maximum number of attempts, including releases | 1 |
backoff = 30.seconds() |
Wait before retrying, or a list such as [10.seconds(), 1.minutes()] |
No delay |
timeout = 2.minutes() |
Maximum duration for a single attempt | 60 seconds |
retry_for = 1.hours() |
Time window after dispatch during which the job may be retried, replacing tries |
No limit |
max_errors = 3 |
Maximum failed attempts before stopping retries | Governed by tries |
debounce_for, max_wait |
Deduplication window for debounced jobs | Not debounced |
name = "podcasts.process" |
Stable job name stored in the queue payload | The type's path |
fail_when_missing_models |
Fails the job when a model row is missing | Deletes the job |
Job options are attached to the job type, so updating them applies to jobs already sitting on the queue once you deploy the new code.
When a job exceeds its timeout, the worker cancels it at its next .await point and fails the attempt with a JobTimedOut error. Because Rust futures can only be cancelled at .await points, move CPU-bound or blocking work into task::spawn_blocking.
When an attempt fails and the job will be retried, the worker logs the error as a warning. Once a job fails permanently, the worker records it in the failed jobs table, invokes its failed hook, and reports the error through your error handler. A job with a retry_for fails permanently as soon as its window would end before its next attempt, and the failed job keeps that attempt's error.
Limiting errors
A job that releases itself repeatedly, such as one waiting on an external rate limit, may need many attempts while still failing quickly if unexpected errors occur. Pair retry_for with max_errors so the job can keep releasing within the time window while failing permanently after a set number of errors:
1#[job(retry_for = 1.hours(), max_errors = 3)]2impl SyncContacts {3 // ...4}1#[job(retry_for = 1.hours(), max_errors = 3)]2impl SyncContacts {3 // ...4}
Workers track error counts in your default cache store, so use a shared store such as database or redis.
Inside a job
A job's handle method may accept an &Attempt to inspect the current execution. number() returns the 1-based attempt count, and id() returns the job's JobId:
1use laravel::queue::{Attempt, job};23#[job(tries = 3)]4impl ProcessPodcast {5 async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {6 tracing::info!(id = %attempt.id(), run = attempt.number(), "processing podcast");78 // ...910 Ok(())11 }12}1use laravel::queue::{Attempt, job};23#[job(tries = 3)]4impl ProcessPodcast {5 async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {6 tracing::info!(id = %attempt.id(), run = attempt.number(), "processing podcast");78 // ...910 Ok(())11 }12}
You can also inspect the current job's metadata with name(), connection(), and queue().
Releasing, deleting, and failing
Attempt also lets a job control its own lifecycle. For example, this job deletes itself if its podcast was archived, and releases itself back onto the queue if the audio upload is still in progress:
1use laravel::prelude::*;2use laravel::queue::{Attempt, job};34#[job(retry_for = 1.hours())]5impl ProcessPodcast {6 async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {7 if self.podcast.archived {8 attempt.delete();9 return Ok(());10 }1112 if !self.podcast.uploaded {13 attempt.release(30.seconds());14 return Ok(());15 }1617 // Process the uploaded podcast...1819 Ok(())20 }21}1use laravel::prelude::*;2use laravel::queue::{Attempt, job};34#[job(retry_for = 1.hours())]5impl ProcessPodcast {6 async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {7 if self.podcast.archived {8 attempt.delete();9 return Ok(());10 }1112 if !self.podcast.uploaded {13 attempt.release(30.seconds());14 return Ok(());15 }1617 // Process the uploaded podcast...1819 Ok(())20 }21}
release(delay)pushes the job back onto its queue to run again after the given delay. Releases count towardtries, so jobs that release frequently should useretry_forinstead, as shown in Limiting errors.delete()removes the job from the queue without retrying it.fail(error)fails the job permanently without further retries.
These instructions take effect when handle returns Ok(()). If handle returns an error, the attempt fails even if you called release. The one exception is a rate limit error: returning TooManyAttempts automatically releases the job back onto the queue until the rate limit allows it to run.
Handling failures
When a job fails permanently, you may want to notify the user or clean up partial work. Add an async failed method alongside handle that accepts &laravel::Error along with any of the same injected arguments handle accepts:
1use laravel::model::update;2use laravel::queue::job;34#[job(tries = 3)]5impl ProcessPodcast {6 async fn handle(self) -> laravel::Result<()> {7 // Process the uploaded podcast...89 Ok(())10 }1112 async fn failed(self, error: &laravel::Error) -> laravel::Result<()> {13 let mut podcast = self.podcast;1415 update!(podcast { failure: Some(error.to_string()) }).await?;1617 Ok(())18 }19}1use laravel::model::update;2use laravel::queue::job;34#[job(tries = 3)]5impl ProcessPodcast {6 async fn handle(self) -> laravel::Result<()> {7 // Process the uploaded podcast...89 Ok(())10 }1112 async fn failed(self, error: &laravel::Error) -> laravel::Result<()> {13 let mut podcast = self.podcast;1415 update!(podcast { failure: Some(error.to_string()) }).await?;1617 Ok(())18 }19}
failed receives a fresh instance deserialized from the stored payload, with any model fields reloaded, so in-memory mutations made during handle are not carried over.
Job middleware
When multiple jobs share the same guard or rate-limiting logic, such as staying within a mail provider's sending limit or skipping unverified users, extract it into job middleware instead of repeating it in every handle method. To stop a job from overlapping with itself, build a middleware around a cache lock.
Defining middleware
Job middleware is an async function annotated with #[middleware] from laravel::queue. It receives next representing the remainder of the pipeline and returns laravel::Result<()>. For example, this middleware rate limits mail jobs to 14 per second across all workers, releasing any job over the limit back onto the queue until capacity is available:
1use laravel::queue::{Next, middleware};2use laravel::rate_limit::{self, Limit};34#[middleware]5pub async fn mail_rate_limit(next: Next) -> laravel::Result<()> {6 rate_limit::attempt("mail", Limit::per_second(14)).await??;78 next.run().await9}1use laravel::queue::{Next, middleware};2use laravel::rate_limit::{self, Limit};34#[middleware]5pub async fn mail_rate_limit(next: Next) -> laravel::Result<()> {6 rate_limit::attempt("mail", Limit::per_second(14)).await??;78 next.run().await9}
next.run() executes the rest of the pipeline and returns its result, allowing your job middleware to run code before and after handle, or skip it altogether. Before next, a middleware function may accept any injected parameters that handle accepts, including &Attempt to release, delete, or fail the job.
To pass data from the job into a middleware function, such as a user ID, declare those parameters after next. Parameters before next are injected by Laravel, while parameters after next become arguments you pass when assigning the middleware to a job, such as skip_unverified_users(self.user_id). For example, this middleware deletes the job when the user has not verified their email address:
1use laravel::queue::{Attempt, Next, middleware};23use crate::models::User;45#[middleware]6pub async fn skip_unverified_users(7 attempt: &Attempt,8 next: Next,9 user_id: i64,10) -> laravel::Result<()> {11 let verified = User::find(user_id)12 .await?13 .is_some_and(|user| user.email_verified_at.is_some());1415 if !verified {16 attempt.delete();17 return Ok(());18 }1920 next.run().await21}1use laravel::queue::{Attempt, Next, middleware};23use crate::models::User;45#[middleware]6pub async fn skip_unverified_users(7 attempt: &Attempt,8 next: Next,9 user_id: i64,10) -> laravel::Result<()> {11 let verified = User::find(user_id)12 .await?13 .is_some_and(|user| user.email_verified_at.is_some());1415 if !verified {16 attempt.delete();17 return Ok(());18 }1920 next.run().await21}
Middleware can also intercept errors returned by the job. For example, this middleware releases the job back onto the queue when handle fails rather than failing the attempt:
1#[middleware]2pub async fn release_on_error(attempt: &Attempt, next: Next) -> laravel::Result<()> {3 if let Err(error) = next.run().await {4 tracing::warn!(%error, "releasing the job after an error");5 attempt.release(1.minutes());6 }78 Ok(())9}1#[middleware]2pub async fn release_on_error(attempt: &Attempt, next: Next) -> laravel::Result<()> {3 if let Err(error) = next.run().await {4 tracing::warn!(%error, "releasing the job after an error");5 attempt.release(1.minutes());6 }78 Ok(())9}
Assigning middleware to jobs
To attach middleware to a job, add a middleware method to its #[job] impl taking &self and returning a single middleware or a tuple of them. Pass any job-specific parameters in order:
1use laravel::queue::{IntoMiddleware, job};23#[job(retry_for = 1.hours())]4impl SendNewsletter {5 fn middleware(&self) -> impl IntoMiddleware {6 (skip_unverified_users(self.user_id), mail_rate_limit)7 }89 async fn handle(self) -> laravel::Result<()> {10 // Send the newsletter...1112 Ok(())13 }14}1use laravel::queue::{IntoMiddleware, job};23#[job(retry_for = 1.hours())]4impl SendNewsletter {5 fn middleware(&self) -> impl IntoMiddleware {6 (skip_unverified_users(self.user_id), mail_rate_limit)7 }89 async fn handle(self) -> laravel::Result<()> {10 // Send the newsletter...1112 Ok(())13 }14}
Job middleware executes in the order listed, so here skip_unverified_users runs first, wrapping mail_rate_limit, which wraps handle.
To apply a middleware only when a condition is met, wrap it in an Option; Laravel skips any None entries:
1fn middleware(&self) -> impl IntoMiddleware {2 (3 skip_unverified_users(self.user_id),4 self.retry_errors.then_some(release_on_error),5 )6}1fn middleware(&self) -> impl IntoMiddleware {2 (3 skip_unverified_users(self.user_id),4 self.retry_errors.then_some(release_on_error),5 )6}
To share a set of middleware across multiple jobs, return a MiddlewareGroup from a helper function and return it from each job's middleware method:
1use laravel::queue::{IntoMiddleware, MiddlewareGroup, job};23pub fn mail() -> MiddlewareGroup {4 MiddlewareGroup::new().with(mail_rate_limit).with(release_on_error)5}67#[job]8impl SendNewsletter {9 fn middleware(&self) -> impl IntoMiddleware {10 mail()11 }1213 async fn handle(self) -> laravel::Result<()> {14 // Send the newsletter...1516 Ok(())17 }18}1use laravel::queue::{IntoMiddleware, MiddlewareGroup, job};23pub fn mail() -> MiddlewareGroup {4 MiddlewareGroup::new().with(mail_rate_limit).with(release_on_error)5}67#[job]8impl SendNewsletter {9 fn middleware(&self) -> impl IntoMiddleware {10 mail()11 }1213 async fn handle(self) -> laravel::Result<()> {14 // Send the newsletter...1516 Ok(())17 }18}
A job's timeout applies to its middleware and handle method together. Middleware runs wherever the job executes, including on the sync connection and in test attempts.
Job chains
Job chaining lets you specify a sequence of jobs that run one after another. Each job is dispatched only after the previous job succeeds; if any job fails, the remaining jobs in the chain will not run. Pass the jobs to queue::chain as a tuple and await it:
1use laravel::prelude::*;2use laravel::queue;34use crate::models::Podcast;56pub async fn publish(podcast: Podcast) -> laravel::Result<Redirect> {7 queue::chain((8 ProcessPodcast { podcast: podcast.clone() },9 OptimizePodcast { podcast_id: podcast.id },10 ReleasePodcast { podcast_id: podcast.id },11 ))12 .await?;1314 Ok(Redirect::back())15}1use laravel::prelude::*;2use laravel::queue;34use crate::models::Podcast;56pub async fn publish(podcast: Podcast) -> laravel::Result<Redirect> {7 queue::chain((8 ProcessPodcast { podcast: podcast.clone() },9 OptimizePodcast { podcast_id: podcast.id },10 ReleasePodcast { podcast_id: podcast.id },11 ))12 .await?;1314 Ok(Redirect::back())15}
queue::chain also accepts a single job or an iterator of jobs of the same type, and you can append more jobs with then when constructing a chain dynamically:
1let mut chain = queue::chain(ProcessPodcast { podcast: podcast.clone() });23if !podcast.transcribed {4 chain = chain.then(TranscribePodcast { podcast_id: podcast.id });5}67chain.then(ReleasePodcast { podcast_id: podcast.id }).await?;1let mut chain = queue::chain(ProcessPodcast { podcast: podcast.clone() });23if !podcast.transcribed {4 chain = chain.then(TranscribePodcast { podcast_id: podcast.id });5}67chain.then(ReleasePodcast { podcast_id: podcast.id }).await?;
Each job retains its configured options, so it is retried on its own before the chain continues. A job that releases itself pauses the chain until it succeeds, while a job that deletes itself lets the chain continue. A job deleted because a model's row is gone ends the chain without running subsequent jobs.
By default, each job in the chain uses its own connection and queue. To send every job in the chain to the same connection or queue, call on_connection and on_queue. Calling delay delays the first job in the chain:
1queue::chain((2 ProcessPodcast { podcast: podcast.clone() },3 OptimizePodcast { podcast_id: podcast.id },4))5.on_connection("redis")6.on_queue("podcasts")7.await?;1queue::chain((2 ProcessPodcast { podcast: podcast.clone() },3 OptimizePodcast { podcast_id: podcast.id },4))5.on_connection("redis")6.on_queue("podcasts")7.await?;
Design each job in a chain to be idempotent. If a job succeeds but the worker fails to enqueue the next job in the chain, the worker will retry the completed job.
Adding jobs to the chain
A running job can add more jobs to its active chain through &Attempt. prepend_to_chain inserts one or more jobs to run immediately next, while append_to_chain adds them to the end of the chain:
1use laravel::queue::{Attempt, job};23#[job]4impl ProcessPodcast {5 async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {6 // ...78 // Run next...9 attempt.prepend_to_chain(TranscribePodcast { podcast_id: self.podcast.id });1011 // Run at the end of the chain...12 attempt.append_to_chain((13 NotifyHosts { podcast_id: self.podcast.id },14 UpdatePodcastFeed { podcast_id: self.podcast.id },15 ));1617 Ok(())18 }19}1use laravel::queue::{Attempt, job};23#[job]4impl ProcessPodcast {5 async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {6 // ...78 // Run next...9 attempt.prepend_to_chain(TranscribePodcast { podcast_id: self.podcast.id });1011 // Run at the end of the chain...12 attempt.append_to_chain((13 NotifyHosts { podcast_id: self.podcast.id },14 UpdatePodcastFeed { podcast_id: self.podcast.id },15 ));1617 Ok(())18 }19}
Both methods accept a single job, a tuple of jobs of different types, or an iterator of jobs of the same type. When you pass multiple jobs to prepend_to_chain, they run in the order listed before any remaining jobs in the chain. Added jobs are only enqueued if the current job succeeds or deletes itself. If the current job wasn't part of a chain, adding jobs starts a new chain.
Chain failures
When a job in a chain fails permanently, the remaining jobs do not run. To react to a chain failure, register a callback with catch:
1queue::chain((2 ProcessPodcast { podcast: podcast.clone() },3 OptimizePodcast { podcast_id: podcast.id },4))5.catch(PodcastFailed { podcast_id: podcast.id })6.await?;1queue::chain((2 ProcessPodcast { podcast: podcast.clone() },3 OptimizePodcast { podcast_id: podcast.id },4))5.catch(PodcastFailed { podcast_id: podcast.id })6.await?;
Like a job, a callback is a struct deriving Queueable so Laravel can store it alongside the chain. Annotate its impl with #[callback] and implement an async catch method that receives the failing error:
1use laravel::model::update;2use laravel::queue::{Queueable, callback};34use crate::models::Podcast;56#[derive(Queueable)]7pub struct PodcastFailed {8 pub podcast_id: i64,9}1011#[callback]12impl PodcastFailed {13 async fn catch(self, error: &laravel::Error) -> laravel::Result<()> {14 let mut podcast = Podcast::find_or_fail(self.podcast_id).await?;1516 update!(podcast { failure: Some(error.to_string()) }).await?;1718 Ok(())19 }20}1use laravel::model::update;2use laravel::queue::{Queueable, callback};34use crate::models::Podcast;56#[derive(Queueable)]7pub struct PodcastFailed {8 pub podcast_id: i64,9}1011#[callback]12impl PodcastFailed {13 async fn catch(self, error: &laravel::Error) -> laravel::Result<()> {14 let mut podcast = Podcast::find_or_fail(self.podcast_id).await?;1516 update!(podcast { failure: Some(error.to_string()) }).await?;1718 Ok(())19 }20}
The worker invokes catch immediately, before running the failed job's failed hook. Because callbacks run inline rather than as queued jobs, they are not retried; any error they return is reported to your error handler. If one of a callback's model rows has been deleted, the worker skips the callback, unless you add fail_when_missing_models to its #[callback] attribute to report a MissingModels error instead. For long-running or retryable cleanup, dispatch a job from the callback instead.
If you later retry the failed job and it succeeds, the chain resumes with the remaining jobs.
Job batches
Laravel's job batching lets you execute a group of jobs in parallel and then run callbacks once the entire batch has completed. For example, if a user uploads a CSV file of 300 contacts, you can split the import into three jobs of 100 rows each, process them concurrently across your workers, and mark the import complete once all three finish.
Pass the jobs to queue::batch and await it. Here, ImportCsv is a job that imports a slice of rows:
1use laravel::prelude::*;2use laravel::queue;34pub async fn start(Params(import_id): Params<i64>) -> laravel::Result<Redirect> {5 let batch_id = queue::batch([6 ImportCsv { import_id, rows: 1..=100 },7 ImportCsv { import_id, rows: 101..=200 },8 ImportCsv { import_id, rows: 201..=300 },9 ])10 .name("Import CSV")11 .then(ImportFinished { import_id })12 .catch(ImportFinished { import_id })13 .await?;1415 Ok(Redirect::to(format!("/imports/{import_id}/batches/{batch_id}")))16}1use laravel::prelude::*;2use laravel::queue;34pub async fn start(Params(import_id): Params<i64>) -> laravel::Result<Redirect> {5 let batch_id = queue::batch([6 ImportCsv { import_id, rows: 1..=100 },7 ImportCsv { import_id, rows: 101..=200 },8 ImportCsv { import_id, rows: 201..=300 },9 ])10 .name("Import CSV")11 .then(ImportFinished { import_id })12 .catch(ImportFinished { import_id })13 .await?;1415 Ok(Redirect::to(format!("/imports/{import_id}/batches/{batch_id}")))16}
queue::batch accepts an iterator of jobs of the same type or a tuple of jobs of different types. Awaiting dispatches every job and returns the batch's BatchId, which you can use to inspect its progress. Jobs in a batch may finish in any order. Call on_connection and on_queue to route every job in the batch to a specific connection and queue.
The batches tables
Laravel tracks batch progress in two database tables, job_batches and job_batch_jobs. Your application's create_jobs_table migration creates them alongside the jobs table, so run your migrations before dispatching your first batch.
Batch records are stored on your default database connection regardless of which queue driver runs the jobs.
Batch callbacks
You can register callbacks for three points in a batch's lifecycle. The worker invokes the matching method on your callback:
| Method | Invoked when | Optional arguments |
|---|---|---|
then |
Every job in the batch succeeds | &Batch |
catch |
The first job in the batch fails permanently | &Batch and &laravel::Error |
finally |
Every job has finished, whether it succeeded, failed, or was skipped | &Batch |
For example, this callback marks the Import model complete or records the failure reason:
1use laravel::model::update;2use laravel::queue::{Queueable, callback};34use crate::models::Import;56#[derive(Queueable)]7pub struct ImportFinished {8 pub import_id: i64,9}1011#[callback]12impl ImportFinished {13 async fn then(self) -> laravel::Result<()> {14 let mut import = Import::find_or_fail(self.import_id).await?;1516 update!(import { completed: true }).await?;1718 Ok(())19 }2021 async fn catch(self, error: &laravel::Error) -> laravel::Result<()> {22 let mut import = Import::find_or_fail(self.import_id).await?;2324 update!(import { failure: Some(error.to_string()) }).await?;2526 Ok(())27 }28}1use laravel::model::update;2use laravel::queue::{Queueable, callback};34use crate::models::Import;56#[derive(Queueable)]7pub struct ImportFinished {8 pub import_id: i64,9}1011#[callback]12impl ImportFinished {13 async fn then(self) -> laravel::Result<()> {14 let mut import = Import::find_or_fail(self.import_id).await?;1516 update!(import { completed: true }).await?;1718 Ok(())19 }2021 async fn catch(self, error: &laravel::Error) -> laravel::Result<()> {22 let mut import = Import::find_or_fail(self.import_id).await?;2324 update!(import { failure: Some(error.to_string()) }).await?;2526 Ok(())27 }28}
The &Batch parameter reflects the batch's state at the moment the callback runs. You may call then, catch, and finally multiple times to register additional callbacks.
For a single-purpose callback, you can annotate an async function with #[callback] instead. Owned parameters such as import_id are stored with the batch, while framework parameters such as &Batch are injected when it runs:
1use laravel::queue::Batch;23#[callback]4async fn log_import(import_id: i64, batch: &Batch) {5 tracing::info!(6 import_id,7 jobs = batch.total_jobs(),8 failed = batch.failed_jobs(),9 "import finished",10 );11}1213queue::batch(jobs).finally(log_import(import_id)).await?;1use laravel::queue::Batch;23#[callback]4async fn log_import(import_id: i64, batch: &Batch) {5 tracing::info!(6 import_id,7 jobs = batch.total_jobs(),8 failed = batch.failed_jobs(),9 "import finished",10 );11}1213queue::batch(jobs).finally(log_import(import_id)).await?;
Chains and batches
A batch may contain job chains. Each chain runs its jobs sequentially while running in parallel with the other items in the batch:
1queue::batch((2 queue::chain(ReleasePodcast { podcast_id: 1 })3 .then(SendReleaseNotification { podcast_id: 1 }),4 queue::chain(ReleasePodcast { podcast_id: 2 })5 .then(SendReleaseNotification { podcast_id: 2 }),6))7.then(ReleaseFinished)8.await?;1queue::batch((2 queue::chain(ReleasePodcast { podcast_id: 1 })3 .then(SendReleaseNotification { podcast_id: 1 }),4 queue::chain(ReleasePodcast { podcast_id: 2 })5 .then(SendReleaseNotification { podcast_id: 2 }),6))7.then(ReleaseFinished)8.await?;
A batch can also be a step inside a chain. The chain advances once every job in the batch finishes:
1queue::chain(FlushPodcastCache)2 .then(queue::batch([ReleasePodcast { podcast_id: 1 }, ReleasePodcast { podcast_id: 2 }]))3 .then(queue::batch([4 SendReleaseNotification { podcast_id: 1 },5 SendReleaseNotification { podcast_id: 2 },6 ]))7 .await?;1queue::chain(FlushPodcastCache)2 .then(queue::batch([ReleasePodcast { podcast_id: 1 }, ReleasePodcast { podcast_id: 2 }]))3 .then(queue::batch([4 SendReleaseNotification { podcast_id: 1 },5 SendReleaseNotification { podcast_id: 2 },6 ]))7 .await?;
If the batch is cancelled, such as when one of its jobs fails, the outer chain stops as well.
Adding jobs and cancelling batches
A job inside a batch can dynamically add more jobs to its batch through &Attempt. For a large import, your handler can dispatch a single starter job that splits the file in the background rather than building thousands of jobs during the HTTP request:
1use laravel::queue::{Attempt, Queueable, job};23#[derive(Queueable)]4pub struct SplitImport {5 pub import_id: i64,6}78#[job]9impl SplitImport {10 async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {11 let import = Import::find_or_fail(self.import_id).await?;1213 let jobs = (0..import.total_rows)14 .step_by(100)15 .map(|start| ImportCsv { import_id: import.id, rows: start + 1..=start + 100 });1617 attempt.add_to_batch(jobs);1819 Ok(())20 }21}1use laravel::queue::{Attempt, Queueable, job};23#[derive(Queueable)]4pub struct SplitImport {5 pub import_id: i64,6}78#[job]9impl SplitImport {10 async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {11 let import = Import::find_or_fail(self.import_id).await?;1213 let jobs = (0..import.total_rows)14 .step_by(100)15 .map(|start| ImportCsv { import_id: import.id, rows: start + 1..=start + 100 });1617 attempt.add_to_batch(jobs);1819 Ok(())20 }21}
The batch remains open until all added jobs finish as well. To cancel the batch from within a job, call attempt.cancel_batch(); workers skip any remaining pending jobs, and the batch's then callbacks will not run. Outside a job, cancel a batch with queue::cancel_batch(batch_id).await?.
Inspecting batches
Use queue::find_batch to look up a batch by ID and report its progress. It returns None if no matching batch exists:
1use laravel::prelude::*;2use laravel::queue::{self, Batch, BatchId};34pub async fn show(Params(batch_id): Params<BatchId>) -> laravel::Result<Json<Batch>> {5 let batch = queue::find_batch(batch_id).await?.or_abort(404)?;67 Ok(Json(batch))8}1use laravel::prelude::*;2use laravel::queue::{self, Batch, BatchId};34pub async fn show(Params(batch_id): Params<BatchId>) -> laravel::Result<Json<Batch>> {5 let batch = queue::find_batch(batch_id).await?.or_abort(404)?;67 Ok(Json(batch))8}
Batch implements Serialize, so you can return it directly as JSON. It provides progress as a percentage from 0 to 100, along with total_jobs, pending_jobs, failed_jobs, is_finished, and is_cancelled.
Batch failures
By default, when any job in a batch fails permanently, Laravel cancels the batch, invokes its catch callbacks, and skips the remaining jobs. To keep processing remaining jobs even if some fail, call allow_failures:
1queue::batch(jobs).allow_failures().catch(ImportFinished { import_id }).await?;1queue::batch(jobs).allow_failures().catch(ImportFinished { import_id }).await?;
With allow_failures, catch callbacks run on the first failure, while then callbacks run only after every failed job has been retried and succeeded. You can retry all failed jobs in a batch with queue:retry-batch. Batches without allow_failures are cancelled on their first failure and cannot be retried this way:
1laravel queue:retry-batch 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f531laravel queue:retry-batch 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f53
A retried job may add new jobs to a finished batch or resume its chain. In that case, the batch stays open until those jobs finish and then runs its finally callbacks again, so write finally callbacks to be idempotent.
Pruning batches
Completed batch records stay in the database until you prune them. queue:prune-batches removes batches that finished more than 24 hours ago. Pass --hours to keep them longer, and schedule the command daily in src/console/mod.rs:
1use laravel::schedule::{self, Schedule};23#[schedule::tasks]4fn schedule(schedule: &mut Schedule) {5 schedule.command("queue:prune-batches --hours=48").daily();6}1use laravel::schedule::{self, Schedule};23#[schedule::tasks]4fn schedule(schedule: &mut Schedule) {5 schedule.command("queue:prune-batches --hours=48").daily();6}
Pass --unfinished=N to also prune unfinished batches older than N hours, or --cancelled=N for cancelled batches. Only prune unfinished batches you no longer plan to retry, since their callbacks will never run once deleted.
Running the worker
Start a queue worker with the queue:work command to begin processing queued jobs:
1laravel queue:work1laravel queue:work
The worker runs continuously until you stop it, printing each job's name without the leading app::, its outcome, and its duration:
1◆ jobs::ProcessPodcast 412.4ms2▲ jobs::SendInvoice retrying 18.2ms3 the payment service timed out1◆ jobs::ProcessPodcast 412.4ms2▲ jobs::SendInvoice retrying 18.2ms3 the payment service timed out
Because workers are long-lived processes, they continue running the compiled binary they started with until restarted. During local development, you can use npm run dev instead of managing a separate worker terminal. It starts your web server, queue worker, and Vite dev server together, automatically rebuilding and restarting both the server and worker whenever your Rust code or .env file changes:
1npm run dev1npm run dev
Worker options
By default, the worker processes the default queue on your default connection. You can pass a specific connection name or list multiple queues in priority order. When listing multiple queues, the worker drains higher-priority queues before pulling from lower-priority ones:
1laravel queue:work redis2laravel queue:work --queue=high,default1laravel queue:work redis2laravel queue:work --queue=high,default
| Option | Description | Default |
|---|---|---|
[connection] |
The queue connection to process | The default connection |
--queue=high, |
Queues to process, in priority order | The connection's default queue |
--concurrency=4 |
Number of jobs to process concurrently | 1 |
--sleep=3 |
Seconds to wait before polling again when no jobs are available | 3 |
--max-jobs=1000 |
Exit after processing this many jobs | No limit |
--max-time=3600 |
Exit after running for this many seconds | No limit |
--stop-when-empty |
Exit once all monitored queues are empty | Off |
Before exiting, the worker finishes any jobs currently in flight.
Queue workers also run your application's ticks alongside the HTTP server. If a tick only applies to web requests (such as flushing counters buffered by HTTP handlers), restrict it with .when(|host| host.is_server()).
Worker concurrency
To process multiple jobs concurrently within a single worker process, pass --concurrency:
1laravel queue:work --concurrency=81laravel queue:work --concurrency=8
Because concurrent jobs share one worker process, concurrency works best for I/O-bound jobs waiting on the network or database. Offload CPU-heavy or blocking work, such as image processing, to task::spawn_blocking so it does not stall other jobs. You may also run multiple worker processes across one or more servers; each job is claimed by only one worker.
Running workers in production
In production, run your queue workers under a process supervisor such as systemd or Supervisor so they restart automatically if they exit:
1# /etc/systemd/system/app-worker.service2[Unit]3Description=Queue worker4After=network.target56[Service]7WorkingDirectory=/srv/app8ExecStart=/srv/app/app queue:work --concurrency=49Restart=always10KillSignal=SIGTERM11TimeoutStopSec=1501213[Install]14WantedBy=multi-user.target1# /etc/systemd/system/app-worker.service2[Unit]3Description=Queue worker4After=network.target56[Service]7WorkingDirectory=/srv/app8ExecStart=/srv/app/app queue:work --concurrency=49Restart=always10KillSignal=SIGTERM11TimeoutStopSec=1501213[Install]14WantedBy=multi-user.target
When the worker receives SIGTERM, it stops claiming new jobs and waits for in-flight jobs to finish. Set your supervisor's stop timeout to more than twice your longest job's timeout so a job timing out on its final attempt still has time to run its failed hook.
If a worker is killed abruptly or its server crashes, another worker reclaims its in-flight jobs roughly a minute later. The interrupted run counts as one attempt.
Running workers on Laravel Cloud
When deploying to Laravel Cloud with managed queues, you don't need to configure systemd, Supervisor, or manually size worker clusters. Laravel Cloud continuously monitors your queues and scales worker concurrency automatically based on queue depth, job latency, and throughput.
During traffic spikes, Cloud spins up additional workers to drain backlogs before wait times build up. When your queues are idle, workers can scale down to zero so you aren't paying for idle compute between bursts. Workers also roll over automatically on every deployment, and the Laravel Cloud dashboard provides real-time visibility into queue depth, throughput, and failed jobs.
Restarting workers
Because workers keep running the binary they started with, restart them on every deploy. Running queue:restart signals all running workers to finish their current jobs and exit gracefully so your process supervisor can boot them with the new release:
1laravel queue:restart1laravel queue:restart
Restart signals are coordinated through your default cache store, so use a shared store such as database or redis.
Pausing queues
To stop workers from claiming jobs from a specific queue without shutting the workers down, such as during maintenance, pause the queue. Specify connection:queue, or pass only the queue name to target the default connection:
1laravel queue:pause database:emails2laravel queue:pause emails1laravel queue:pause database:emails2laravel queue:pause emails
Workers finish any jobs already running and leave new jobs on the paused queue untouched until you resume it with queue:continue:
1laravel queue:continue database:emails1laravel queue:continue database:emails
Pass --all to queue:pause or queue:continue to pause or resume every queue across all connections. Like queue:restart, pause state is shared through your default cache store.
Counting jobs
To monitor queue depth, call sizes on the queue manager, such as from a scheduled health check that alerts you when a queue backs up:
1use laravel::queue;23if let Some(sizes) = queue::manager().sizes("database", "emails").await? {4 tracing::info!(5 pending = sizes.pending,6 running = sizes.reserved,7 total = sizes.total(),8 "emails",9 );10}1use laravel::queue;23if let Some(sizes) = queue::manager().sizes("database", "emails").await? {4 tracing::info!(5 pending = sizes.pending,6 running = sizes.reserved,7 total = sizes.total(),8 "emails",9 );10}
pending reports jobs ready to run, delayed reports jobs waiting out a delay, and reserved reports jobs currently being processed. sizes returns None for drivers that do not support queue depth queries, and SQS counts are approximate.
Failed jobs
Things don't always go as planned. When a job fails permanently, Laravel records it in the failed_jobs table. Run queue:failed to inspect failed jobs, ordered with the most recent first:
1laravel queue:failed1laravel queue:failed
To retry a failed job, pass its ID to queue:retry, or pass all to retry every failed job. Retried jobs are pushed back onto their original connection and queue with a fresh attempt count:
1laravel queue:retry 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f532laravel queue:retry all1laravel queue:retry 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f532laravel queue:retry all
To delete a single failed job, pass its ID to queue:forget. To clear the entire table, run queue:flush, or pass --hours=48 to delete only jobs that failed more than 48 hours ago. You can schedule queue:flush to keep the table manageable:
1laravel queue:forget 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f532laravel queue:flush --hours=481laravel queue:forget 0199f3c2-5b8d-7f3e-9a16-2d4b8e0c7f532laravel queue:flush --hours=48
To delete all pending jobs from a queue, run queue:clear:
1laravel queue:clear redis --queue=emails1laravel queue:clear redis --queue=emails
When using Laravel Cloud managed queues, permanently failed jobs are tracked in the Laravel Cloud dashboard rather than your database's failed_jobs table. You can inspect error details and payloads, retry individual or bulk failed jobs, and delete failed records directly from the dashboard without running CLI commands against your server.
Events
Workers dispatch events in laravel::queue::events as they process jobs. Listeners run in the job's context, inheriting any context values it was dispatched with or added during execution.
Both JobProcessed and JobFailed include an event.job field of type JobInfo describing the job: id, name, connection, queue, and the 1-based attempt number.
JobProcessed fires after every attempt with event.duration and event.outcome, which is one of Succeeded, Released, Deleted, Debounced, MissingModels, Retrying, or Failed. A job the worker deleted because a model's row was deleted reports MissingModels, so you may count or alert on those jobs without failing them. For example, this listener logs a warning whenever a job takes longer than 30 seconds:
1use laravel::event::{Event, listener};2use laravel::prelude::*;3use laravel::queue::events::JobProcessed;45#[listener]6pub async fn warn_about_slow_jobs(event: Event<JobProcessed>) -> laravel::Result<()> {7 if event.duration > 30.seconds() {8 tracing::warn!(9 job = %event.job.name,10 queue = %event.job.queue,11 duration = %event.duration,12 "slow job",13 );14 }1516 Ok(())17}1use laravel::event::{Event, listener};2use laravel::prelude::*;3use laravel::queue::events::JobProcessed;45#[listener]6pub async fn warn_about_slow_jobs(event: Event<JobProcessed>) -> laravel::Result<()> {7 if event.duration > 30.seconds() {8 tracing::warn!(9 job = %event.job.name,10 queue = %event.job.queue,11 duration = %event.duration,12 "slow job",13 );14 }1516 Ok(())17}
JobFailed fires once a job fails permanently, after its failed hook has run. Because failed jobs are already reported to your error handler, listen for JobFailed when you want custom alerting or metrics. Along with event.job, it provides event.error, which you can inspect with is::<E>() or downcast_ref::<E>():
1use laravel::event::{Event, listener};2use laravel::queue::events::JobFailed;3use laravel::queue::{JobTimedOut, MissingModels};45#[listener]6pub async fn notify_on_job_failure(event: Event<JobFailed>) -> laravel::Result<()> {7 let reason = if event.error.is::<JobTimedOut>() {8 "timed out"9 } else if event.error.is::<MissingModels>() {10 "lost its models"11 } else {12 "failed"13 };1415 tracing::error!(16 id = %event.job.id,17 job = %event.job.name,18 queue = %event.job.queue,19 attempt = event.job.attempt,20 error = %event.error,21 "job {reason}",22 );2324 Ok(())25}1use laravel::event::{Event, listener};2use laravel::queue::events::JobFailed;3use laravel::queue::{JobTimedOut, MissingModels};45#[listener]6pub async fn notify_on_job_failure(event: Event<JobFailed>) -> laravel::Result<()> {7 let reason = if event.error.is::<JobTimedOut>() {8 "timed out"9 } else if event.error.is::<MissingModels>() {10 "lost its models"11 } else {12 "failed"13 };1415 tracing::error!(16 id = %event.job.id,17 job = %event.job.name,18 queue = %event.job.queue,19 attempt = event.job.attempt,20 error = %event.error,21 "job {reason}",22 );2324 Ok(())25}
Common error types you can match on event.error include:
| Error type | Cause |
|---|---|
laravel::queue::JobTimedOut |
The attempt exceeded the job's configured timeout |
laravel::queue::MissingModels |
A model field's database record was deleted before a job with fail_when_missing_models ran |
laravel::rate_limit::TooManyAttempts |
A rate-limited job could not run before its retry_for window expired |
| Application errors | Any error type returned from handle or passed to attempt.fail(error) |
The sync connection and dispatch_sync do not dispatch these events.
Writing a driver
Packages can support additional queue backends, such as Cloudflare Queues, by registering a custom driver. Implement Driver to push, reserve, and clear jobs, and ReservedJob to manage each reserved job's lease and completion. Laravel's worker handles retries, timeouts, and failed job recording automatically, renewing active reservations every HEARTBEAT against a LEASE duration so a driver only manages job storage and reservation.
Here is an example driver for Cloudflare Queues' HTTP pull API using Laravel's HTTP client:
1use std::time::Duration;23use laravel::http::client::{self, PendingRequest};4use laravel::queue::{Driver, LEASE, Reservation, ReservedJob};5use serde::Deserialize;6use serde_json::json;78#[derive(Debug, Clone)]9pub struct CloudflareSettings {10 pub account_id: String,11 pub token: String,12}1314#[derive(Clone)]15pub struct CloudflareDriver {16 settings: CloudflareSettings,17}1819impl CloudflareDriver {20 fn queue_api(&self, queue: &str) -> PendingRequest {21 client::base_url(format!(22 "https://api.cloudflare.com/client/v4/accounts/{}/queues/{queue}",23 self.settings.account_id24 ))25 .token(&self.settings.token)26 .accept_json()27 .ensure_successful()28 }29}3031pub struct CloudflareJob {32 driver: CloudflareDriver,33 queue: String,34 payload: String,35 attempts: u32,36 lease_id: String,37}3839#[derive(Deserialize)]40struct Envelope<T> {41 result: T,42}4344#[derive(Deserialize)]45struct PullResult {46 messages: Vec<PulledMessage>,47}4849#[derive(Deserialize)]50struct PulledMessage {51 body: String,52 attempts: u32,53 lease_id: String,54}5556#[derive(Deserialize)]57#[serde(rename_all = "camelCase")]58struct AckResult {59 #[serde(default)]60 ack_count: u64,61 #[serde(default)]62 retry_count: u64,63}6465impl Driver for CloudflareDriver {66 type Job = CloudflareJob;6768 async fn push(69 &self,70 queue: &str,71 payload: String,72 delay: Duration,73 ) -> laravel::Result<()> {74 self.queue_api(queue)75 .post("/messages")76 .json(json!({77 "body": payload,78 "content_type": "text",79 "delay_seconds": delay.as_secs(),80 }))81 .await?;8283 Ok(())84 }8586 async fn reserve(&self, queues: &[String]) -> laravel::Result<Option<CloudflareJob>> {87 for queue in queues {88 let response: Envelope<PullResult> = self89 .queue_api(queue)90 .post("/messages/pull")91 .json(json!({92 "batch_size": 1,93 "visibility_timeout_ms": LEASE.as_millis(),94 }))95 .await?96 .json()?;9798 if let Some(message) = response.result.messages.into_iter().next() {99 return Ok(Some(CloudflareJob {100 driver: self.clone(),101 queue: queue.clone(),102 payload: message.body,103 attempts: message.attempts,104 lease_id: message.lease_id,105 }));106 }107 }108109 Ok(None)110 }111112 async fn clear(&self, queue: &str) -> laravel::Result<u64> {113 self.queue_api(queue)114 .post("/purge")115 .json(json!({ "delete_messages_permanently": true }))116 .await?;117118 Ok(0)119 }120}121122impl ReservedJob for CloudflareJob {123 fn queue(&self) -> &str {124 &self.queue125 }126127 fn payload(&self) -> &str {128 &self.payload129 }130131 fn attempts(&self) -> u32 {132 self.attempts133 }134135 async fn renew(&self) -> laravel::Result<Reservation> {136 // Cloudflare Queues sets the visibility window on pull rather than renewing per lease...137 Ok(Reservation::Held)138 }139140 async fn delete(&self) -> laravel::Result<Reservation> {141 let response: Envelope<AckResult> = self142 .driver143 .queue_api(&self.queue)144 .post("/messages/ack")145 .json(json!({ "acks": [{ "lease_id": self.lease_id }] }))146 .await?147 .json()?;148149 if response.result.ack_count > 0 {150 Ok(Reservation::Held)151 } else {152 Ok(Reservation::Lost)153 }154 }155156 async fn release(&self, delay: Duration) -> laravel::Result<Reservation> {157 let response: Envelope<AckResult> = self158 .driver159 .queue_api(&self.queue)160 .post("/messages/ack")161 .json(json!({162 "retries": [{163 "lease_id": self.lease_id,164 "delay_seconds": delay.as_secs(),165 }],166 }))167 .await?168 .json()?;169170 if response.result.retry_count > 0 {171 Ok(Reservation::Held)172 } else {173 Ok(Reservation::Lost)174 }175 }176}1use std::time::Duration;23use laravel::http::client::{self, PendingRequest};4use laravel::queue::{Driver, LEASE, Reservation, ReservedJob};5use serde::Deserialize;6use serde_json::json;78#[derive(Debug, Clone)]9pub struct CloudflareSettings {10 pub account_id: String,11 pub token: String,12}1314#[derive(Clone)]15pub struct CloudflareDriver {16 settings: CloudflareSettings,17}1819impl CloudflareDriver {20 fn queue_api(&self, queue: &str) -> PendingRequest {21 client::base_url(format!(22 "https://api.cloudflare.com/client/v4/accounts/{}/queues/{queue}",23 self.settings.account_id24 ))25 .token(&self.settings.token)26 .accept_json()27 .ensure_successful()28 }29}3031pub struct CloudflareJob {32 driver: CloudflareDriver,33 queue: String,34 payload: String,35 attempts: u32,36 lease_id: String,37}3839#[derive(Deserialize)]40struct Envelope<T> {41 result: T,42}4344#[derive(Deserialize)]45struct PullResult {46 messages: Vec<PulledMessage>,47}4849#[derive(Deserialize)]50struct PulledMessage {51 body: String,52 attempts: u32,53 lease_id: String,54}5556#[derive(Deserialize)]57#[serde(rename_all = "camelCase")]58struct AckResult {59 #[serde(default)]60 ack_count: u64,61 #[serde(default)]62 retry_count: u64,63}6465impl Driver for CloudflareDriver {66 type Job = CloudflareJob;6768 async fn push(69 &self,70 queue: &str,71 payload: String,72 delay: Duration,73 ) -> laravel::Result<()> {74 self.queue_api(queue)75 .post("/messages")76 .json(json!({77 "body": payload,78 "content_type": "text",79 "delay_seconds": delay.as_secs(),80 }))81 .await?;8283 Ok(())84 }8586 async fn reserve(&self, queues: &[String]) -> laravel::Result<Option<CloudflareJob>> {87 for queue in queues {88 let response: Envelope<PullResult> = self89 .queue_api(queue)90 .post("/messages/pull")91 .json(json!({92 "batch_size": 1,93 "visibility_timeout_ms": LEASE.as_millis(),94 }))95 .await?96 .json()?;9798 if let Some(message) = response.result.messages.into_iter().next() {99 return Ok(Some(CloudflareJob {100 driver: self.clone(),101 queue: queue.clone(),102 payload: message.body,103 attempts: message.attempts,104 lease_id: message.lease_id,105 }));106 }107 }108109 Ok(None)110 }111112 async fn clear(&self, queue: &str) -> laravel::Result<u64> {113 self.queue_api(queue)114 .post("/purge")115 .json(json!({ "delete_messages_permanently": true }))116 .await?;117118 Ok(0)119 }120}121122impl ReservedJob for CloudflareJob {123 fn queue(&self) -> &str {124 &self.queue125 }126127 fn payload(&self) -> &str {128 &self.payload129 }130131 fn attempts(&self) -> u32 {132 self.attempts133 }134135 async fn renew(&self) -> laravel::Result<Reservation> {136 // Cloudflare Queues sets the visibility window on pull rather than renewing per lease...137 Ok(Reservation::Held)138 }139140 async fn delete(&self) -> laravel::Result<Reservation> {141 let response: Envelope<AckResult> = self142 .driver143 .queue_api(&self.queue)144 .post("/messages/ack")145 .json(json!({ "acks": [{ "lease_id": self.lease_id }] }))146 .await?147 .json()?;148149 if response.result.ack_count > 0 {150 Ok(Reservation::Held)151 } else {152 Ok(Reservation::Lost)153 }154 }155156 async fn release(&self, delay: Duration) -> laravel::Result<Reservation> {157 let response: Envelope<AckResult> = self158 .driver159 .queue_api(&self.queue)160 .post("/messages/ack")161 .json(json!({162 "retries": [{163 "lease_id": self.lease_id,164 "delay_seconds": delay.as_secs(),165 }],166 }))167 .await?168 .json()?;169170 if response.result.retry_count > 0 {171 Ok(Reservation::Held)172 } else {173 Ok(Reservation::Lost)174 }175 }176}
Return Reservation::Lost from renew, delete, or release if the reservation lapsed and another worker claimed the job, signaling the current worker to stop touching it. You may also override Driver::bulk for batched pushes, Driver::sizes to report QueueSizes, and ReservedJob::fail if your backend records failed jobs itself.
Register your driver by name in a service provider's register method:
1use laravel::container::Registrar;2use laravel::foundation::ServiceProvider;34impl ServiceProvider for CloudflareQueueServiceProvider {5 fn register(&self, app: &mut Registrar) {6 app.queue().extend("cloudflare", async |_app, definition| {7 let settings = definition.settings::<CloudflareSettings>()?.clone();89 Ok(CloudflareDriver { settings })10 });11 }12}1use laravel::container::Registrar;2use laravel::foundation::ServiceProvider;34impl ServiceProvider for CloudflareQueueServiceProvider {5 fn register(&self, app: &mut Registrar) {6 app.queue().extend("cloudflare", async |_app, definition| {7 let settings = definition.settings::<CloudflareSettings>()?.clone();89 Ok(CloudflareDriver { settings })10 });11 }12}
Then configure a custom connection referencing that driver, passing any custom settings your driver expects:
1use laravel::config::queue::ConnectionConfig;23queue.add_connection(4 "cloudflare",5 ConnectionConfig::custom("cloudflare")6 .queue("emails-queue-id")7 .settings(CloudflareSettings {8 account_id: env.get("CLOUDFLARE_ACCOUNT_ID").unwrap_or_default(),9 token: env.get("CLOUDFLARE_API_TOKEN").unwrap_or_default(),10 }),11);1use laravel::config::queue::ConnectionConfig;23queue.add_connection(4 "cloudflare",5 ConnectionConfig::custom("cloudflare")6 .queue("emails-queue-id")7 .settings(CloudflareSettings {8 account_id: env.get("CLOUDFLARE_ACCOUNT_ID").unwrap_or_default(),9 token: env.get("CLOUDFLARE_API_TOKEN").unwrap_or_default(),10 }),11);
Laravel invokes your driver factory once per configured connection on first use and caches that instance for the lifetime of the application, sharing it across concurrent requests and workers. Drivers built on TCP protocols should hold a connection pool or reconnecting client internally, while drivers built on laravel::http::client share Laravel's pooled HTTP client automatically.
Testing
When testing code that dispatches jobs, you typically want to verify that the right job was queued without executing it, and then test the job's logic independently.
In tests, Laravel routes all jobs to the sync connection by default, even when a job, chain, batch, or queued notification specifies another connection. Unless you fake the queue, dispatched jobs execute immediately. To test against a real queue backend, override QUEUE_CONNECTION in your test configuration.
Faking the queue
Call queue::fake() to intercept dispatched jobs without pushing or executing them, then assert against the returned fake:
1use laravel::queue;2use laravel::testing::prelude::*;34#[laravel::test]5async fn uploading_a_podcast_queues_it_for_processing(app: Application) {6 let queue = queue::fake();78 app.post("/podcasts").json(json!({ "title": "Episode 1" })).await.assert_redirect();910 queue.assert_pushed::<ProcessPodcast>();11 queue.assert_pushed_times::<ProcessPodcast>(1);1213 queue.assert_pushed_where::<ProcessPodcast>(|job| {14 job.podcast.title == "Episode 1" && job.queue() == "default"15 });16}1use laravel::queue;2use laravel::testing::prelude::*;34#[laravel::test]5async fn uploading_a_podcast_queues_it_for_processing(app: Application) {6 let queue = queue::fake();78 app.post("/podcasts").json(json!({ "title": "Episode 1" })).await.assert_redirect();910 queue.assert_pushed::<ProcessPodcast>();11 queue.assert_pushed_times::<ProcessPodcast>(1);1213 queue.assert_pushed_where::<ProcessPodcast>(|job| {14 job.podcast.title == "Episode 1" && job.queue() == "default"15 });16}
The predicate receives the deserialized job along with id(), connection(), queue(), and delay(). connection() reflects the connection requested at dispatch, and delay() compares directly with duration spans such as job.delay() == 10.minutes(). You can also assert with assert_not_pushed::<T>(), assert_not_pushed_where, and assert_nothing_pushed().
The fake respects database transactions and records jobs only after commit. It also round-trips each job through serialization so serialization bugs fail your test immediately. Model fields such as job.user are preserved without relationships and do not require database access inside the predicate.
To fake only specific job types, or fake everything except certain jobs, chain only or except. Unfaked jobs dispatch normally:
1let queue = queue::fake().only::<ProcessPodcast>();2let queue = queue::fake().except::<SendInvoice>();1let queue = queue::fake().only::<ProcessPodcast>();2let queue = queue::fake().except::<SendInvoice>();
The fake remains active until its handle is dropped.
Testing a job
To test a job's handle method directly, execute a single attempt with app.job(..) and assert on the outcome. For example, this test verifies that ProcessPodcast releases itself when the upload has not finished:
1use laravel::model::create;2use laravel::testing::prelude::*;34#[laravel::test]5async fn uploading_podcasts_are_released(app: Application) -> laravel::Result<()> {6 let podcast = create!(Podcast { title: "Episode 1", uploaded: false }).await?;78 app.job(ProcessPodcast { podcast })9 .await10 .assert_released_after(30.seconds());1112 Ok(())13}1use laravel::model::create;2use laravel::testing::prelude::*;34#[laravel::test]5async fn uploading_podcasts_are_released(app: Application) -> laravel::Result<()> {6 let podcast = create!(Podcast { title: "Episode 1", uploaded: false }).await?;78 app.job(ProcessPodcast { podcast })9 .await10 .assert_released_after(30.seconds());1112 Ok(())13}
The job runs through its middleware as it would on a worker. Call attempt(n) to simulate a specific retry count for attempt.number(). Available outcome assertions include assert_succeeded, assert_released, assert_released_after, assert_deleted, assert_failed, and assert_failed_with::<E>(). Test attempts run once without retrying or invoking failed.
Testing chains
The queue fake records each chain alongside its first job. Use assert_chained with a tuple of job types to verify the chain's order:
1let queue = queue::fake();23app.post("/orders/42/ship").await.assert_redirect();45queue.assert_chained::<(ShipOrder, RecordShipment, UpdateInventory)>();1let queue = queue::fake();23app.post("/orders/42/ship").await.assert_redirect();45queue.assert_chained::<(ShipOrder, RecordShipment, UpdateInventory)>();
To inspect the payloads of subsequent jobs in the chain, call chain().get::<T>(index) inside assert_pushed_where:
1queue.assert_pushed_where::<ShipOrder>(|job| {2 job.chain().get::<RecordShipment>(0).is_some_and(|next| next.order_id == 42)3});1queue.assert_pushed_where::<ShipOrder>(|job| {2 job.chain().get::<RecordShipment>(0).is_some_and(|next| next.order_id == 42)3});
To test a job that dynamically modifies its chain, run it with app.job(..) and call assert_chained with a job type or tuple of job types:
1app.job(ProcessPodcast { podcast })2 .await3 .assert_succeeded()4 .assert_chained::<TranscribePodcast>();1app.job(ProcessPodcast { podcast })2 .await3 .assert_succeeded()4 .assert_chained::<TranscribePodcast>();
Testing batches
The queue fake intercepts dispatched batches without writing to the batch tables or executing their jobs. Assert on dispatched batches with assert_batched:
1let queue = queue::fake();23app.post("/imports").json(json!({ "file": "contacts.csv" })).await.assert_redirect();45queue.assert_batched(|batch| {6 batch.name() == Some("Import CSV")7 && batch.jobs().len() == 38 && batch.jobs().get::<ImportCsv>(0).is_some_and(|job| job.rows == (1..=100))9});1let queue = queue::fake();23app.post("/imports").json(json!({ "file": "contacts.csv" })).await.assert_redirect();45queue.assert_batched(|batch| {6 batch.name() == Some("Import CSV")7 && batch.jobs().len() == 38 && batch.jobs().get::<ImportCsv>(0).is_some_and(|job| job.rows == (1..=100))9});
Inside the predicate, you can also inspect then(), catch(), finally(), and allows_failures(). Call queue.assert_nothing_batched() to verify no batches were dispatched.
Because the fake does not execute batch callbacks, you can test callbacks directly with app.callback. By default, the callback receives a synthetic single-job batch, which you can customize with total_jobs, failed_jobs, and related builders:
1app.callback(ImportFinished { import_id: 7 }).total_jobs(3).then().await?;1app.callback(ImportFinished { import_id: 7 }).total_jobs(3).then().await?;
To test a job that adds jobs to its batch or cancels it, execute it with app.job(..).in_batch() and assert with added_to_batch() or assert_batch_cancelled():
1let result = app.job(ImportCsv { rows: 1..=100 }).in_batch().await;23result.assert_succeeded();45assert_eq!(result.added_to_batch().len(), 1);6assert!(7 result8 .added_to_batch()9 .get::<ImportCsv>(0)10 .is_some_and(|job| job.rows == (101..=200))11);1213app.job(ImportCsv { rows: 1..=0 })14 .in_batch()15 .await16 .assert_batch_cancelled();1let result = app.job(ImportCsv { rows: 1..=100 }).in_batch().await;23result.assert_succeeded();45assert_eq!(result.added_to_batch().len(), 1);6assert!(7 result8 .added_to_batch()9 .get::<ImportCsv>(0)10 .is_some_and(|job| job.rows == (101..=200))11);1213app.job(ImportCsv { rows: 1..=0 })14 .in_batch()15 .await16 .assert_batch_cancelled();