intermediate Step 9 of 15

Queues and Jobs

Laravel Framework

Queues and Jobs

Queues allow you to defer time-consuming tasks — like sending emails, processing uploads, generating reports, or calling external APIs — to be processed in the background. This keeps your web responses fast because users do not have to wait for slow operations to complete. Laravel's queue system supports multiple drivers (database, Redis, SQS) and provides features like job retries, rate limiting, batching, and chaining. Queues are essential for any production application that needs to remain responsive under load.

Creating and Dispatching Jobs

<?php
// php artisan make:job ProcessPodcastUpload

namespace App\Jobs;

use App\Models\Podcast;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public $tries = 3;           // Max retry attempts
    public $backoff = [30, 60, 120];  // Delay between retries

    public function __construct(
        private Podcast $podcast
    ) {}

    public function handle(): void
    {
        // Time-consuming processing
        $this->podcast->update(['status' => 'processing']);

        // Transcode audio, generate waveform, etc.
        $this->transcodeAudio($this->podcast);

        $this->podcast->update(['status' => 'ready']);
    }

    public function failed(\\Throwable $exception): void
    {
        $this->podcast->update(['status' => 'failed']);
        // Notify admin of failure
    }
}

// Dispatch the job
ProcessPodcastUpload::dispatch($podcast);
ProcessPodcastUpload::dispatch($podcast)->onQueue('audio');
ProcessPodcastUpload::dispatch($podcast)->delay(now()->addMinutes(5));

// Run the queue worker
// php artisan queue:work --queue=audio,default
Pro tip: Use the database queue driver for development and Redis or SQS for production. Always implement the failed() method to handle job failures gracefully. Use php artisan queue:work with a process manager like Supervisor to keep workers running in production.

Key Takeaways

  • Queues defer slow tasks to background processing, keeping web responses fast.
  • Jobs implement ShouldQueue and define their logic in the handle() method.
  • Configure retries, backoff delays, and failure handlers for reliability.
  • Use named queues (->onQueue('emails')) to prioritize different job types.
  • Run workers with php artisan queue:work and manage them with Supervisor in production.