Custom PHP

PHP Queue Workers Done Right: Async Jobs, Retries and Observability

PHP queue workers move slow work out of the HTTP request so a user gets a response while a background process handles email, imports, image processing or webhooks. In my builds, a job is queued durably, retried with exponential backoff and jitter, made idempotent so replays are safe, and instrumented with failed-job counts, queue depth and retry rate.

By Saif Al Jahanwebdev-saif.com

What a PHP queue worker actually does

A PHP queue worker is a long-running CLI process that pulls jobs from a queue and executes them outside the web request. The web process only writes a small payload to a broker or a database table and returns; the worker claims that job, runs the handler, then deletes it or marks it failed. In Laravel that means a ShouldQueue job, QUEUE_CONNECTION=redis and php artisan queue:work; in Symfony it is a message bus plus messenger:consume. The worker loop, not the HTTP server, owns the slow work. That separation is what keeps response times stable when a third-party API stalls or a CSV import takes ninety seconds.

  • Web request pushes a serializable payload and returns immediately
  • Worker claims one job at a time from Redis, a database table or SQS
  • Handler performs the slow work, then acknowledges or fails the job
  • A process supervisor restarts the worker after a crash or memory limit

Which work belongs in a queue

Not every slow call needs a queue, and not every queued job is worth the extra moving parts. I queue work that is slow, retryable and does not need to change the response the user is waiting for: transactional mail, resizing uploads, syncing to an external API, generating reports, indexing search documents. I keep work in the request when correctness is immediate and cheap, such as validating input or reading a cart total. A useful test is whether the user still needs an answer before the job finishes. If they do, a queue alone will not help; you also need progress state and a polling endpoint.

  • Email, notifications and webhooks sent through unreliable third parties
  • Image resizing, PDF generation and large imports or exports
  • Search indexing, cache warming and aggregate rebuilds
  • Any network call that can time out or hit a rate limit

Payload design and idempotency

A queued job will run again. Either a handler fails after the side effect succeeded, a worker dies before acknowledging, or someone replays a failed job with queue:retry. That is why I design handlers to be idempotent: the same payload run twice produces the same state. I pass identifiers, not whole objects, an order ID or an import batch ID, and let the handler reload current data. I use Cache::lock() or ShouldBeUnique where concurrency would double-send, and check a status column before writing. Payloads stay small and version-tolerant, because a deploy can land while jobs are still waiting.

  • Pass database IDs, never serialized model snapshots or file handles
  • Guard the side effect with a unique key, a lock or row state
  • Handle an older payload shape after a code deploy
  • Log the job ID and correlation ID on every external call

Retries, exponential backoff and jitter

Set public $tries = 3 on the job or pass --tries=3 to the worker, then define backoff so a failing dependency is not hammered. The Laravel backoff() method, or --backoff=10,60,300 on the command line, gives increasing delays between attempts. I add jitter, a small random offset, so a thousand jobs released at once do not retry in lockstep; recent Laravel Redis workers expose jitter through worker options. I retry on transient failures such as timeouts and 429 responses, and fail fast on permanent ones such as a 422 or a missing record.

  • Retry timeouts, 429 responses and 5xx errors from external APIs
  • Fail immediately on validation errors and missing records
  • Use exponential delays with jitter to avoid thundering herds
  • Cap attempts so a poison job cannot loop indefinitely

Timeouts, failure paths and dead-letter queues

Retries only help if a hung job is killed. I set the worker --timeout below the Supervisor stopwaitsecs value so the worker reclaims the job instead of being killed mid-handler, and I set --memory so a leaking job cannot take the daemon down. After the last attempt, Laravel writes to the failed_jobs table through its failed job provider; I inspect that with queue:failed and replay deliberately. On higher-volume systems I route exhausted jobs to a separate dead-letter queue so one bad payload cannot block the main stream. A failure dashboard that shows only a total count is not enough: I want the exception class and the payload ID.

Running the worker process

