Laravel Horizon

Introduction

Horizon provides a beautiful dashboard and code-driven configuration for your Laravel powered Redis queues. Horizon allows you to easily monitor key metrics of your queue system such as job throughput, runtime, and job failures.

All of your worker configuration is stored in a single, simple configuration file, allowing your configuration to stay in source control where your entire team can collaborate.

Installation

{note} You should ensure that your queue connection is set to redis in your queue configuration file.

You may use Composer to install Horizon into your Laravel project:

  1. composer require laravel/horizon

After installing Horizon, publish its assets using the horizon:install Artisan command:

  1. php artisan horizon:install

Configuration

After publishing Horizon’s assets, its primary configuration file will be located at config/horizon.php. This configuration file allows you to configure your worker options and each configuration option includes a description of its purpose, so be sure to thoroughly explore this file.

{note} You should ensure that the environments portion of your horizon configuration file contains an entry for each environment on which you plan to run Horizon.

Balance Options

Horizon allows you to choose from three balancing strategies: simple, auto, and false. The simple strategy, which is the configuration file’s default, splits incoming jobs evenly between processes:

  1. 'balance' => 'simple',

The auto strategy adjusts the number of worker processes per queue based on the current workload of the queue. For example, if your notifications queue has 1,000 waiting jobs while your render queue is empty, Horizon will allocate more workers to your notifications queue until it is empty. When the balance option is set to false, the default Laravel behavior will be used, which processes queues in the order they are listed in your configuration.

When using the auto strategy, you may define the minProcesses and maxProcesses configuration options to control the minimum and maximum number of processes Horizon should scale up and down to:

  1. 'environments' => [
  2. 'production' => [
  3. 'supervisor-1' => [
  4. 'connection' => 'redis',
  5. 'queue' => ['default'],
  6. 'balance' => 'auto',
  7. 'minProcesses' => 1,
  8. 'maxProcesses' => 10,
  9. 'balanceMaxShift' => 1,
  10. 'balanceCooldown' => 3,
  11. 'tries' => 3,
  12. ],
  13. ],
  14. ],

The balanceMaxShift and balanceCooldown configuration values to determine how quickly Horizon will scale to meet worker demand. In the example above, a maximum of one new process will be created or destroyed every three seconds. You are free to tweak these values as necessary based on your application’s needs.

Job Trimming

The horizon configuration file allows you to configure how long recent and failed jobs should be persisted (in minutes). By default, recent jobs are kept for one hour while failed jobs are kept for a week:

  1. 'trim' => [
  2. 'recent' => 60,
  3. 'failed' => 10080,
  4. ],

Dashboard Authorization

Horizon exposes a dashboard at /horizon. By default, you will only be able to access this dashboard in the local environment. Within your app/Providers/HorizonServiceProvider.php file, there is a gate method. This authorization gate controls access to Horizon in non-local environments. You are free to modify this gate as needed to restrict access to your Horizon installation:

  1. /**
  2. * Register the Horizon gate.
  3. *
  4. * This gate determines who can access Horizon in non-local environments.
  5. *
  6. * @return void
  7. */
  8. protected function gate()
  9. {
  10. Gate::define('viewHorizon', function ($user) {
  11. return in_array($user->email, [
  12. '[email protected]',
  13. ]);
  14. });
  15. }

{note} Remember that Laravel injects the authenticated user to the Gate automatically. If your app is providing Horizon security via another method, such as IP restrictions, then your Horizon users may not need to “login”. Therefore, you will need to change function ($user) above to function ($user = null) to force Laravel to not require authentication.

Upgrading Horizon

When upgrading to a new major version of Horizon, it’s important that you carefully review the upgrade guide.

In addition, when upgrading to any new Horizon version, you should re-publish Horizon’s assets:

  1. php artisan horizon:publish

To keep the assets up-to-date and avoid issues in future updates, you may add the command to the post-update-cmd scripts in your composer.json file:

  1. {
  2. "scripts": {
  3. "post-update-cmd": [
  4. "@php artisan horizon:publish --ansi"
  5. ]
  6. }
  7. }

Running Horizon

Once you have configured your workers in the config/horizon.php configuration file, you may start Horizon using the horizon Artisan command. This single command will start all of your configured workers:

  1. php artisan horizon

You may pause the Horizon process and instruct it to continue processing jobs using the horizon:pause and horizon:continue Artisan commands:

  1. php artisan horizon:pause
  2. php artisan horizon:continue

You may check the current status of the Horizon process using the horizon:status Artisan command:

  1. php artisan horizon:status

You may gracefully terminate the master Horizon process on your machine using the horizon:terminate Artisan command. Any jobs that Horizon is currently processing will be completed and then Horizon will exit:

  1. php artisan horizon:terminate

Deploying Horizon

