Skip to main content

Module queue

Module queue 

Source
Expand description

Queues: jobs that run later, outside the request that dispatched them.

Some work, such as transcoding an uploaded podcast or sending a thousand emails, takes too long to do while a request waits. This module lets you push that work to a queue and run it in a worker process. To learn more, check out the queues guide.

A job is a Queueable struct with #[job] on its impl block. Dispatching the job pushes it to a connection, and the connection keeps the job until a worker runs it:

use laravel::container::Inject;
use laravel::queue::job;

#[derive(laravel::queue::Queueable)]
pub struct ProcessPodcast {
    pub podcast_id: i64,
}

#[job(
    queue = "podcasts",
    tries = 3,
    backoff = [10.seconds(), 1.minutes()],
    timeout = 2.minutes(),
)]
impl ProcessPodcast {
    async fn handle(self, audio: Inject<AudioProcessor>) -> laravel::Result<()> {
        audio.process(self.podcast_id).await
    }
}

ProcessPodcast { podcast_id: 42 }.dispatch().await?;

config.queue names the application’s connections. Each connection uses the database, redis, sqs, cloud, sync, or discard driver, or a driver that an application or package registered with Drivers::extend. Laravel creates a connection’s driver the first time a job is pushed to the connection or a worker starts working it.

§Running jobs

Each job runs in a fresh application context that starts with the dispatching context’s values. Values that the job adds to its context carry on to its error reports, its failed hook, the worker’s events about the job, the callbacks the job triggers, and the next job in its chain. The job’s log lines carry a job span with its ID, name, connection, queue, and attempt number.

Before each run, the worker checks whether the job may still run. If the job’s retry_for has passed, or the job has no retry_for and has already run tries times, the worker fails the job for good without running it.

When a run fails, the worker fails the job for good if the job called Attempt::fail, the job can’t be decoded, the run was the job’s last, or the run used up the job’s max_errors. Otherwise, the worker retries the job after the backoff for that run’s number. A release also uses up a run, so a retry after a release waits as long as it would after a failed run.

When a job fails for good, the worker removes it from its queue and stores it with the failed jobs. Then the job’s failed hook runs, the worker dispatches events::JobFailed, and the worker reports the job’s error. A job that can’t be decoded doesn’t run its failed hook or dispatch events.

queue:retry pushes a failed job back onto its queue with the same ID, all of its tries, and a fresh retry_for. When the retried job succeeds, its chain continues, and its batch stops counting it as failed. A retried job on an SQS FIFO queue gets a new deduplication ID.

§Workers

queue:work fails for the sync and discard connections. When a connection’s backend is unavailable, the worker reports the error and tries again, doubling its wait each time up to a minute. A worker started with --stop-when-empty exits with status 1 instead.

When a worker is killed, its jobs stay reserved until their reservations lapse, about a minute later. The interrupted run counts as an attempt and as an error toward max_errors.

queue:restart and queue:pause reach workers through the default cache store. With the memory store, queue:restart warns that other processes won’t see the restart. With the discard store, queue:restart fails. An idle worker sees a restart after its current sleep or long poll, and a worker that started after the restart ignores it. While a worker can’t read the cache, it logs a warning, keeps working, and uses the pauses it last read.

queue:pause --all is separate from pauses of single queues. queue:continue --all doesn’t resume a queue that was paused by name, and queue:continue emails doesn’t resume emails while every queue is paused. A worker started with --stop-when-empty stops when all of its queues are paused.

Modules§

events
Events that the queue worker dispatches as it processes jobs.

Macros§

tables
Define a migration’s migrate function to create the database queue driver’s tables.

Structs§

