Expand description
§Horizon for Laravel Rust
laravel-horizon is a port of laravel/horizon to Laravel Rust. It runs your Redis queue workers from one code-driven configuration, balances worker processes between queues, records every job, its tags and its failures in Redis, keeps throughput and runtime metrics, and shows all of it in Horizon’s dashboard.
[!NOTE] This is a community port maintained by Rivervo. It is not an official Laravel package. It follows laravel/horizon 5.52.0: the same dashboard (the package’s compiled Vue app, unchanged), the same
/horizon/apiJSON endpoints, Redis keys, configuration, balancing, trimming, metrics, tags andhorizon:*commands, with Rust naming. All credit for the design goes to Taylor Otwell and the package’s contributors.
- Installation
- Configuration
- Balancing
- Dashboard authorization
- Content Security Policy
- Running Horizon
- Tags
- Metrics
- Differences from PHP
- Not yet ported (planned for a later release)
- License
§Installation
Horizon works with Redis queues, so enable Laravel’s redis feature, then add the crate:
cargo add laravel-rust --features redis
cargo add laravel-horizonRegister the service provider in src/app.rs:
use laravel_horizon::HorizonServiceProvider;
Application::configure()
.with_providers(|providers| {
providers.add(HorizonServiceProvider::new());
})and send your jobs to Redis:
QUEUE_CONNECTION=redis
REDIS_URL=redis://127.0.0.1:6379There is nothing to migrate: Horizon keeps everything in Redis. The dashboard is at /horizon.
The provider registers Horizon’s own redis queue driver, as PHP Horizon replaces Laravel’s Redis connector. It stores jobs exactly as Laravel Rust’s Redis driver does (the same keys), so queue:work, queue:clear and queue sizes keep working, and it records each job in Horizon as it’s pushed, reserved and released.
§Configuration
HorizonConfig holds config/horizon.php with the same environment variables: HORIZON_NAME, HORIZON_DOMAIN, HORIZON_PATH (horizon), HORIZON_PREFIX (the slug of APP_NAME followed by _horizon:) and HORIZON_ENV. Change the rest in src/app.rs, or with the provider’s configure:
use laravel_horizon::{Balance, HorizonConfig, SupervisorConfig};
Application::configure().with_config(|config, _| {
let horizon = config.section_mut::<HorizonConfig>();
horizon.use_connection = "default".into(); // `use`
horizon.trim.recent = 60; // minutes
horizon.trim.failed = 10080;
horizon.silenced = vec!["app::jobs::Heartbeat".into()];
horizon.environment(
"production",
[(
"supervisor-1",
SupervisorConfig::new()
.connection("redis")
.queue(["high", "default"])
.balance(Balance::Auto)
.min_processes(1)
.max_processes(10)
.balance_max_shift(1)
.balance_cooldown(3)
.memory(128),
)],
);
})PHP (config/horizon.php) | Rust (HorizonConfig) | Default |
|---|---|---|
name, domain, path, prefix, env | name, domain, path, prefix, env | from the environment variables above |
use | use_connection | default |
waits | waits | redis:default → 60 |
trim.recent, pending, completed, recent_failed, failed, monitored | trim.* | 60, 60, 60, 10080, 10080, 10080 |
silenced, silenced_tags | silenced, silenced_tags (job names, tags) | empty |
metrics.trim_snapshots.job, .queue | trim_snapshots.job, .queue | 24, 24 |
metrics.snapshot_lock | snapshot_lock | 300 |
fast_termination | fast_termination | false |
memory_limit | memory_limit (MB) | 64 |
defaults | defaults | supervisor-1 as in PHP |
environments | environments | production and local as in PHP |
A supervisor’s options in environments fall back to the same supervisor’s defaults, as array_replace_recursive does. Environments are matched in order with * wildcards, and horizon starts the first environment that matches --environment, HORIZON_ENV or APP_ENV.
SupervisorConfig has connection, queue, balance (Balance::Off, Simple, Auto), auto_scaling_strategy (Time, Size, Log), min_processes, max_processes, balance_max_shift, balance_cooldown, max_time, max_jobs, memory, tries, timeout, sleep and nice.
§Balancing
Each supervisor runs worker processes: your application’s own binary running queue:work <connection> --queue=<queues>, one job at a time, restarted when it exits. With Balance::Off, one pool of processes works the supervisor’s queues in order. With Balance::Simple, each queue gets an equal pool. With Balance::Auto, the processes move every balance_cooldown seconds, by at most balance_max_shift, to the queues with the most work, measured by the time their jobs take to clear (Time), their number of jobs (Size) or its logarithm (Log), between min_processes and max_processes. The scaling is PHP’s AutoScaler, line for line.
§Dashboard authorization
As in PHP, the dashboard opens only in the local environment until you say who may open it, Horizon::auth():
HorizonServiceProvider::new().auth(|request| {
Box::pin(async move {
let Ok(auth) = laravel::auth::Auth::<User>::of(request).await else { return false };
auth.user().await.ok().flatten().is_some_and(|user| user.email == "taylor@laravel.com")
})
})Each application keeps its own callback, so several applications in one process (such as parallel tests) don’t share it.
The dashboard is served under the web middleware group, on HORIZON_DOMAIN when it’s set.
§Content Security Policy
When the request has a CSP nonce, the dashboard’s <style> and <script> tags and the font stylesheet’s <link> carry it as nonce="...", as Laravel’s Vite helper does for stylesheets. Without one, they have no nonce attribute. The nonce is Laravel Rust’s per-request laravel::view::csp_nonce(), which laravel-csp’s middleware sets. With another CSP middleware, set it with laravel::view::use_csp_nonce(..) or with PHP’s Horizon::cspNonce():
laravel_horizon::csp_nonce(&nonce); // for the current requestThe nonce alone isn’t enough for a strict policy. As in PHP, the dashboard’s Vue app compiles its templates in the browser, which needs 'unsafe-eval' in script-src, and the page loads the Figtree font from fonts.bunny.net (font-src; the stylesheet itself carries the nonce). Its favicon is a data: image (img-src).
§Running Horizon
Run the master supervisor in the foreground, under systemd or Supervisor in production:
laravel horizon
laravel horizon --environment=productionlaravel horizon:status # exits 0 when running, 1 when paused, 2 when inactive
laravel horizon:pause # signals this machine's masters (USR2)
laravel horizon:continue # (CONT)
laravel horizon:terminate # (TERM) — run it on every deploy; --wait with fast_termination
laravel horizon:list # the running machines
laravel horizon:clear redis --queue=emails
laravel horizon:snapshot # schedule it every five minutes
laravel horizon:clear-metricsSchedule the snapshot that fills the metrics graphs:
#[schedule::tasks]
fn schedule(schedule: &mut Schedule) {
schedule.command("horizon:snapshot").every_five_minutes();
}§Tags
Jobs get tags as they’re pushed. In PHP a job’s tags() method gives them; here the provider takes a function of the job’s name and data:
HorizonServiceProvider::new().tags(|name, data| match name {
"app::jobs::RenderVideo" => vec![format!("video:{}", data["video_id"])],
_ => Vec::new(),
})Monitor a tag from the dashboard’s Monitoring screen to keep its jobs for trim.monitored minutes. Failed jobs are tagged failed:{tag} too, and jobs with a tag in silenced_tags, or a name in silenced or registered with laravel_horizon::silence_jobs([...]) (for packages, whatever the order of the providers), show under Silenced instead of Completed. Inside the application, silence_jobs silences the names for that application only; called outside any application (such as in a provider’s register), it can’t reach one, so the names apply to every application in the process. In register, use laravel_horizon::silence_jobs_in(app.config(), [...]) to silence them for that application only. The provider’s tags(..) and spawn_workers_with(..) also belong to its own application.
§Metrics
Every job that completes adds its runtime to its job’s and its queue’s throughput and average runtime. horizon:snapshot stores them, with each queue’s wait time, keeps the last trim_snapshots of each, and starts the counts again. The dashboard’s jobs per minute, maximum runtime and throughput, wait times and the metrics graphs read them.
§Long waits
Once a minute, the master supervisor works out how long each queue its supervisors work takes to clear, as the dashboard’s wait times do, and dispatches laravel_horizon::events::LongWaitDetected for each queue whose wait is over its waits threshold. A queue without a threshold has 60 seconds, and a threshold of 0 turns the check off for that queue. As in PHP, a Redis lock lets only one machine check each minute. Listen for the event to be told about it:
use laravel::event::Event;
use laravel_horizon::events::LongWaitDetected;
Application::configure()
.with_events(|events, _| {
events.listen(|event: Event<LongWaitDetected>| async move {
tracing::warn!(
"Queue {}:{} has a wait of {} seconds",
event.connection, event.queue, event.seconds
);
});
})§Differences from PHP
- Workers. PHP runs each supervisor as its own
horizon:supervisorprocess, whose workers runhorizon:work. Here the supervisors are part of thehorizonprocess, which loops them every second, and each worker is a process of your binary running Laravel Rust’squeue:workwith--sleep,--max-jobsand--max-time(undernice -nwhenniceis set). A supervisor’spidin the dashboard is the master’s.HorizonServiceProvider::spawn_workers_withreplaces how workers start, asWorkerCommandString::$commanddoes. triesandtimeoutdon’t reach the workers: Laravel Rust’squeue:workhas no--triesor--timeout; they’re set on each job with#[job(tries = .., timeout = ..)]. The supervisor keeps them in its options, andtimeoutis how long a scaled-down worker may take to exit before it’s killed, as in PHP.memoryis checked by the supervisor, which asks a worker over the limit to finish its job and exit, and starts it again; PHP’s worker checks itself.- Pausing. Laravel Rust’s worker can’t pause, so
horizon:pauseasks each worker to finish its job and exit, andhorizon:continuestarts them again. The supervisor keeps its process count while paused. - Tags come from the provider’s
tags(..)function instead of a job’stags()method, and there’s no automatic tagging of Eloquent models. - Job data. The dashboard shows the job’s data as Laravel Rust stores it (JSON), not PHP’s serialized command, so the “delayed until” line from the serialized command isn’t shown.
- Recording never fails a dispatch: if Horizon can’t write its record, it logs a warning, and the job stays queued.
- The dashboard’s monitor, stop-monitoring and retry actions run at once rather than as queued
MonitorTag,StopMonitoringTagandRetryFailedJobjobs. A retry gets a new ID andretry_of, and itsdispatched_atis reset so aretry_forwindow starts again, as PHP resetsretryUntil. - Horizon’s own data is on the Redis connection
use_connectionwithprefixbefore each key, as PHP’shorizonconnection. horizon:terminatealso stores Laravel Rust’squeue:restartsignal, as PHP storesilluminate:queue:restart.- Laravel Rust has no maintenance mode, so the dashboard has no maintenance banner. Horizon needs Unix: the master is managed with signals, as in PHP.
§Not yet ported (planned for a later release)
- Long-wait notifications: the mail, Slack and SMS notification PHP’s
SendNotificationsends forLongWaitDetected, and theHorizon::routeMailNotificationsTo/routeSlackNotificationsTo/routeSmsNotificationsTosettings. The event itself is dispatched (see Long waits). - The Batches screen and its API (
/api/batches), over Laravel Rust’s job batches. horizon:supervisor,horizon:work,horizon:supervisors,horizon:supervisor-status,horizon:pause-supervisor,horizon:continue-supervisor,horizon:forget,horizon:purge,horizon:timeout,horizon:listen,horizon:install,horizon:publish, and the Redis command queue they use.- The events
MasterSupervisorLooped,SupervisorLooped,WorkerProcessRestarting,UnableToLaunchProcessand the others inLaravel\Horizon\Events, as Laravel Rust events. Horizon::night(),proxy_path,MasterSupervisor::determineNameUsing(), and Redis Cluster hash-tagged prefixes.
§License
MIT. See LICENSE.md.
Modules§
- events
- The events Horizon dispatches, as Laravel Rust events:
Laravel\Horizon\Events. - repositories
- The repositories Horizon keeps its data in, on its Redis connection.
- supervisor
- The master supervisor and its supervisors:
MasterSupervisor,Supervisor,ProcessPool,WorkerProcessandAutoScaler.
Structs§
- Authenticate
Authenticate: a403unlesscheckallows the request.- Horizon
Config - The package’s settings:
config/horizon.php, with the same environment variables and defaults. - Horizon
Job - A job
HorizonRedisQueuereserved for a worker. - Horizon
Redis Queue - Horizon’s
redisqueue driver: Laravel Rust’s Redis queue, recording each job in Horizon. - Horizon
Service Provider - Registers the
HorizonConfigsection, Horizon’sredisqueue driver, the listeners that record jobs and metrics, the dashboard and thehorizoncommands: - JobPayload
- A job’s payload, decoded:
JobPayload. - Provisioning
Plan - The supervisors each environment starts:
ProvisioningPlan. - Supervisor
Config - One supervisor’s options in
defaultsorenvironments. Options leftNonecome from the supervisor’s defaults, asarray_replace_recursivedoes in PHP. - Supervisor
Options - A supervisor’s settings:
SupervisorOptions. - Trim
- How many minutes Horizon keeps each list of jobs:
trim. - Trim
Snapshots - How many metric snapshots Horizon keeps:
metrics.trim_snapshots.
Enums§
- Auto
Scaling Strategy - How
autobalancing measures a queue’s work: theautoScalingStrategyoption. - Balance
- How a supervisor shares its processes among its queues: the
balanceoption.
Functions§
- check
Horizon::check(): theauth()callback, or only in thelocalenvironment.- csp_
nonce Horizon::cspNonce(): sets the Content Security Policy nonce that the dashboard’s<style>,<script>and stylesheet<link>tags carry, for the current request.- is_
recording - Whether Horizon records the jobs of the queue connection
connection: those using theredisdriver, which Horizon replaces. - retry_
failed_ job - Pushes the failed job
idagain under a new ID, and records the retry on it:RetryFailedJob. Does nothing when no failed job has the ID. - silence_
jobs - Silences jobs by name, as
silenceddoes, for the current application: a package can call it at any time, whatever the order of the providers, as PHP packages push tohorizon.silencedin theirboot. Horizon checks these names alongsideHorizonConfig::silenced. - silence_
jobs_ in - Silences jobs by name for the application whose configuration is
config, such as from a provider’sregisterwithapp.config(). Without Horizon’s provider in that application, it does nothing. - silenced_
job_ names - The job names
silence_jobssilenced: the current application’s and those silenced outside any application.