If you are deploying Horizon to a live server, you should configure a process monitor to monitor the php artisan horizon command and restart it if it quits unexpectedly. When deploying fresh code to your server, you will need to instruct the master Horizon process to terminate so it can be restarted by your process monitor and receive your code changes.

Installing Supervisor

Supervisor is a process monitor for the Linux operating system, and will automatically restart your horizon process if it fails. To install Supervisor on Ubuntu, you may use the following command:

  1. sudo apt-get install supervisor

{tip} If configuring Supervisor yourself sounds overwhelming, consider using Laravel Forge, which will automatically install and configure Supervisor for your Laravel projects.

Supervisor Configuration

Supervisor configuration files are typically stored in the /etc/supervisor/conf.d directory. Within this directory, you may create any number of configuration files that instruct supervisor how your processes should be monitored. For example, let’s create a horizon.conf file that starts and monitors a horizon process:

  1. [program:horizon]
  2. process_name=%(program_name)s
  3. command=php /home/forge/app.com/artisan horizon
  4. autostart=true
  5. autorestart=true
  6. user=forge
  7. redirect_stderr=true
  8. stdout_logfile=/home/forge/app.com/horizon.log
  9. stopwaitsecs=3600

{note} You should ensure that the value of stopwaitsecs is greater than the number of seconds consumed by your longest running job. Otherwise, Supervisor may kill the job before it is finished processing.

Starting Supervisor

Once the configuration file has been created, you may update the Supervisor configuration and start the processes using the following commands:

  1. sudo supervisorctl reread
  2. sudo supervisorctl update
  3. sudo supervisorctl start horizon

For more information on Supervisor, consult the Supervisor documentation.

Tags

Horizon allows you to assign “tags” to jobs, including mailables, event broadcasts, notifications, and queued event listeners. In fact, Horizon will intelligently and automatically tag most jobs depending on the Eloquent models that are attached to the job. For example, take a look at the following job:

  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\Video;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Bus\Dispatchable;
  7. use Illuminate\Queue\InteractsWithQueue;
  8. use Illuminate\Queue\SerializesModels;
  9. class RenderVideo implements ShouldQueue
  10. {
  11. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  12. /**
  13. * The video instance.
  14. *
  15. * @var \App\Models\Video
  16. */
  17. public $video;
  18. /**
  19. * Create a new job instance.
  20. *
  21. * @param \App\Models\Video $video
  22. * @return void
  23. */
  24. public function __construct(Video $video)
  25. {
  26. $this->video = $video;
  27. }
  28. /**
  29. * Execute the job.
  30. *
  31. * @return void
  32. */
  33. public function handle()
  34. {
  35. //
  36. }
  37. }

If this job is queued with an App\Models\Video instance that has an id of 1, it will automatically receive the tag App\Models\Video:1. This is because Horizon will examine the job’s properties for any Eloquent models. If Eloquent models are found, Horizon will intelligently tag the job using the model’s class name and primary key:

  1. $video = App\Models\Video::find(1);
  2. App\Jobs\RenderVideo::dispatch($video);

Manually Tagging

If you would like to manually define the tags for one of your queueable objects, you may define a tags method on the class:

  1. class RenderVideo implements ShouldQueue
  2. {
  3. /**
  4. * Get the tags that should be assigned to the job.
  5. *
  6. * @return array
  7. */
  8. public function tags()
  9. {
  10. return ['render', 'video:'.$this->video->id];
  11. }
  12. }

Notifications

Note: When configuring Horizon to send Slack or SMS notifications, you should review the prerequisites for the relevant notification driver.

If you would like to be notified when one of your queues has a long wait time, you may use the Horizon::routeMailNotificationsTo, Horizon::routeSlackNotificationsTo, and Horizon::routeSmsNotificationsTo methods. You may call these methods from your application’s HorizonServiceProvider:

  1. Horizon::routeMailNotificationsTo('[email protected]');
  2. Horizon::routeSlackNotificationsTo('slack-webhook-url', '#channel');
  3. Horizon::routeSmsNotificationsTo('15556667777');

Configuring Notification Wait Time Thresholds

You may configure how many seconds are considered a “long wait” within your config/horizon.php configuration file. The waits configuration option within this file allows you to control the long wait threshold for each connection / queue combination:

  1. 'waits' => [
  2. 'redis:default' => 60,
  3. 'redis:critical,high' => 90,
  4. ],

Metrics

Horizon includes a metrics dashboard which provides information on your job and queue wait times and throughput. In order to populate this dashboard, you should configure Horizon’s snapshot Artisan command to run every five minutes via your application’s scheduler:

  1. /**
  2. * Define the application's command schedule.
  3. *
  4. * @param \Illuminate\Console\Scheduling\Schedule $schedule
  5. * @return void
  6. */
  7. protected function schedule(Schedule $schedule)
  8. {
  9. $schedule->command('horizon:snapshot')->everyFiveMinutes();
  10. }