Laravel Queue Internals
“The --timeout value should always be at least several seconds shorter than your retry_after configuration value.” — Laravel 13.x documentation, Queues: Job Expiration and Timeouts
Summary: How Laravel 13 turns dispatch() into a JSON payload, stores it in a driver, leases it to a worker, and records success, release, or failure, read from the framework source. Focus: The Redis driver's list + sorted sets + Lua scripts, the database driver's SKIP LOCKED reservation, the worker loop, middleware, uniqueness, batches, chains, failed jobs, and Horizon. Learning goal: Predict exactly when a Laravel job runs twice, waits, is skipped, or is lost, and configure retry_after, timeouts, locks, and workers so that it does not surprise you.
This chapter reads the queue component as code. The application-level patterns live in sibling chapters: retry and backoff owns schedules, dead-letter queues owns parking and replay, durable workflows and jobs owns multi-step workflow design, competing consumers owns worker scaling theory, and locks and concurrency owns row-lock semantics. Every claim about behaviour below cites a file on the 13.x branch of laravel/framework, read on 2026-11-26.
Page map
| If you are looking for | Go to |
|---|---|
What dispatch() actually stores | Payload |
| Why an Eloquent model in a job is re-queried | SerializesModels |
| The Redis keys and Lua scripts | Redis driver |
| Why a job ran twice | retry_after vs timeout |
FOR UPDATE SKIP LOCKED in the jobs table | Database driver |
--max-jobs, --memory, signals, queue:restart | Worker loop |
RateLimited, WithoutOverlapping, ThrottlesExceptions, Skip | Job middleware |
ShouldBeUnique, ShouldBeEncrypted, afterCommit | Uniqueness, After commit |
Bus::batch, Bus::chain, job_batches | Batches and chains |
failed_jobs, queue:retry, queue:prune-failed | Failed jobs |
| Horizon supervisors and balancing | Horizon |
Writing a driver with Queue::extend | Custom drivers |
| RabbitMQ, Kafka, Redis Streams packages | Broker differences |
| Reproducible experiments | Lab |
Everything in one minute
| Piece | Source file (13.x) | What it really does | Surprise if you ignore it |
|---|---|---|---|
ShouldQueue | Contracts/Queue/ShouldQueue.php | Marker; Bus\Dispatcher::dispatch sends the command to a queue instead of running it | Without it, dispatch() runs inline in the request |
PendingDispatch | Foundation/Bus/PendingDispatch.php | Dispatches in __destruct; acquires the unique lock first | Dispatch happens at end of statement, not at the call |
| Payload | Queue/Queue.php createObjectPayload | JSON with uuid, displayName, job, maxTries, backoff, timeout, retryUntil, data.command | Changing a class name breaks queued payloads |
SerializesModels | Queue/SerializesAndRestoresModelIdentifiers.php | Stores class + key, re-queries on the worker | The worker sees current rows, not the dispatch-time object |
| Redis driver | Queue/RedisQueue.php, Queue/LuaScripts.php | Ready list, :delayed and :reserved sorted sets, :notify list, Lua for atomic moves | Reservations expire after retry_after and re-run |
| Database driver | Queue/DatabaseQueue.php | SELECT ... FOR UPDATE SKIP LOCKED, then set reserved_at and attempts | Old MySQL/PostgreSQL fall back to plain FOR UPDATE |
| Worker | Queue/Worker.php | One job at a time, pcntl_alarm timeout, limits checked after each job | A timeout kills the whole process |
| Middleware | Queue/Middleware/*.php | Wraps handle(); may release, delete, or skip | A release spends an attempt |
| Unique lock | Bus/UniqueLock.php | Cache lock laravel_unique_job:NAME:ID | Duplicate dispatch is silently skipped |
| Batch | Bus/Batch.php, Bus/DatabaseBatchRepository.php | Counters in job_batches updated under lockForUpdate | then never fires while a failed job is unretried |
| Failed jobs | Queue/Failed/DatabaseUuidFailedJobProvider.php | Row in failed_jobs written on JobFailed by queue:work | Sync-driver failures are not stored |
| Horizon | laravel/horizon Supervisor.php, AutoScaler.php | Supervisors spawn and rebalance worker processes per queue | Redis-only; not compatible with Redis Cluster |
| Driver | Store primitive | Reservation | Delay | Lease / redelivery |
|---|---|---|---|---|
sync | None: runs in the calling process | None | Ignored | Exceptions propagate to the caller |
database | jobs table row | Row lock + reserved_at | available_at in the future | retry_after against reserved_at |
redis | List queues:NAME | Lua LPOP + ZADD :reserved | ZADD :delayed | retry_after as the reserved score |
beanstalkd | Beanstalkd tube | Beanstalkd reserve | Beanstalkd delay | retry_after is passed as the job's TTR (time-to-run) |
sqs | Amazon SQS queue | ReceiveMessage | DelaySeconds | Visibility timeout (no retry_after) |
null | Nothing | Nothing | Nothing | Jobs are discarded |
Where it comes from
Laravel's queue component is the Illuminate\Queue namespace of laravel/framework. The 13.x documentation states that config/queue.php contains connections for “the database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver that will execute jobs immediately (for use during development or testing). A null queue driver is also included which discards queued jobs.” Those six names (sync, database, beanstalkd, sqs, redis, null) are the built-in drivers. RabbitMQ and Kafka are not built in; they arrive through packages, which is why the broker section exists.
The component is layered. The Illuminate\Contracts\Queue\Queue interface defines push, pushRaw, later, pop, bulk, and size methods. Each driver extends the abstract Illuminate\Queue\Queue, which builds payloads. A connector (Connectors/RedisConnector.php, DatabaseConnector.php, ...) turns a config array into a driver instance, and QueueManager keeps a map of driver name to connector closure. The worker (Queue/Worker.php) only knows the contract: it calls pop() and receives an Illuminate\Contracts\Queue\Job. Horizon is a separate package (laravel/horizon) that supervises Redis workers.
This chapter pins every source link to the 13.x branch. A branch moves; when an upgrade changes a script or a column, re-read the file rather than this page.
Why it exists
A web request should answer in milliseconds. Sending email, resizing images, calling a slow payment API, or importing a CSV takes longer and can fail. A queue moves that work out of the request and lets it retry.
| Run inside the request | Push to a Laravel queue |
|---|---|
| The user waits for every step | The user waits only for the insert/push |
| An exception fails the request immediately | An exception releases the job for another attempt |
| No extra infrastructure | Needs a store (database/Redis/SQS) and supervised workers |
| Exactly one execution per request | At-least-once: a job can run more than once |
| Code sees in-memory objects | The worker sees a serialized copy and re-queried models |
Three misunderstandings to remove first. A Laravel queue is not exactly-once: the Redis and database drivers both re-run a job whose lease (retry_after) expired, even if the first worker is still running. A job is not a message in a broker sense: it is a serialized PHP object plus metadata, readable only by an application with the same classes. And queue:work is not a daemon manager: it exits on purpose (limits, queue:restart, timeouts) and expects Supervisor, systemd, or Horizon to start it again.
What it is really about
Every driver implements the same four-state lifecycle: ready (visible to pop), reserved (leased to one worker until a deadline), delayed (invisible until a timestamp), and gone (deleted after success, or moved to failed_jobs after the last attempt). The worker never tells the store “I am alive”. The only liveness signal is the deadline: reserved_at + retry_after in the database, the reserved score in Redis, the visibility timeout in SQS. That single design choice explains most production incidents with Laravel queues.
The picture is read left to right, then back. dispatch() creates a PendingDispatch; its destructor checks the unique lock; Bus\Dispatcher decides to queue because the command implements ShouldQueue; Queue::createPayload serializes the command into JSON; enqueueUsing either pushes now or registers an after-commit callback. The worker pops, CallQueuedHandler::call unserializes the command and sends it through its middleware to handle(). Success deletes; an exception releases with backoff; exhaustion calls failed() and writes failed_jobs.
An everyday picture
A restaurant kitchen has a ticket rail. Waiters pin tickets at the end of the rail (push). A cook takes the first ticket and clips it to the “in progress” board with a kitchen timer set to ten minutes (reserve with retry_after). If the dish goes out, the ticket is thrown away (delete). If the cook needs the oven later, the ticket goes to the “come back at 19:30” board (release with delay). If the timer rings and the ticket is still on the board, the head chef gives it to another cook, even if the first cook is just slow (lease expiry). Nobody checks whether the first cook is still cooking: a slow cook and a cook who went home look the same. Keep that timer in mind through the page.
Concept catalogue
ShouldQueue and dispatch Must-know
In plain words: Marking a job class with ShouldQueue makes dispatch() store it for a worker instead of running it now.
Common misunderstanding: “ProcessPodcast::dispatch($p) pushes immediately.” It returns a PendingDispatch; the push happens in that object's __destruct, at the end of the statement. Chained modifiers (->onQueue(), ->delay(), ->afterCommit()) work because nothing has been sent yet.
Definition: Bus\Dispatcher::dispatch() checks commandShouldBeQueued() (the command implements ShouldQueue) and calls dispatchToQueue(), which resolves the connection (attribute, queue route, or default), then push() or later() on that driver. dispatchSync() forces the sync connection; dispatchAfterResponse() runs after the HTTP response is sent, in the same PHP process. The Illuminate\Foundation\Queue\Queueable trait bundles Dispatchable, InteractsWithQueue, Bus\Queueable, and SerializesModels.
1 Controller -> SendInvoice::dispatch($invoice) returns PendingDispatch
2 Statement ends -> PendingDispatch::__destruct()
3 __destruct -> UniqueLock::acquire() only for ShouldBeUnique
4 __destruct -> Bus\Dispatcher::dispatch() ShouldQueue? yes
5 Dispatcher -> RedisQueue::push() createPayload + Lua push
6 Controller -> response 200 the job has not run yetReal scenarios: A controller dispatches inside DB::transaction and the worker reads a row that is not committed yet; a test with QUEUE_CONNECTION=sync passes while production fails because the job now runs in another process; a job dispatched in a loop of 10,000 iterations creates 10,000 round-trips where Bus::batch or Queue::bulk would pipeline them.
| Call | Where it runs | Notes |
|---|---|---|
Job::dispatch() | Worker, later | Default for ShouldQueue |
Job::dispatchSync() | Current process, now | Uses the sync connection; exceptions reach the caller |
Job::dispatchAfterResponse() | Current process, after response | No retries, no worker; for short work only |
dispatch(function () { ... }) | Worker | Wrapped in CallQueuedClosure |
Queue::bulk([...]) | Worker | Redis driver pipelines or uses one Lua bulkPush on cluster |
How to use it: Keep ShouldQueue on anything slow or failure-prone, decide transaction behaviour explicitly with after commit, and never rely on sync to test retry, timeout, or serialization behaviour.
The payload Must-know
In plain words: A queued job is a JSON document; the PHP object is a serialized string inside it.
Common misunderstanding: “The worker gets my object.” It gets unserialize(data.command) of a clone taken at dispatch, with models replaced by identifiers. Properties you set later in the request are not there.
Definition: Queue::createObjectPayload() (13.x) builds these keys: uuid (a fresh Str::uuid()), displayName (class name or displayName()), job (Illuminate\Queue\CallQueuedHandler@call), maxTries, maxExceptions, failOnTimeout, countCrashesAsExceptions, backoff (comma-joined seconds), timeout, retryUntil (Unix timestamp), deleteWhenMissingModels, data.commandName, data.command (serialized, or encrypted when ShouldBeEncrypted), data.batchId, and createdAt. createPayload() adds delay. The Redis driver merges id (32 random characters) and attempts (0). JSON encoding failure throws InvalidPayloadException with the message “Unable to JSON encode payload for job [...]”.
{
"uuid": "6f1c1c56-2a77-4b8e-9d55-0a3c2f5f6b11",
"displayName": "App\\Jobs\\SendInvoice",
"job": "Illuminate\\Queue\\CallQueuedHandler@call",
"maxTries": 5, "maxExceptions": null, "failOnTimeout": false,
"backoff": "10,30,60", "timeout": 60, "retryUntil": null,
"data": {
"commandName": "App\\Jobs\\SendInvoice",
"command": "eyJpdiI6... (encrypted serialize() output)",
"batchId": null
},
"createdAt": 1764115200, "delay": null,
"id": "q3n8Vh1...32 chars", "attempts": 0
}Real scenarios: A deploy renames App\Jobs\SendInvoice; queued payloads still name the old class and fail to unserialize. Raw binary image bytes in a property make json_encode fail; the docs require base64_encode. A Horizon dashboard shows displayName, which is why a closure job appears as Closure (web.php:12). maxTries comes from #[Tries], a tries property, or a tries() method; the worker's --tries applies only when the payload value is null.
| Payload key | Source | Read by |
|---|---|---|
uuid | Str::uuid() per dispatch | failed_jobs.uuid, queue:retry, batch counters |
maxTries | #[Tries] / tries / tries() | Worker::markJobAsFailedIfAlreadyExceedsMaxAttempts |
backoff | #[Backoff] / backoff() | Worker::calculateBackoff (index attempts - 1, else last) |
timeout | #[Timeout] / timeout | pcntl_alarm in Worker::registerTimeoutHandler |
retryUntil | retryUntil() / #[RetryFor] | Overrides maxTries while in the future |
attempts | Redis payload / database column | Incremented on reservation, not on failure |
How to use it: Treat payloads as a wire format: keep job class names stable across deploys or drain queues first, keep properties small, and put identifiers rather than data in jobs.
SerializesModels and closures Important
In plain words: Models travel as “class + primary key”; the worker loads them again from the database.
Common misunderstanding: “Loading a relation with a constraint before dispatch limits what the job sees.” The docs warn that relationship constraints are not re-applied; the relation is re-retrieved in full.
Definition: SerializesModels uses SerializesAndRestoresModelIdentifiers: on __serialize, an Eloquent model becomes a ModelIdentifier(class, id, relations, connection); a collection keeps all ids. On the worker, getRestoredPropertyValue re-queries. If the row is gone, ModelNotFoundException fails the job, unless #[DeleteWhenMissingModels] makes CallQueuedHandler::handleModelNotFound delete it quietly. #[WithoutRelations] (property or class) drops relations from the identifier. A closure is wrapped by CallQueuedClosure::create() in Laravel\SerializableClosure\SerializableClosure, signed with the app key.
1 Request -> $invoice = Invoice::with('lines')->find(7)
2 Request -> SendInvoice::dispatch($invoice) stores ModelIdentifier(Invoice, 7, ['lines'])
3 Admin -> deletes invoice 7
4 Worker -> unserialize -> Invoice::findOrFail(7) -> ModelNotFoundException
5 Worker -> job fails, or is deleted when DeleteWhenMissingModels is setReal scenarios: An order changes status between dispatch and execution, and the job sees the new status (usually what you want); a job dispatched for 50,000 users stores 50,000 ids in one payload; a closure job captured $this from a controller and serialized the whole controller; a model on a non-default connection is restored on that same connection name.
How to use it: Pass models (not arrays of attributes) when you want fresh state, pass plain values when you need the dispatch-time snapshot, and add #[WithoutRelations] unless the job needs relations.
The Redis driver: lists, sorted sets, and Lua Must-know
In plain words: Ready jobs wait in a Redis list; leased and delayed jobs wait in sorted sets ordered by a timestamp; small Lua scripts move them atomically.
Common misunderstanding: “Laravel's Redis queue uses Redis Streams.” It uses only lists and sorted sets. There is no consumer group, no pending entries list, and no server-side acknowledgment; see Redis Streams below.
Definition: For queue default, RedisQueue::getQueueRedisKey() returns queues:default (or queues:{default} on a cluster connection, so all keys share a hash slot). The keys are:
| Key | Type | Content | Written by |
|---|---|---|---|
queues:default | List | Ready payloads in FIFO order | LuaScripts::push (RPUSH), migrateExpiredJobs |
queues:default:notify | List | One token per ready job | push, migrateExpiredJobs; consumed by pop (LPOP) and BLPOP |
queues:default:delayed | Sorted set | Payloads scored by available_at | later (ZADD), release |
queues:default:reserved | Sorted set | Payloads with attempts+1, scored by now + retry_after | pop (ZADD); removed by delete (ZREM) or release |
pop() first calls migrate(): migrateExpiredJobs(:delayed → queue) and, when retry_after is not null, migrateExpiredJobs(:reserved → queue). The migration script runs ZRANGEBYSCORE key -inf now LIMIT 0 N, removes those members with ZREMRANGEBYRANK, RPUSHes them to the ready list in chunks of 100, and pushes a notify token per job. N is migration_batch_size (-1 means all). Then LuaScripts::pop does LPOP on the list, decodes the JSON with cjson, increments attempts, re-encodes, ZADDs the new string to :reserved with score now + retry_after, and pops one notify token. If nothing was ready and block_for is set, the driver BLPOPs the notify list for up to block_for seconds and retries once.
Worker A Worker B
1 EVAL pop -> LPOP queues:default -> J (attempts 0)
2 ZADD :reserved (now+90) J' (attempts 1)
3 handle() ... still running at t=91
4 EVAL migrateExpiredJobs(:reserved) -> J' back to list
5 EVAL pop -> J'' (attempts 2), ZADD :reserved
6 ZREM :reserved J' -> no-op (member gone) handle() runs the same job again
7 or release(): ZREM no-op, ZADD :delayed J' -> a third copy is scheduledReal scenarios: A 2-minute PDF render on a connection with retry_after 90 is executed twice by two workers; block_for = 0 makes a worker ignore SIGTERM until a job arrives (the docs warn about this); a burst of 200,000 delayed jobs becoming due at once makes the first pop move all of them in one Lua call unless migration_batch_size caps it; KEYS queues:* in allQueueNames() on a non-cluster connection is O(N) over the keyspace.
| Operation | Redis commands | Atomic unit |
|---|---|---|
push | RPUSH queue, RPUSH queue:notify 1 | One EVAL |
later | ZADD queue:delayed availableAt payload | One EVAL |
pop | LPOP queue, ZADD queue:reserved, LPOP queue:notify | One EVAL |
migrateExpiredJobs | ZRANGEBYSCORE, ZREMRANGEBYRANK, RPUSH | One EVAL per source set |
deleteReserved | ZREM queue:reserved member | Single command |
deleteAndRelease | ZREM queue:reserved, ZADD queue:delayed | One EVAL |
size | LLEN + ZCARD :delayed + ZCARD :reserved | One EVAL |
clear | DEL of all four keys | One EVAL |
How to use it: Size retry_after above your slowest job, set block_for to a few seconds, cap migration_batch_size on queues with large delayed backlogs, and use one Redis connection with maxmemory-policy noeviction for queues (an evicted list is lost work). The Go port in Go reproduces the scripts and tests the double-execution case.
retry_after vs job timeout Must-know
In plain words: retry_after is how long the store waits before giving the job to someone else; timeout is how long the worker lets the job run before killing itself. The second must be shorter.
Common misunderstanding: “--timeout releases the job for a retry.” On timeout the worker's SIGALRM handler may mark the job failed (if this was the last attempt, or failOnTimeout), fires JobTimedOut, and then kills the whole worker process with SIGKILL. The job is not released: it stays reserved until retry_after expires, then runs again.
Definition: Worker::registerTimeoutHandler calls pcntl_alarm(timeout) before each job, where timeout is the payload timeout or --timeout (default 60). The alarm needs the pcntl extension. retry_after is a connection option (config/queue.php, documented default 90; the code default is 60 when the key is missing). SQS has no retry_after; the visibility timeout plays that role. The docs: “If your --timeout option is longer than your retry_after configuration value, your jobs may be processed twice.”
Real scenarios: A payment capture with #[Timeout(120)] on a retry_after 90 connection is charged twice; Horizon's supervisor timeout is set above retry_after; HTTP and database clients inside the job need their own timeouts so the job fails on its own terms before the alarm kills the process; a long import is split into batch chunks so that each chunk fits comfortably under the lease.
| Setting | Where | Default | Rule |
|---|---|---|---|
retry_after | Connection config | 90 in the stock config | Longest job + safety margin |
--timeout | queue:work | 60 | Several seconds below retry_after |
#[Timeout(n)] | Job class | null (use --timeout) | Below retry_after |
#[FailOnTimeout] | Job class | false | Fail instead of retrying after a timeout |
Horizon timeout | Supervisor config | Docs example: 60 | Above job timeouts, below retry_after |
Supervisor stopwaitsecs | Process monitor | Docs example: 3600 | Above the longest job, or deploys kill jobs |
How to use it: Write the three numbers down per connection: job timeout below worker/Horizon timeout below retry_after. Make the job idempotent anyway; a crash between the side effect and delete() also re-runs it.
The database driver and SKIP LOCKED Must-know
In plain words: Workers grab the oldest available row, lock it, stamp reserved_at, and commit; other workers skip locked rows instead of waiting.
Common misunderstanding: “The row stays locked while the job runs.” The lock lasts only for the short reservation transaction. While the job runs, only reserved_at protects it, and only for retry_after seconds.
Definition: DatabaseQueue::pop() opens a transaction and runs getNextAvailableJob(): WHERE queue = ? AND ((reserved_at IS NULL AND available_at <= now) OR reserved_at <= now - retry_after) ORDER BY id ASC LIMIT 1 with the lock from getLockForPopping(). Then markJobAsReserved() updates reserved_at = now and attempts = attempts + 1, and the transaction commits. deleteReserved() deletes the row inside a transaction after lockForUpdate()->find($id). release() deletes the row and inserts a new one with the same payload and attempts, available_at = now + delay, and a new id, so a released job goes to the back of the line.
-- Skeleton migration 0001_01_01_000002_create_jobs_table.php (laravel/laravel 13.x), as PostgreSQL DDL
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
queue varchar(255) NOT NULL,
payload text NOT NULL,
attempts smallint NOT NULL,
reserved_at integer NULL,
available_at integer NOT NULL,
created_at integer NOT NULL
);
CREATE INDEX jobs_queue_index ON jobs (queue);
-- What pop() sends on PostgreSQL 9.5+ (bindings shown inline)
BEGIN;
SELECT * FROM jobs
WHERE queue = 'default'
AND ((reserved_at IS NULL AND available_at <= 1764115200)
OR reserved_at <= 1764115110) -- now - retry_after (90)
ORDER BY id ASC
LIMIT 1
FOR UPDATE SKIP LOCKED;
UPDATE jobs SET reserved_at = 1764115200, attempts = 1 WHERE id = 41;
COMMIT;| Engine (detected from PDO) | Lock clause chosen | Effect with 10 workers |
|---|---|---|
| PostgreSQL 9.5+ | FOR UPDATE SKIP LOCKED | Each worker gets a different row, no waiting |
| MySQL 8.0.1+ | FOR UPDATE SKIP LOCKED | Same; InnoDB skips locked index records |
| MariaDB 10.6+ | FOR UPDATE SKIP LOCKED | Same |
| Vitess / PlanetScale 19+ | FOR UPDATE SKIP LOCKED | Same |
| SQL Server | with(rowlock,updlock,readpast) | READPAST skips locked rows |
| Older versions, others | FOR UPDATE (lock(true)) | Workers queue behind one row lock; throughput collapses |
| SQLite | lock(true), but SQLiteGrammar::compileLock emits nothing | One writer at a time for the whole file |
Worker A (tx) Worker B (tx)
1 BEGIN; SELECT ... id=41 FOR UPDATE SKIP LOCKED
2 BEGIN; SELECT ... -> skips 41, gets 42
3 UPDATE jobs SET reserved_at=now WHERE id=41
4 COMMIT UPDATE ... id=42; COMMIT
5 handle(41) runs with no row lock held handle(42)
6 DELETE FROM jobs WHERE id=41 (after lockForUpdate find)Real scenarios: A small app runs the database driver on PostgreSQL and never needs Redis; MySQL 5.7 users see workers waiting on each other because the fallback lock does not skip; a jobs table with millions of delayed rows slows pop because the skeleton index covers only queue, so a composite index on (queue, reserved_at, available_at) or pruning helps; pop errors that are not concurrency errors now fail the offending job (#58978 in the source comment) instead of crashing the worker forever.
How to use it: Use the database driver when you already run PostgreSQL or MySQL 8 and want transactional simplicity; move to Redis when polling load or row churn on jobs starts to show in database observability. Row-lock details live in locks and concurrency.
The worker loop Must-know
In plain words: queue:work is a PHP loop that pops one job, runs it, checks whether it should exit, and repeats.
Common misunderstanding: “A worker picks up new code after deploy.” A daemon worker keeps the booted application in memory and never re-reads code; you must run queue:restart (or horizon:terminate) and let the process monitor start new workers.
Definition: Worker::daemon() installs signal handlers when pcntl is loaded, records the illuminate:queue:restart cache value and the start time, then loops: skip when paused or in maintenance mode (unless --force), getNextJob() across the listed queues in order, arm the timeout alarm, runJob(), optionally sleep --rest, or sleep --sleep when idle; then stopIfNecessary() returns a status in this order: lost connection, interrupted, memory exceeded (exit code 12), restart signal, --stop-when-empty, --stop-when-empty-for, --max-time, --max-jobs. SIGTERM, SIGINT, SIGQUIT set shouldQuit (finish the current job, then exit); SIGUSR2 pauses; SIGCONT resumes. --once uses runNextJob() instead of the loop. queue:listen starts a fresh queue:work --once child process per job, which reloads code but is much slower.
1 Deploy script -> php artisan queue:restart Cache::forever('illuminate:queue:restart', now)
2 Worker -> finishes current job
3 Worker -> stopIfNecessary(): cached value != value at start -> exit 0
4 Supervisor -> autorestart=true -> starts queue:work with new code
5 New worker -> boots the new release| Flag | Default | Meaning |
|---|---|---|
--queue=high,default | Connection's queue | Priority order: high is always checked first |
--sleep=3 | 3 | Seconds to sleep when no job was found |
--rest=0 | 0 | Seconds to rest after each job |
--timeout=60 | 60 | Per-job alarm, unless the job sets its own |
--tries=1 | 1 | Used only if the payload has no maxTries; 0 means unlimited |
--backoff=0 | 0 | Used only if the job has no backoff |
--memory=128 | 128 | MB, or a percentage of memory_limit; exit code 12 |
--max-jobs=0 | 0 | Exit after N jobs (0 = unlimited) |
--max-time=0 | 0 | Exit after N seconds |
--stop-when-empty | off | Exit when a pop finds nothing (good for cron or containers) |
--stop-when-empty-for=0 | 0 | Exit after N idle seconds |
--once | off | Process one job and exit |
--force | off | Run during maintenance mode |
--daemon | deprecated | The loop is already the default |
Real scenarios: A worker leaks memory through a static cache and is recycled with --max-jobs=1000; Kubernetes sends SIGTERM and waits terminationGracePeriodSeconds, which must exceed the longest job; a worker with --queue=high,default starves default while high is busy; a deploy without queue:restart keeps running old code against a new schema.
How to use it: Run workers under Supervisor (numprocs, stopwaitsecs above the longest job, --max-time to recycle), run queue:restart in every deploy, and give each latency class its own queue and workers rather than relying on --queue priority alone. Scaling theory lives in competing consumers.
Job middleware Important
In plain words: Middleware wraps handle() inside the worker and can decide to run it, delay it, or drop it.
Common misunderstanding: “A rate-limited job waits without cost.” RateLimited, WithoutOverlapping, and ThrottlesExceptions call $job->release(), and every release followed by a new reservation increments attempts. A job with #[Tries(3)] behind a busy limiter can fail without ever reaching handle(); use retryUntil() for such jobs.
Definition: CallQueuedHandler::dispatchThroughMiddleware() runs the job's middleware() array (and any $middleware property) through a pipeline. The built-ins in Illuminate\Queue\Middleware:
| Middleware | Mechanism (13.x source) | When blocked | Knobs |
|---|---|---|---|
RateLimited('name') | RateLimiter::for limits, checked per job | release(releaseAfter or limiter wait) | releaseAfter(), dontRelease(); RateLimitedWithRedis variant |
WithoutOverlapping($key) | Cache lock per key, released in finally | release(releaseAfter), default 0 seconds | releaseAfter(), expireAfter(), dontRelease(), shared() |
ThrottlesExceptions($max, $decay) | Counts exceptions per key in the cache | release until the decay window ends | backoff(minutes), by(), byJob(), when(), deleteWhen(), failWhen(), report() |
Skip::when($cond) / Skip::unless($cond) | Returns false instead of calling $next | Job is deleted, handle() never runs | Condition evaluated when middleware() is called |
SkipIfBatchCancelled | Checks the job's batch | Job is deleted | Use in batched jobs |
1 Worker -> pop job J (attempts 1)
2 RateLimited -> limiter "mail-provider" exhausted -> J->release(42)
3 Worker -> J back in :delayed, nothing ran
4 t+42 -> pop J (attempts 2) -> limiter OK -> WithoutOverlapping lock OK -> handle()Real scenarios: A third-party API allows 60 calls per minute across all workers (RateLimited); two jobs for the same customer must not update the same balance concurrently (WithoutOverlapping keyed by customer id, with expireAfter so a crash does not hold the lock forever); an unstable partner API is protected from a retry storm (ThrottlesExceptions); a job that became pointless (order already cancelled) is dropped (Skip). WithoutOverlapping and the unique lock both need a lock-capable cache: memcached, redis, dynamodb, database, file, or array.
How to use it: Pair release-based middleware with retryUntil() or #[RetryFor] instead of a small #[Tries]; give WithoutOverlapping an expireAfter longer than the job timeout; set releaseAfter explicitly so blocked jobs do not spin.
Uniqueness and encryption Important
In plain words: ShouldBeUnique takes a cache lock at dispatch time so a second identical job is not queued while the first exists; ShouldBeEncrypted encrypts the serialized command in the payload.
Common misunderstanding: “ShouldBeUnique guarantees the job runs once.” It only prevents a second dispatch while the lock is held. It does not stop retry_after redelivery, and a dispatch that loses the race is dropped silently (only a UniqueJobSkipped event is fired).
Definition: PendingDispatch::shouldDispatch() calls UniqueLock::acquire(): Cache::lock('laravel_unique_job:'.NAME.':'.uniqueId(), uniqueFor), where NAME is hash('xxh128', displayName()) when the job defines displayName(), else the class name, and uniqueFor comes from uniqueFor() or #[UniqueFor] (0 means no expiry). The lock owner token is stored on the job (uniqueLockOwner) so the worker can release that exact lock. ShouldBeUnique releases after successful processing or after the final failure; ShouldBeUniqueUntilProcessing releases just before handle() runs, so one more copy may be queued while it runs. uniqueVia() selects another cache store. Laravel 13 also documents #[DebounceFor], which is mutually exclusive with ShouldBeUnique. ShouldBeEncrypted makes createObjectPayload store encrypt(serialize(clone $job)) in data.command; the rest of the payload stays readable.
1 Request 1 -> dispatch UpdateSearchIndex(product 9) -> lock laravel_unique_job:...:9 acquired -> pushed
2 Request 2 -> dispatch UpdateSearchIndex(product 9) -> lock held -> skipped silently
3 Worker -> handle() succeeds -> lock released
4 Request 3 -> dispatch again -> queuedReal scenarios: A search re-index for the same product is requested 50 times in a second; a nightly report must not be queued twice by overlapping schedulers; a queue is flushed with queue:clear while uniqueFor is 0, leaving a lock that blocks every future dispatch for that id; a job carrying a customer's tax id is encrypted so Redis dumps and Horizon payload views do not expose it.
| Contract / attribute | Lock taken | Lock released | Trap |
|---|---|---|---|
ShouldBeUnique | At dispatch | After success or final failure | Lost job + uniqueFor 0 = permanent lock |
ShouldBeUniqueUntilProcessing | At dispatch | Before handle() | A second copy can queue while the first runs |
#[UniqueFor(seconds)] | TTL of the lock | Expiry or release | Too short: duplicates; too long: blocked dispatches |
uniqueVia() | On a chosen store | Same store | Must support atomic locks |
ShouldBeEncrypted | n/a | n/a | Workers need the same APP_KEY |
How to use it: Always set #[UniqueFor] above the worst-case queue wait plus run time, keep business idempotency (a unique key in the database) as the real guarantee, and encrypt jobs that carry personal data; see messaging security.
After-commit dispatch Must-know
In plain words: With afterCommit, a job dispatched inside a database transaction is pushed only after the transaction commits, and discarded if it rolls back.
Common misunderstanding: “After commit is an outbox.” The job is held in PHP memory until COMMIT; if the process dies between COMMIT and the push, the job is lost. A transactional outbox writes the job in the same transaction instead.
Definition: Queue::enqueueUsing() checks shouldDispatchAfterCommit($job): true when the job implements ShouldQueueAfterCommit (unless afterCommit === false), when $job->afterCommit is set, or when the connection has 'after_commit' => true. Then it registers a callback with the db.transactions manager instead of pushing. ->afterCommit() and ->beforeCommit() override per dispatch. Events implement ShouldDispatchAfterCommit for the same effect on listeners; ShouldQueueAfterCommit works on queued listeners.
1 Request -> DB::beginTransaction(); Order::create(...) order 501 not visible to others
2 Request -> ShipOrder::dispatch($order) without afterCommit: pushed now
3 Worker -> pops ShipOrder -> Order::findOrFail(501) ModelNotFoundException
4 Request -> COMMIT too late
--- with after_commit = true: step 2 waits; push happens after step 4 ---Real scenarios: A worker on a fast Redis queue beats the request's commit and fails with a missing model; a rollback after payment failure must not send the confirmation email; nested transactions defer the push until the outermost commit; a long transaction delays all its jobs.
How to use it: Set after_commit => true on every connection unless you have a reason not to, and use an outbox when losing a job after commit is unacceptable.
Batches and chains Important
In plain words: A batch runs many jobs in parallel and tracks counters in a job_batches row; a chain runs jobs one after another by carrying the rest of the chain inside the current job.
Common misunderstanding: “then() runs when all jobs have finished.” then runs when pending_jobs reaches 0, which only happens when every job succeeded. With allowFailures(), a failed job keeps its pending slot until a retry of it succeeds; use finally() for “every job ran once”.
Definition: Bus::batch($jobs) returns a PendingBatch; dispatch() stores a row (id, name, total_jobs, pending_jobs, failed_jobs, failed_job_ids, options with serialized callbacks, cancelled_at, created_at, finished_at) and pushes the jobs with data.batchId. On success Batch::recordSuccessfulJob() decrements pending_jobs inside a transaction with lockForUpdate() on that row, fires progress, then then at zero, and finally when pending_jobs - failed_jobs == 0. On failure recordFailedJob() increments failed_jobs; without allowFailures the first failure cancels the batch and fires catch. Jobs use the Batchable trait and check $this->batch()->cancelled(). A chain (Bus::chain([...])) serializes jobs 2..n into the first job's chained property; CallQueuedHandler calls dispatchNextJobInChain() after a success; a failure stops the chain and runs the catch callbacks stored in chainCatchCallbacks.
1 Bus::batch([J1..J4])->dispatch() job_batches: total=4 pending=4 failed=0
2 J1 ok -> UPDATE ... pending=3 (row locked) progress()
3 J2 fail -> failed=1, failed_job_ids=[J2] catch(); cancel unless allowFailures
4 J3, J4 ok -> pending=1 then() not called: pending != 0
5 pending - failed = 0 finally()
6 queue:retry-batch BATCH_ID -> J2 ok -> pending=0 then() now runsReal scenarios: A 2 million-row CSV import split into 4,000 chunk jobs with a progress bar; a video pipeline transcode → thumbnail → publish as a chain; a batch row becomes a hot spot because 64 workers update the same job_batches row for every job; a cancelled batch keeps executing queued jobs that do not check cancelled().
| Need | Use | Watch out |
|---|---|---|
| Parallel independent jobs + completion callback | Bus::batch | One counter row per batch; prune with queue:prune-batches |
| Strict sequence | Bus::chain | Delete inside a job does not stop the chain; only failure does |
| Sequence inside parallel work | Arrays of chains inside Bus::batch | All batched jobs share one connection and queue |
| Add work at runtime | $this->batch()->add(), prependToChain, appendToChain | Added jobs count toward total_jobs |
| Retry failed members | queue:retry-batch | Re-runs side effects of those jobs |
How to use it: Create the table with make:queue-batches-table, schedule queue:prune-batches (--unfinished, --cancelled), keep chunk jobs idempotent, and use durable workflows when the process needs timers, human steps, or compensation.
Failed jobs Must-know
In plain words: When a job has no attempts left, Laravel calls its failed() method and saves the payload and exception in failed_jobs so you can retry it by uuid.
Common misunderstanding: “Every failure lands in failed_jobs.” The row is written by a JobFailed listener that queue:work registers (WorkCommand::logFailedJob); a job run by sync or dispatchAfterResponse raises its exception in the caller instead. The DLQ view of this table lives in dead-letter queues.
Definition: After an exception, Worker::handleJobException() fails the job when the next attempt would exceed maxTries (or retryUntil has passed), when maxExceptions is reached, or when the exception handler says to stop retries; otherwise it releases with backoff. Before running, markJobAsFailedIfAlreadyExceedsMaxAttempts() fails a job that a timeout or crash already pushed past its limit, with the message “App\Jobs\X has been attempted too many times.” A timeout produces “App\Jobs\X has timed out.” Job::fail() marks failed, deletes the job, calls failed() on a fresh unserialized instance, and dispatches JobFailed; the database-uuids provider then inserts uuid, connection, queue, payload, exception, failed_at.
1 attempt 5 of #[Tries(5)] -> exception
2 Worker -> attempts (5) >= maxTries (5) -> failJob()
3 Job::fail() -> delete from store -> SendInvoice::failed($e) on a new instance
4 JobFailed event -> DatabaseUuidFailedJobProvider::log() -> INSERT failed_jobs
5 Operator -> php artisan queue:retry 6f1c1c56-... -> pushRaw(original payload, attempts reset)| Command | Effect |
|---|---|
php artisan queue:failed | List failed jobs (uuid, connection, queue, class, failed_at) |
php artisan queue:retry UUID [UUID...] | Push the stored payload again |
php artisan queue:retry all / --queue=name / --range=1-5 | Bulk retry; review before using |
php artisan queue:retry-batch BATCH_ID | Retry failed jobs of one batch |
php artisan queue:forget UUID / queue:flush | Delete records without retrying |
php artisan queue:prune-failed --hours=48 | Delete records older than the window (default 24) |
php artisan make:queue-failed-table | Create the migration if missing |
Real scenarios: A provider outage fails 3,000 jobs overnight and an operator retries by --queue after the fix; failed() sends a Slack alert but itself throws, hiding the original error; a job keeps timing out, so it is failed at the start of its next attempt without running; payloads in failed_jobs contain personal data and must be pruned.
How to use it: Keep failed() small and safe, register one global alert with Queue::failing() (it receives the JobFailed event), prune on a schedule, retry selectively after fixing the cause, and keep business effects idempotent because a retry is a new delivery of an old command.
Monitoring and Horizon Important
In plain words: queue:monitor raises an event when a queue is too long; Horizon replaces hand-managed queue:work processes for Redis with configured supervisors that scale workers per queue.
Common misunderstanding: “Horizon is a different queue driver.” Horizon's workers pop through Laravel\Horizon\RedisQueue, which extends the framework RedisQueue, so the same lists, sorted sets, and Lua scripts apply, including retry_after.
Definition: queue:monitor redis:default,redis:mail --max=100 reads size() per queue and dispatches Illuminate\Queue\Events\QueueBusy when the size is at least --max. Horizon's master process (php artisan horizon) starts one supervisor per entry in config/horizon.php for the current environment; each supervisor owns process pools. balance chooses auto (the AutoScaler assigns processes per queue by autoScalingStrategy time = jobs × average runtime, size = job count, or log), simple (split evenly), or false (fixed, in queue order). minProcesses, maxProcesses, balanceMaxShift, and balanceCooldown bound the change rate. horizon:terminate drains gracefully; horizon:pause, horizon:continue, and horizon:status control it. Horizon requires Redis and is not compatible with Redis Cluster.
| Concern | Plain queue:work | Horizon |
|---|---|---|
| Process count | Fixed by Supervisor numprocs | Per-queue pools, auto-balanced |
| Configuration | Shell flags per program | config/horizon.php, versioned |
| Metrics | Build your own (events, queue:monitor) | Throughput, runtime, wait time, failed jobs dashboard |
| Drivers | Any | Redis only (and packages that emit Horizon events) |
| Deploy | queue:restart | horizon:terminate |
| Process monitor | Required | Still required for the master process |
Real scenarios: A notifications queue spikes to 10,000 jobs and Horizon moves workers from an idle default; a team sets Horizon timeout to 300 for a slow export while retry_after stays 90 and sees duplicates; queue:monitor scheduled every minute pages the on-call engineer when the payments queue exceeds 100.
How to use it: Pick Horizon when you use Redis and have several queues with uneven load; keep queue:work for the database driver, SQS, or packages without Horizon support. Lag and tracing metrics live in messaging observability.
Custom drivers with Queue::extend Good to know
In plain words: A driver is three classes: a connector that builds it from config, a queue that pushes and pops raw strings, and a job wrapper that acknowledges or releases one delivery.
Common misunderstanding: “A package driver changes how jobs run.” The worker, middleware, payload format, and failure rules are the same; only storage, reservation, and the meaning of attempts() differ.
Definition: QueueManager::extend($driver, Closure $resolver) (alias addConnector) registers a closure returning an Illuminate\Queue\Connectors\ConnectorInterface, whose connect(array $config) returns an Illuminate\Contracts\Queue\Queue. Extending Illuminate\Queue\Queue gives createPayload(), enqueueUsing() (after-commit and JobQueued events), pushOn, laterOn, and bulk. pop() returns a subclass of Illuminate\Queue\Jobs\Job that implements getJobId(), getRawBody(), attempts(), and overrides delete() and release().
| Contract method | Must implement | Typical broker call |
|---|---|---|
push / later | Yes | Publish (with delay) |
pushRaw | Yes | Publish a raw payload |
pop | Yes | Receive with a lease |
size, pendingSize, delayedSize, reservedSize | Yes | Depth APIs, or 0 when unknown |
creationTimeOfOldestPendingJob | Yes | Oldest message age, or null |
Job::delete / release / attempts | Yes | Ack / nack with delay / delivery count |
How to use it: Start from RedisQueue or DatabaseQueue as the reference implementation, map attempts() to the broker's redelivery counter, and keep the payload JSON unchanged so queue:retry and Horizon-style tooling keep working.
Mechanics: exact knobs, commands, and messages
Connection options Must-know
| Key | Drivers | Meaning |
|---|---|---|
driver | All | sync, database, beanstalkd, sqs, redis, null, or a registered extension |
queue | All | Default queue name |
retry_after | database, redis, beanstalkd | Lease seconds before a reserved job is handed out again |
block_for | redis | Seconds to BLPOP the notify list; null = no blocking; 0 = forever |
after_commit | All | Push queued work only after open transactions commit |
migration_batch_size | redis | Max due jobs moved per migrateExpiredJobs call; -1 = all |
connection | redis, database | Named Redis or database connection |
table | database | Jobs table (default jobs) |
queue.batching.database / .table | Batches | Where job_batches lives (DynamoDB also supported) |
queue.failed.driver | Failed jobs | database-uuids (stock config), dynamodb, or null to disable storage |
Error and event reference Important
| Signal | Raised by | Meaning |
|---|---|---|
MaxAttemptsExceededException “... has been attempted too many times.” | Worker | Attempt count passed maxTries before or after running |
TimeoutExceededException “... has timed out.” | Worker alarm | The job exceeded its timeout; the worker process is killed |
InvalidPayloadException “Unable to JSON encode payload ...” | Queue::createPayload | A property cannot be JSON-encoded |
ModelNotFoundException | SerializesModels restore | A serialized model was deleted |
JobQueueing / JobQueued | Queue::enqueueUsing | Before / after the store accepted a push |
JobProcessing / JobProcessed | Worker | Around fire() |
JobReleasedAfterException | Worker::handleJobException | Released with computed backoff |
JobFailed | Job::fail | Final failure; triggers failed_jobs logging in queue:work |
JobTimedOut | Worker alarm | Fired before the kill |
WorkerStopping | Worker::stop / kill | Includes the status and stop reason |
QueueBusy | queue:monitor | Size reached --max |
UniqueJobSkipped | PendingDispatch | Dispatch dropped because the unique lock was held |
Attempts accounting
attempts is incremented at reservation (Redis: inside the pop script; database: markJobAsReserved), not at failure. A release keeps the incremented count; a lease expiry also re-reserves and increments. Therefore three things consume attempts: exceptions, middleware releases, and crashes or timeouts. maxExceptions (and #[CountCrashesAsExceptions]) count only exceptions, using cache keys job-exceptions:UUID and job-processing:UUID.
Solving the classic problems
A job ran twice
| Cause | Fix | Advantage | Cost |
|---|---|---|---|
Job timeout above retry_after | Job timeout below worker timeout below retry_after | Removes the systematic duplicate | Long jobs need splitting |
| Worker crashed after the side effect | Idempotency key at the side effect (unique index, provider key) | Covers every redelivery cause | Schema and provider support |
| Same job dispatched twice | ShouldBeUnique with #[UniqueFor] | Stops duplicate enqueue | Not a processing guarantee |
| Two jobs for the same entity overlap | WithoutOverlapping($entityId)->expireAfter(...) | Serializes per entity | Releases spend attempts |
queue:retry all after partial success | Retry by uuid after checking effects | Targeted recovery | Manual effort |
-- The real guarantee lives at the effect: a unique key per business operation.
CREATE TABLE invoice_emails (
invoice_id bigint PRIMARY KEY,
provider_message_id text NOT NULL,
sent_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO invoice_emails (invoice_id, provider_message_id)
VALUES (7, 'msg-123')
ON CONFLICT (invoice_id) DO NOTHING; -- 0 rows: an earlier attempt already sent itWorkers run old code or stop silently
| Symptom | Cause | Fix |
|---|---|---|
| New columns unknown to jobs after deploy | Daemon workers kept the old code | queue:restart in the deploy, Supervisor restarts them |
| Queue grows, no workers | Worker exited (memory, --max-time) without a process monitor | Supervisor autorestart=true or Horizon |
| Jobs killed mid-run on deploy | stopwaitsecs or pod grace period shorter than the job | Raise it above the longest job |
SIGTERM ignored | block_for 0 or no pcntl | block_for a few seconds; install pcntl |
Jobs see missing or stale data
Dispatch inside a transaction without after_commit lets the worker run before the commit. Turn on after_commit, or dispatch from an afterCommit callback; for strict durability use an outbox. When the job must use the dispatch-time values, pass scalars instead of models.
Unique lock never clears
A ShouldBeUnique job that was removed from the store by queue:clear, a Redis eviction, or a manual delete leaves its lock behind. With uniqueFor 0 the lock never expires and dispatches are skipped forever. Set #[UniqueFor], and remove a stuck lock by key (laravel_unique_job:...) in the lock store after confirming no copy is queued.
A batch never reaches then()
Find the failed member in job_batches.failed_job_ids, fix the cause, then queue:retry-batch BATCH_ID. If the failure is accepted, rely on finally for completion logic and catch for alerts, not then.
Choosing a driver and a runner
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Small app, PostgreSQL or MySQL 8 already | database driver | after_commit, composite index, pruning | No extra infrastructure; SKIP LOCKED scales to moderate load |
| High throughput, many queues, dashboard wanted | redis + Horizon | noeviction, block_for, per-queue supervisors | Lua-based pops, auto-balancing |
| Serverless or AWS-native | sqs | Visibility timeout above job timeout, DLQ redrive in SQS | Managed durability; no retry_after |
| Tests | sync or Queue::fake() | Separate tests for serialization and retries | sync hides worker behaviour |
| Fan-out to other services and languages | A broker (RabbitMQ, Kafka, NATS, Pulsar) | Package driver or a consumer command | Laravel payloads are PHP-specific |
| Event log, replay, many consumer groups | Kafka via laravel-kafka | Bridge to Laravel jobs, manual commit | Kafka is not a work queue |
| Need per-entity ordering | One queue per key range, or Kafka partitions | WithoutOverlapping per entity | Laravel queues do not preserve order under concurrency |
| Long multi-step business process | Durable workflow engine | Idempotent activities | Batches/chains have no timers or compensation |
Go
Example: the Redis driver algorithm
The Lua bodies are copied from LuaScripts.php (13.x) so the same text can run against Redis through go-redis:
// Package redisqueue ports the algorithm of Laravel 13's Redis queue driver
// (Illuminate\Queue\RedisQueue + LuaScripts) to Go, to show the mechanics
// without PHP. Keys: queues:NAME (ready list), :delayed and :reserved
// (sorted sets scored by a Unix timestamp) and :notify (a list of tokens).
package redisqueue
// The scripts below are the Lua bodies Laravel 13.x ships in LuaScripts.php,
// trimmed of comments. KEYS and ARGV positions match the PHP callers.
// pushScript: KEYS[1]=queue, KEYS[2]=queue:notify, ARGV[1]=payload.
const pushScript = `
redis.call('rpush', KEYS[1], ARGV[1])
redis.call('rpush', KEYS[2], 1)
`
// laterScript: KEYS[1]=queue:delayed, ARGV[1]=availableAt, ARGV[2]=payload.
const laterScript = `
redis.call('zadd', KEYS[1], ARGV[1], ARGV[2])
`
// popScript: KEYS[1]=queue, KEYS[2]=queue:reserved, KEYS[3]=queue:notify,
// ARGV[1]=now+retry_after. Returns {original, reserved-with-attempts+1}.
const popScript = `
local job = redis.call('lpop', KEYS[1])
local reserved = false
if(job ~= false) then
reserved = cjson.decode(job)
reserved['attempts'] = reserved['attempts'] + 1
reserved = cjson.encode(reserved)
redis.call('zadd', KEYS[2], ARGV[1], reserved)
redis.call('lpop', KEYS[3])
end
return {job, reserved}
`
// releaseScript: KEYS[1]=queue:delayed, KEYS[2]=queue:reserved,
// ARGV[1]=reserved payload, ARGV[2]=availableAt.
const releaseScript = `
redis.call('zrem', KEYS[2], ARGV[1])
redis.call('zadd', KEYS[1], ARGV[2], ARGV[1])
return true
`
// migrateScript: KEYS[1]=source zset, KEYS[2]=queue, KEYS[3]=queue:notify,
// ARGV[1]=now, ARGV[2]=batch limit (-1 = all).
const migrateScript = `
local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1], 'limit', 0, ARGV[2])
if(next(val) ~= nil) then
redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)
for i = 1, #val, 100 do
redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val)))
for j = i, math.min(i+99, #val) do
redis.call('rpush', KEYS[3], 1)
end
end
end
return val
`The queue logic follows RedisQueue::pop: migrate due delayed jobs, migrate expired reservations, pop into :reserved, and optionally block on :notify:
package redisqueue
import (
"context"
"encoding/json"
"errors"
"time"
)
// Store is the set of atomic operations the driver needs. In Redis each one
// is a single command or one Lua script, so no other client interleaves.
type Store interface {
Push(ctx context.Context, key, payload string) error
Later(ctx context.Context, key string, availableAt int64, payload string) error
Pop(ctx context.Context, key string, reserveUntil int64) (job, reserved string, ok bool, err error)
Release(ctx context.Context, key, reserved string, availableAt int64) error
DeleteReserved(ctx context.Context, key, reserved string) error
Migrate(ctx context.Context, from, to string, now int64, limit int) (int, error)
WaitNotify(ctx context.Context, key string, timeout time.Duration) (bool, error)
}
// Payload is the subset of Laravel's JSON payload this port reads.
type Payload struct {
UUID string `json:"uuid"`
ID string `json:"id"`
DisplayName string `json:"displayName"`
Attempts int `json:"attempts"`
MaxTries *int `json:"maxTries"`
Timeout *int `json:"timeout"`
Data any `json:"data"`
}
// Reserved is what a worker holds while a job runs.
type Reserved struct {
Raw string // payload as pushed (attempts not yet incremented)
Reserved string // exact member stored in :reserved; needed to delete it
Payload Payload
}
// Queue mirrors RedisQueue: retry_after, block_for and migration_batch_size.
type Queue struct {
Store Store
Name string
RetryAfter time.Duration // 0 disables reserved-job migration (null in PHP)
BlockFor time.Duration // 0 means no BLPOP on :notify
MigrationBatch int // -1 migrates every due job
Now func() time.Time
}
func (q *Queue) key() string { return "queues:" + q.Name }
func (q *Queue) now() time.Time {
if q.Now != nil {
return q.Now()
}
return time.Now()
}
// Push appends a ready job; Later parks it in :delayed until availableAt.
func (q *Queue) Push(ctx context.Context, p Payload) error {
raw, err := json.Marshal(p)
if err != nil {
return err
}
return q.Store.Push(ctx, q.key(), string(raw))
}
func (q *Queue) Later(ctx context.Context, delay time.Duration, p Payload) error {
raw, err := json.Marshal(p)
if err != nil {
return err
}
return q.Store.Later(ctx, q.key()+":delayed", q.now().Add(delay).Unix(), string(raw))
}
// Pop follows RedisQueue::pop: migrate due delayed jobs, migrate reserved
// jobs whose retry_after expired, then pop atomically into :reserved.
func (q *Queue) Pop(ctx context.Context) (*Reserved, error) {
key := q.key()
now := q.now().Unix()
if _, err := q.Store.Migrate(ctx, key+":delayed", key, now, q.MigrationBatch); err != nil {
return nil, err
}
if q.RetryAfter > 0 {
if _, err := q.Store.Migrate(ctx, key+":reserved", key, now, q.MigrationBatch); err != nil {
return nil, err
}
}
return q.retrieve(ctx, key, true)
}
func (q *Queue) retrieve(ctx context.Context, key string, block bool) (*Reserved, error) {
until := q.now().Add(q.RetryAfter).Unix()
job, reserved, ok, err := q.Store.Pop(ctx, key, until)
if err != nil {
return nil, err
}
if !ok {
if block && q.BlockFor > 0 {
woke, err := q.Store.WaitNotify(ctx, key+":notify", q.BlockFor)
if err != nil || !woke {
return nil, err
}
return q.retrieve(ctx, key, false)
}
return nil, nil
}
r := &Reserved{Raw: job, Reserved: reserved}
if err := json.Unmarshal([]byte(reserved), &r.Payload); err != nil {
return nil, errors.Join(errors.New("redisqueue: undecodable reserved payload"), err)
}
return r, nil
}
// Delete acknowledges success: ZREM the exact reserved member.
func (q *Queue) Delete(ctx context.Context, r *Reserved) error {
return q.Store.DeleteReserved(ctx, q.key(), r.Reserved)
}
// Release moves the reserved member to :delayed (attempts already counted).
func (q *Queue) Release(ctx context.Context, r *Reserved, delay time.Duration) error {
return q.Store.Release(ctx, q.key(), r.Reserved, q.now().Add(delay).Unix())
}The Redis-backed store runs the scripts; an in-memory store with a mutex stands in for Lua atomicity in tests:
package redisqueue
import (
"context"
"errors"
"time"
"github.com/redis/go-redis/v9"
)
// RedisStore runs the same Lua bodies against a real Redis. go-redis Script
// sends EVALSHA and falls back to EVAL on NOSCRIPT; Laravel's phpredis
// connection sends EVAL with the full script text on every call.
type RedisStore struct {
C redis.UniversalClient
}
var (
push = redis.NewScript(pushScript)
later = redis.NewScript(laterScript)
pop = redis.NewScript(popScript)
release = redis.NewScript(releaseScript)
migrate = redis.NewScript(migrateScript)
)
func (s RedisStore) Push(ctx context.Context, key, payload string) error {
return push.Run(ctx, s.C, []string{key, key + ":notify"}, payload).Err()
}
func (s RedisStore) Later(ctx context.Context, key string, availableAt int64, payload string) error {
return later.Run(ctx, s.C, []string{key}, availableAt, payload).Err()
}
func (s RedisStore) Pop(ctx context.Context, key string, reserveUntil int64) (string, string, bool, error) {
res, err := pop.Run(ctx, s.C, []string{key, key + ":reserved", key + ":notify"}, reserveUntil).Slice()
if err != nil {
return "", "", false, err
}
if len(res) != 2 || res[0] == nil {
return "", "", false, nil
}
job, ok1 := res[0].(string)
reserved, ok2 := res[1].(string)
if !ok1 || !ok2 {
return "", "", false, errors.New("redisqueue: unexpected pop reply")
}
return job, reserved, true, nil
}
func (s RedisStore) Release(ctx context.Context, key, reserved string, availableAt int64) error {
return release.Run(ctx, s.C, []string{key + ":delayed", key + ":reserved"}, reserved, availableAt).Err()
}
func (s RedisStore) DeleteReserved(ctx context.Context, key, reserved string) error {
return s.C.ZRem(ctx, key+":reserved", reserved).Err()
}
func (s RedisStore) Migrate(ctx context.Context, from, to string, now int64, limit int) (int, error) {
res, err := migrate.Run(ctx, s.C, []string{from, to, to + ":notify"}, now, limit).Slice()
if errors.Is(err, redis.Nil) {
return 0, nil
}
return len(res), err
}
// WaitNotify is BLPOP on :notify. A zero timeout would block forever, which
// is why Laravel warns that block_for=0 delays SIGTERM handling.
func (s RedisStore) WaitNotify(ctx context.Context, key string, timeout time.Duration) (bool, error) {
_, err := s.C.BLPop(ctx, timeout, key).Result()
if errors.Is(err, redis.Nil) {
return false, nil
}
return err == nil, err
}The tests show FIFO order, delayed visibility, the lease-expiry double execution, the stale-delete no-op, and the migration batch cap:
package redisqueue
import (
"context"
"testing"
"time"
)
type clock struct{ t time.Time }
func (c *clock) now() time.Time { return c.t }
func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) }
func newQueue() (*Queue, *MemoryStore, *clock) {
c := &clock{t: time.Unix(1_700_000_000, 0)}
s := NewMemoryStore()
return &Queue{Store: s, Name: "default", RetryAfter: 90 * time.Second, MigrationBatch: -1, Now: c.now}, s, c
}
func TestFIFOAndAttemptsIncrementOnReserve(t *testing.T) {
ctx := context.Background()
q, s, _ := newQueue()
_ = q.Push(ctx, Payload{ID: "a", DisplayName: "App\\Jobs\\A"})
_ = q.Push(ctx, Payload{ID: "b", DisplayName: "App\\Jobs\\B"})
r, err := q.Pop(ctx)
if err != nil || r == nil {
t.Fatalf("pop: %v %v", r, err)
}
if r.Payload.ID != "a" || r.Payload.Attempts != 1 {
t.Fatalf("want a with attempts 1, got %s %d", r.Payload.ID, r.Payload.Attempts)
}
ready, _, reserved := s.Sizes("queues:default")
if ready != 1 || reserved != 1 {
t.Fatalf("ready=%d reserved=%d", ready, reserved)
}
if n := len(s.lists["queues:default:notify"]); n != 1 {
t.Fatalf("notify tokens=%d, want 1", n)
}
}
func TestDelayedJobIsInvisibleUntilDue(t *testing.T) {
ctx := context.Background()
q, _, c := newQueue()
_ = q.Later(ctx, 30*time.Second, Payload{ID: "later"})
if r, _ := q.Pop(ctx); r != nil {
t.Fatalf("delayed job popped early")
}
c.advance(30 * time.Second)
if r, _ := q.Pop(ctx); r == nil || r.Payload.ID != "later" {
t.Fatalf("due job not migrated")
}
}
func TestExpiredReservationIsRedelivered(t *testing.T) {
ctx := context.Background()
q, _, c := newQueue()
_ = q.Push(ctx, Payload{ID: "slow"})
first, _ := q.Pop(ctx)
// The worker is still running (or crashed) and never deleted the job.
c.advance(91 * time.Second)
second, _ := q.Pop(ctx)
if second == nil || second.Payload.ID != "slow" || second.Payload.Attempts != 2 {
t.Fatalf("expected redelivery with attempts 2, got %+v", second)
}
// The first worker's late Delete removes nothing: its member no longer exists.
if err := q.Delete(ctx, first); err != nil {
t.Fatal(err)
}
_, _, reserved := q.Store.(*MemoryStore).Sizes("queues:default")
if reserved != 1 {
t.Fatalf("second reservation must survive the stale delete, reserved=%d", reserved)
}
}
func TestReleaseMovesToDelayedAndDeleteAcks(t *testing.T) {
ctx := context.Background()
q, s, c := newQueue()
_ = q.Push(ctx, Payload{ID: "r"})
r, _ := q.Pop(ctx)
if err := q.Release(ctx, r, 10*time.Second); err != nil {
t.Fatal(err)
}
if _, delayed, reserved := s.Sizes("queues:default"); delayed != 1 || reserved != 0 {
t.Fatalf("delayed=%d reserved=%d", delayed, reserved)
}
c.advance(10 * time.Second)
again, _ := q.Pop(ctx)
if again == nil || again.Payload.Attempts != 2 {
t.Fatalf("released job should come back with attempts 2: %+v", again)
}
_ = q.Delete(ctx, again)
if ready, delayed, reserved := s.Sizes("queues:default"); ready+delayed+reserved != 0 {
t.Fatalf("queue not empty: %d %d %d", ready, delayed, reserved)
}
}
func TestMigrationBatchLimit(t *testing.T) {
ctx := context.Background()
q, s, c := newQueue()
q.MigrationBatch = 2
for _, id := range []string{"1", "2", "3"} {
_ = q.Later(ctx, time.Second, Payload{ID: id})
}
c.advance(time.Second)
n, _ := s.Migrate(ctx, "queues:default:delayed", "queues:default", c.now().Unix(), q.MigrationBatch)
if n != 2 {
t.Fatalf("migrated %d, want 2", n)
}
}Example: the database reservation
LockClause reproduces getLockForPopping engine/version thresholds; Reserve is the short transaction:
// Package dbqueue ports the reservation step of Laravel 13's database queue
// driver (Illuminate\Queue\DatabaseQueue::pop) to database/sql.
package dbqueue
import (
"context"
"database/sql"
"errors"
"strconv"
"strings"
"time"
)
// LockClause mirrors DatabaseQueue::getLockForPopping: SKIP LOCKED where the
// engine supports it, READPAST hints on SQL Server, plain FOR UPDATE otherwise.
func LockClause(engine, version string) string {
switch {
case engine == "mysql" && versionAtLeast(version, "8.0.1"),
engine == "mariadb" && versionAtLeast(version, "10.6.0"),
engine == "pgsql" && versionAtLeast(version, "9.5"),
engine == "vitess" && versionAtLeast(version, "19.0"):
return "FOR UPDATE SKIP LOCKED"
case engine == "sqlsrv":
return "with(rowlock,updlock,readpast)"
default:
return "FOR UPDATE"
}
}
func versionAtLeast(have, want string) bool {
h, w := strings.Split(have, "."), strings.Split(want, ".")
for i := 0; i < len(w); i++ {
var hv int
if i < len(h) {
hv, _ = strconv.Atoi(strings.TrimFunc(h[i], func(r rune) bool { return r < '0' || r > '9' }))
}
wv, _ := strconv.Atoi(w[i])
if hv != wv {
return hv > wv
}
}
return true
}
// Row is one record of the jobs table created by make:queue-table.
type Row struct {
ID int64
Queue string
Payload string
Attempts int
ReservedAt sql.NullInt64
AvailableAt int64
}
// Eligible is the WHERE clause in Go: available and unreserved, or reserved
// longer ago than retry_after (the worker is presumed dead or stuck).
func Eligible(r Row, now time.Time, retryAfter time.Duration) bool {
if !r.ReservedAt.Valid {
return r.AvailableAt <= now.Unix()
}
return r.ReservedAt.Int64 <= now.Add(-retryAfter).Unix()
}
// reserveSQL is the PostgreSQL text the query builder produces for pop().
const reserveSQL = `SELECT id, queue, payload, attempts, reserved_at, available_at
FROM jobs
WHERE queue = $1
AND ((reserved_at IS NULL AND available_at <= $2) OR reserved_at <= $3)
ORDER BY id ASC
LIMIT 1
FOR UPDATE SKIP LOCKED`
// Reserve claims the oldest eligible job in a short transaction. Concurrent
// workers skip rows another transaction has locked instead of waiting.
func Reserve(ctx context.Context, db *sql.DB, queue string, now time.Time, retryAfter time.Duration) (*Row, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback() }()
var r Row
err = tx.QueryRowContext(ctx, reserveSQL, queue, now.Unix(), now.Add(-retryAfter).Unix()).
Scan(&r.ID, &r.Queue, &r.Payload, &r.Attempts, &r.ReservedAt, &r.AvailableAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
r.Attempts++
r.ReservedAt = sql.NullInt64{Int64: now.Unix(), Valid: true}
if _, err := tx.ExecContext(ctx,
`UPDATE jobs SET reserved_at = $1, attempts = $2 WHERE id = $3`,
r.ReservedAt.Int64, r.Attempts, r.ID); err != nil {
return nil, err
}
return &r, tx.Commit()
}
// Delete acknowledges success. Release in Laravel deletes the row and inserts
// a new one carrying the same payload and attempts with a later available_at.
func Delete(ctx context.Context, db *sql.DB, id int64) error {
_, err := db.ExecContext(ctx, `DELETE FROM jobs WHERE id = $1`, id)
return err
}Example: the worker loop
Daemon keeps the order of stopIfNecessary checks and the memory exit code 12:
// Package worker ports the control flow of Laravel 13's Worker::daemon and
// Worker::stopIfNecessary: one job at a time, limits checked after each turn.
package worker
import (
"context"
"time"
)
// Exit codes and reasons follow Illuminate\Queue\Worker.
const (
ExitSuccess = 0
ExitMemoryLimit = 12
)
type Reason string
const (
Interrupted Reason = "interrupted"
MaxMemory Reason = "max-memory"
RestartSignal Reason = "restart-signal"
QueueEmpty Reason = "queue-empty"
MaxTimeExceeded Reason = "max-time"
MaxJobsExceeded Reason = "max-jobs"
)
// Options mirrors WorkerOptions / the queue:work flags.
type Options struct {
Sleep time.Duration // --sleep (default 3s) when no job is available
Rest time.Duration // --rest between jobs
MaxJobs int // --max-jobs
MaxTime time.Duration // --max-time
MemoryMB int // --memory (default 128)
StopWhenEmpty bool // --stop-when-empty
}
// Env abstracts the process: next job, memory, restart marker, signals.
type Env interface {
Next(ctx context.Context) (run func(context.Context), ok bool)
MemoryMB() int
RestartMarker() int64 // value of cache key illuminate:queue:restart
ShouldQuit() bool // set by SIGTERM/SIGINT/SIGQUIT
Now() time.Time
Sleep(time.Duration)
}
// Daemon runs until a stop condition holds, then returns (code, reason).
// A supervisor (Supervisor, systemd, Horizon) is expected to start it again.
func Daemon(ctx context.Context, env Env, o Options) (int, Reason) {
lastRestart := env.RestartMarker()
start := env.Now()
processed := 0
for {
run, ok := env.Next(ctx)
if ok {
processed++
run(ctx)
if o.Rest > 0 {
env.Sleep(o.Rest)
}
} else {
env.Sleep(o.Sleep)
}
// Same order as stopIfNecessary's match(true) arms.
switch {
case env.ShouldQuit():
return ExitSuccess, Interrupted
case o.MemoryMB > 0 && env.MemoryMB() >= o.MemoryMB:
return ExitMemoryLimit, MaxMemory
case env.RestartMarker() != lastRestart:
return ExitSuccess, RestartSignal
case o.StopWhenEmpty && !ok:
return ExitSuccess, QueueEmpty
case o.MaxTime > 0 && env.Now().Sub(start) >= o.MaxTime:
return ExitSuccess, MaxTimeExceeded
case o.MaxJobs > 0 && processed >= o.MaxJobs:
return ExitSuccess, MaxJobsExceeded
}
}
}The Go angle
Go programs usually do not need a Laravel-shaped queue: a goroutine pool reading from a broker client already has acknowledgments. The port is useful for two things. First, it makes the lease model testable without PHP: the TestExpiredReservationIsRedelivered case is the exact incident behind the docs' timeout warning. Second, a Go service sometimes must produce or consume Laravel jobs. Producing is possible (write the payload JSON with a PHP-serialized data.command, which is fragile); consuming Laravel payloads from Go is not realistic because data.command is PHP serialize() output. Exchange plain JSON messages over a broker instead. go-redis Script.Run sends EVALSHA and falls back to EVAL; Laravel's phpredis connection sends EVAL with the full script every time. For the database pattern, pgx or database/sql with FOR UPDATE SKIP LOCKED is the standard Go job-queue technique.
Laravel
Example: a job that uses every per-job knob
<?php
namespace App\Jobs;
use App\Models\Invoice;
use App\Services\InvoiceMailer;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\Attributes\WithoutRelations;
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\Middleware\Skip;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Support\Facades\Log;
use Throwable;
// Every attribute below ends up in the JSON payload (maxTries, timeout,
// backoff) or in a cache lock key (UniqueFor), so the worker can enforce it
// without unserializing the command first.
#[Tries(5)]
#[Timeout(60)] // must stay below the connection's retry_after (90)
#[Backoff([10, 30, 60])] // seconds before attempt 2, 3, 4+
#[UniqueFor(600)] // lock laravel_unique_job:...:{id} for at most 10 minutes
class SendInvoice implements ShouldQueue, ShouldBeUnique, ShouldBeEncrypted
{
// Queueable = Dispatchable + InteractsWithQueue + Bus\Queueable + SerializesModels.
use Queueable;
public function __construct(
// SerializesModels stores only class + id (a ModelIdentifier); the
// model is re-queried when the job runs. Do not ship loaded relations.
#[WithoutRelations]
public Invoice $invoice,
) {}
public function uniqueId(): string
{
return (string) $this->invoice->getKey();
}
/**
* Middleware runs inside the worker, around handle(), in this order.
*/
public function middleware(): array
{
return [
// Already sent by an earlier attempt? Delete the job without running it.
Skip::when(fn (): bool => $this->invoice->fresh()?->sent_at !== null),
// Limiter defined with RateLimiter::for('mail-provider', ...); over the
// limit the job is released back to the queue (one attempt spent).
new RateLimited('mail-provider'),
// One invoice email per customer at a time (needs a lock-capable cache).
(new WithoutOverlapping('customer:'.$this->invoice->customer_id))
->releaseAfter(30)
->expireAfter(120),
// After 10 exceptions within 5 minutes, back off for 1 minute.
(new ThrottlesExceptions(10, 5 * 60))->backoff(1),
];
}
public function handle(InvoiceMailer $mailer): void
{
// The provider call carries an idempotency key: a retry_after
// redelivery or a second attempt must not send a second email.
$mailer->send($this->invoice, idempotencyKey: 'invoice-'.$this->invoice->getKey());
$this->invoice->forceFill(['sent_at' => now()])->save();
}
/**
* Called on a fresh instance after the last attempt, before the
* failed_jobs row is written by the failed-job provider.
*/
public function failed(?Throwable $exception): void
{
Log::warning('invoice email failed', [
'invoice_id' => $this->invoice->getKey(),
'exception' => $exception ? $exception::class : null,
]);
}
}The connection settings that the job's timeout must respect:
<?php
// config/queue.php (excerpt). retry_after is a per-connection reservation
// lease; every worker --timeout and job #[Timeout] must be shorter than it.
return [
'default' => env('QUEUE_CONNECTION', 'database'),
'connections' => [
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => true, // hold dispatches until the outer DB transaction commits
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => 5, // BLPOP queues:default:notify for up to 5s; never 0 in production
'after_commit' => true,
'migration_batch_size' => 1000, // cap per pop on how many due jobs a Lua call moves
],
'sync' => ['driver' => 'sync'],
'null' => ['driver' => 'null'],
],
'batching' => [
'database' => env('DB_CONNECTION', 'pgsql'),
'table' => 'job_batches',
],
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'pgsql'),
'table' => 'failed_jobs',
],
];Rate limiters, global failure hooks, QueueBusy, and driver registration in one provider:
<?php
namespace App\Providers;
use App\Queue\OutboxConnector;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\Events\QueueBusy;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class QueueServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Named limiter used by the RateLimited job middleware.
RateLimiter::for('mail-provider', function (object $job) {
return Limit::perMinute(60);
});
// Global failure hook (fires on JobFailed for every connection).
Queue::failing(function (JobFailed $event) {
Log::error('job failed', [
'connection' => $event->connectionName,
'job' => $event->job->resolveName(),
'uuid' => $event->job->uuid(),
]);
});
// Dispatched by `php artisan queue:monitor redis:default --max=100`.
Event::listen(function (QueueBusy $event) {
Log::critical('queue busy', [
'connection' => $event->connectionName,
'queue' => $event->queue,
'size' => $event->size,
]);
});
// A custom driver: config/queue.php can now use 'driver' => 'outbox'.
Queue::extend('outbox', function () {
return new OutboxConnector($this->app->make('db'));
});
}
}Example: batches and chains
<?php
namespace App\Jobs;
use App\Services\CsvImporter;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
#[Tries(3)]
class ImportCsvChunk implements ShouldQueue
{
use Batchable, Queueable;
public function __construct(
public string $importId,
public int $fromRow,
public int $toRow,
) {}
public function handle(CsvImporter $importer): void
{
// A cancelled batch still has queued jobs; they must stop themselves.
if ($this->batch()?->cancelled()) {
return;
}
// Upsert by (import_id, row_number) so a redelivered chunk is harmless.
$importer->importRows($this->importId, $this->fromRow, $this->toRow);
}
}<?php
namespace App\Services;
use App\Jobs\ImportCsvChunk;
use App\Jobs\NotifyImportFinished;
use App\Jobs\PublishCatalog;
use App\Jobs\RebuildSearchIndex;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Log;
use Throwable;
class ImportPipeline
{
/**
* Parallel fan-out: every chunk is an independent job; one job_batches row
* tracks total_jobs, pending_jobs, failed_jobs and failed_job_ids.
*/
public function start(string $importId, int $rows, int $chunk = 500): Batch
{
$jobs = [];
for ($from = 1; $from <= $rows; $from += $chunk) {
$jobs[] = new ImportCsvChunk($importId, $from, min($from + $chunk - 1, $rows));
}
return Bus::batch($jobs)
->name("import:{$importId}")
->allowFailures() // keep going; without it the first failure cancels the batch
->progress(function (Batch $batch) {
Log::info('import progress', ['id' => $batch->id, 'percent' => $batch->progress()]);
})
->then(function (Batch $batch) use ($importId) {
// Only when pending_jobs reaches 0: a failed job keeps its pending slot
// until a later retry of it succeeds.
Bus::chain([
new RebuildSearchIndex($importId),
new PublishCatalog($importId),
])->catch(function (Throwable $e) use ($importId) {
Log::error('post-import chain failed', ['import' => $importId, 'error' => $e::class]);
})->onQueue('imports')->dispatch();
})
->catch(function (Batch $batch, Throwable $e) {
// First failed job only (failed_jobs === 1).
Log::warning('import has failures', ['id' => $batch->id]);
})
->finally(function (Batch $batch) use ($importId) {
// Every job ran (successfully or failed) exactly once.
NotifyImportFinished::dispatch($importId, $batch->failedJobs);
})
->onConnection('redis')
->onQueue('imports')
->dispatch();
}
}Example: a custom connector
<?php
namespace App\Queue;
use Illuminate\Contracts\Queue\Job as JobContract;
use Illuminate\Contracts\Queue\Queue as QueueContract;
use Illuminate\Database\DatabaseManager;
use Illuminate\Queue\Connectors\ConnectorInterface;
use Illuminate\Queue\Jobs\Job;
use Illuminate\Queue\Queue;
/**
* Skeleton of a custom driver. BrokerClient stands in for your SDK (NATS,
* Pub/Sub, an HTTP queue...). Laravel needs three pieces: a connector that
* QueueManager calls with the connection config, a Queue that pushes and
* pops raw payload strings, and a Job wrapper that knows how to delete
* (ack) and release (nack with delay) one delivery.
*/
interface BrokerClient
{
public function publish(string $queue, string $payload, int $delaySeconds = 0): string;
/** @return array{id: string, body: string, deliveries: int}|null */
public function receive(string $queue, int $leaseSeconds): ?array;
public function ack(string $queue, string $id): void;
public function nack(string $queue, string $id, int $delaySeconds): void;
public function depth(string $queue): int;
}
class OutboxConnector implements ConnectorInterface
{
public function __construct(private DatabaseManager $db) {}
public function connect(array $config)
{
$client = app()->make($config['client']); // bound BrokerClient implementation
return new OutboxQueue($client, $config['queue'] ?? 'default', (int) ($config['lease'] ?? 90));
}
}
class OutboxQueue extends Queue implements QueueContract
{
public function __construct(
private BrokerClient $client,
private string $default,
private int $lease,
) {}
public function size($queue = null)
{
return $this->client->depth($this->getQueue($queue));
}
public function pendingSize($queue = null)
{
return $this->size($queue);
}
public function delayedSize($queue = null)
{
return 0; // unknown for this broker
}
public function reservedSize($queue = null)
{
return 0;
}
public function creationTimeOfOldestPendingJob($queue = null)
{
return null;
}
public function push($job, $data = '', $queue = null)
{
// createPayload builds the same JSON every driver uses (uuid,
// displayName, job, maxTries, backoff, timeout, retryUntil, data).
// enqueueUsing honours afterCommit and fires JobQueueing/JobQueued.
return $this->enqueueUsing(
$job,
$this->createPayload($job, $this->getQueue($queue), $data),
$queue,
null,
fn ($payload, $queue) => $this->pushRaw($payload, $queue),
);
}
public function pushRaw($payload, $queue = null, array $options = [])
{
return $this->client->publish($this->getQueue($queue), $payload);
}
public function later($delay, $job, $data = '', $queue = null)
{
return $this->enqueueUsing(
$job,
$this->createPayload($job, $this->getQueue($queue), $data, $delay),
$queue,
$delay,
fn ($payload, $queue, $delay) => $this->client->publish(
$this->getQueue($queue), $payload, $this->secondsUntil($delay)
),
);
}
public function pop($queue = null)
{
$queue = $this->getQueue($queue);
$message = $this->client->receive($queue, $this->lease);
return $message === null
? null
: new OutboxJob($this->container, $this->client, $message, $this->connectionName, $queue);
}
public function getQueue($queue): string
{
return $queue ?: $this->default;
}
}
class OutboxJob extends Job implements JobContract
{
/** @param array{id: string, body: string, deliveries: int} $message */
public function __construct(
$container,
private BrokerClient $client,
private array $message,
$connectionName,
$queue,
) {
$this->container = $container;
$this->connectionName = $connectionName;
$this->queue = $queue;
}
public function getJobId()
{
return $this->message['id'];
}
public function getRawBody()
{
return $this->message['body'];
}
public function attempts()
{
// The broker's delivery counter plays the role of payload['attempts'].
return $this->message['deliveries'];
}
public function delete()
{
parent::delete();
$this->client->ack($this->queue, $this->getJobId());
}
public function release($delay = 0)
{
parent::release($delay);
$this->client->nack($this->queue, $this->getJobId(), (int) $delay);
}
}The Laravel angle
The documented surface (attributes #[Tries], #[Timeout], #[Backoff], #[UniqueFor], #[RetryFor], #[WithoutRelations], middleware, Bus::batch, Bus::chain) is thin; the behaviour lives in four files: Queue.php (payload), the driver (RedisQueue.php or DatabaseQueue.php), Worker.php (attempts, timeouts, failure), and CallQueuedHandler.php (middleware, unique-lock release, chain and batch bookkeeping). Attributes are read by ReadsClassAttributes::getAttributeValue, and a non-default property value still overrides an attribute, so legacy public $tries = 5 keeps working. Queue::fake(), Bus::fake(), and Bus::assertBatched() test dispatch without these internals; see testing messaging.
Broker differences
RabbitMQ
vladimir-yuldashev/laravel-queue-rabbitmq registers a rabbitmq connector with QueueManager::addConnector, so jobs keep the Laravel payload and run through the normal worker. The mapping, from RabbitMQQueue.php and Jobs/RabbitMQJob.php on the package's master branch:
| Laravel operation | AMQP action in the package |
|---|---|
push | basic_publish persistent message (delivery_mode 2), correlation_id = payload id |
later($delay) | Declare QUEUE.delay.TTL_MS with x-message-ttl, x-dead-letter-exchange, x-dead-letter-routing-key back to the work queue, x-expires = 2 × TTL; publish there |
pop (queue:work) | basic_get (polling) |
rabbitmq:consume | basic_consume with basic_qos prefetch; about 2× faster per the README, one queue only |
delete() | basic_ack |
release($delay) | Publish a new copy with laravel.attempts header via laterRaw, then basic_ack the original |
markAsFailed() | basic_reject without requeue; with reroute_failed the queue's DLX routes it |
attempts() | laravel.attempts header + 1 |
There is no retry_after: RabbitMQ redelivers an unacknowledged message when the consumer's channel or connection closes, not after a Laravel lease, so a hung worker holds its message until its connection ends. Delays use per-TTL queues and dead-lettering, not the delayed-message exchange plugin; each distinct delay creates a queue. The Go program reproduces the delay-queue topology and a prefetching manual-ack consumer:
// Command rabbitmq reproduces how vladimir-yuldashev/laravel-queue-rabbitmq
// maps a delayed Laravel job onto AMQP: a per-TTL delay queue whose
// dead-letter exchange routes the expired message back to the work queue.
// It exits unless AMQP_URL is set, so it compiles and runs without a broker.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
// delayQueueArgs matches RabbitMQQueue::getDelayQueueArguments.
func delayQueueArgs(exchange, routingKey string, ttlMS int64) amqp.Table {
return amqp.Table{
"x-dead-letter-exchange": exchange,
"x-dead-letter-routing-key": routingKey,
"x-message-ttl": ttlMS,
"x-expires": ttlMS * 2,
}
}
func main() {
url := os.Getenv("AMQP_URL")
if url == "" {
fmt.Println("AMQP_URL not set; nothing to do")
return
}
conn, err := amqp.Dial(url)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatal(err)
}
if err := ch.Confirm(false); err != nil {
log.Fatal(err)
}
const work = "default"
if _, err := ch.QueueDeclare(work, true, false, false, false, nil); err != nil {
log.Fatal(err)
}
// release(30) in the package publishes a NEW message to default.delay.30000
// and acks the original delivery. The default exchange ("") routes by name.
ttl := int64(30_000)
delayQ := fmt.Sprintf("%s.delay.%d", work, ttl)
if _, err := ch.QueueDeclare(delayQ, true, false, false, false, delayQueueArgs("", work, ttl)); err != nil {
log.Fatal(err)
}
payload := []byte(`{"uuid":"00000000-0000-4000-8000-000000000001","displayName":"App\\Jobs\\SendInvoice","attempts":0}`)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
conf, err := ch.PublishWithDeferredConfirmWithContext(ctx, "", delayQ, true, false, amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
CorrelationId: "job-id-from-payload",
Headers: amqp.Table{"laravel": amqp.Table{"attempts": int32(1)}},
Body: payload,
})
if err != nil {
log.Fatal(err)
}
if ok, err := conf.WaitContext(ctx); err != nil || !ok {
log.Fatalf("publish not confirmed: ok=%v err=%v", ok, err)
}
// A consumer like rabbitmq:consume: prefetch, manual ack after the job.
if err := ch.Qos(10, 0, false); err != nil {
log.Fatal(err)
}
deliveries, err := ch.Consume(work, "worker-1", false, false, false, false, nil)
if err != nil {
log.Fatal(err)
}
for d := range deliveries {
log.Printf("job %s attempts header=%v", d.CorrelationId, d.Headers["laravel"])
// Success -> Ack; terminal failure -> Reject(false) so a DLX can route it.
if err := d.Ack(false); err != nil {
log.Fatal(err)
}
}
}<?php
// config/queue.php connection for vladimir-yuldashev/laravel-queue-rabbitmq.
// The package registers the 'rabbitmq' connector with QueueManager::addConnector.
return [
'rabbitmq' => [
'driver' => 'rabbitmq',
'hosts' => [
[
'host' => env('RABBITMQ_HOST', '127.0.0.1'),
'port' => env('RABBITMQ_PORT', 5672),
'user' => env('RABBITMQ_USER', 'guest'),
'password' => env('RABBITMQ_PASSWORD', 'guest'),
'vhost' => env('RABBITMQ_VHOST', '/'),
],
],
'options' => [
'queue' => [
// Publish through a topic exchange instead of the default exchange.
'exchange' => 'application-x',
'exchange_type' => 'topic',
'exchange_routing_key' => '',
// markAsFailed() rejects the delivery; with this, the queue is
// declared with x-dead-letter-exchange so RabbitMQ routes it on.
'reroute_failed' => true,
'failed_exchange' => 'failed-exchange',
'failed_routing_key' => 'application-x.%s',
// Released (delayed) messages get AMQP priority = attempts.
'prioritize_delayed' => false,
'queue_max_priority' => 10,
],
],
// 'horizon' swaps in a Queue class that emits the events Horizon reads.
'worker' => env('RABBITMQ_WORKER', 'default'),
],
];Kafka
mateusjunges/laravel-kafka is not a Queue driver. It provides a producer (Kafka::publish('broker')->onTopic(...)->withMessage(...)->send()) and a consumer builder (Kafka::consumer($topics, $groupId, $brokers)->withHandler(...)->build()->consume()) that you run as a long-lived command. Kafka has no per-message pop, release, or delete: a consumer group owns partitions and commits an offset that covers every earlier record in the partition. A Laravel-style “release this one for 30 seconds” does not exist; failure handling means retry topics, a DLQ topic (withDlq()), or stopping. The package's default is auto-commit after the handler returns; withManualCommit() with $consumer->commit($message) gives at-least-once control.
The common Laravel pattern is a bridge: consume from Kafka, dispatch a Laravel job, then commit, so Kafka's ordering and replay sit in front of Laravel's retry and failure machinery:
<?php
namespace App\Console\Commands;
use App\Jobs\ProcessOrder;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
/**
* mateusjunges/laravel-kafka is not a queue driver: it is a long-running
* consumer you start yourself (artisan command under Supervisor). This one
* bridges a Kafka topic into Laravel's queue and commits the offset only
* after the job is durably queued.
*/
class ConsumeOrders extends Command
{
protected $signature = 'orders:consume';
protected $description = 'Bridge the orders topic into the Laravel queue';
public function handle(): int
{
$consumer = Kafka::consumer(['orders'], 'billing', env('KAFKA_BROKERS', 'localhost:9092'))
->withManualCommit()
->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) {
// dispatch() returns after the job reached the queue store
// (no after_commit here: there is no open DB transaction).
ProcessOrder::dispatch($message->getBody(), $message->getKey());
// At-least-once: a crash between dispatch and commit queues the
// order twice, so ProcessOrder must be idempotent on the order id.
$consumer->commit($message);
})
->build();
$consumer->consume();
return self::SUCCESS;
}
}The same loop in Go with franz-go commits only records that succeeded and stops on failure, because a later commit would skip an earlier failed record:
// Command kafka shows why Kafka does not fit Laravel's Queue contract: there is
// no per-message pop/release/delete, only an ordered partition log and a
// committed offset per consumer group. It exits unless KAFKA_BROKERS is set.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/twmb/franz-go/pkg/kgo"
)
func handle(r *kgo.Record) error {
// Dispatch a Laravel-style job here, or do the work directly.
log.Printf("partition=%d offset=%d key=%s", r.Partition, r.Offset, r.Key)
return nil
}
func main() {
brokers := os.Getenv("KAFKA_BROKERS")
if brokers == "" {
fmt.Println("KAFKA_BROKERS not set; nothing to do")
return
}
cl, err := kgo.NewClient(
kgo.SeedBrokers(strings.Split(brokers, ",")...),
kgo.ConsumerGroup("billing"),
kgo.ConsumeTopics("orders"),
kgo.DisableAutoCommit(),
)
if err != nil {
log.Fatal(err)
}
defer cl.Close()
ctx := context.Background()
for {
fetches := cl.PollFetches(ctx)
if errs := fetches.Errors(); len(errs) > 0 {
log.Fatalf("fetch errors: %v", errs)
}
var done []*kgo.Record
var failed error
fetches.EachRecord(func(r *kgo.Record) {
if failed != nil {
return
}
// "release(30)" has no Kafka equivalent: a failed record either
// blocks the partition or is copied to a retry/DLQ topic.
if err := handle(r); err != nil {
failed = err
return
}
done = append(done, r)
})
// Commit only what succeeded; an offset commit covers every earlier record.
if err := cl.CommitRecords(ctx, done...); err != nil {
log.Fatal(err)
}
if failed != nil {
log.Fatalf("stopping on failure to keep the partition position: %v", failed)
}
}
}Redis Streams
Laravel's redis driver needs only list and sorted-set commands plus EVAL, and implements delays and leases itself with sorted-set scores. Streams would give server-side delivery tracking (the PEL), consumer groups, XACK, and XAUTOCLAIM, but no native delay, so a stream-based driver would still need a sorted set for later(). Use streams through the Redis facade when you need fan-out to several consumer groups or replay by ID:
<?php
namespace App\Console\Commands;
use App\Jobs\ProcessOrder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
/**
* A Redis Streams consumer group through the Redis facade (phpredis). This is
* NOT Laravel's redis queue driver, which uses lists and sorted sets; it is a
* separate consumer you run under Supervisor.
*/
class RedisStreamWorker extends Command
{
protected $signature = 'orders:stream-work {--consumer=worker-1}';
protected $description = 'Consume the orders stream with a consumer group';
public function handle(): int
{
$stream = 'orders:stream';
$group = 'billing';
$consumer = (string) $this->option('consumer');
// Producer side, for comparison with RPUSH queues:NAME:
// Redis::xadd($stream, '*', ['order_id' => '42']);
while (true) {
// phpredis: xReadGroup($group, $consumer, [$stream => '>'], $count, $blockMs)
$batch = Redis::xreadgroup($group, $consumer, [$stream => '>'], 10, 5000);
foreach ($batch[$stream] ?? [] as $id => $fields) {
ProcessOrder::dispatch($fields, $fields['order_id'] ?? null);
// Acknowledge only after the work is handed off; unacknowledged
// ids stay in the group's PEL for XAUTOCLAIM recovery.
Redis::xack($stream, $group, [$id]);
}
}
}
}// Command redisstreams contrasts Laravel's list-based Redis driver with a
// Redis Streams consumer group: delivery state lives in the server-side PEL
// instead of a :reserved sorted set. It exits unless REDIS_ADDR is set.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
fmt.Println("REDIS_ADDR not set; nothing to do")
return
}
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
const stream, group = "jobs:stream", "workers"
if err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err(); err != nil &&
!strings.HasPrefix(err.Error(), "BUSYGROUP") {
log.Fatal(err)
}
if err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: stream, Values: map[string]any{
"displayName": "App\\Jobs\\SendInvoice", "payload": `{"invoice":42}`,
}}).Err(); err != nil {
log.Fatal(err)
}
for {
res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: group, Consumer: "worker-1", Streams: []string{stream, ">"},
Count: 10, Block: 5 * time.Second,
}).Result()
if err == redis.Nil {
continue
}
if err != nil {
log.Fatal(err)
}
for _, s := range res {
for _, m := range s.Messages {
log.Printf("id=%s job=%v", m.ID, m.Values["displayName"])
// XACK removes the entry from this group's PEL. There is no
// retry_after: idle entries are recovered with XAUTOCLAIM.
if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
log.Fatal(err)
}
}
}
}
}| Concern | Laravel redis driver | Redis Streams consumer group |
|---|---|---|
| Ready work | List queues:NAME | Stream entries after the group's last-delivered ID |
| In-flight tracking | :reserved sorted set (client-maintained) | PEL (server-maintained) |
| Acknowledge | ZREM of the exact member | XACK stream group id |
| Recovery | retry_after score migration on the next pop | XPENDING + XAUTOCLAIM by idle time |
| Delay | :delayed sorted set | Not native |
| Fan-out | One consumer per job | Many groups read the same entries |
| History | Deleted on success | Kept until XTRIM/MAXLEN |
Other brokers follow the same split. Amazon SQS is a built-in driver with a visibility timeout instead of retry_after. NATS JetStream and Apache Pulsar have community drivers or are used through consumer commands like the Kafka bridge; see other brokers.
In production systems
- The Laravel 13.x docs state that
retry_aftermust exceed the worker--timeout, and Horizon's docs repeat the rule for supervisor timeouts; both are encoded in the Redis reserved score and the databasereserved_atcomparison read above. DatabaseQueue::getLockForPopping(13.x) selectsFOR UPDATE SKIP LOCKEDfor MySQL 8.0.1+, MariaDB 10.6+, PostgreSQL 9.5+, and Vitess 19+; PostgreSQL'sSELECTdocumentation describesSKIP LOCKEDas suitable to “avoid lock contention with multiple consumers accessing a queue-like table”.- Horizon's documentation states it requires Redis and is not compatible with Redis Cluster, while
RedisQueueitself wraps queue names in hash tags on cluster connections so its multi-key Lua scripts stay in one slot. - The RabbitMQ package README documents that
queue:workusesbasic_getandrabbitmq:consumeusesbasic_consume; its source shows releases republish a copy and acknowledge the original.
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel app on PostgreSQL uses the database driver: with after_commit off and the queue on the same database connection, the order insert and the jobs insert share one transaction, which gives outbox-like atomicity for free. Two Supervisor programs run queue:work --queue=high and queue:work --queue=default. The simplest correct setup: after_commit on, job timeout 60, retry_after 90, queue:restart on deploy.
Modular monolith: queues per module
Billing and Catalog share a codebase but own their queues (billing, catalog) and workers, so a slow catalog import cannot delay invoices. Job classes are internal to their module; cross-module work is triggered by domain events with queued listeners (ShouldQueueAfterCommit). Rename job classes only after draining, because payloads carry class names.
Microservices: Laravel jobs stay inside one service
A Laravel orders service publishes OrderPlaced to RabbitMQ or Kafka as plain JSON (via the outbox), and a Go shipping service consumes it. Inside each Laravel service, a consumer command turns broker messages into Laravel jobs for retries and failure tracking. Laravel job payloads never cross service boundaries: they contain PHP-serialized objects and class names. Idempotency by event id is enforced at the consumer, see idempotent consumers.
1 orders (Laravel) -> outbox row + COMMIT
2 relay -> RabbitMQ exchange orders.events: {"event_id":"e-9","type":"OrderPlaced"}
3 billing (Laravel) -> rabbitmq:consume -> ChargeOrder job (uuid u-1) -> handle()
4 shipping (Go) -> amqp091 consumer -> ack after insert ON CONFLICT (event_id) DO NOTHINGDistributed data: replicas, Redis failover, regions
A job that reads from a read replica can miss a row committed on the primary a moment ago; use the primary (sticky connection) for job reads that follow a dispatch. Redis replication is asynchronous: after a failover, recently pushed jobs or recent ZREMs can be lost or resurrected, so a job may disappear or run twice; use AOF persistence and idempotent jobs. Redis Cluster requires all four keys of a queue in one slot, which RedisQueue ensures with {name} hash tags. Multi-region setups run workers per region against regional queues; a global queue across regions is a broker's job, see replication and failover.
Scaling path
| Load | Design | Example |
|---|---|---|
| 1× (hundreds of jobs/min) | database driver, 2–4 Supervisor workers | Emails and PDFs for a B2B app |
| 10× (thousands/min) | redis + Horizon, per-queue supervisors, block_for, batches for imports | Marketplace with notification spikes |
| 100× (hundreds of thousands/min) | Dedicated Redis per queue group or SQS, migration_batch_size, Kafka/RabbitMQ in front for fan-out, idempotent jobs everywhere | Event ingestion bridged from Kafka into short Laravel jobs |
At each step the per-job lease rule stays the same; what changes is where the bottleneck sits: database row churn, then a single Redis primary's CPU (Lua scripts are single-threaded), then cross-service fan-out that Laravel queues were never meant to provide.
Lab
The Go tests below were run for this chapter. Every Redis, database, and Laravel experiment after them is expected, not run: use a disposable local environment; no Docker or Compose is required by this chapter.
1. Run the Go port (run)
cd docs/snippets/messaging/laravel-queue-internals/go
go test ./...
# ok academy/laravel-queue-internals/dbqueue
# ok academy/laravel-queue-internals/redisqueue
# ok academy/laravel-queue-internals/worker
go test -run TestExpiredReservationIsRedelivered -v ./redisqueue
# --- PASS: TestExpiredReservationIsRedelivered2. Watch the Redis commands of one dispatch (expected, not run)
redis-cli MONITOR # terminal 1
php artisan tinker --execute='App\Jobs\SendInvoice::dispatch(App\Models\Invoice::find(7));' # terminal 2
php artisan queue:work redis --once # terminal 2
# expected in terminal 1:
# "EVAL" "-- Push the job onto the queue..." "2" "queues:default" "queues:default:notify" "{...}"
# "EVAL" "-- Get all of the jobs with an expired..." "3" "queues:default:delayed" "queues:default" ...
# "EVAL" "-- Pop the first job off of the queue..." "3" "queues:default" "queues:default:reserved" ...
# "zrem" "queues:default:reserved" "{...\"attempts\":1}"3. Reproduce a duplicate execution (expected, not run)
# config/queue.php redis connection: 'retry_after' => 10
# Job handle(): sleep(15); Log::info('ran', ['uuid' => $this->job->uuid()]);
php artisan queue:work redis --timeout=30 & # worker A
php artisan queue:work redis --timeout=30 & # worker B
php artisan tinker --execute='App\Jobs\SlowJob::dispatch();'
# expected: two "ran" log lines with the same uuid, about 10 s apart.
# Set retry_after to 40 and repeat: one line.4. SKIP LOCKED with two sessions (expected, not run)
psql session 1 psql session 2
1 BEGIN;
2 SELECT id FROM jobs WHERE queue='default'
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- 41
3 BEGIN;
4 SELECT id FROM jobs WHERE queue='default'
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED; -- 42
5 -- remove SKIP LOCKED: the statement waits for session 1
6 COMMIT;5. Graceful restart and limits (expected, not run)
php artisan queue:work redis --max-jobs=3 -v
# expected: exits after the third job with status 0 (WorkerStopping reason MaxJobsExceeded)
php artisan queue:work redis --memory=1 -v
# expected: exits after the first job with status 12
php artisan queue:restart
# expected: running workers exit after their current job6. Batch counters (expected, not run)
-- after Bus::batch([...4 jobs...])->allowFailures()->dispatch() with one job throwing
SELECT total_jobs, pending_jobs, failed_jobs, failed_job_ids, finished_at
FROM job_batches ORDER BY created_at DESC LIMIT 1;
-- expected: 4 | 1 | 1 | ["<uuid>"] | NULL -> then() not called, finally() calledCommon misconceptions
| Belief | Reality |
|---|---|
| Laravel queues deliver exactly once | Leases expire and redeliver; jobs must be idempotent |
--timeout retries a slow job | It kills the worker; the lease expiry causes the retry |
| The Redis driver uses Redis Streams | Lists, sorted sets, and EVAL only |
| The database driver keeps the row locked while running | The lock lasts only for the reservation transaction |
ShouldBeUnique means "processed once" | It only blocks a second enqueue while the lock exists |
A failed dispatch is always visible | A unique-lock conflict skips silently |
| Rate-limited jobs wait for free | Each release consumes an attempt |
then() runs after every batch job finished | Only when all succeeded; use finally() |
Every failure is in failed_jobs | Only failures processed by queue:work (or Horizon) |
| Workers reload code automatically | Only queue:listen does; daemons need queue:restart |
after_commit is an outbox | A crash after commit and before push loses the job |
| Horizon is a separate driver | It uses the framework Redis driver underneath |
--queue=high,default balances queues | It is strict priority; default waits while high has work |
| Any Redis eviction policy is fine | An evicted queue key loses jobs; use noeviction |
Cheat sheet
| Topic | Remember |
|---|---|
| Drivers | sync, database, beanstalkd, sqs, redis, null; RabbitMQ/Kafka via packages |
| Payload | uuid, displayName, job, maxTries, backoff, timeout, retryUntil, data.command |
| Redis keys | queues:NAME list, :delayed ZSET, :reserved ZSET, :notify list |
| Redis scripts | push, later, pop, release, migrateExpiredJobs, size, clear |
| Lease | Job timeout below worker/Horizon timeout below retry_after |
| Database | FOR UPDATE SKIP LOCKED, then reserved_at + attempts; release inserts a new row |
| Attempts | Incremented at reservation; releases, crashes and timeouts consume them |
| Worker exit | queue:restart, --max-jobs, --max-time, --memory (code 12), signals |
| Middleware | RateLimited, WithoutOverlapping, ThrottlesExceptions, Skip |
| Unique | Lock laravel_unique_job:NAME:ID; always set #[UniqueFor] |
| After commit | after_commit => true; not a replacement for an outbox |
| Batches | job_batches counters; then = all succeeded, finally = all ran |
| Chains | Remaining jobs ride in chained; failure stops and calls catch |
| Failed jobs | queue:failed, queue:retry, queue:prune-failed, failed() on a fresh instance |
| Horizon | Supervisors, balance auto/simple/false, horizon:terminate on deploy |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does the Redis pop script do, in order? Good to know
Answer
Answer: LPOP the ready list, decode the payload, increment attempts, ZADD the new payload to the reserved set with score now plus retry_after, and LPOP one token from the notify list, all inside one EVAL.
2 — Why can a job with #[Timeout(120)] run twice on a connection with retry_after 90? Must-know
Answer
Answer: At 90 seconds the next pop migrates the still-running job's reserved entry back to the ready list, and another worker reserves it while the first is still executing.
3 — What happens to a job when its worker's timeout alarm fires? Must-know
Answer
Answer: The handler may mark it failed if this was the last attempt or failOnTimeout is set, fires JobTimedOut, and kills the worker process. Otherwise the job stays reserved until retry_after expires and is then retried.
4 — Which lock clause does Laravel use on MySQL 5.7, and what is the consequence? Good to know
Answer
Answer: Plain FOR UPDATE, so concurrent workers wait on the same first row instead of skipping it, which serializes reservations.
5 — Why does a rate-limited job with #[Tries(3)] sometimes fail without running? Important
Answer
Answer: Each RateLimited release is followed by a new reservation that increments attempts. Three releases exhaust the tries before handle() is reached.
6 — When does ShouldBeUnique release its lock, and how can the lock get stuck? Important
Answer
Answer: After successful processing or final failure. If the queued job disappears (queue cleared, eviction) and uniqueFor is 0, nobody releases it and later dispatches are skipped forever.
7 — Is after_commit enough to guarantee the job is queued after the transaction? Important
Answer
Answer: It prevents dispatch before commit and drops jobs on rollback, but a crash between COMMIT and the push loses the job. An outbox is needed for that guarantee.
8 — A batch with allowFailures() had one failed job. Which callbacks fired? Good to know
Answer
Answer: catch on the first failure and finally once every job ran; then did not fire because pending_jobs is still 1 until the failed job is retried successfully.
9 — Why is a failure under the sync driver not in failed_jobs? Important
Answer
Answer: The failed_jobs row is written by the JobFailed listener that queue:work registers; with sync the exception is thrown to the caller.
10 — Why is mateusjunges/laravel-kafka not a queue driver? Important
Answer
Answer: Kafka has no per-message pop, release, or delete; consumers own partitions and commit offsets that cover all earlier records, so the package provides producer and consumer APIs you run as commands instead.
11 — How does Horizon differ from running queue:work under Supervisor? Must-know
Answer
Answer: Horizon starts supervisors from config, each with process pools that it can balance per queue by time, size, or log strategy, and adds metrics; it still uses the framework Redis driver and still needs a process monitor for its master process.
Glossary
| Term | Meaning |
|---|---|
ShouldQueue | Marker interface; makes the bus queue the command instead of running it |
dispatch / PendingDispatch | Helper that queues a job when the pending object is destroyed |
dispatchSync / dispatchAfterResponse | Run now on sync / run after the HTTP response in-process |
Queueable | Trait bundle: Dispatchable, InteractsWithQueue, Bus\Queueable, SerializesModels |
SerializesModels | Stores models as ModelIdentifier and re-queries them on the worker |
ModelIdentifier | Class, key(s), relations, and connection of a serialized model |
WithoutRelations | Attribute that drops loaded relations from serialized models |
CallQueuedClosure | Wrapper that queues a closure through SerializableClosure |
CallQueuedHandler | The payload's job target; unserializes the command, runs middleware and handle() |
| Payload | JSON stored per job: uuid, displayName, job, maxTries, backoff, timeout, retryUntil, data |
uuid | Per-dispatch identity used by failed jobs and batches |
displayName | Name shown in tools and used in the unique lock key |
maxTries / maxExceptions | Attempt limit / exception limit enforced by the worker |
backoff | Seconds before the next attempt; a list indexed by attempt number |
timeout | Seconds before the worker's SIGALRM kills the process |
retryUntil / RetryFor | Deadline that replaces the attempt limit |
retry_after | Connection lease: seconds before a reserved job is handed out again |
block_for | Seconds the Redis driver blocks on the notify list with BLPOP |
migration_batch_size | Cap on jobs moved per migration script call |
| Redis list | Ready jobs in queues:NAME, RPUSH in, LPOP out |
| Sorted set | :delayed and :reserved keys scored by Unix timestamps |
:delayed | Sorted set of jobs waiting for available_at |
:reserved | Sorted set of leased jobs, score = lease deadline |
:notify | List of tokens enabling BLPOP wake-ups |
Lua / LuaScripts | Server-side scripts that make multi-key moves atomic |
pop / release / migrateExpiredJobs | The three central scripts: reserve, delay a reserved job, move due jobs |
EVAL / EVALSHA | Run a Lua script by text / by SHA1 digest |
RPUSH, LPOP, BLPOP | List append, pop, blocking pop |
ZADD, ZRANGEBYSCORE, ZREM | Sorted-set add, range by score, remove |
SKIP LOCKED | Row-lock option that skips rows locked by other transactions |
lockForUpdate | Query-builder FOR UPDATE lock |
reserved_at / available_at / attempts | Database columns: lease start, visibility time, reservation count |
Worker / daemon | The loop class and its long-running mode |
queue:work / queue:listen | Daemon worker / one child process per job |
queue:restart | Sets illuminate:queue:restart so workers exit after their job |
--max-jobs, --max-time, --memory | Worker recycling limits; memory exit code 12 |
--stop-when-empty, --rest, --sleep, --once | Drain-and-exit, pause between jobs, idle sleep, single job |
pcntl / SIGTERM / SIGALRM | Extension and signals used for graceful stop and timeouts |
| Supervisor (process monitor) | Linux process manager restarting workers; numprocs, stopwaitsecs |
RateLimited | Middleware that releases jobs over a named limiter |
WithoutOverlapping | Middleware holding a cache lock per key during handle() |
ThrottlesExceptions | Middleware that backs off after repeated exceptions |
Skip | Middleware that deletes the job when a condition holds |
ShouldBeUnique / ShouldBeUniqueUntilProcessing | Dispatch-time lock released after processing / before processing |
UniqueFor / uniqueId / uniqueVia | Lock TTL / lock key suffix / lock store |
ShouldBeEncrypted | Encrypts data.command with the app key |
afterCommit / after_commit | Defer push until open transactions commit |
ShouldQueueAfterCommit / ShouldDispatchAfterCommit | After-commit marker for jobs and listeners / for events |
Bus::batch / job_batches | Parallel group and its counter table |
allowFailures | Keep a batch running after failures |
Bus::chain | Sequential jobs carried in the chained property |
failed_jobs | Table of final failures written by DatabaseUuidFailedJobProvider |
failed() | Job hook called on a fresh instance after the last attempt |
queue:failed / queue:retry / queue:prune-failed | List, re-push, prune failed jobs |
queue:monitor / QueueBusy | Size check and the event it fires |
| Horizon | Redis queue supervisor package with dashboard |
| supervisor (Horizon) | Horizon config entry owning process pools for queues |
balance / autoScalingStrategy | auto/simple/false; time/size/log |
Queue::extend / Connector | Register a driver / class that builds a driver from config |
laravel-queue-rabbitmq | RabbitMQ driver package (vladimir-yuldashev) |
laravel-kafka | Kafka producer/consumer package (mateusjunges), not a driver |
basic_get / basic_consume | AMQP polling vs push consumption |
x-dead-letter-exchange / x-message-ttl | Queue arguments used by the RabbitMQ package for delays |
withManualCommit | laravel-kafka option to commit offsets explicitly |
XREADGROUP / XACK | Redis Streams group read and acknowledgment |
References
- Laravel 13.x documentation: Queues, Horizon, Events, Redis.
- laravel/framework 13.x source: Queue/RedisQueue.php, Queue/LuaScripts.php, Queue/DatabaseQueue.php, Queue/Worker.php, Queue/WorkerOptions.php, Queue/Queue.php, Queue/Jobs/Job.php, Queue/Jobs/RedisJob.php, Queue/Jobs/DatabaseJob.php, Queue/CallQueuedHandler.php, Queue/Console/WorkCommand.php, Queue/Failed/DatabaseUuidFailedJobProvider.php, Queue/Middleware, Queue/QueueManager.php, Bus/Batch.php, Bus/PendingBatch.php, Bus/Dispatcher.php, Bus/UniqueLock.php, Bus/DatabaseBatchRepository.php, Foundation/Bus/PendingDispatch.php, Contracts/Queue.
- laravel/laravel 13.x: jobs, job_batches, failed_jobs migration.
- laravel/horizon 5.x: Supervisor.php, AutoScaler.php, RedisQueue.php.
- RabbitMQ package: README, RabbitMQQueue.php, RabbitMQJob.php.
- Laravel Kafka v2.13: Creating a consumer, Consumer options, Message handlers, Publishing, Message payload.
- Redis commands: RPUSH, LPOP, BLPOP, ZADD, ZRANGEBYSCORE, ZREM, EVAL, EVALSHA, XREADGROUP; phpredis README.
- PostgreSQL: SELECT, The Locking Clause.
- Go clients: go-redis, amqp091-go, franz-go kgo.