In production I run php artisan queue:work --queue=high,default under Supervisor with autorestart=true, numprocs matched to the CPU and I/O profile, and stopwaitsecs above the job timeout. queue:work boots the app once and loops, which is far cheaper than queue:listen for steady traffic. I deploy with php artisan queue:restart so old workers stop after finishing their current jobs, and use --stop-when-empty for short-lived workers in containers that scale to zero. Separate queue names matter: a slow report queue should not starve password-reset mail, so I keep at least one worker per critical queue.

  • Use queue:work for long-lived daemons and queue:listen only where reload matters
  • Keep stopwaitsecs higher than the longest job timeout
  • Restart workers on deploy so handlers pick up new code
  • Split queues by latency class, not by team or feature

Observability: measure the queue, not the process

A worker process being alive tells you almost nothing. The signals I watch are queue depth, oldest pending job age, throughput per minute, failure rate, retry rate and time spent waiting before execution. Oldest job age is the metric that maps to user-perceived delay, so I alert on that rather than on a raw length that naturally spikes. I emit structured logs with job class, job ID and correlation ID, send them to the same aggregation as web requests, and add a trace span around each external call. Laravel Horizon and Symfony Messenger expose much of this; where they do not, a scheduled snapshot into the metrics store fills the gap.

  • Queue depth and oldest pending job age, per queue name
  • Failure and retry rate, grouped by exception class
  • Throughput and p95 wait time before execution
  • Structured logs keyed by job ID and correlation ID

Where this fits in a WordPress or custom PHP build

On WordPress sites I use WP-Cron only for low-stakes, low-frequency tasks; anything that must survive a traffic spike goes to a real queue driven by Redis or a database table with a separate worker. In custom PHP applications I make the queue part of the initial architecture, not an afterthought added when a checkout email times out. As a freelance WordPress and PHP developer in Mymensingh, Bangladesh, I build these systems at webdev-saif.com with the same care I give to page speed and structured data. The background layer is part of performance, even if it never appears in a Lighthouse report.

Frequently asked questions

What is a PHP queue worker?

A PHP queue worker is a long-running command-line process that reads jobs from a queue and runs them outside the HTTP request. The request stores a small payload and responds; the worker claims the job, executes the handler, then acknowledges or fails it. Laravel uses ShouldQueue jobs with queue:work, while Symfony Messenger uses handlers with messenger:consume.

When should I move work out of the request?

Move work to a queue when it is slow, externally dependent and does not need to change the response the user is waiting for. Good candidates are email, image processing, API sync, imports and search indexing. Keep validation, pricing and anything needed immediately in the request. If the outcome must be visible before the response ends, add progress state or a polling endpoint.

How do retries and exponential backoff work in Laravel?

Laravel retries a failed job up to its tries limit. With backoff(), or --backoff=10,60,300 on the worker, each retry waits longer than the last, so a 429 from an API gets progressively more room to recover. I add jitter so many jobs released together do not retry at the same instant. Permanent errors such as a 422 should fail on the first attempt instead of being retried.

How do I make a queued job safe to retry?

Treat every handler as if it will run twice. Pass database IDs rather than serialized objects, reload the current record inside the handler, and guard the side effect with a unique key, a lock or a status check before writing. ShouldBeUnique and Cache::lock() help with concurrency. Also design payloads to tolerate an old shape, because a deploy can land while jobs are still waiting.

What should I monitor on a production queue?

Monitor queue depth, oldest pending job age, throughput, failure rate, retry rate and pre-execution wait time. Oldest job age is the closest proxy for user-perceived delay, so I alert on that instead of raw depth, which naturally spikes. Emit structured logs with job ID, class and correlation ID, group failures by exception type, and keep a dead-letter path for jobs that exhaust their attempts.

Do queue workers replace cron jobs?

No. Cron is for time-based schedules such as nightly reports or token refresh; a queue is for work triggered by an event that should run asynchronously. In Laravel, the scheduler can dispatch a job to the queue, so the two work together. What you should avoid is WP-Cron for anything that must survive a traffic spike; use a real worker with a persistent broker instead.

Written by Saif Al Jahan, webdev-saif.com · Mymensingh, Bangladesh. Last updated .