Laravel Horizon: A Comprehensive Guide
Laravel Horizon is a powerful and user-friendly queue monitoring dashboard built for Laravel applications. It provides developers with an intuitive interface to monitor and manage queues, jobs, and workers. Horizon is particularly useful in applications that rely heavily on asynchronous job processing, offering real-time insights and analytics into queue performance and health.
Key Features of Laravel Horizon
1. Queue Monitoring
Horizon allows you to monitor the status of your queues and jobs in real time. You can track:
- Job progress
- Job failures
- Active workers
- Job retry counts
- Queue performance metrics
2. Dashboard
The Horizon dashboard is a web-based interface where developers can:
- View all running and completed jobs.
- Monitor job retries and failures.
- Inspect detailed job information, including payloads and execution time.
3. Metrics and Analytics
Horizon provides detailed metrics, including:
- Average job runtime
- Job throughput (jobs per second)
- Recent jobs processed
- Failure trends and retry statistics
4. Job Prioritization
You can define priority levels for queues, ensuring critical tasks are executed before less important ones.
5. Notifications and Alerts
Horizon integrates with Laravel's notification system to send alerts when certain thresholds are exceeded, such as job failures or long runtimes.
6. Worker Management
Horizon provides tools to:
- Scale workers dynamically.
- Assign workers to specific queues.
- Monitor worker performance and status.
7. Redis Integration
Horizon is tightly integrated with Redis, which serves as the backend for managing queues. It leverages Redis’s speed and reliability for optimal performance.
Installing Laravel Horizon
To install Horizon in a Laravel application, follow these steps:
Install Horizon via Composer:
composer require laravel/horizonPublish Horizon's Assets: Run the following command to publish the configuration file:
php artisan horizon:installThis creates the
config/horizon.phpfile, where you can customize Horizon's settings.Run Horizon: Start Horizon by running:
php artisan horizonAccess the Dashboard: By default, Horizon is available at
/horizonin your application (e.g.,http://your-app-domain/horizon).
Configuration
The config/horizon.php file contains all configuration options for Horizon. Key options include:
- Environments: Define worker settings for different environments (e.g., local, production).
- Supervisor Configuration: Manage worker pools with parameters like queue, balance strategy, and process count.
- Queue Priorities: Specify the order in which queues should be processed.
- Timeouts: Configure timeout values for jobs and processes.
Example supervisor configuration:
'supervisors' => [
'default' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'simple',
'processes' => 10,
'tries' => 3,
],
],
Monitoring Metrics
Job Metrics
Horizon records key performance metrics for jobs:
- Runtime: The time taken to execute a job.
- Throughput: The number of jobs processed per minute.
- Failures: The number and details of failed jobs.
Tags
Jobs can be tagged to enable filtering and analysis in the dashboard:
public function tags()
{
return ['user:'.$this->user->id];
}
Tags allow you to group jobs by categories, such as users or specific processes.
Horizon in Production
Securing Horizon
In production, you should secure the Horizon dashboard by:
- Restricting access using Laravel’s middleware:
Route::middleware(['auth', 'admin'])->group(function () { Horizon::routes(); }); - Using HTTPS to encrypt dashboard access.
Scaling Workers
To optimize performance, scale workers based on your application’s needs:
- Increase the number of workers for high-priority queues.
- Use the
auto-scalingfeature to dynamically adjust worker processes.
Deploying with Supervisord
In production, use Supervisord to manage Horizon processes. Example configuration:
[program:horizon]
process_name=%(program_name)s
command=php /path-to-your-project/artisan horizon
autostart=true
autorestart=true
user=your-user
redirect_stderr=true
stdout_logfile=/path-to-your-project/horizon.log
Restart Supervisord to apply changes:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start horizon
Horizon Alerts and Notifications
Laravel Horizon supports notifications for critical events. Example:
Slack Notifications: Configure Slack notifications in
config/horizon.php:'notifications' => [ 'slack' => [ 'webhook_url' => env('SLACK_WEBHOOK_URL'), 'channel' => '#alerts', 'username' => 'Horizon', ], ],Email Notifications: Use Laravel’s built-in notification channels to send emails for job failures or queue issues.
Best Practices
- Monitor Regularly: Use the dashboard frequently to identify bottlenecks and failures.
- Optimize Queues: Prioritize critical tasks by adjusting queue priorities and worker counts.
- Use Tags: Group jobs by tags to simplify monitoring and debugging.
- Secure the Dashboard: Restrict access and enforce HTTPS for the Horizon dashboard.
- Scale Dynamically: Use auto-scaling to adjust worker counts based on queue load.
Conclusion
Laravel Horizon is an indispensable tool for managing and monitoring queues in Laravel applications. With its rich set of features, real-time dashboard, and robust analytics, it simplifies job management and ensures smooth queue operations. By leveraging Horizon effectively, developers can optimize performance, enhance reliability, and maintain the health of their queue systems effortlessly.