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 one queueing API across your database, Redis, Amazon SQS, and Laravel Cloud's managed queues, so your jobs need no changes when you move from one to another. Each job is a struct with a Handle method that runs when a worker started with laravel queue:work picks it up.
For quick work that you can afford to lose in a crash, r.Background runs in the current process without a queue. Some features also queue their work for you: mail and notifications send from a worker when you call Queue in place of Send, and a queued listener runs an event's listener on the queue.
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. An application without DATABASE_URL uses the sync connection instead, which runs each job as soon as it's dispatched. You may choose a different connection or customize the defaults through your environment variables:
| Variable | Sets | Default |
|---|---|---|
QUEUE_CONNECTION |
The default connection | database, or sync without a database |
DB_QUEUE_CONNECTION, DB_QUEUE_TABLE, DB_QUEUE |
The database connection's database connection, table, and default queue |
The default database, 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 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 |
sqs |
Pushes jobs to Amazon SQS queues |
cloud |
Pushes jobs to Laravel Cloud's managed queues |
sync |
Runs each job as soon as you dispatch it, in the current process, and returns its error from the 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 turn queued work off 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. Your application's create_jobs_table migration creates these tables and the batch tables using queue.CreateTables(ctx), so run your migrations before dispatching jobs:
1laravel migrate1laravel migrate
If you need to add the queue tables to an existing application, call queue.CreateTables(ctx) inside a migration. It creates jobs, failed_jobs, job_batches, and job_batch_jobs using your configured table names (DB_QUEUE_TABLE and DB_QUEUE_FAILED_TABLE). Permanently failed jobs are written to failed_jobs whichever queue driver you use, except on Laravel Cloud, where managed queues keep failed jobs in the Laravel Cloud dashboard so you can inspect, retry, or delete them there instead. If you'd rather discard failed jobs than store them, set cfg.Queue.Failed.Discard in your options' configure function:
1// bootstrap/app.go2func configure(cfg *config.Config, env *config.Env) {3 cfg.Queue.Failed.Discard = true4}1// bootstrap/app.go2func configure(cfg *config.Config, env *config.Env) {3 cfg.Queue.Failed.Discard = true4}
Redis
To store queued jobs in Redis, configure a Redis connection and set QUEUE_CONNECTION=redis. The redis queue connection uses the default Redis connection, which REDIS_URL and REDIS_DB set, and which defaults to database 0 of redis://127.0.0.1:6379.
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 names a database number, both connections share it, so you should add a dedicated Redis connection for queues and set REDIS_QUEUE_CONNECTION to its name:
1// bootstrap/app.go2func configure(cfg *config.Config, env *config.Env) {3 cfg.Redis.Connections["queues"] = config.RedisConnection{4 URL: env.String("REDIS_QUEUES_URL", "redis://queues.internal:6379"),5 }6}1// bootstrap/app.go2func configure(cfg *config.Config, env *config.Env) {3 cfg.Redis.Connections["queues"] = config.RedisConnection{4 URL: env.String("REDIS_QUEUES_URL", "redis://queues.internal:6379"),5 }6}
Because Laravel doesn't prefix queue keys, separate applications should use their own Redis servers or databases. Failed jobs and batches still go to your database, so keep the jobs table migration if you use them.
Blocking
By default, an idle worker sleeps for --sleep seconds before polling for new jobs. With BlockFor, the worker instead waits on Redis for up to that long, and claims a job the moment one is pushed. Set BlockFor on the redis connection in your configure function:
1redisQueue := cfg.Queue.Connections["redis"]2redisQueue.BlockFor = 5 * time.Second3cfg.Queue.Connections["redis"] = redisQueue1redisQueue := cfg.Queue.Connections["redis"]2redisQueue.BlockFor = 5 * time.Second3cfg.Queue.Connections["redis"] = redisQueue
Amazon SQS
To use Amazon SQS for your queues, set QUEUE_CONNECTION=sqs. You may configure the sqs connection using these environment variables:
| Variable | Description | Default |
|---|---|---|
AWS_DEFAULT_REGION |
The AWS region | The region AWS finds, such as AWS_REGION |
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN |
AWS credentials | The default credential chain, 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 doesn't create SQS queues, create them in AWS first. To enable long polling so idle workers wait for new jobs efficiently, set 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, and Laravel holds them until they're due. Because failed jobs from SQS are written to the failed_jobs table, keep that migration unless you discard failed jobs.
FIFO queues
Any queue name ending in .fifo is treated as an SQS FIFO queue, which processes the 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 OnGroup to assign a message group; jobs dispatched without one share a single group. For example, this handler gives each customer a group of their own, so one customer's orders ship in the order they were placed while other customers' orders ship alongside them:
1func Ship(r *web.Request) *web.Response {2 order, err := model.FromRoute[models.Order](r, "order")3 if err != nil {4 return web.Fail(err)5 }67 _, err = queue.OnQueue("orders.fifo").8 OnGroup(fmt.Sprintf("customer-%d", order.CustomerID)).9 Dispatch(r, jobs.ShipOrder{OrderID: order.ID})10 if err != nil {11 return web.Fail(err)12 }1314 return web.Back()15}1func Ship(r *web.Request) *web.Response {2 order, err := model.FromRoute[models.Order](r, "order")3 if err != nil {4 return web.Fail(err)5 }67 _, err = queue.OnQueue("orders.fifo").8 OnGroup(fmt.Sprintf("customer-%d", order.CustomerID)).9 Dispatch(r, jobs.ShipOrder{OrderID: order.ID})10 if err != nil {11 return web.Fail(err)12 }1314 return web.Back()15}
A chain or batch dispatched with OnGroup puts every one of its jobs in the group.
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, such as when a customer clicks the ship button twice, pass your own DeduplicationID:
1_, err := queue.OnQueue("orders.fifo").2 DeduplicationID(fmt.Sprintf("ship-order-%d", order.ID)).3 Dispatch(r, jobs.ShipOrder{OrderID: order.ID})1_, err := queue.OnQueue("orders.fifo").2 DeduplicationID(fmt.Sprintf("ship-order-%d", order.ID)).3 Dispatch(r, jobs.ShipOrder{OrderID: order.ID})
A deduplication ID names one job. A chain dispatched with DeduplicationID gives it to its first job, while Bulk or a batch of more than one job fails to dispatch, since the queue would keep only the first of them.
SQS FIFO queues don't support per-message delays, so dispatch delayed jobs to a standard queue. Other drivers ignore OnGroup and DeduplicationID.
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 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 cache store that every process shares, 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 no 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; set QUEUE_CONNECTION=cloud to use it as your default connection.
Managed queues are backed by SQS, so they support every sqs driver feature, including FIFO queues and large payloads. You may turn on 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, so you can 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, add it to cfg.Queue.Connections in your options' configure function. Laravel calls configure with the default connections already in place, for your application and its tests, and several connections may share the same driver with different settings:
1// bootstrap/app.go2func configure(cfg *config.Config, env *config.Env) {3 cfg.Queue.Connections["reports"] = config.QueueConnection{4 Driver: "database",5 Connection: "reporting",6 Table: "report_jobs",7 Queue: "reports",8 }9}1// bootstrap/app.go2func configure(cfg *config.Config, env *config.Env) {3 cfg.Queue.Connections["reports"] = config.QueueConnection{4 Driver: "database",5 Connection: "reporting",6 Table: "report_jobs",7 Queue: "reports",8 }9}
You may then dispatch jobs to the connection by name, as Connections, queues, and delays shows.
Creating jobs
A job is a struct with a Handle(ctx context.Context) error method. New applications keep their jobs in the jobs package, and list a value of each job type in jobs.All, so a worker can find a job's type when it runs. The make:job command writes a new job and adds it to that list:
1laravel make:job ProcessPodcast1laravel make:job ProcessPodcast
For example, consider a podcast publishing application that processes each uploaded episode before publishing it. This job receives a podcast's ID and reads the models.Podcast when it runs:
1// jobs/process_podcast.go2package jobs34import (5 "context"67 "go.laravel.com/model"89 "app/models"10 "app/store"11)1213type ProcessPodcast struct {14 PodcastID int6415}1617func (j ProcessPodcast) Handle(ctx context.Context) error {18 podcast, err := model.Find[models.Podcast](ctx, j.PodcastID)19 if err != nil {20 return err21 }2223 return store.ProcessPodcast(ctx, podcast)24}1// jobs/process_podcast.go2package jobs34import (5 "context"67 "go.laravel.com/model"89 "app/models"10 "app/store"11)1213type ProcessPodcast struct {14 PodcastID int6415}1617func (j ProcessPodcast) Handle(ctx context.Context) error {18 podcast, err := model.Find[models.Podcast](ctx, j.PodcastID)19 if err != nil {20 return err21 }2223 return store.ProcessPodcast(ctx, podcast)24}
When you write a job by hand, add it to jobs.All yourself:
1// jobs/jobs.go2package jobs34var All = []any{5 ProcessPodcast{},6}1// jobs/jobs.go2package jobs34var All = []any{5 ProcessPodcast{},6}
A job may also live in your own package, beside the code that dispatches it. For example, a FulfillOrder job may live in store, beside the store.PlaceOrder function that queues it. If FulfillOrder lived in jobs, it would import store for its work while store imported jobs to dispatch it, and Go doesn't allow that import cycle. To write such a job, name its package before the type:
1laravel make:job store.FulfillOrder1laravel make:job store.FulfillOrder
The command writes store/fulfill_order.go and lists store.FulfillOrder{} in jobs.All. To learn more about organizing your application's packages, check out the structure guide's section on adding your own packages.
Because the queue stores a job's exported fields as JSON until a worker runs it, a job should carry plain data or models rather than database connections or open files. A json tag renames a field, and json:"-" leaves one out.
Handle returns nil when the job succeeds, or an error to fail it. Its ctx carries your application, so the job reaches the database, the cache, the queue, and your configuration through ctx, as a command does, though there is no HTTP request, session, or logged-in user. Laravel carries the log values of the context that dispatched the job, such as the active tenant, into the job's ctx.
Models in jobs
Instead of storing an ID and reading the record yourself, a job may store models directly as fields. Tag a model field queue:"model", and the queue stores only the model's ID. Before Handle runs, the worker reads the row again, so your job always works with fresh data:
1// jobs/send_welcome_email.go2package jobs34import (5 "context"67 "app/models"8)910type SendWelcomeEmail struct {11 User models.User `queue:"model"`12}1314func (j SendWelcomeEmail) Handle(ctx context.Context) error {15 // Send the welcome email to j.User.Email...1617 return nil18}1// jobs/send_welcome_email.go2package jobs34import (5 "context"67 "app/models"8)910type SendWelcomeEmail struct {11 User models.User `queue:"model"`12}1314func (j SendWelcomeEmail) Handle(ctx context.Context) error {15 // Send the welcome email to j.User.Email...1617 return nil18}
Pass a model you've saved when dispatching, as in jobs.SendWelcomeEmail{User: user}, because a model without an ID fails the dispatch. A *models.User field also stores only the user's ID and may be nil, and a []models.User field stores each user's ID. Relationships aren't stored, so load any relationships Handle needs, such as model.Load(ctx, &j.User, "posts").
If a model lives in another database, such as a reporting database, name its connection in the tag:
1type SummarizeRegion struct {2 Region models.Region `queue:"model,connection=reporting"`3}1type SummarizeRegion struct {2 Region models.Region `queue:"model,connection=reporting"`3}
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 send a welcome email to a user who has already deleted their account, and retrying the job couldn't bring the row back anyway. The worker logs each job it deletes this way at the INFO level, naming the missing model and its IDs, and the JobProcessed event for the job reports the queue.MissingModels outcome. For a slice field, the worker leaves out the models whose rows are gone, and the job runs with the rest.
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 row 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, set the FailWhenMissingModels option to fail the job permanently with a *queue.MissingModelsError instead:
1func (ChargeInvoice) JobOptions() queue.Options {2 return queue.Options{FailWhenMissingModels: true}3}1func (ChargeInvoice) JobOptions() queue.Options {2 return queue.Options{FailWhenMissingModels: true}3}
Even when using FailWhenMissingModels, the failed job's Failed method does not run, since the worker can't read the job's models to pass to it.
The job of a queued listener may hold models in queue:"model" fields too. For example, a queued listener of model.Created[models.User] may put e.Model in a queue:"model" field of its job.
Services in jobs
A job's fields hold data and models, so a job that needs a service of your own, such as a payment provider's client, can't carry it. It reaches your application's services from its ctx instead, with services.From:
1// jobs/charge_invoice.go2package jobs34import (5 "context"67 "app/services"8)910type ChargeInvoice struct {11 InvoiceID int6412}1314func (j ChargeInvoice) Handle(ctx context.Context) error {15 return services.From(ctx).Billing.Charge(ctx, j.InvoiceID)16}1// jobs/charge_invoice.go2package jobs34import (5 "context"67 "app/services"8)910type ChargeInvoice struct {11 InvoiceID int6412}1314func (j ChargeInvoice) Handle(ctx context.Context) error {15 return services.From(ctx).Billing.Charge(ctx, j.InvoiceID)16}
A job's Failed method, its middleware, and a batch's callbacks reach the services from their ctx too. In tests, jobs run with the test's application, so a test that replaces a service gives its jobs the replacement.
A job runs without the user who dispatched it, so give the job the user in a model field when it needs them. To run code that reads the logged-in user or checks an ability, log the user in with auth.WithUser.
Job names
Laravel records each job's name in the queue payload and finds the job's type by that name when a worker runs it. By default, the name is the type's package path and name, such as app/jobs.ProcessPodcast. If you rename or move the type, jobs already sitting on the queue have no type to run. To keep a job's name stable across refactors, give it a JobName method:
1func (ProcessPodcast) JobName() string { return "podcasts.process" }1func (ProcessPodcast) JobName() string { return "podcasts.process" }
Jobs already on the queue keep the fields they were stored with. A field you add reads as its zero value from those jobs, so choose a zero value that means what the old jobs meant. When renaming a field, keep its old name in a json tag so previously queued jobs still decode. For example, this job renamed PodcastID to EpisodeID, and added IncludeTimestamps, which is false for the jobs queued before it:
1type TranscribeEpisode struct {2 EpisodeID int64 `json:"PodcastID"`3 IncludeTimestamps bool4}1type TranscribeEpisode struct {2 EpisodeID int64 `json:"PodcastID"`3 IncludeTimestamps bool4}
If you add a new model field to a job, make it a pointer or a slice, which reads as nil or empty from the jobs already on the queue.
Dispatching jobs
Once you've written a job, dispatch it by passing it to queue.Dispatch, which pushes the job onto your default queue connection. This handler creates a podcast and queues it for background processing:
1package podcasts23import (4 "go.laravel.com/model"5 "go.laravel.com/queue"6 "go.laravel.com/web"78 "app/jobs"9 "app/models"10)1112func Store(r *web.Request) *web.Response {13 var form struct {14 Title string `json:"title"`15 }16 if err := r.BindInto(&form); err != nil {17 return web.Fail(err)18 }1920 podcast := models.Podcast{Title: form.Title}21 if err := model.Create(r, &podcast); err != nil {22 return web.Fail(err)23 }2425 if _, err := queue.Dispatch(r, jobs.ProcessPodcast{PodcastID: podcast.ID}); err != nil {26 return web.Fail(err)27 }2829 return web.Redirect("/podcasts")30}1package podcasts23import (4 "go.laravel.com/model"5 "go.laravel.com/queue"6 "go.laravel.com/web"78 "app/jobs"9 "app/models"10)1112func Store(r *web.Request) *web.Response {13 var form struct {14 Title string `json:"title"`15 }16 if err := r.BindInto(&form); err != nil {17 return web.Fail(err)18 }1920 podcast := models.Podcast{Title: form.Title}21 if err := model.Create(r, &podcast); err != nil {22 return web.Fail(err)23 }2425 if _, err := queue.Dispatch(r, jobs.ProcessPodcast{PodcastID: podcast.ID}); err != nil {26 return web.Fail(err)27 }2829 return web.Redirect("/podcasts")30}
Dispatch returns the job's queue.JobID, matching the ID that queue.AttemptOf(ctx).ID() returns and the failed jobs commands show. You may dispatch jobs from handlers, commands, scheduled tasks, listeners, or other jobs. A handler passes r, and the others pass the ctx they received.
Connections, queues, and delays
Sometimes a job belongs on another connection or queue, or shouldn't run until later. Start the dispatch with queue.OnConnection, queue.OnQueue, or queue.Delay, and chain the others before Dispatch:
1_, err := queue.OnConnection("reports").2 OnQueue("podcasts").3 Delay(10*time.Minute).4 Dispatch(r, jobs.ProcessPodcast{PodcastID: podcast.ID})1_, err := queue.OnConnection("reports").2 OnQueue("podcasts").3 Delay(10*time.Minute).4 Dispatch(r, jobs.ProcessPodcast{PodcastID: podcast.ID})
When the job should run at a certain time, such as a reminder an hour before an event starts, use queue.DelayUntil instead of working out the delay yourself. The delay counts down on your application's clock, so a test that travels in time sees the delay it expects:
1_, err := queue.DelayUntil(event.StartsAt.Add(-time.Hour)).2 Dispatch(r, jobs.SendReminder{EventID: event.ID})1_, err := queue.DelayUntil(event.StartsAt.Add(-time.Hour)).2 Dispatch(r, jobs.SendReminder{EventID: event.ID})
A time that has already passed runs the job without waiting. 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 queue.Options{Queue: "podcasts"}. Calling OnQueue at dispatch time overrides that default.
Database transactions
When you dispatch a job inside a database transaction with the transaction's ctx, Laravel waits until the outermost transaction commits before pushing the job onto the queue, and discards it if the transaction rolls back. This ensures a worker never tries to process a job before its database records are visible:
1err := db.Transaction(r, func(ctx context.Context) error {2 podcast := models.Podcast{Title: form.Title}3 if err := model.Create(ctx, &podcast); err != nil {4 return err5 }67 _, err := queue.Dispatch(ctx, jobs.ProcessPodcast{PodcastID: podcast.ID})89 return err10})1err := db.Transaction(r, func(ctx context.Context) error {2 podcast := models.Podcast{Title: form.Title}3 if err := model.Create(ctx, &podcast); err != nil {4 return err5 }67 _, err := queue.Dispatch(ctx, jobs.ProcessPodcast{PodcastID: podcast.ID})89 return err10})
Inside the transaction, Dispatch returns the JobID immediately and pushes the job once the transaction commits. Bulk, chains, and batches wait for the commit too. If pushing to the queue fails after the commit, your data stays committed, and db.Transaction reports the error rather than returning it, as described in work after the commit.
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, such as in a command that you run by hand and want to watch finish, call queue.DispatchSync:
1err := queue.DispatchSync(r, jobs.ProcessPodcast{PodcastID: podcast.ID})1err := queue.DispatchSync(r, jobs.ProcessPodcast{PodcastID: podcast.ID})
The job runs through its normal lifecycle, including its middleware, and DispatchSync returns any error from Handle. Unlike Dispatch, it runs 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, such as one for each of a podcast's subscribers, pass them, or a typed slice of them, to queue.Bulk. Laravel sends them in as few backend requests as possible rather than pushing each job individually:
1subscriberIDs, err := db.Table("subscribers").2 WhereEq("podcast_id", podcast.ID).3 Pluck[int64](r, "id")4if err != nil {5 return web.Fail(err)6}78notify := make([]jobs.NotifySubscriber, len(subscriberIDs))9for i, id := range subscriberIDs {10 notify[i] = jobs.NotifySubscriber{PodcastID: podcast.ID, SubscriberID: id}11}1213if _, err := queue.OnQueue("notifications").Bulk(r, notify); err != nil {14 return web.Fail(err)15}1subscriberIDs, err := db.Table("subscribers").2 WhereEq("podcast_id", podcast.ID).3 Pluck[int64](r, "id")4if err != nil {5 return web.Fail(err)6}78notify := make([]jobs.NotifySubscriber, len(subscriberIDs))9for i, id := range subscriberIDs {10 notify[i] = jobs.NotifySubscriber{PodcastID: podcast.ID, SubscriberID: id}11}1213if _, err := queue.OnQueue("notifications").Bulk(r, notify); err != nil {14 return web.Fail(err)15}
Bulk returns the jobs' IDs in order. If pushing fails partway through, earlier jobs 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. Set the DebounceFor option and add a DebounceID method to group dispatches that should supersede each other:
1type UpdateSearchIndex struct {2 PostID int643}45func (UpdateSearchIndex) JobOptions() queue.Options {6 return queue.Options{DebounceFor: 30 * time.Second}7}89func (j UpdateSearchIndex) DebounceID() string {10 return strconv.FormatInt(j.PostID, 10)11}1213func (j UpdateSearchIndex) Handle(ctx context.Context) error {14 // Update the post's search index...1516 return nil17}1type UpdateSearchIndex struct {2 PostID int643}45func (UpdateSearchIndex) JobOptions() queue.Options {6 return queue.Options{DebounceFor: 30 * time.Second}7}89func (j UpdateSearchIndex) DebounceID() string {10 return strconv.FormatInt(j.PostID, 10)11}1213func (j UpdateSearchIndex) Handle(ctx context.Context) error {14 // Update the post's search index...1516 return nil17}
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. Without a DebounceID method, every dispatch of that job type supersedes earlier ones.
If edits arrive continuously, each dispatch would reset the window indefinitely. To cap the total delay, set MaxWait. Once the oldest pending dispatch reaches that age, the next dispatch runs immediately:
1return queue.Options{DebounceFor: 30 * time.Second, MaxWait: 2 * time.Minute}1return queue.Options{DebounceFor: 30 * time.Second, MaxWait: 2 * time.Minute}
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 doesn't debounce dispatches.
Retries and timeouts
By default, a job that returns an error or panics is attempted once and not retried. A job that calls another service may succeed on a second try, so you may configure retries, backoff delays, and execution timeouts in a JobOptions method:
1func (ProcessPodcast) JobOptions() queue.Options {2 return queue.Options{3 Queue: "podcasts",4 Tries: 3,5 Backoff: []time.Duration{10 * time.Second, time.Minute},6 Timeout: 2 * time.Minute,7 }8}1func (ProcessPodcast) JobOptions() queue.Options {2 return queue.Options{3 Queue: "podcasts",4 Tries: 3,5 Backoff: []time.Duration{10 * time.Second, time.Minute},6 Timeout: 2 * time.Minute,7 }8}
With these options, a failing job waits 10 seconds before its second attempt and one minute before its third before failing permanently. Each entry in Backoff sets the wait before the corresponding retry, and the final duration repeats for any later retries.
| Option | Description | Default |
|---|---|---|
Queue |
Default queue when the dispatch doesn't call OnQueue |
The connection's default queue |
Tries |
Maximum number of attempts, including releases | 1 |
Backoff |
Wait before each retry | No delay |
Timeout |
Maximum duration for a single attempt | 60 seconds |
RetryFor |
Time window after dispatch during which the job may be retried, replacing Tries |
No limit |
MaxErrors |
Maximum failed attempts before stopping retries | Governed by Tries |
DebounceFor, MaxWait |
Deduplication window for debounced jobs | Not debounced |
FailWhenMissingModels |
Fails the job when a model row is missing | Deletes the job |
The worker calls JobOptions on the job it reads from the queue, so updating the method applies to jobs already sitting on the queue once you deploy the new code. Because the method receives the job, it may also return options from the job's fields, such as a Tries that the dispatching code chose.
When a job exceeds its Timeout, the worker ends the attempt's ctx and fails the attempt with a *queue.TimeoutError. Go can't stop a goroutine from outside, so pass ctx to the queries and requests your job makes, and they stop when the context ends.
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, calls its Failed method, and reports the error, which logs it and passes it to your error reporting. A job with a RetryFor 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 RetryFor with MaxErrors, so the job can keep releasing within the time window while failing permanently after a set number of errors:
1func (SyncContacts) JobOptions() queue.Options {2 return queue.Options{RetryFor: time.Hour, MaxErrors: 3}3}1func (SyncContacts) JobOptions() queue.Options {2 return queue.Options{RetryFor: time.Hour, MaxErrors: 3}3}
Workers track error counts in your default cache store, so use a shared store such as database or redis.
Inside a job
A job may call queue.AttemptOf(ctx) to inspect the current execution. Number() returns the attempt count, starting at 1, and ID() returns the job's JobID:
1func (j ProcessPodcast) Handle(ctx context.Context) error {2 attempt := queue.AttemptOf(ctx)3 slog.InfoContext(ctx, "processing podcast", "id", attempt.ID(), "run", attempt.Number())45 // ...67 return nil8}1func (j ProcessPodcast) Handle(ctx context.Context) error {2 attempt := queue.AttemptOf(ctx)3 slog.InfoContext(ctx, "processing podcast", "id", attempt.ID(), "run", attempt.Number())45 // ...67 return nil8}
You may also inspect the current job's name, connection, and queue with Name(), Connection(), and Queue().
Releasing, deleting, and failing
A job may also control its own lifecycle by returning one of the queue's errors from Handle. For example, this job deletes itself if its podcast was deleted, and releases itself back onto the queue if the audio upload is still in progress:
1func (ProcessPodcast) JobOptions() queue.Options {2 return queue.Options{RetryFor: time.Hour}3}45func (j ProcessPodcast) Handle(ctx context.Context) error {6 podcast, err := model.Find[models.Podcast](ctx, j.PodcastID)7 switch {8 case errors.Is(err, sql.ErrNoRows):9 return queue.Delete()10 case err != nil:11 return err12 case !podcast.Uploaded:13 return queue.Release(30 * time.Second)14 }1516 // Process the uploaded podcast...1718 return nil19}1func (ProcessPodcast) JobOptions() queue.Options {2 return queue.Options{RetryFor: time.Hour}3}45func (j ProcessPodcast) Handle(ctx context.Context) error {6 podcast, err := model.Find[models.Podcast](ctx, j.PodcastID)7 switch {8 case errors.Is(err, sql.ErrNoRows):9 return queue.Delete()10 case err != nil:11 return err12 case !podcast.Uploaded:13 return queue.Release(30 * time.Second)14 }1516 // Process the uploaded podcast...1718 return nil19}
queue.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 useRetryForinstead, as shown in Limiting errors.queue.Delete()removes the job from the queue without retrying it.queue.Fail(err)fails the job permanently witherr, without further retries.
Any other error fails the attempt, and the worker retries the job if its options allow. The one exception is a rate limit's *rate.TooManyAttemptsError: returning it releases the job back onto the queue until the rate limit allows it to run, and fails the job permanently if that wait would run past its RetryFor.
Handling failures
When a job fails permanently, you may want to notify the user or clean up partial work. Add a Failed method alongside Handle, and the worker calls it with the error that failed the job. For example, this method records the error on the podcast, so your application can show the podcast's owner what went wrong:
1func (j ProcessPodcast) Failed(ctx context.Context, err error) error {2 _, updateErr := db.Table("podcasts").3 WhereEq("id", j.PodcastID).4 Update(ctx, db.Values{"failure": err.Error()})56 return updateErr7}1func (j ProcessPodcast) Failed(ctx context.Context, err error) error {2 _, updateErr := db.Table("podcasts").3 WhereEq("id", j.PodcastID).4 Update(ctx, db.Values{"failure": err.Error()})56 return updateErr7}
Failed receives a fresh copy of the job decoded from the stored payload, with any model fields read again, so changes Handle made to its own copy are not carried over. The worker logs any error that Failed returns.
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
A job middleware is a queue.Middleware: a function that receives the attempt's ctx and a next function representing the rest of the job. For example, this middleware rate limits mail jobs to 14 per second across all workers. When a job is over the limit, rate.Attempt returns a *rate.TooManyAttemptsError, and the worker releases the job back onto the queue until capacity is available:
1// jobs/middleware.go2package jobs34import (5 "context"67 "go.laravel.com/rate"8)910func MailRateLimit(ctx context.Context, next func(ctx context.Context) error) error {11 if _, err := rate.Attempt(ctx, "mail", rate.PerSecond(14)); err != nil {12 return err13 }1415 return next(ctx)16}1// jobs/middleware.go2package jobs34import (5 "context"67 "go.laravel.com/rate"8)910func MailRateLimit(ctx context.Context, next func(ctx context.Context) error) error {11 if _, err := rate.Attempt(ctx, "mail", rate.PerSecond(14)); err != nil {12 return err13 }1415 return next(ctx)16}
next(ctx) runs the rest of the job and returns its error, allowing your middleware to run code before and after Handle, or skip it altogether. The middleware's ctx is the job's, so it may call queue.AttemptOf(ctx) and return queue.Release, queue.Delete, or queue.Fail as Handle would.
To pass data from the job into a middleware, such as a user ID, write a function that takes the data and returns a queue.Middleware. You then call it with the job's fields when assigning the middleware to a job, such as SkipUnverifiedUsers(j.UserID). For example, this middleware deletes the job when the user hasn't verified their email address:
1func SkipUnverifiedUsers(userID int64) queue.Middleware {2 return func(ctx context.Context, next func(ctx context.Context) error) error {3 user, err := model.Find[models.User](ctx, userID)4 switch {5 case errors.Is(err, sql.ErrNoRows):6 return queue.Delete()7 case err != nil:8 return err9 case user.EmailVerifiedAt == nil:10 return queue.Delete()11 }1213 return next(ctx)14 }15}1func SkipUnverifiedUsers(userID int64) queue.Middleware {2 return func(ctx context.Context, next func(ctx context.Context) error) error {3 user, err := model.Find[models.User](ctx, userID)4 switch {5 case errors.Is(err, sql.ErrNoRows):6 return queue.Delete()7 case err != nil:8 return err9 case user.EmailVerifiedAt == nil:10 return queue.Delete()11 }1213 return next(ctx)14 }15}
Middleware may 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:
1func ReleaseOnError(ctx context.Context, next func(ctx context.Context) error) error {2 if err := next(ctx); err != nil {3 slog.WarnContext(ctx, "releasing the job after an error", "error", err)45 return queue.Release(time.Minute)6 }78 return nil9}1func ReleaseOnError(ctx context.Context, next func(ctx context.Context) error) error {2 if err := next(ctx); err != nil {3 slog.WarnContext(ctx, "releasing the job after an error", "error", err)45 return queue.Release(time.Minute)6 }78 return nil9}
Assigning middleware to jobs
To attach middleware to a job, add a Middleware method that returns them. The worker calls the method on the job it read from the queue, so the method may pass the job's fields to the middleware:
1type SendNewsletter struct {2 UserID int643 RetryErrors bool4}56func (j SendNewsletter) JobOptions() queue.Options {7 return queue.Options{RetryFor: time.Hour}8}910func (j SendNewsletter) Middleware() []queue.Middleware {11 return []queue.Middleware{SkipUnverifiedUsers(j.UserID), MailRateLimit}12}1314func (j SendNewsletter) Handle(ctx context.Context) error {15 // Send the newsletter...1617 return nil18}1type SendNewsletter struct {2 UserID int643 RetryErrors bool4}56func (j SendNewsletter) JobOptions() queue.Options {7 return queue.Options{RetryFor: time.Hour}8}910func (j SendNewsletter) Middleware() []queue.Middleware {11 return []queue.Middleware{SkipUnverifiedUsers(j.UserID), MailRateLimit}12}1314func (j SendNewsletter) Handle(ctx context.Context) error {15 // Send the newsletter...1617 return nil18}
Job middleware runs in the order listed, so here SkipUnverifiedUsers runs first, wrapping MailRateLimit, which wraps Handle.
Because Middleware returns a slice, you may build the list as you would any other slice. To apply a middleware only when a condition is met, append it in an if:
1func (j SendNewsletter) Middleware() []queue.Middleware {2 middleware := []queue.Middleware{SkipUnverifiedUsers(j.UserID)}3 if j.RetryErrors {4 middleware = append(middleware, ReleaseOnError)5 }67 return middleware8}1func (j SendNewsletter) Middleware() []queue.Middleware {2 middleware := []queue.Middleware{SkipUnverifiedUsers(j.UserID)}3 if j.RetryErrors {4 middleware = append(middleware, ReleaseOnError)5 }67 return middleware8}
To share a set of middleware across multiple jobs, return it from a function of your own and call that function from each job's Middleware method:
1func Mail() []queue.Middleware {2 return []queue.Middleware{MailRateLimit, ReleaseOnError}3}45func (j SendNewsletter) Middleware() []queue.Middleware {6 return Mail()7}1func Mail() []queue.Middleware {2 return []queue.Middleware{MailRateLimit, ReleaseOnError}3}45func (j SendNewsletter) Middleware() []queue.Middleware {6 return Mail()7}
A job's Timeout applies to its middleware and Handle together. Middleware runs wherever the job executes, including on the sync connection, with DispatchSync, and in test attempts.
Job chains
Job chaining lets you specify a sequence of jobs that run one after another. For example, before a podcast goes live, your application processes its audio, then optimizes it, then releases the podcast. Each job is dispatched only after the previous job succeeds; if any job fails, the remaining jobs in the chain won't run. Pass the jobs to queue.NewChain in order and dispatch the chain:
1func Publish(r *web.Request) *web.Response {2 podcast, err := model.FromRoute[models.Podcast](r, "podcast")3 if err != nil {4 return web.Fail(err)5 }67 _, err = queue.NewChain(8 jobs.ProcessPodcast{PodcastID: podcast.ID},9 jobs.OptimizePodcast{PodcastID: podcast.ID},10 jobs.ReleasePodcast{PodcastID: podcast.ID},11 ).Dispatch(r)12 if err != nil {13 return web.Fail(err)14 }1516 return web.Back()17}1func Publish(r *web.Request) *web.Response {2 podcast, err := model.FromRoute[models.Podcast](r, "podcast")3 if err != nil {4 return web.Fail(err)5 }67 _, err = queue.NewChain(8 jobs.ProcessPodcast{PodcastID: podcast.ID},9 jobs.OptimizePodcast{PodcastID: podcast.ID},10 jobs.ReleasePodcast{PodcastID: podcast.ID},11 ).Dispatch(r)12 if err != nil {13 return web.Fail(err)14 }1516 return web.Back()17}
When you only know a chain's jobs at runtime, you may append more jobs with the chain's Then method, which returns a copy of the chain with the jobs added at its end. For example, this handler adds a transcript step only when the podcast hasn't been transcribed:
1chain := queue.NewChain(jobs.ProcessPodcast{PodcastID: podcast.ID})2if !podcast.Transcribed {3 chain = chain.Then(jobs.TranscribePodcast{PodcastID: podcast.ID})4}56_, err := chain.Then(jobs.ReleasePodcast{PodcastID: podcast.ID}).Dispatch(r)1chain := queue.NewChain(jobs.ProcessPodcast{PodcastID: podcast.ID})2if !podcast.Transcribed {3 chain = chain.Then(jobs.TranscribePodcast{PodcastID: podcast.ID})4}56_, err := chain.Then(jobs.ReleasePodcast{PodcastID: podcast.ID}).Dispatch(r)
Each job keeps its configured options, so it's 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 the jobs after it.
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, chain OnConnection, OnQueue, Delay, or DelayUntil before Dispatch. A Delay delays the first job in the chain:
1_, err := queue.NewChain(2 jobs.ProcessPodcast{PodcastID: podcast.ID},3 jobs.OptimizePodcast{PodcastID: podcast.ID},4).5 OnConnection("redis").6 OnQueue("podcasts").7 Dispatch(r)1_, err := queue.NewChain(2 jobs.ProcessPodcast{PodcastID: podcast.ID},3 jobs.OptimizePodcast{PodcastID: podcast.ID},4).5 OnConnection("redis").6 OnQueue("podcasts").7 Dispatch(r)
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 may add more jobs to its active chain through its attempt. PrependToChain inserts one or more jobs to run immediately next, while AppendToChain adds them to the end of the chain:
1func (j ProcessPodcast) Handle(ctx context.Context) error {2 // ...34 attempt := queue.AttemptOf(ctx)56 // Run next...7 attempt.PrependToChain(TranscribePodcast{PodcastID: j.PodcastID})89 // Run at the end of the chain...10 attempt.AppendToChain(11 NotifyHosts{PodcastID: j.PodcastID},12 UpdatePodcastFeed{PodcastID: j.PodcastID},13 )1415 return nil16}1func (j ProcessPodcast) Handle(ctx context.Context) error {2 // ...34 attempt := queue.AttemptOf(ctx)56 // Run next...7 attempt.PrependToChain(TranscribePodcast{PodcastID: j.PodcastID})89 // Run at the end of the chain...10 attempt.AppendToChain(11 NotifyHosts{PodcastID: j.PodcastID},12 UpdatePodcastFeed{PodcastID: j.PodcastID},13 )1415 return nil16}
When you pass several jobs to PrependToChain, 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 don't run. To react to a chain failure, pass a callback to the chain's Catch:
1_, err := queue.NewChain(2 jobs.ProcessPodcast{PodcastID: podcast.ID},3 jobs.OptimizePodcast{PodcastID: podcast.ID},4).5 Catch(jobs.PodcastFailed{PodcastID: podcast.ID}).6 Dispatch(r)1_, err := queue.NewChain(2 jobs.ProcessPodcast{PodcastID: podcast.ID},3 jobs.OptimizePodcast{PodcastID: podcast.ID},4).5 Catch(jobs.PodcastFailed{PodcastID: podcast.ID}).6 Dispatch(r)
Like a job, a callback is a struct that Laravel stores alongside the chain until the worker needs it, so list each callback in jobs.All with your jobs. Give it a Catch method that receives the failing error:
1// jobs/podcast_failed.go2package jobs34import (5 "context"67 "go.laravel.com/db"8)910type PodcastFailed struct {11 PodcastID int6412}1314func (c PodcastFailed) Catch(ctx context.Context, err error) error {15 _, updateErr := db.Table("podcasts").16 WhereEq("id", c.PodcastID).17 Update(ctx, db.Values{"failure": err.Error()})1819 return updateErr20}1// jobs/podcast_failed.go2package jobs34import (5 "context"67 "go.laravel.com/db"8)910type PodcastFailed struct {11 PodcastID int6412}1314func (c PodcastFailed) Catch(ctx context.Context, err error) error {15 _, updateErr := db.Table("podcasts").16 WhereEq("id", c.PodcastID).17 Update(ctx, db.Values{"failure": err.Error()})1819 return updateErr20}
The worker calls Catch immediately, before running the failed job's Failed method. Because callbacks run inline rather than as queued jobs, they aren't retried, and the worker logs any error they return. If one of a callback's model rows has been deleted, the worker skips the callback, unless its JobOptions method sets FailWhenMissingModels to log a *queue.MissingModelsError 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 may 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.NewBatch and dispatch the batch. Here, ImportCsv is a job that imports a range of rows:
1func Start(r *web.Request) *web.Response {2 importID, err := r.PathInt("import")3 if err != nil {4 return web.Fail(err)5 }67 batchID, err := queue.NewBatch(8 jobs.ImportCsv{ImportID: importID, From: 1, To: 100},9 jobs.ImportCsv{ImportID: importID, From: 101, To: 200},10 jobs.ImportCsv{ImportID: importID, From: 201, To: 300},11 ).12 Name("Import CSV").13 Then(jobs.ImportFinished{ImportID: importID}).14 Catch(jobs.ImportFinished{ImportID: importID}).15 Dispatch(r)16 if err != nil {17 return web.Fail(err)18 }1920 return web.Redirect(fmt.Sprintf("/imports/%d/batches/%s", importID, batchID))21}1func Start(r *web.Request) *web.Response {2 importID, err := r.PathInt("import")3 if err != nil {4 return web.Fail(err)5 }67 batchID, err := queue.NewBatch(8 jobs.ImportCsv{ImportID: importID, From: 1, To: 100},9 jobs.ImportCsv{ImportID: importID, From: 101, To: 200},10 jobs.ImportCsv{ImportID: importID, From: 201, To: 300},11 ).12 Name("Import CSV").13 Then(jobs.ImportFinished{ImportID: importID}).14 Catch(jobs.ImportFinished{ImportID: importID}).15 Dispatch(r)16 if err != nil {17 return web.Fail(err)18 }1920 return web.Redirect(fmt.Sprintf("/imports/%d/batches/%s", importID, batchID))21}
Dispatch stores the batch, dispatches every job, and returns the batch's queue.BatchID, which you may use to inspect its progress. Jobs in a batch may finish in any order. To route or delay every job in the batch, chain OnConnection, OnQueue, Delay, or DelayUntil before Dispatch, as in queue.NewBatch(...).OnQueue("imports").Dispatch(r).
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 with queue.CreateTables(ctx) alongside the jobs table, so run your migrations before dispatching your first batch.
Batch records are stored on your default database connection whichever queue driver runs the jobs.
Batch callbacks
You may register callbacks for three points in a batch's lifecycle. Like a chain's callbacks, they're structs listed in jobs.All, and the worker calls the method with the same name as the point:
| Method | Called when |
|---|---|
Then(ctx context.Context) error |
Every job in the batch succeeds |
Catch(ctx context.Context, |
The first job in the batch fails permanently |
Finally(ctx context.Context) error |
Every job has finished, whether it succeeded, failed, or was skipped |
For example, this callback marks the import complete or records the failure reason:
1// jobs/import_finished.go2package jobs34import (5 "context"67 "go.laravel.com/db"8)910type ImportFinished struct {11 ImportID int6412}1314func (c ImportFinished) Then(ctx context.Context) error {15 _, err := db.Table("imports").16 WhereEq("id", c.ImportID).17 Update(ctx, db.Values{"completed": true})1819 return err20}2122func (c ImportFinished) Catch(ctx context.Context, err error) error {23 _, updateErr := db.Table("imports").24 WhereEq("id", c.ImportID).25 Update(ctx, db.Values{"failure": err.Error()})2627 return updateErr28}1// jobs/import_finished.go2package jobs34import (5 "context"67 "go.laravel.com/db"8)910type ImportFinished struct {11 ImportID int6412}1314func (c ImportFinished) Then(ctx context.Context) error {15 _, err := db.Table("imports").16 WhereEq("id", c.ImportID).17 Update(ctx, db.Values{"completed": true})1819 return err20}2122func (c ImportFinished) Catch(ctx context.Context, err error) error {23 _, updateErr := db.Table("imports").24 WhereEq("id", c.ImportID).25 Update(ctx, db.Values{"failure": err.Error()})2627 return updateErr28}
When a callback needs the batch's job counts, such as to log how many jobs failed, its method may also take a *queue.Batch after ctx. The batch reflects its state at the moment the callback runs:
1func (c ImportFinished) Finally(ctx context.Context, batch *queue.Batch) error {2 slog.InfoContext(ctx, "import finished",3 "import", c.ImportID,4 "jobs", batch.TotalJobs,5 "failed", batch.FailedJobs,6 )78 return nil9}1func (c ImportFinished) Finally(ctx context.Context, batch *queue.Batch) error {2 slog.InfoContext(ctx, "import finished",3 "import", c.ImportID,4 "jobs", batch.TotalJobs,5 "failed", batch.FailedJobs,6 )78 return nil9}
A chain's callback has no batch, so a Catch method that takes a *queue.Batch receives nil there. You may call Then, Catch, and Finally more than once to register additional callbacks.
Chains and batches
A batch may contain job chains. Each chain runs its jobs one after another while running in parallel with the other items in the batch:
1_, err := queue.NewBatch(2 queue.NewChain(jobs.ReleasePodcast{PodcastID: 1}, jobs.SendReleaseNotification{PodcastID: 1}),3 queue.NewChain(jobs.ReleasePodcast{PodcastID: 2}, jobs.SendReleaseNotification{PodcastID: 2}),4).Then(jobs.ReleaseFinished{}).Dispatch(r)1_, err := queue.NewBatch(2 queue.NewChain(jobs.ReleasePodcast{PodcastID: 1}, jobs.SendReleaseNotification{PodcastID: 1}),3 queue.NewChain(jobs.ReleasePodcast{PodcastID: 2}, jobs.SendReleaseNotification{PodcastID: 2}),4).Then(jobs.ReleaseFinished{}).Dispatch(r)
A batch may also be a step inside a chain. The chain advances once every job in the batch finishes:
1_, err := queue.NewChain(2 jobs.FlushPodcastCache{},3 queue.NewBatch(jobs.ReleasePodcast{PodcastID: 1}, jobs.ReleasePodcast{PodcastID: 2}),4 queue.NewBatch(5 jobs.SendReleaseNotification{PodcastID: 1},6 jobs.SendReleaseNotification{PodcastID: 2},7 ),8).Dispatch(r)1_, err := queue.NewChain(2 jobs.FlushPodcastCache{},3 queue.NewBatch(jobs.ReleasePodcast{PodcastID: 1}, jobs.ReleasePodcast{PodcastID: 2}),4 queue.NewBatch(5 jobs.SendReleaseNotification{PodcastID: 1},6 jobs.SendReleaseNotification{PodcastID: 2},7 ),8).Dispatch(r)
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 may add more jobs to its batch through its attempt. For a large import, your handler may dispatch a batch with a single starter job that splits the file in the background, rather than building thousands of jobs during the HTTP request:
1// jobs/split_import.go2package jobs34import (5 "context"67 "go.laravel.com/db"8 "go.laravel.com/queue"9)1011type SplitImport struct {12 ImportID int6413}1415func (j SplitImport) Handle(ctx context.Context) error {16 total, err := db.Table("imports").WhereEq("id", j.ImportID).Value[int64](ctx, "total_rows")17 if err != nil {18 return err19 }2021 attempt := queue.AttemptOf(ctx)22 for from := int64(1); from <= total; from += 100 {23 attempt.AddToBatch(ImportCsv{ImportID: j.ImportID, From: from, To: from + 99})24 }2526 return nil27}1// jobs/split_import.go2package jobs34import (5 "context"67 "go.laravel.com/db"8 "go.laravel.com/queue"9)1011type SplitImport struct {12 ImportID int6413}1415func (j SplitImport) Handle(ctx context.Context) error {16 total, err := db.Table("imports").WhereEq("id", j.ImportID).Value[int64](ctx, "total_rows")17 if err != nil {18 return err19 }2021 attempt := queue.AttemptOf(ctx)22 for from := int64(1); from <= total; from += 100 {23 attempt.AddToBatch(ImportCsv{ImportID: j.ImportID, From: from, To: from + 99})24 }2526 return nil27}
The batch remains open until all added jobs finish as well. To cancel the batch from within a job, call attempt.CancelBatch(); workers skip any remaining pending jobs, and the batch's Then callbacks won't run. Outside a job, cancel a batch with queue.CancelBatch(ctx, batchID).
Inspecting batches
Use queue.FindBatch to look up a batch by ID and report its progress, such as on the import's page. It reports false if no matching batch exists:
1func Show(r *web.Request) *web.Response {2 batch, ok, err := queue.FindBatch(r, queue.BatchID(r.PathValue("batch")))3 switch {4 case err != nil:5 return web.Fail(err)6 case !ok:7 return web.Abort(http.StatusNotFound)8 }910 return web.JSON(batch)11}1func Show(r *web.Request) *web.Response {2 batch, ok, err := queue.FindBatch(r, queue.BatchID(r.PathValue("batch")))3 switch {4 case err != nil:5 return web.Fail(err)6 case !ok:7 return web.Abort(http.StatusNotFound)8 }910 return web.JSON(batch)11}
A *queue.Batch encodes as JSON with processed_jobs and progress alongside its fields, so you may return it directly to a page that polls for a progress bar. It holds TotalJobs, PendingJobs, and FailedJobs, and provides Progress() as a percentage from 0 to 100, along with Finished() and Cancelled().
Batch failures
By default, when any job in a batch fails permanently, Laravel cancels the batch, calls its Catch callbacks, and skips the remaining jobs. To keep processing the remaining jobs even if some fail, such as an import that should keep every row that imports cleanly, call AllowFailures:
1_, err := queue.NewBatch(importJobs).2 AllowFailures().3 Catch(jobs.ImportFinished{ImportID: importID}).4 Dispatch(r)1_, err := queue.NewBatch(importJobs).2 AllowFailures().3 Catch(jobs.ImportFinished{ImportID: importID}).4 Dispatch(r)
With AllowFailures, Catch callbacks run on the first failure, while Then callbacks run only after every failed job has been retried and succeeded. You may retry all failed jobs in a batch with queue:retry-batch. Batches without AllowFailures are cancelled on their first failure and can't be retried this way:
1laravel queue:retry-batch 01a1cd68-56b9-78a0-97cb-35ffb6a41b051laravel queue:retry-batch 01a1cd68-56b9-78a0-97cb-35ffb6a41b05
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 commands/schedule.go:
1func Schedule(ctx context.Context, s *schedule.Schedule) {2 s.Command("queue:prune-batches --hours=48").Daily()3}1func Schedule(ctx context.Context, s *schedule.Schedule) {2 s.Command("queue:prune-batches --hours=48").Daily()3}
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 keep running the code they started with until restarted. During local development, you may use npm run dev instead of managing a separate worker terminal. It starts your web server, queue worker, scheduler, and Vite dev server together, and restarts the server and worker whenever your Go 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 may 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.
Worker concurrency
To process multiple jobs concurrently within a single worker process, pass --concurrency:
1laravel queue:work --concurrency=81laravel queue:work --concurrency=8
Each job runs in a goroutine of its own, so concurrency works best for jobs that spend their time waiting on the network or the database. 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 method.
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 or Supervisor, or size worker clusters by hand. Laravel Cloud continuously monitors your queues and scales worker concurrency automatically based on queue depth, job latency, and throughput.
During traffic spikes, Laravel Cloud starts additional workers to drain backlogs before wait times build up. When your queues are idle, workers may 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 shows queue depth, throughput, and failed jobs in real time.
Restarting workers
Because workers keep running the code 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 start 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 application's queue, such as from a scheduled health check that alerts you when a queue backs up:
1sizes, ok, err := queue.From(ctx).Sizes(ctx, "database", "emails")2if err != nil {3 return err4}56if ok {7 slog.InfoContext(ctx, "emails",8 "pending", sizes.Pending,9 "running", sizes.Reserved,10 "total", sizes.Total(),11 )12}1sizes, ok, err := queue.From(ctx).Sizes(ctx, "database", "emails")2if err != nil {3 return err4}56if ok {7 slog.InfoContext(ctx, "emails",8 "pending", sizes.Pending,9 "running", sizes.Reserved,10 "total", sizes.Total(),11 )12}
Pending reports jobs ready to run, Delayed reports jobs waiting out a delay, and Reserved reports jobs currently being processed. ok is false for drivers that can't count their jobs.
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 01a1cd68-56b9-7d71-b378-e1ee2d238aa12laravel queue:retry all1laravel queue:retry 01a1cd68-56b9-7d71-b378-e1ee2d238aa12laravel 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 may schedule queue:flush to keep the table manageable:
1laravel queue:forget 01a1cd68-56b9-7d71-b378-e1ee2d238aa12laravel queue:flush --hours=481laravel queue:forget 01a1cd68-56b9-7d71-b378-e1ee2d238aa12laravel queue:flush --hours=48
To delete all pending jobs from a queue, such as emails queued by mistake, run queue:clear:
1laravel queue:clear database --queue=emails1laravel queue:clear database --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 commands against your server.
Events
Workers dispatch events as they process jobs, so you may record how long jobs take or report failed jobs to a service of your own. Both queue.JobProcessed and queue.JobFailed have a Job field of type queue.JobInfo describing the job: its ID, Name, Connection, Queue, and Attempt number, starting at 1.
JobProcessed fires after every attempt with Duration and Outcome, which is one of queue.Succeeded, queue.Released, queue.Deleted, queue.Debounced, queue.MissingModels, queue.Retrying, or queue.Failed. A job the worker deleted because a model's row was deleted reports queue.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:
1// listeners/warn_about_slow_jobs.go2package listeners34import (5 "context"6 "log/slog"7 "time"89 "go.laravel.com/queue"10)1112func WarnAboutSlowJobs(ctx context.Context, e queue.JobProcessed) error {13 if e.Duration > 30*time.Second {14 slog.WarnContext(ctx, "slow job",15 "job", e.Job.Name,16 "queue", e.Job.Queue,17 "duration", e.Duration,18 )19 }2021 return nil22}1// listeners/warn_about_slow_jobs.go2package listeners34import (5 "context"6 "log/slog"7 "time"89 "go.laravel.com/queue"10)1112func WarnAboutSlowJobs(ctx context.Context, e queue.JobProcessed) error {13 if e.Duration > 30*time.Second {14 slog.WarnContext(ctx, "slow job",15 "job", e.Job.Name,16 "queue", e.Job.Queue,17 "duration", e.Duration,18 )19 }2021 return nil22}
Register the listener in listeners.All with laravel.Listen(WarnAboutSlowJobs). Nothing waits for these listeners, so the worker logs any error they return.
JobFailed fires once a job fails permanently, after its Failed method has run. Because the worker already logs failed jobs, listen for JobFailed when you want custom alerting or metrics. Along with Job, it provides Err, which you may inspect with errors.AsType or errors.Is:
1func NotifyOnJobFailure(ctx context.Context, e queue.JobFailed) error {2 reason := "failed"3 if _, ok := errors.AsType[*queue.TimeoutError](e.Err); ok {4 reason = "timed out"5 } else if _, ok := errors.AsType[*queue.MissingModelsError](e.Err); ok {6 reason = "lost its models"7 }89 slog.ErrorContext(ctx, "job "+reason,10 "id", e.Job.ID,11 "job", e.Job.Name,12 "queue", e.Job.Queue,13 "attempt", e.Job.Attempt,14 "error", e.Err,15 )1617 return nil18}1func NotifyOnJobFailure(ctx context.Context, e queue.JobFailed) error {2 reason := "failed"3 if _, ok := errors.AsType[*queue.TimeoutError](e.Err); ok {4 reason = "timed out"5 } else if _, ok := errors.AsType[*queue.MissingModelsError](e.Err); ok {6 reason = "lost its models"7 }89 slog.ErrorContext(ctx, "job "+reason,10 "id", e.Job.ID,11 "job", e.Job.Name,12 "queue", e.Job.Queue,13 "attempt", e.Job.Attempt,14 "error", e.Err,15 )1617 return nil18}
Common error types you may match on Err include:
| Error type | Cause |
|---|---|
*queue.TimeoutError |
The attempt exceeded the job's configured Timeout |
*queue.MissingModelsError |
A model field's database row was deleted before a job with FailWhenMissingModels ran |
*queue.PanicError |
The job panicked |
*rate.TooManyAttemptsError |
A rate-limited job couldn't run before its RetryFor window expired |
| Application errors | Any error returned from Handle or passed to queue.Fail(err) |
The sync connection and DispatchSync don't dispatch these events.
Writing a driver
Packages may support additional queue backends, such as Cloudflare Queues, by adding a custom driver. Implement queue.Driver to push, reserve, and clear jobs, and queue.Reserved to manage each reserved job's lease and completion. Laravel's worker handles retries, timeouts, and failed job recording, renewing active reservations every queue.Heartbeat against a queue.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:
1// cloudflare/driver.go2package cloudflare34import (5 "context"6 "fmt"7 "time"89 "go.laravel.com/httpclient"10 "go.laravel.com/queue"11)1213type Driver struct {14 accountID string15 token string16 http *httpclient.Client17}1819func New(accountID, token string) *Driver {20 return &Driver{accountID: accountID, token: token, http: httpclient.New(httpclient.Options{})}21}2223func (d *Driver) queueAPI(queue string) *httpclient.Client {24 endpoint := fmt.Sprintf(25 "https://api.cloudflare.com/client/v4/accounts/%s/queues/%s",26 d.accountID,27 queue,28 )2930 return d.http.31 BaseURL(endpoint).32 Token(d.token).33 AcceptJSON().34 EnsureSuccessful()35}3637type pullResult struct {38 Result struct {39 Messages []struct {40 Body string `json:"body"`41 Attempts int `json:"attempts"`42 LeaseID string `json:"lease_id"`43 } `json:"messages"`44 } `json:"result"`45}4647type ackResult struct {48 Result struct {49 AckCount int `json:"ackCount"`50 RetryCount int `json:"retryCount"`51 } `json:"result"`52}5354func (d *Driver) Push(ctx context.Context, queue string, payload []byte, delay time.Duration) error {55 _, err := d.queueAPI(queue).56 JSON(map[string]any{57 "body": string(payload),58 "content_type": "text",59 "delay_seconds": int(delay.Seconds()),60 }).61 Post(ctx, "/messages")6263 return err64}6566func (d *Driver) Reserve(ctx context.Context, queues []string) (queue.Reserved, error) {67 for _, name := range queues {68 res, err := d.queueAPI(name).69 JSON(map[string]any{70 "batch_size": 1,71 "visibility_timeout_ms": queue.Lease.Milliseconds(),72 }).73 Post(ctx, "/messages/pull")74 if err != nil {75 return nil, err76 }7778 pulled, err := res.JSON[pullResult]()79 if err != nil {80 return nil, err81 }8283 if len(pulled.Result.Messages) > 0 {84 message := pulled.Result.Messages[0]8586 return &Job{87 driver: d,88 queue: name,89 payload: []byte(message.Body),90 attempts: message.Attempts,91 leaseID: message.LeaseID,92 }, nil93 }94 }9596 return nil, nil97}9899func (d *Driver) Clear(ctx context.Context, queue string) (int64, error) {100 _, err := d.queueAPI(queue).101 JSON(map[string]any{"delete_messages_permanently": true}).102 Post(ctx, "/purge")103104 return 0, err105}106107type Job struct {108 driver *Driver109 queue string110 payload []byte111 attempts int112 leaseID string113}114115func (j *Job) Queue() string { return j.queue }116func (j *Job) Payload() []byte { return j.payload }117func (j *Job) Attempts() int { return j.attempts }118119func (j *Job) Renew(ctx context.Context) (bool, error) {120 // Cloudflare Queues sets the visibility window on pull rather than renewing per lease...121 return true, nil122}123124func (j *Job) Delete(ctx context.Context) (bool, error) {125 acked, err := j.ack(ctx, map[string]any{126 "acks": []map[string]any{{"lease_id": j.leaseID}},127 })128129 return acked.Result.AckCount > 0, err130}131132func (j *Job) Release(ctx context.Context, delay time.Duration) (bool, error) {133 acked, err := j.ack(ctx, map[string]any{134 "retries": []map[string]any{{135 "lease_id": j.leaseID,136 "delay_seconds": int(delay.Seconds()),137 }},138 })139140 return acked.Result.RetryCount > 0, err141}142143func (j *Job) ack(ctx context.Context, body map[string]any) (ackResult, error) {144 res, err := j.driver.queueAPI(j.queue).JSON(body).Post(ctx, "/messages/ack")145 if err != nil {146 return ackResult{}, err147 }148149 return res.JSON[ackResult]()150}1// cloudflare/driver.go2package cloudflare34import (5 "context"6 "fmt"7 "time"89 "go.laravel.com/httpclient"10 "go.laravel.com/queue"11)1213type Driver struct {14 accountID string15 token string16 http *httpclient.Client17}1819func New(accountID, token string) *Driver {20 return &Driver{accountID: accountID, token: token, http: httpclient.New(httpclient.Options{})}21}2223func (d *Driver) queueAPI(queue string) *httpclient.Client {24 endpoint := fmt.Sprintf(25 "https://api.cloudflare.com/client/v4/accounts/%s/queues/%s",26 d.accountID,27 queue,28 )2930 return d.http.31 BaseURL(endpoint).32 Token(d.token).33 AcceptJSON().34 EnsureSuccessful()35}3637type pullResult struct {38 Result struct {39 Messages []struct {40 Body string `json:"body"`41 Attempts int `json:"attempts"`42 LeaseID string `json:"lease_id"`43 } `json:"messages"`44 } `json:"result"`45}4647type ackResult struct {48 Result struct {49 AckCount int `json:"ackCount"`50 RetryCount int `json:"retryCount"`51 } `json:"result"`52}5354func (d *Driver) Push(ctx context.Context, queue string, payload []byte, delay time.Duration) error {55 _, err := d.queueAPI(queue).56 JSON(map[string]any{57 "body": string(payload),58 "content_type": "text",59 "delay_seconds": int(delay.Seconds()),60 }).61 Post(ctx, "/messages")6263 return err64}6566func (d *Driver) Reserve(ctx context.Context, queues []string) (queue.Reserved, error) {67 for _, name := range queues {68 res, err := d.queueAPI(name).69 JSON(map[string]any{70 "batch_size": 1,71 "visibility_timeout_ms": queue.Lease.Milliseconds(),72 }).73 Post(ctx, "/messages/pull")74 if err != nil {75 return nil, err76 }7778 pulled, err := res.JSON[pullResult]()79 if err != nil {80 return nil, err81 }8283 if len(pulled.Result.Messages) > 0 {84 message := pulled.Result.Messages[0]8586 return &Job{87 driver: d,88 queue: name,89 payload: []byte(message.Body),90 attempts: message.Attempts,91 leaseID: message.LeaseID,92 }, nil93 }94 }9596 return nil, nil97}9899func (d *Driver) Clear(ctx context.Context, queue string) (int64, error) {100 _, err := d.queueAPI(queue).101 JSON(map[string]any{"delete_messages_permanently": true}).102 Post(ctx, "/purge")103104 return 0, err105}106107type Job struct {108 driver *Driver109 queue string110 payload []byte111 attempts int112 leaseID string113}114115func (j *Job) Queue() string { return j.queue }116func (j *Job) Payload() []byte { return j.payload }117func (j *Job) Attempts() int { return j.attempts }118119func (j *Job) Renew(ctx context.Context) (bool, error) {120 // Cloudflare Queues sets the visibility window on pull rather than renewing per lease...121 return true, nil122}123124func (j *Job) Delete(ctx context.Context) (bool, error) {125 acked, err := j.ack(ctx, map[string]any{126 "acks": []map[string]any{{"lease_id": j.leaseID}},127 })128129 return acked.Result.AckCount > 0, err130}131132func (j *Job) Release(ctx context.Context, delay time.Duration) (bool, error) {133 acked, err := j.ack(ctx, map[string]any{134 "retries": []map[string]any{{135 "lease_id": j.leaseID,136 "delay_seconds": int(delay.Seconds()),137 }},138 })139140 return acked.Result.RetryCount > 0, err141}142143func (j *Job) ack(ctx context.Context, body map[string]any) (ackResult, error) {144 res, err := j.driver.queueAPI(j.queue).JSON(body).Post(ctx, "/messages/ack")145 if err != nil {146 return ackResult{}, err147 }148149 return res.JSON[ackResult]()150}
Return false from Renew, Delete, or Release if the reservation lapsed and another worker claimed the job, which tells the current worker to stop touching it. You may also implement queue.BulkPusher for batched pushes, queue.Sizer to report queue.Sizes, and queue.Failer on reserved jobs if your backend records failed jobs itself.
Add a connection that uses your driver in your options' Register function in bootstrap/app.go (or a package's Register method), reading any settings your driver expects from app.Env():
1// bootstrap/app.go2Register: func(app *laravel.Registrar) error {3 app.QueueConnection("cloudflare", queue.Connection{4 Driver: cloudflare.New(5 app.Env().String("CLOUDFLARE_ACCOUNT_ID", ""),6 app.Env().String("CLOUDFLARE_API_TOKEN", ""),7 ),8 Queue: "emails-queue-id",9 })1011 return nil12},1// bootstrap/app.go2Register: func(app *laravel.Registrar) error {3 app.QueueConnection("cloudflare", queue.Connection{4 Driver: cloudflare.New(5 app.Env().String("CLOUDFLARE_ACCOUNT_ID", ""),6 app.Env().String("CLOUDFLARE_API_TOKEN", ""),7 ),8 Queue: "emails-queue-id",9 })1011 return nil12},
Set QUEUE_CONNECTION=cloudflare to make it the default connection. A package lists its own job types with Registrar.Jobs, alongside the application's Options.Jobs.
To check that your driver keeps the contract the worker relies on, run queuetest.TestDriver against a real backend in your driver's tests:
1func TestTheDriverKeepsTheContract(t *testing.T) {2 driver := cloudflare.New(3 os.Getenv("CLOUDFLARE_ACCOUNT_ID"),4 os.Getenv("CLOUDFLARE_API_TOKEN"),5 )67 queuetest.TestDriver(t, driver)8}1func TestTheDriverKeepsTheContract(t *testing.T) {2 driver := cloudflare.New(3 os.Getenv("CLOUDFLARE_ACCOUNT_ID"),4 os.Getenv("CLOUDFLARE_API_TOKEN"),5 )67 queuetest.TestDriver(t, driver)8}
Laravel shares each connection's driver value across every dispatch and every worker goroutine for the lifetime of the application, so its methods must be safe for concurrent use. Drivers built on TCP protocols should hold a connection pool or a reconnecting client, and drivers built on the HTTP client should hold one client from httpclient.New, as the example does, which reuses its connections across requests.
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 names another connection. Unless you fake the queue, dispatched jobs execute immediately. To test against a real queue, give the test a queue connection with laraveltest.Queue.
Faking the queue
Call queuetest.New with your test's client to intercept dispatched jobs without pushing or executing them, then assert against the returned fake:
1package feature_test23import (4 "net/url"5 "testing"67 "go.laravel.com/model"8 "go.laravel.com/queuetest"910 "app/jobs"11 "app/models"12 "app/tests"13)1415func TestUploadingAPodcastQueuesItForProcessing(t *testing.T) {16 client := tests.New(t)17 queued := queuetest.New(client)1819 client.Post("/podcasts", url.Values{"title": {"Episode 1"}}).AssertRedirect("/podcasts")2021 podcast, err := model.Query[models.Podcast]().WhereEq("title", "Episode 1").First(client.Context())22 if err != nil {23 t.Fatal(err)24 }2526 queued.AssertPushed[jobs.ProcessPodcast]()27 queued.AssertPushedTimes[jobs.ProcessPodcast](1)2829 queued.AssertPushed(func(job queuetest.Job[jobs.ProcessPodcast]) bool {30 return job.Job.PodcastID == podcast.ID && job.Delay == 031 })32}1package feature_test23import (4 "net/url"5 "testing"67 "go.laravel.com/model"8 "go.laravel.com/queuetest"910 "app/jobs"11 "app/models"12 "app/tests"13)1415func TestUploadingAPodcastQueuesItForProcessing(t *testing.T) {16 client := tests.New(t)17 queued := queuetest.New(client)1819 client.Post("/podcasts", url.Values{"title": {"Episode 1"}}).AssertRedirect("/podcasts")2021 podcast, err := model.Query[models.Podcast]().WhereEq("title", "Episode 1").First(client.Context())22 if err != nil {23 t.Fatal(err)24 }2526 queued.AssertPushed[jobs.ProcessPodcast]()27 queued.AssertPushedTimes[jobs.ProcessPodcast](1)2829 queued.AssertPushed(func(job queuetest.Job[jobs.ProcessPodcast]) bool {30 return job.Job.PodcastID == podcast.ID && job.Delay == 031 })32}
The match function receives a queuetest.Job, which holds the job in Job along with its ID, Connection, Queue, and Delay. Connection reflects the connection requested at dispatch, and Delay is a time.Duration, so you may compare it directly, as in job.Delay == 10*time.Minute. You may also assert with AssertNotPushed[T](), which takes the same optional match function, and AssertNothingPushed(), and Pushed[T]() returns the recorded jobs of a type.
The fake respects database transactions and records jobs only after commit. It also stores and reads back each job as the queue would, so a job the queue can't store fails your test immediately.
To fake only specific job types, or fake everything except certain jobs, pass queuetest.Only or queuetest.Except with a value of each type. Unfaked jobs dispatch normally:
1queued := queuetest.New(client, queuetest.Only(jobs.ProcessPodcast{}))2queued := queuetest.New(client, queuetest.Except(jobs.SendInvoice{}))1queued := queuetest.New(client, queuetest.Only(jobs.ProcessPodcast{}))2queued := queuetest.New(client, queuetest.Except(jobs.SendInvoice{}))
Testing a job
To test a job's Handle method directly, execute a single attempt with client.Attempt and assert on the outcome. For example, this test verifies that the ProcessPodcast job releases itself when the upload hasn't finished:
1func TestUploadingPodcastsAreReleased(t *testing.T) {2 client := tests.New(t)34 podcast := models.Podcast{Title: "Episode 1"}5 if err := model.Create(client.Context(), &podcast); err != nil {6 t.Fatal(err)7 }89 client.Attempt(jobs.ProcessPodcast{PodcastID: podcast.ID}).10 AssertReleasedAfter(30 * time.Second)11}1func TestUploadingPodcastsAreReleased(t *testing.T) {2 client := tests.New(t)34 podcast := models.Podcast{Title: "Episode 1"}5 if err := model.Create(client.Context(), &podcast); err != nil {6 t.Fatal(err)7 }89 client.Attempt(jobs.ProcessPodcast{PodcastID: podcast.ID}).10 AssertReleasedAfter(30 * time.Second)11}
The job runs through its middleware as it would on a worker, and reaches the test application's services. To test a job that charges an invoice without charging anyone, replace the billing client with one that talks to a fake provider, as Replacing dependencies shows:
1client := tests.New(t)2services.From(client.Context()).Billing = fakeBilling34client.Attempt(jobs.ChargeInvoice{InvoiceID: 42}).AssertSucceeded()1client := tests.New(t)2services.From(client.Context()).Billing = fakeBilling34client.Attempt(jobs.ChargeInvoice{InvoiceID: 42}).AssertSucceeded()
Pass queuetest.Number(3) to simulate a specific retry count for Number(). Available outcome assertions include AssertSucceeded, AssertReleased, AssertReleasedAfter, AssertDeleted, AssertFailed, and AssertFailedWith(target), which checks the error with errors.Is. Test attempts run once without retrying or calling Failed.
Testing chains
The queue fake records each chain alongside its first job. Use AssertChained with the first job's type and a value of each chained job's type to verify the chain's order:
1queued := queuetest.New(client)23client.Post("/orders/42/ship", nil).AssertRedirect("/orders/42")45queued.AssertChained[jobs.ShipOrder](jobs.RecordShipment{}, jobs.UpdateInventory{})1queued := queuetest.New(client)23client.Post("/orders/42/ship", nil).AssertRedirect("/orders/42")45queued.AssertChained[jobs.ShipOrder](jobs.RecordShipment{}, jobs.UpdateInventory{})
To inspect the payloads of later jobs in the chain, read the recorded job's Chain inside AssertPushed:
1queued.AssertPushed(func(job queuetest.Job[jobs.ShipOrder]) bool {2 if len(job.Chain) == 0 {3 return false4 }56 next, ok := job.Chain[0].(jobs.RecordShipment)78 return ok && next.OrderID == 429})1queued.AssertPushed(func(job queuetest.Job[jobs.ShipOrder]) bool {2 if len(job.Chain) == 0 {3 return false4 }56 next, ok := job.Chain[0].(jobs.RecordShipment)78 return ok && next.OrderID == 429})
AssertPushedWithoutChain[T]() checks that a job was dispatched on its own, without a chain after it.
To test a job that dynamically modifies its chain, run it with client.Attempt and call AssertChained with a value of each added job's type, in the order they would run. The result's Chained field holds the added jobs themselves, so you may check their fields:
1client.Attempt(jobs.ProcessPodcast{PodcastID: podcast.ID}).2 AssertSucceeded().3 AssertChained(jobs.TranscribePodcast{}, jobs.NotifyHosts{}, jobs.UpdatePodcastFeed{})1client.Attempt(jobs.ProcessPodcast{PodcastID: podcast.ID}).2 AssertSucceeded().3 AssertChained(jobs.TranscribePodcast{}, jobs.NotifyHosts{}, jobs.UpdatePodcastFeed{})
Testing batches
The queue fake intercepts dispatched batches without writing to the batch tables or executing their jobs. Assert on dispatched batches with AssertBatched:
1queued := queuetest.New(client)23client.Post("/imports/7/start", nil)45queued.AssertBatched(func(batch queue.Batched) bool {6 if batch.Name != "Import CSV" || len(batch.Jobs) != 3 {7 return false8 }910 first, ok := batch.Jobs[0].(jobs.ImportCsv)1112 return ok && first.From == 1 && first.To == 10013})1queued := queuetest.New(client)23client.Post("/imports/7/start", nil)45queued.AssertBatched(func(batch queue.Batched) bool {6 if batch.Name != "Import CSV" || len(batch.Jobs) != 3 {7 return false8 }910 first, ok := batch.Jobs[0].(jobs.ImportCsv)1112 return ok && first.From == 1 && first.To == 10013})
Inside the match function, you may also inspect the batch's Then, Catch, and Finally callbacks and AllowFailures. Call queued.AssertBatchCount(n) to check how many batches were dispatched, or queued.AssertNothingBatched() to verify no batches were.
Because the fake doesn't run batch callbacks, you may test a callback by calling its method directly with client.Context(), building a *queue.Batch when the method takes one:
1batch := &queue.Batch{TotalJobs: 3}23if err := (jobs.ImportFinished{ImportID: 7}).Finally(client.Context(), batch); err != nil {4 t.Fatal(err)5}1batch := &queue.Batch{TotalJobs: 3}23if err := (jobs.ImportFinished{ImportID: 7}).Finally(client.Context(), batch); err != nil {4 t.Fatal(err)5}
To test a job that adds jobs to its batch or cancels it, pass queuetest.InBatch() to client.Attempt, then read the result's AddedToBatch or call AssertBatchCancelled(). For example, this test checks that SplitImport adds three jobs for an import of 300 rows, and that ImportCsv cancels its batch when its import has been deleted:
1// Import 7 has 300 rows...23result := client.Attempt(jobs.SplitImport{ImportID: 7}, queuetest.InBatch()).AssertSucceeded()45if len(result.AddedToBatch) != 3 {6 t.Fatalf("SplitImport added %d jobs, want 3", len(result.AddedToBatch))7}89client.Attempt(jobs.ImportCsv{ImportID: 404, From: 1, To: 100}, queuetest.InBatch()).10 AssertBatchCancelled()1// Import 7 has 300 rows...23result := client.Attempt(jobs.SplitImport{ImportID: 7}, queuetest.InBatch()).AssertSucceeded()45if len(result.AddedToBatch) != 3 {6 t.Fatalf("SplitImport added %d jobs, want 3", len(result.AddedToBatch))7}89client.Attempt(jobs.ImportCsv{ImportID: 404, From: 1, To: 100}, queuetest.InBatch()).10 AssertBatchCancelled()
Testing the worker
To test jobs end to end, run your migrations in the test database and send jobs to the database connection with laraveltest.Queue. Jobs then wait in the jobs table instead of running when they're dispatched, until the test runs the worker:
1func TestQueuedPodcastsAreProcessed(t *testing.T) {2 client := tests.New(t, laraveltest.Queue("database"))34 if _, err := queue.Dispatch(client.Context(), jobs.ProcessPodcast{PodcastID: 42}); err != nil {5 t.Fatal(err)6 }78 client.Command("queue:work --stop-when-empty").AssertSuccessful()9 client.AssertDatabaseCount("jobs", 0)10}1func TestQueuedPodcastsAreProcessed(t *testing.T) {2 client := tests.New(t, laraveltest.Queue("database"))34 if _, err := queue.Dispatch(client.Context(), jobs.ProcessPodcast{PodcastID: 42}); err != nil {5 t.Fatal(err)6 }78 client.Command("queue:work --stop-when-empty").AssertSuccessful()9 client.AssertDatabaseCount("jobs", 0)10}