Laravel Queued Job with Retry and Backoff

Laravel Queued Job with Retry and Backoff

Laravel Queued Job with Retry and Backoff

Define retry behaviour directly on the job class using properties and the backoff() method.

// app/Jobs/SendWelcomeEmail.php
namespace App\Jobs;

use App\Models\User;
use App\Mail\WelcomeMail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class SendWelcomeEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $timeout = 30;

    public function __construct(public User $user) {}

    public function backoff(): array
    {
        return [10, 30, 60]; // seconds between retries
    }

    public function handle(): void
    {
        Mail::to($this->user)->send(new WelcomeMail($this->user));
    }

    public function failed(\Throwable $e): void
    {
        // log or notify after all retries exhausted
        logger()->error("Welcome email failed for user {$this->user->id}: {$e->getMessage()}");
    }
}

// Dispatch
SendWelcomeEmail::dispatch($user)->onQueue('emails');
All Comments