Module 7: Queues & Redis

Asynchronous Processing and Caching

Queues

Offload time-consuming tasks (emails, image processing) to a background queue to keep your app snappy.

Configuration

Set QUEUE_CONNECTION=redis in your .env file.

Creating Jobs

php artisan make:job ProcessPodcast
class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(public Podcast $podcast) {}

    public function handle(): void
    {
        // Process the podcast upload...
    }
}

Dispatching Jobs

ProcessPodcast::dispatch($podcast)
    ->onQueue('processing')
    ->delay(now()->addMinutes(10));

Running Workers

You need a worker process to consume the queue.

php artisan queue:work --tries=3 --timeout=90

In production, use Supervisor to keep the worker running.

Laravel Horizon

Horizon provides a beautiful dashboard and code-driven configuration for your Redis queues.

composer require laravel/horizon
php artisan horizon:install

Access it at /horizon.

Caching with Redis

Cache expensive database queries or API calls.

// Remember for 60 seconds
$users = Cache::remember('users', 60, function () {
    return DB::table('users')->get();
});

// Atomic Locks
$lock = Cache::lock('processing-invoice-1', 10);
if ($lock->get()) {
    // Process invoice...
    $lock->release();
}