When building web applications with Laravel, offloading time-consuming tasks like email dispatching or API interactions to queues can dramatically improve performance. Laravel provides a powerful, flexible queue system out of the box. In this post, we’ll walk through configuring queues with Redis, managing workers in production using Supervisor, and writing clean, maintainable jobs for high-scale environments.
Why Use Queues?
Queues allow you to defer the processing of time-consuming tasks, like sending emails or generating reports, until later. This keeps your application responsive and improves user experience.
Supported Queue Drivers
Laravel supports multiple queue backends:
sync
(for local, immediate processing)database
Redis
Amazon SQS
Beanstalkd
For this guide, we’ll use Redis for its performance and popularity.
Step 1: Configure Redis
First, install Redis:
sudo apt install redis-server
In .env
, set:
QUEUE_CONNECTION=redis
And ensure your config/queue.php
is set to use Redis.
Step 2: Create a Job
Generate a job using Artisan:
php artisan make:job SendWelcomeEmail
Update the handle()
method to send an email:
public function handle()
{
Mail::to($this->user->email)->send(new WelcomeMail($this->user));
}
Dispatch it:
SendWelcomeEmail::dispatch($user);
Step 3: Run the Worker
Start processing the queue with:
php artisan queue:work
Use --daemon
in production for long-running workers.
Step 4: Use Supervisor in Production
Install Supervisor:
sudo apt install supervisor
Create a config file /etc/supervisor/conf.d/laravel-worker.conf
:
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/your/app/artisan queue:work redis --sleep=3 --tries=3
autostart=true
autorestart=true
user=youruser
numprocs=1
redirect_stderr=true
stdout_logfile=/path/to/your/app/storage/logs/worker.log
Reload and update:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-worker:*
Monitoring & Debugging
Use horizon
for dashboard-based queue monitoring:
composer require laravel/horizon
php artisan horizon:install
php artisan migrate
php artisan horizon
Queues are essential for scalable Laravel applications. Once you integrate them into your workflow, your apps will be faster, more reliable, and easier to maintain. Next, try combining queues with events for even cleaner architecture.