Laravel Queue Workers: Fix Timeouts and Failed Jobs
A practical guide to queue timeouts, retry windows, safe recovery, worker supervision and reliable deployments on Linux.
Quick answer: To fix Laravel queue worker timeouts, configure a bounded execution time for each job and keep the queue reservation window longer than that execution time. For database or Redis queues, the worker timeout must be shorter than retry_after. Give HTTP requests their own time limits, supervise workers, record durable operation identifiers, and reconcile uncertain outcomes before retrying jobs that can charge money, publish content or send messages. A timeout is not proof that an external action failed.

A queue can make a Laravel application feel faster by moving slow work out of the web request. It can also create a hidden production incident. The customer sees a successful response, but a worker later crashes, a reservation expires, another worker starts the same job, and a third-party service receives two requests. Increasing every timeout may hide the symptoms without fixing the underlying problem.
This guide focuses on the operational decisions that make background work reliable on a small Linux VPS. It uses Laravel 12 as the reference for configuration examples. Confirm the options available in your installed framework version and queue driver before applying them. The examples are illustrative engineering recommendations, not measurements from a Rubic8 production load test.
1. What is the difference between timeout and retry_after?
Worker timeout: The execution limit enforced by the worker. A job can also declare its own timeout. When the effective limit is exceeded, the worker may terminate and require a process manager to bring it back.
Retry window: For database and Redis queues, retry_after controls when a reserved job can become available again if it was not completed or released. Amazon SQS uses its own visibility timeout instead.
HTTP timeout: A separate limit for the network call itself. If a job contacts an AI model, payment provider or partner API, the HTTP client must not wait indefinitely.
These settings solve different problems. The network timeout limits a dependency, the job timeout limits execution, and the retry window controls when another worker can receive the reservation. Laravel's official queue documentation describes the relationship between worker timeouts and job expiration. An unsafe relationship can lead to overlapping attempts.
2. How duplicate jobs happen: a timing example
Consider two workers sharing the same database queue. The reservation window is 90 seconds, but the first worker is allowed to run for 120 seconds. At the start, worker A reserves an image-generation job. If the job remains unacknowledged when its reservation expires, worker B may be able to reserve the same record while worker A is still working.
Illustrative unsafe configuration:
t=0 Worker A reserves job
t=90 Reservation can expire
t=91 Worker B may reserve the same job
t=120 Worker A reaches its execution limit
Result: two attempts may overlap.
The exact scheduling depends on the driver, worker polling and process behavior. The danger is not that duplication occurs at precisely second 91. It is that a reservation can expire before the original attempt has stopped.
Now consider a safer example: a worker execution limit of 60 seconds, with a reservation window of 100 seconds. There is a margin for termination and scheduling uncertainty. This removes one common cause of overlapping attempts but cannot guarantee that external side effects happen exactly once. A worker might already have sent a successful payment request before its process terminates.

