| name | laravel-queue-patterns |
| description | Best practices for Laravel queues including job structure, batching, chaining, middleware, retry strategies, and error handling. |
Laravel Queue Patterns
Job Structure
<?php
namespace App\Jobs;
use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProcessOrder implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public readonly Order $order,
) {}
public function handle(PaymentGateway $gateway): void
{
$gateway->charge($this->order);
$this->order->update(['status' => 'processed']);
}
public function failed(\Throwable $exception): void
{
$this->order->update(['status' => 'failed']);
}
}
Dispatch Patterns
ProcessOrder::dispatch($order);
ProcessOrder::dispatch($order)
->onQueue('payments')
->onConnection('redis');
ProcessOrder::dispatch($order)->delay(now()->addMinutes(5));
ProcessOrder::dispatchIf($order->isPaid(), $order);
ProcessOrder::dispatchUnless($order->isCancelled(), $order);
ProcessOrder::dispatch($order)->afterCommit();
DB::transaction(function () use ($order) {
$order->save();
ProcessOrder::dispatch($order);
});
DB::transaction(function () use ($order) {
$order->save();
ProcessOrder::dispatch($order)->afterCommit();
});
Job Middleware
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Queue\Middleware\WithoutOverlapping;
class ProcessOrder implements ShouldQueue
{
public function middleware(): array
{
return [
new RateLimited('orders'),
(new WithoutOverlapping($this->order->id))
->releaseAfter(60)
->expireAfter(300),
(new ThrottlesExceptions(3, 5))
->backoff(5),
];
}
}
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
RateLimiter::for('orders', function ($job) {
return Limit::perMinute(10);
});
Job Chaining
use Illuminate\Support\Facades\Bus;
Bus::chain([
new ValidateOrder($order),
new ChargePayment($order),
new SendConfirmation($order),
new UpdateInventory($order),
])->onQueue('orders')->dispatch();
Bus::chain([
new ValidateOrder($order),
new ChargePayment($order),
])->catch(function (\Throwable $e) use ($order) {
$order->update(['status' => 'failed']);
})->dispatch();
Job Batching
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
$batch = Bus::batch([
new ProcessCsvChunk($file, 0, 1000),
new ProcessCsvChunk($file, 1000, 2000),
new ProcessCsvChunk($file, 2000, 3000),
])
->then(function (Batch $batch) {
Notification::send($user, new ImportComplete());
})
->catch(function (Batch $batch, \Throwable $e) {
})
->finally(function (Batch $batch) {
Storage::delete($file);
})
->name('CSV Import')
->onQueue('imports')
->allowFailures()
->dispatch();
$batch = Bus::findBatch($batchId);
echo $batch->progress();
Jobs in a batch must use the Illuminate\Bus\Batchable trait.
Unique Jobs
use Illuminate\Contracts\Queue\ShouldBeUnique;
class RecalculateReport implements ShouldQueue, ShouldBeUnique
{
public function __construct(
public readonly int $reportId,
) {}
public int $uniqueFor = 3600;
public function uniqueId(): string
{
return (string) $this->reportId;
}
}
Retry Strategies
class ProcessWebhook implements ShouldQueue
{
public int $tries = 5;
public function retryUntil(): \DateTime
{
return now()->addHours(2);
}
public int $maxExceptions = 3;
public array $backoff = [10, 60, 300];
public int $timeout = 120;
public function handle(): void
{
if ($this->isInvalid()) {
$this->fail('Invalid webhook payload.');
return;
}
}
}
Idempotency Patterns
class ChargePayment implements ShouldQueue
{
public function handle(PaymentGateway $gateway): void
{
if ($this->order->payment_id) {
return;
}
$payment = $gateway->charge($this->order->total);
$affected = Order::where('id', $this->order->id)
->whereNull('payment_id')
->update(['payment_id' => $payment->id]);
if ($affected === 0) {
return;
}
}
}
Testing Queues
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Queue;
public function test_order_dispatches_processing_job(): void
{
Queue::fake();
$order = Order::factory()->create();
$order->process();
Queue::assertPushed(ProcessOrder::class, function ($job) use ($order) {
return $job->order->id === $order->id;
});
}
public function test_order_dispatches_chain(): void
{
Bus::fake();
$order = Order::factory()->create();
$order->fulfill();
Bus::assertChained([
ValidateOrder::class,
ChargePayment::class,
SendConfirmation::class,
]);
}
public function test_import_dispatches_batch(): void
{
Bus::fake();
(new CsvImporter)->import($file);
Bus::assertBatched(function ($batch) {
return $batch->jobs->count() === 3
&& $batch->jobs->every(fn ($job) => $job instanceof ProcessCsvChunk);
});
}
public function test_process_order_charges_payment(): void
{
$order = Order::factory()->create();
ProcessOrder::dispatchSync($order);
$this->assertNotNull($order->fresh()->payment_id);
}
Checklist