Keep Laravel Jobs from Running Too Long with Job Timeouts
Queued jobs are great for moving slow work away from a web request.
For example:
SendMonthlyReport::dispatch($user);
But what happens if the job gets stuck while calling an external API?
Without a suitable timeout, the worker may keep waiting longer than you expect.
Set a Timeout for a Job
Laravel allows you to define a $timeout property:
class SendMonthlyReport implements ShouldQueue
{
public $timeout = 120;
public function handle(): void{
// Generate and send report...
}
}
This tells the queue worker that the job should not run longer than 120 seconds.
Why Is This Useful?
Imagine your job calls an external service:
$response = Http::post($url, $data);
If that service becomes slow, your job can remain active for too long.
A job timeout provides another layer of protection.
Configure It for Different Jobs
Not every job needs the same amount of time.
A small notification job might need:
public $timeout = 30;
While a large import might need:
public $timeout = 300;
Set the timeout according to the work the job actually performs.
Timeout Isn't a Replacement for HTTP Timeouts
If your job makes an HTTP request, also configure the HTTP client's timeout:
$response = Http::timeout(30)
->post($url, $data);
Think of them as two different protections:
HTTP timeout
↓
Controls the external request
Job timeout
↓
Controls the overall job execution
Be Careful with Worker Configuration
Your queue worker's timeout should also be configured appropriately.
For example:
php artisan queue:work --timeout=120
The worker timeout and job timeout should be planned together rather than configured independently.