3. Configure a realistic timeout budget
Start from the business task, not an arbitrary number copied from another server. A thumbnail conversion, a bulk CSV export and an AI report have different processing characteristics. Measure representative durations on a staging environment and decide how long a user can reasonably wait for the result.
For a hypothetical short AI enrichment job, you might allow five seconds to establish a connection, 30 seconds for the HTTP request, and additional time for validation and database writes. Set a 60-second job budget and reserve the job for 100 seconds. These are example values, not a universal recommendation. If the task regularly needs longer, split the workload or move it into a dedicated queue rather than increasing the execution limit of all workers.
Illustrative timing budget
Connection timeout: 5 seconds
HTTP timeout: 30 seconds
Job timeout: 60 seconds
Retry window: 100 seconds
Do not assume a connection timeout and request timeout always add together. Check the HTTP library's behavior. Multiple calls, retries, file uploads, database lock waits and cleanup can consume additional time. Keep the entire attempt within the job's budget.
For a database queue, verify the active connection definition in config/queue.php. A simplified Laravel configuration might include:
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 100,
'after_commit' => true,
],
This is a partial configuration example. Preserve the other settings required by your installation. The equivalent Redis connection uses different connection options. With SQS, configure and verify the visibility period separately rather than copying a database-specific key.
A matching example worker command is:
php artisan queue:work database --queue=default --timeout=60 --tries=3 --sleep=3
Run this command only in a controlled environment with an intentional queue configuration. It processes real queued work. If jobs declare their own timeouts, check those values as well. Inspect the configuration actually loaded by the worker, not just an edited environment file. PHP's PCNTL extension and platform support also matter for worker timeout behavior.
4. Put time limits inside external API calls
A worker-level timeout should not be your only method for stopping a slow HTTP operation. Configure the HTTP client directly so your application has an opportunity to record a useful failure or a reconciliation requirement.
use Illuminate\Support\Facades\Http;
// Example read-only lookup; use your approved API hostname.
$response = Http::acceptJson()
->connectTimeout(5)
->timeout(30)
->get('https://api.partner.example/v1/status');
$response->throw();
The hostname is a reserved example, not a working service. The application should validate the returned data before storing it. Do not add an unconditional HTTP retry to every POST request. An HTTP timeout can occur after the remote server has already accepted a request. If the operation writes to an external system, use its documented idempotency mechanism or a stable operation lookup before repeating the action.
Keep outbound destinations restricted to approved services and avoid treating a URL supplied by an AI model as trusted. Rubic8's Laravel SSRF prevention guide explains the related security risks of external HTTP requests.
5. Design jobs around operations, not attempts
The queue job is a delivery mechanism. The business operation is the action that must be correct. Those identifiers should not be confused. For example, a customer may request one report, but a worker can attempt to generate that report more than once. A persistent operation record should still represent one report request.
Use a unique business key, an explicit state and a recorded external reference when available. Before a job starts an irreversible action, make an atomic claim through your application service. An already completed operation should return its recorded result. An operation with an unknown external outcome should enter a reconciliation state rather than start a new write.
QUEUED
-> PROCESSING
-> VERIFIED
PROCESSING
-> RETRYABLE_FAILURE
-> NEEDS_RECONCILIATION
-> PERMANENT_FAILURE
This state model is a conceptual example. It must be implemented with atomic transitions, a unique database constraint and a recovery strategy for abandoned claims. A lock alone cannot establish whether a remote service already performed the requested action. Do not keep a database transaction open around a long external HTTP request merely to simulate exactly-once execution.
Laravel offers unique-job and overlapping-job controls, but they solve narrower coordination problems. They depend on appropriate cache locking configuration and do not establish that a payment, email or publication was completed exactly once. See Rubic8's Laravel webhook idempotency guide for a deeper discussion of durable operation identifiers.
6. Avoid dispatching work before its data is committed
Suppose a web request creates a customer record inside a transaction and immediately dispatches a welcome-email job. A fast worker may try to look up the customer before the transaction becomes visible. If the transaction rolls back, the job may refer to a record that never existed.
Laravel provides an after-commit dispatch mechanism. Use it when the queued action depends on data created in the transaction.
DB::transaction(function () use ($customerId) {
// Save the application records needed by the job.
GenerateCustomerReport::dispatch($customerId)
->afterCommit();
});
The class and identifier are illustrative. This example assumes the application already defines the job and has imported the database facade. After-commit dispatch avoids one visibility race, but it does not by itself make the database commit and queue publication an indivisible distributed operation. Workflows that cannot tolerate missing dispatches should consider a transactional outbox with a supervised relay and idempotent consumers.
7. Run Laravel queue workers under a process manager
Starting a worker in an interactive SSH session is useful during development. It is not a dependable production deployment. A worker may stop after a timeout, a release or a host reboot. Use a process manager appropriate to your Linux environment, such as Supervisor or systemd, and run the worker under an unprivileged application account.
For a small VPS, a single dedicated worker is often a useful baseline. The following Supervisor example is a starting point for an application located at an illustrative path. Adapt the account, PHP executable, application path, memory limit, queue name and shutdown budget to your deployment. Create the log directory with appropriate permissions before starting the worker.
[program:app-queue]
directory=/srv/example-app
command=/usr/bin/php artisan queue:work database --queue=default --timeout=60 --tries=3 --sleep=3 --max-time=3600
user=appuser
numprocs=1
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stopwaitsecs=120
redirect_stderr=true
stdout_logfile=/var/log/example-app/queue.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=3
The example allows a longer shutdown grace period than the sample job's runtime limit. Check that the process manager is allowed enough time for the longest intended job, including shutdown handling. Use the official Laravel queue documentation's Supervisor section as a reference for the installed version. Do not install both Supervisor and systemd definitions for the same worker unless you intentionally need separate processes.
On a shared VPS, additional workers compete for CPU, RAM, database connections and outbound API limits. A long backlog may indicate a slow database query or an upstream rate limit, not a shortage of processes. Review Rubic8's Laravel slow query troubleshooting guide before increasing concurrency without measurements.
8. Deploy new Laravel code without leaving old workers behind
Queue workers are long-running processes. Replacing PHP files or reloading PHP-FPM does not necessarily replace the process handling queued jobs. Your deployment plan needs to cover both HTTP and queue execution.
After the new release and compatible configuration are in place, Laravel's graceful worker restart signal can be part of the deployment procedure:
php artisan queue:restart
Run it in the correct application and environment only after checking that the worker manager will restart exiting processes. The restart signal is stored in the application cache, so separate cache namespaces and incorrect cache connections can prevent the intended workers from noticing it. A worker processing a job may take time to exit. Verify actual process replacement and completion of a canary job rather than treating the command's successful exit as proof that deployment is finished.
Schema changes also need care: old jobs may have been serialized before the deployment and can still arrive afterward. Make changes compatible across the rollout, or deliberately drain and pause the relevant queue under an approved maintenance plan. Avoid deleting a queue simply because old messages exist. Rubic8's PHP and Laravel upgrade compatibility guide covers the broader runtime verification process.
9. Diagnose failed jobs before retrying them
When a queue incident occurs, first identify the application, connection, queue name, worker process and affected operation. A job can be delayed without being failed, and a failed job can correspond to a successful remote transaction. Those require different responses.
Step 1: inspect the runtime. From the intended application directory, use read-only checks to identify the PHP runtime and supported queue commands. Avoid dumping environment variables or configuration files containing secrets.
php -v
php -m
php artisan --version
php artisan queue:failed
The failed-job command depends on your application's failure storage configuration. For a Supervisor-managed worker, inspect the relevant program status and logs. For a systemd-managed worker, inspect the specific unit and its journal. Correlate timestamps and operation IDs with application records.
Step 2: classify the failure. A malformed payload or invalid permission may require a code or data fix. A transient rate limit may justify controlled backoff. A network timeout after sending a write requires outcome reconciliation. A database deadlock may require a bounded retry of the transaction rather than a repeat of every external side effect.
Step 3: verify what happened externally. For a payment, query the provider with the existing transaction or operation identifier. For an article publication, check the destination CMS using its stable record identity. For a generated image, check whether the existing artifact is complete and associated with the original request.
Step 4: authorize a narrow retry only when safe. Laravel provides a failed-job retry command. Replace the placeholder with a verified identifier and confirm that replaying the job will not repeat a completed action.
php artisan queue:retry FAILED_JOB_ID
This command changes queue state and is not a read-only diagnostic. Do not run it blindly on a production queue, and do not use a bulk retry as the first incident response. If the remote outcome cannot be determined, preserve the evidence for manual review. See the current Laravel queue reference for supported options in newer releases.
10. Monitor queue health, not just worker uptime
A process can be active while doing no useful work. Monitor the age of the oldest pending job, completed jobs per interval, time to completion, failed-job counts and the number of operations requiring reconciliation. If an AI queue consumes paid model calls, track cost per verified result rather than cost per attempt.
For a simple application, record a structured log containing the job identifier, operation identifier, queue name, attempt number, duration and outcome. Redact customer data, credentials, raw authorization headers and unnecessary prompt contents. Logs should make it possible to correlate a worker failure with a specific business operation without becoming a second database of sensitive information.
Distinguish a healthy idle queue from a stuck queue. Zero completions can be normal when no work is pending. Zero completions while pending-job age rises is actionable. Alert thresholds should reflect the service's expected completion time and business impact, not a universal threshold copied from an unrelated system.
For asynchronous AI workflows, a result arriving too late can be unusable even if the worker technically succeeded. Rubic8's async tools and deadline-aware agent guide explains why task-level deadlines and durable delivery state are important.
11. Production readiness checklist
Timing: The effective timeout for every worker and job is below the relevant reservation or visibility window, with a suitable margin. External calls and database waits have independent limits.
Correctness: Business-operation identifiers are unique, claims are atomic, external receipts are durable, and uncertain outcomes have a reconciliation path.
Deployment: The worker runs as the intended user, with the intended PHP executable and environment. The process manager restarts it after a crash or graceful release. Queued payloads remain compatible with the rollout.
Recovery: Failed jobs are inspected individually before replay, with a clear distinction between transient errors, permanent errors and unknown outcomes.
Capacity: Worker concurrency is justified by measured queue age, CPU, memory, database usage and API rate limits. Test an upstream timeout, a crashed worker and duplicate delivery in an isolated environment.
Verification: A successful job means that the intended result is validated, not simply that the handler returned without throwing an exception.
Frequently asked questions
Why does my Laravel queue job run twice?
Common causes include a reservation expiring before the previous attempt stops, repeated dispatch, failure after an external side effect, or missing application-level deduplication. Inspect job identifiers, attempt history and external operation records before changing timeout values.
Should Laravel retry_after be greater than timeout?
Yes, for queue drivers that use retry_after, choose a reservation window longer than the effective execution limit. Allow a margin appropriate to termination behavior and workload. For SQS, use the corresponding visibility timeout instead.
Can I use a database queue instead of Redis?
Yes. A database queue can be a reasonable starting point for modest workloads. Measure reservation-query latency, database contention and pending-job age. Redis or a dedicated managed queue becomes a candidate when measurements and operational requirements justify the additional service.
Does queue:restart delete pending jobs?
No. Its purpose is to signal workers to exit gracefully so a process manager can replace them. It does not intentionally clear the backlog. Confirm that your worker can receive the signal and that the replacement process starts successfully.
Is retrying a failed job always safe?
No. A previous attempt may already have modified another system. Reconcile the operation, confirm that the failure is retryable and use a stable operation identifier before authorizing another attempt.
How many Laravel queue workers should a small VPS run?
There is no universal number. Begin with a controlled baseline and increase concurrency only when pending-job latency requires it and CPU, memory, database capacity and dependency quotas permit it. Test the actual workload rather than relying on a server-size formula.
Final thoughts: reliable queues are a product feature
Do not judge a background system by whether its workers are running. Judge it by whether the right business operation completes, within an acceptable time, without an unauthorized or duplicate effect. A practical starting architecture combines explicit timing budgets, durable state, supervised workers, safe recovery and independent verification.
Editorial note: Reviewed November 26, 2026. The Laravel 12 and current Laravel queue references linked above are the primary framework sources. Timing values, workflow states, code snippets and VPS configuration are illustrative Rubic8 recommendations, not production benchmark results. Check your framework version, queue connection, external API contract and runtime before adopting the examples.
Rubic8 Editorial Team
Editorial Team
Rubic8 creates practical guides and free tools for developers, webmasters, and digital publishers. Our fast-changing technical content is reviewed against current primary documentation before publication.