Attempt
One run of a job, with the job’s ID, where the job came from, and how many times it has run.
Batch
A snapshot of a batch at the time it was read, with its job counts and the times it was created, cancelled, and finished.
BatchId
A batch’s unique ID, which is a time-ordered UUID.
CallbackList
A batch’s or chain’s callbacks, as a test sees them.
ConnectionDefinition
The name and configuration of the connection that a driver’s factory creates a driver for.
Drivers
Queue driver factories, configured before the application boots.
JobId
A dispatched job’s unique ID, which is a time-ordered UUID.
JobList
The jobs waiting in a chain or a batch, as a test sees them.
JobOptions
A job’s queue, retries, and timeout, from the options of #[job(..)].
JobTimedOut
The error for a job that ran longer than its timeout and was stopped.
MiddlewareGroup
An ordered list of job middleware, where the first middleware runs first and wraps the rest.
MissingModels
The error for a queued job, listener, or callback that can’t run because the rows of some of its models are gone.
Next
The rest of a job’s middleware, and its handle.
ParseIdError
The error from parsing text that isn’t a UUID as a JobId or BatchId.
PendingBatch
A batch of jobs on its way to the queue.
PendingBulk
Several jobs on their way to the queue together.
PendingChain
A chain of jobs on its way to the queue.
PendingDispatch
A job on its way to the queue.
Pushed
A job that a QueueFake recorded, decoded as a worker would read it.
PushedBatch
A batch that a QueueFake recorded, or a batch that’s a step of a chain, with its jobs, name, and options.
QueueFake
An active queue fake and its typed assertions.
QueueManager
The application’s queue connections, by name.
QueueSizes
How many jobs a queue holds in each state, as QueueManager::sizes reports them.

Enums§

ChainDispatched
The first step dispatched by a chain.
Failed
What became of a job that failed for good, as ReservedJob::fail reports it.
Reservation
Whether a job was still a worker’s when the worker renewed, deleted, or released it, as ReservedJob reports it.

Constants§

HEARTBEAT
How often a worker renews the reservation of a job it’s running.
LEASE
How long a reservation lasts without being renewed. A job whose worker stopped renewing it is available to other workers once its reservation lapses.

Traits§

Callback
A Queueable struct with then, catch, or finally methods that a batch or chain calls directly, without queueing them, when it reaches each method’s point.
Catch
A callback with a catch method.
ChainCatch
A catch callback that doesn’t take a &Batch, so a chain can call it too.
Driver
A queue backend, which stores a connection’s jobs and hands each one to a worker.
Finally
A callback with a finally method, which a batch calls once every one of its jobs has run.
IntoBatchJob
One job of a batch, which is either a job or a chain of jobs.
IntoBatchJobs
The jobs of a batch.
IntoJobs
One or more jobs to add to a chain, in order.
IntoMiddleware
A type that a job’s middleware method may return.
Job
A Queueable struct with a handler, which the queue keeps and runs later.
JobResult
A return type that a job’s handle and failed methods and a callback’s methods support.
JobTypes
A job type or a tuple of job types that names a chain, such as TranscribePodcast or (ShipOrder, RecordShipment).
Middleware
Code that runs around a job’s handle, such as a check that decides whether the job runs now.
Queueable
A job, a queued listener’s event, or a callback that the queue can store until a worker runs it.
ReservedJob
One reservation of a job, which a worker runs and then settles.
Then
A callback with a then method, which a batch calls once every one of its jobs has succeeded.

Functions§

batch
Dispatch jobs as a batch and call its callbacks once they’ve all run.
bulk
Push several jobs at once.
cancel_batch
Cancel a batch.
chain
Chain jobs so that each one runs after the one before it succeeds.
dispatch
Dispatch a job to its queue.
dispatch_sync
Run a job immediately in this process instead of queueing it.
fake
Record this application’s dispatched jobs without pushing or running them.
find_batch
Find a batch by its ID, such as to show how far along the batch is.
manager
Resolve the application’s queue manager from its context.

Attribute Macros§

callback
Make a Queueable struct a batch or chain Callback.
job
Make a Queueable struct a queued job.
middleware
Turn an async function into a job Middleware struct with the function’s name.

Derive Macros§

Queueable
Implement Queueable so that the queue can store the struct, with its model fields stored as keys.