Laravel Horizon Explained
🎯 Summary
Laravel Horizon provides a beautiful dashboard and code-driven configuration for your Laravel powered Redis queues. Managing asynchronous tasks becomes a breeze with its real-time insights into queue health, throughput, and failed jobs. This guide provides a comprehensive overview, from installation to advanced configuration, ensuring you harness the full power of Laravel Horizon for optimized application performance. We'll explore core concepts like supervisors, metrics, and tags.
Understanding Laravel Horizon
Laravel Horizon is the official Redis-powered queue monitoring system for Laravel. It allows you to easily monitor your queue system. Instead of SSHing into your server and running queue:work, Laravel Horizon allows you to monitor your queues through a single dashboard. Let's explore why this is important.
Why Use Laravel Horizon?
- Simplified Queue Management: Forget complex command-line juggling. Horizon provides a user-friendly dashboard for monitoring and managing your queues.
- Real-time Insights: Get instant feedback on queue health, throughput, and any failed jobs.
- Code-Driven Configuration: Define your queue configuration directly in your codebase for easy version control and deployment.
- Concurrency Control: Easily adjust the number of worker processes to optimize queue processing based on demand.
Installation and Configuration
Let's get Laravel Horizon up and running in your Laravel project.
Installation Steps
- Install Horizon via Composer:
- Publish Assets:
This command publishes Horizon's assets, including its configuration file.php artisan horizon:install
- Configure Redis: Ensure your
.env
file is properly configured to connect to your Redis server. Key configurations includeREDIS_HOST
,REDIS_PORT
, andREDIS_PASSWORD
. - Configure Horizon: Open the
config/horizon.php
file to customize your Horizon settings. You can define environments, queues, and worker configurations here.
composer require laravel/horizon
Basic Configuration Options
The config/horizon.php
file offers several key configuration options:
- Environments: Define different Horizon configurations for your various environments (e.g., local, staging, production).
- Queues: Specify which queues Horizon should monitor. You can assign different worker configurations to different queues.
- Workers: Configure the number of worker processes, memory limits, and other worker-specific settings.
- Supervisor Name: Configure the name that appears in the supervisor process.
Running Horizon
Once configured, starting Horizon is simple.
Starting and Stopping Horizon
- Start Horizon:
This command starts the Horizon process, which will monitor your queues and process jobs.php artisan horizon
- Stop Horizon: To stop Horizon, simply use
Ctrl+C
in your terminal or use your deployment system to stop the Horizon process. - Deploying Horizon: When deploying Horizon to a production environment, you'll typically use a process manager like Supervisor to ensure Horizon stays running.
Using Supervisors
Supervisors are a key part of Horizon's architecture. They define how many worker processes should be running for each queue.
Defining Supervisors
Supervisors are configured within the config/horizon.php
file. Here's an example:
'environments' => [ 'production' => [ 'supervisor-1' => [ 'connection' => 'redis', 'queue' => ['default'], 'balance' => 'simple', 'processes' => 10, 'tries' => 3, ], ], ]
In this example, we've defined a supervisor named supervisor-1
for the production environment. This supervisor will run 10 worker processes for the default
queue.
Supervisor Strategies
Horizon offers 3 balancing strategies for your supervisors:
Digging Deeper: Advanced Features
Horizon offers a wealth of advanced features to fine-tune your queue management.
Job Retries and Failures
Horizon provides built-in support for job retries and handling failed jobs. You can configure the number of retry attempts and define a dedicated queue for failed jobs.
Tags
Tagging jobs allows you to categorize and filter jobs in the Horizon dashboard. This is useful for tracking jobs related to specific users, features, or processes. Here's how to tag a job:
dispatch(new ProcessPodcast(123))->tag(['podcast:123', 'user:1']);
You can view stats about specific tags by using the Horizon dashboard.
Metrics
Horizon collects various metrics about your queues, including throughput, runtime, and failure rates. These metrics can be used to identify performance bottlenecks and optimize your queue configuration.
Common Issues and Troubleshooting
Even with careful configuration, you might encounter issues. Here's a quick troubleshooting guide.
Horizon Not Processing Jobs
If Horizon isn't processing jobs, check the following:
- Ensure Redis is running and accessible.
- Verify that your queue connections are correctly configured in
config/queue.php
and.env
. - Check the Horizon logs for any error messages.
- Make sure your supervisors are running and configured correctly.
High Memory Usage
If your Horizon worker processes are consuming too much memory, try the following:
- Reduce the number of worker processes.
- Optimize your job code to reduce memory consumption.
- Increase the memory limit for your worker processes in
config/horizon.php
.
Example Bug Fix
Occasionally, you may see an error like "Class 'App\Jobs\YourJob' not found" even when the class exists. This can be caused by composer autoload issues. Try running the following:
composer dump-autoload php artisan optimize:clear
Interactive Example: Simulating a Long-Running Job
To demonstrate the power of Horizon, let's simulate a long-running job and observe how Horizon tracks it. We'll use a simple Artisan command to dispatch a job that sleeps for 60 seconds.
use Illuminate\Support\Facades\Bus; use App\Jobs\LongRunningJob; Route::get('/simulate-job', function () { Bus::dispatch(new LongRunningJob()); return 'Job dispatched!'; }); class LongRunningJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function handle() { sleep(60); Log::info('Long running job completed!'); } }
- Create a new Job with the artisan command:
- Edit the job with the code above
- Visit the simulate-job route and observe the Horizon dashboard
php artisan make:job LongRunningJob
To view the job dashboard, you will need to access the Horizon dashboard in your browser. Typically, this can be found at the route: /horizon
Final Thoughts
Laravel Horizon significantly simplifies queue management, providing a powerful dashboard and code-driven configuration. By understanding its core concepts and features, you can optimize your application's performance and ensure reliable background processing.
Keywords
Laravel Horizon, Redis, queue management, job monitoring, queue system, Laravel queues, supervisor configuration, job retries, failed jobs, tags, metrics, Horizon dashboard, worker processes, queue throughput, Redis queues, asynchronous tasks, background processing, performance optimization, Laravel development, queue configuration.
Frequently Asked Questions
What is Laravel Horizon?
Laravel Horizon is the official Redis-powered queue monitoring and configuration dashboard for Laravel. It provides a beautiful UI and code-driven configuration for managing your queues.
How do I install Laravel Horizon?
You can install Horizon via Composer using the command composer require laravel/horizon
. Then, run php artisan horizon:install
to publish the assets.
How do I start Horizon?
You can start Horizon by running the command php artisan horizon
in your terminal.
How do I configure Horizon?
You can configure Horizon using the config/horizon.php
file. This file allows you to define environments, queues, supervisors, and other settings.
What are supervisors in Horizon?
Supervisors define how many worker processes should be running for each queue. They are configured within the config/horizon.php
file.