How do I handle long-running jobs in Laravel without hitting timeouts?
Laravel queue workers stop any job that runs past the worker’s --timeout, which is 60 seconds by default. Handle it by keeping each job short enough to finish inside its timeout, and by making the worker, job, and queue connection timeouts agree. If the timeout happens inside a web request instead, move that work onto a queue first.
Quick answer
For long-running Laravel jobs, split the work into chunked jobs with Bus::batch(), set a job timeout that stays several seconds below the connection’s retry_after, and set Supervisor’s stopwaitsecs above your longest job. A timeout longer than retry_after makes Laravel retry a job that is still running, so the same job can process twice.
Why do Laravel jobs time out?
Three separate limits can end a long job. Identify which one you hit before you change anything.
- A web request ends when PHP-FPM or the web server gives up, so the work never reached a queue.
- The queue worker stops a job that exceeds its timeout. The worker exits with an error and a process manager restarts it.
- The queue connection releases a job after
retry_afterseconds, even if a worker is still running it. A second worker then picks the same job up.
Which timeout setting controls what?
These values come from Laravel’s queue documentation. Keep them in this order: job timeout below retry_after, and stopwaitsecs above the job timeout.
| Setting | Where it lives | What it does |
|---|---|---|
--timeout | queue:work flag | Defaults to 60 seconds. The worker exits with an error when a job runs longer. Keep it several seconds below retry_after. |
| Job timeout | #[Timeout] attribute on the job class | Overrides --timeout for that one job. It must stay below retry_after. |
retry_after | config/queue.php, per connection | Seconds before Laravel retries a job that is still processing. Amazon SQS uses its Default Visibility Timeout instead. |
timeout | Horizon supervisor config | Force-kills a worker after that many seconds. Keep it above job-level timeouts and a few seconds below retry_after. |
stopwaitsecs | Supervisor program config | How long Supervisor waits for a stopping worker to finish its current job before it kills the process. The timeout settings above control job run time. Set it above your longest job. |
How to handle long-running jobs in Laravel without timeouts
1. Move the work out of the web request
Create a queued job with php artisan make:job and implement ShouldQueue. Dispatch it from the controller or command and return a response right away. The request no longer waits for the work, so web server timeouts stop mattering.
Use an asynchronous connection such as Redis or the database driver, and keep a worker running. The sync driver runs jobs immediately, so it gives you no background processing.
2. Split the job into chunks
A job that loops over every order in one pass outgrows any timeout as the table grows. Read ids with chunkById(), create one small job per chunk, and group the jobs in a batch. This snippet is illustrative, so adapt the model and job names.
use App\Jobs\SyncOrderChunk;
use App\Models\Order;
use Illuminate\Support\Facades\Bus;
$jobs = [];
Order::query()->select('id')->chunkById(500, function ($orders) use (&$jobs) {
$jobs[] = new SyncOrderChunk($orders->pluck('id')->all());
});
Bus::batch($jobs)->allowFailures()->dispatch();
The chunk job must implement ShouldQueue and use the Batchable trait:
namespace App\Jobs;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class SyncOrderChunk implements ShouldQueue
{
use Batchable, Queueable;
public function __construct(public array $orderIds) {}
public function handle(): void
{
if ($this->batch()->cancelled()) {
return;
}
// Process the orders listed in $this->orderIds.
}
}
The 500 in chunkById(500, ...) is only an example. A safe chunk size depends on how complex the work is, how much memory each record uses, and how long a chunk takes to run. Start small, measure, then adjust.
The allowFailures() call stops one failed chunk from cancelling the whole batch. The CSV example below shows how that differs from retries.
When several workers run, the jobs in a batch run in parallel. They may finish in a different order than you added them. Use Bus::chain() when steps must run in sequence. Batches also need a table for batch data, which you create with php artisan make:queue-batches-table and then php artisan migrate.
3. Set a job timeout and keep retry_after above it
Some work cannot be split, such as one large export file. Give that job its own timeout with the Timeout attribute. The job value takes precedence over --timeout. Treat every number in this article as an example to adjust for your own jobs.
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Timeout;
#[Timeout(600)] // illustrative value, in seconds
class BuildExport implements ShouldQueue
{
use Queueable;
}
On Laravel 12 and earlier, the documentation uses a public $timeout property instead. Then raise retry_after on the connection in config/queue.php above the job timeout, for example to 720 seconds. The sample Redis connection ships with 90 seconds, so a 600-second job would otherwise start twice.
retry_after applies to every job on that connection. A high value delays the retry of short jobs whose worker crashed. Define a second connection with its own retry_after and run a dedicated worker for the long jobs.
4. Set timeouts on the I/O inside the job
Some blocking I/O, such as sockets or outgoing HTTP connections, may not respond promptly to the worker timeout. Laravel’s docs tell you to set a timeout in the API you are calling as well.
use Illuminate\Support\Facades\Http;
$response = Http::connectTimeout(5)->timeout(30)->get($url);
With Laravel’s HTTP client, connectTimeout(5) waits at most 5 seconds to connect to the server. timeout(30) waits at most 30 seconds for the response. When a call runs past the timeout, the client throws a ConnectionException. Keep the total of all calls inside the job timeout.
5. Align Supervisor or Horizon, and restart workers on deploy
When you stop or restart workers through Supervisor, each worker finishes its current job first. The stopwaitsecs value sets how long Supervisor waits before it kills the process. Laravel’s docs warn that the value must be greater than the seconds your longest job consumes.
[program:laravel-worker]
command=php /var/www/app/artisan queue:work --timeout=600 --max-time=3600
numprocs=4
stopwaitsecs=660
With a 600-second job timeout, a stopwaitsecs of 660 leaves a 60-second margin. The 720-second retry_after from step 3 still sits above the timeout. All three values are illustrative. The --max-time=3600 flag makes each worker exit after an hour so Supervisor restarts it with fresh memory.
On Horizon, set timeout on the supervisor instead. For plain queue:work workers, run php artisan queue:restart in every deploy. Workers finish their current job, then exit gracefully. Laravel keeps the restart signal in the cache, so configure a cache driver first. Horizon deploys use php artisan horizon:terminate instead.
6. Decide what a timeout and a failure should do
Laravel attempts a job once by default. A timeout consumes an attempt, and the job returns to the queue only if attempts remain. Raise the limit with --tries or the #[Tries] attribute. With --tries=3 --backoff=10, a job that throws an exception gets up to three attempts, and Laravel waits 10 seconds before each retry. Retries stop when attempts run out, and the job goes to the failed_jobs table. Setting tries to 0 retries indefinitely, so avoid it for long jobs.
Mark a job as failed on timeout when a retry would be unsafe. A job that fails on timeout is not retried, regardless of the tries value.
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\Attributes\FailOnTimeout;
use Illuminate\Queue\Attributes\Timeout;
#[Timeout(600)]
#[FailOnTimeout]
class BuildExport implements ShouldQueue
{
// ...
}
On Laravel 12 and earlier, use the public $failOnTimeout = true; property. In the job’s failed() method, a timeout arrives as Illuminate\Queue\TimeoutExceededException. A job that simply used all its attempts arrives as Illuminate\Queue\MaxAttemptsExceededException.
Example: a 50,000-row CSV import
Here is how the steps fit together for a large CSV upload. The row count is an illustrative size.
- The user uploads the file. Laravel stores it and creates an import record with a pending status.
- The controller dispatches one import job and returns a response at once.
- The import job reads the file in chunks of 500 rows and dispatches a batch of chunk jobs.
- Each chunk job runs well inside the 60-second default, and the batch tracks overall progress.
- The batch’s
then()callback marks the import completed when every chunk succeeds.
Temporary failures
A brief API error should not lose a chunk. Set #[Tries(3)] on the chunk job (Illuminate\Queue\Attributes\Tries), and Laravel retries that chunk while attempts remain. Without --tries or a Tries attribute, the chunk gets one attempt.
Permanently failed chunks
When a chunk uses all its attempts, it lands in failed_jobs. By default, that failure also marks the batch as cancelled, and the catch() callback runs for the first failure only. Chunks that start after the cancellation return early because of the cancelled() check in handle().
What allowFailures() changes
The allowFailures() method stops a failed job from cancelling the batch, so the other chunks keep running. It does not retry anything. You can pass it a closure that runs on each job failure.
Investigate and retry failed chunks
List failures with php artisan queue:failed. After you fix the cause, retry one job with php artisan queue:retry <job-id>, or retry every failed job in a batch with php artisan queue:retry-batch <batch-uuid>.
Make chunk jobs idempotent
A retry can run rows that a failed attempt already processed. Use unique keys or upserts, and check before repeating an external action, so a retry does not create duplicate records or charge a customer twice.
What to check before you raise any timeout
- PCNTL: Laravel needs the PCNTL PHP extension to enforce job timeouts.
- Double runs: A timeout at or above
retry_afterlets two workers run the same job. Make long jobs idempotent so a repeat run is harmless. - Memory: Laravel’s
--memoryoption is a worker threshold, not a per-job hard limit. It defaults to 128 MB and also accepts a percentage of PHP’smemory_limit. When the worker passes it, the worker exits and Supervisor restarts it. PHP’s ownmemory_limitand your server or container limit apply separately, and either can stop a job first. - Heavy resources: Workers do not reboot the framework between jobs. Chunk large datasets and release heavy resources after each job.
What to do first
For Laravel long-running jobs, start with step 2. Smaller jobs make every other setting less critical, and a failed chunk retries cheaply instead of redoing hours of work. Raise timeouts only for work that cannot be split, and always keep retry_after above them. If you want a second opinion on a queue setup, Stagebit’s Laravel development team can review it with you.
Related Answers
Still need help?
Questions about Laravel queue timeouts?
If your long-running jobs still time out or run twice, we're happy to walk through your queue setup and what your options are.
