alata.
Packages

Horizon

A real-time web dashboard and process manager for your Alata queue workers, published as taskiq-horizon.

Horizon manages your queue workers and gives you a dashboard for jobs, failures, batches, and performance. Start it with ./alata horizon, then use the dashboard to monitor work and retry failed jobs.

Horizon ships as its own package, taskiq-horizon, and requires Redis for job history, metrics, and supervisor commands. Jobs may use Redis, database, or SQS queues. The process manager supports Linux and macOS.

What You Get

  • Real-time dashboard — pending, completed, silenced, and failed jobs as they happen, with payloads and runtimes.
  • Failed job forensics — every failure stores the full traceback plus a structured exception context (type, queue, attempts, tags), and can be retried from the UI.
  • Batches — inspect and retry job batches from the dashboard.
  • Metrics — throughput and runtime charts per job type and per queue, built from periodic snapshots.
  • Tag monitoring — tag jobs (for example tenant:42) and watch just that subset.
  • Process management — supervisors with auto, simple, and false balancing modes, per-queue autoscaling, and memory limits.

Installation

Install Horizon from PyPI into your Alata application:

uv add taskiq-horizon

Horizon needs a running Redis service. For a local application using Redis queues, configure:

.env
QUEUE_CONNECTION=redis
REDIS_URL=redis://127.0.0.1:6379/0

Applications using database or SQS queues can keep their existing queue connection; Horizon still uses Redis for its dashboard. Complete the queue setup for your chosen connection, including the application's migrations.

Configuration

Create config/horizon.py with a supervisor for each environment where you run workers:

config/horizon.py
from taskiq_horizon.config import HorizonConfig
from taskiq_horizon.supervisor import SupervisorOptions

from config.settings import settings

worker_args = [
    "--max-async-tasks", "25",
]

horizon_config = HorizonConfig(
    prefix="myapp-horizon:",
    redis_url=settings.REDIS_URL,
    environments={
        "production": {
            "supervisor-1": SupervisorOptions(
                broker_path="bootstrap.broker:broker",
                queue="default",
                worker_args=worker_args,
                max_processes=20,
            )
        },
        "local": {
            "supervisor-1": SupervisorOptions(
                broker_path="bootstrap.broker:broker",
                queue="default",
                worker_args=worker_args,
                max_processes=3,
            )
        },
    },
)

The active application environment (APP_ENV or --env) selects the supervisor configuration. Add matching entries for other environments, such as staging. The example allows up to twenty worker processes in production and three locally. Choose a prefix unique to the application and environment when sharing Redis.

Set queue to the names your application dispatches to. For multiple queues, use a comma-separated list such as "high,default,low". Horizon discovers ShouldQueue jobs and decorated tasks using the same queue configuration as queue:work.

See the configuration reference for scaling limits, retention, and other options.

Registering the Provider

Add the package's service provider to your application providers:

bootstrap/providers.py
from taskiq_horizon.alata_provider import HorizonProvider

PROVIDERS = [
    # Your other application providers...
    HorizonProvider,
]

The provider registers the Horizon commands and dashboard. Keep the framework queue provider in FRAMEWORK_PROVIDERS and append Horizon to your existing application providers.

To supply configuration directly, register (HorizonProvider, horizon_config) instead.

Queue connections

ConnectionWorkload and autoscaling
RedisReads the queue broker's pending jobs. Horizon history can use a separate Redis connection.
DatabaseCounts runnable jobs, including expired reservations, on PostgreSQL, MySQL, or SQLite. Delayed jobs and active reservations are excluded.
SQSUses SQS's approximate visible-message count. Use auto or simple balancing for multiple queues; each worker consumes one queue.

The sync and null connections run without an external queue. Horizon refuses to start workers for these connections.

Running Horizon

Start the master supervisor with a single command:

./alata horizon

Horizon starts the configured worker pools, balances their workload, and replaces workers that exit or exceed their memory limit. Leave it running while your application dispatches jobs.

Stopping the master with Ctrl+C (or SIGTERM in production) shuts the whole tree down gracefully.

Run one Horizon process per application instance. Horizon starts its own queue workers; you do not need an additional queue:work process for those queues.

Pausing and resuming

Control the supervisors sharing this application's Horizon Redis connection and prefix:

./alata horizon:pause      # stop taking new jobs
./alata horizon:continue   # resume processing
./alata horizon:terminate  # gracefully stop Horizon

These commands apply across all servers sharing that configuration. Pausing lets current jobs finish while stopping new work; horizon:continue starts processing again. horizon:terminate waits for current jobs and exits. Your process manager should restart Horizon automatically.

Metrics snapshots

The dashboard's throughput and runtime charts are built from periodic snapshots. Capture one with:

./alata horizon:snapshot

Schedule it every five minutes in your console kernel so the graphs stay populated:

app/console/kernel.py
def schedule(self, schedule: Schedule):
    schedule.command("horizon:snapshot").every_five_minutes()

Add this line to your existing AppKernel.schedule() method. Ensure the scheduler runs every minute and take snapshots on one server per Horizon Redis connection and prefix.

Horizon keeps the latest metrics.trim_snapshots.job / .queue snapshots (24 by default). With snapshots every five minutes, that covers roughly two hours. Set both to 288 for a full day.

The Dashboard

Run your HTTP application alongside Horizon. Locally, start ./alata serve in another terminal and open /horizon on your application's address. The Horizon worker command does not start an HTTP server.

The dashboard includes:

  • Overview — jobs per minute, current workload per queue, max wait times, and the status of every master and supervisor.
  • Pending / Completed / Silenced jobs — live job lists with payloads and runtimes.
  • Failed jobs — full stored traceback, structured exception context, and one-click retry.
  • Batches — batch progress and per-batch retry of failed jobs.
  • Metrics — throughput and runtime charts per job type and per queue.
  • Monitoring — follow all jobs carrying a specific tag.

Tagging jobs

Add tags to a job class:

app/jobs/charge_invoice.py
from alata.queue import ShouldQueue


class ChargeInvoice(ShouldQueue):
    tags = ("billing", "invoices")

    async def handle(self, invoice_id: int):
        ...

A list works too (tags = ["billing", "invoices"]). Decorated functions can declare @broker.task(tags=["billing", "invoices"]). Tags show up on every job in the dashboard, and any tag added under Monitoring collects its jobs into a dedicated view. Tags listed in silenced_tags (or task names in silenced) are diverted to the Silenced tab instead of the main feed.

Failed Jobs and Exception Context

When a job fails permanently, Horizon stores the complete traceback for the dashboard's stacktrace panel — and builds a structured context alongside it, automatically:

{
  "exception_type": "PaymentDeclinedError",
  "connection": "redis",
  "queue": "default",
  "task_name": "charge_invoice",
  "attempts": 3,
  "tags": ["tenant:42", "billing"],
  "labels": {"queue_name": "default"}
}

If the exception itself carries a context attribute — or a context() method returning a dict — Horizon merges it into the stored context, so you can attach domain details at the point of failure:

class PaymentDeclinedError(Exception):
    def __init__(self, invoice_id: int, reason: str):
        super().__init__(f"Payment declined: {reason}")
        self.invoice_id = invoice_id
        self.reason = reason

    def context(self) -> dict:
        return {"invoice_id": self.invoice_id, "decline_reason": self.reason}

The dashboard renders the merged context next to the traceback on the failed-job page. Failed job records are kept for trim.failed minutes (7 days by default) and can be retried or deleted from the UI. Automatic retries remain pending until they succeed or exhaust their retry allowance. Retrying from the dashboard starts a fresh attempt with the full retry allowance.

This is the same context() convention used by the framework's exception handler for report enrichment — one method serves both your logs and your queue dashboard.

Securing the Dashboard

Restrict dashboard access to authorized operators before exposing it in production. Horizon does not add an access policy automatically. Use an authenticated reverse proxy or your application's verified authentication and global middleware.

Protect both /horizon and every path beneath it, including /horizon/api/*. If you change path or use a proxy prefix, protect the corresponding public URLs. Check that signed-out users and signed-in users without operator access cannot view job payloads, retry jobs, or clear queued jobs.

Running in Production

Keep Horizon running under your process manager, alongside your HTTP service and scheduler. On Linux, a systemd service can start it at boot and restart it after an exit.

Create /etc/systemd/system/myapp-horizon.service, replacing the application path, Python environment path, and service user with your deployment's values:

myapp-horizon.service
[Unit]
Description=MyApp Horizon
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=myapp
WorkingDirectory=/srv/myapp
Environment="PATH=/srv/myapp/.venv/bin:/usr/local/bin:/usr/bin:/bin"
ExecStart=/srv/myapp/alata horizon --env=production
Restart=always
RestartSec=5
KillMode=mixed
TimeoutStopSec=90

[Install]
WantedBy=multi-user.target

The service user needs access to the application, its environment settings, and writable storage. The PATH above selects the application's Python installation when running alata.

Enable the service and check its logs:

sudo systemctl daemon-reload
sudo systemctl enable --now myapp-horizon
sudo systemctl status myapp-horizon
sudo journalctl -u myapp-horizon -f

Horizon allows workers up to SupervisorOptions.timeout seconds to finish during shutdown. Set that timeout above your longest expected job duration, and keep TimeoutStopSec longer than Horizon's timeout. The example uses the default 60-second Horizon timeout with a 90-second service timeout. Mixed shutdown mode lets Horizon stop its workers before the service manager forces any remaining processes to exit.

Deploying new code

After deploying application code or changing its configuration, ask Horizon to finish current work and exit:

./alata horizon:terminate

This reaches every Horizon master sharing the configured Redis connection and prefix. The process manager starts fresh workers using the deployed code after the old workers finish. Confirm the dashboard shows active workers and that new jobs complete. You can also use sudo systemctl restart myapp-horizon on each worker server, or your container platform’s rollout operation.

Troubleshooting

SymptomCheck
No supervisors configuredAdd an environments entry matching the active APP_ENV.
Jobs stay pendingConfirm the queue name matches the job's destination, workers are running, and the module is inside a configured task package.
Dashboard is unavailableRun the HTTP application, register HorizonProvider, and check the configured dashboard path and access policy.
Dashboard history is missingUse the same Horizon Redis connection and prefix in the HTTP application, job producers, and workers.
Charts stay emptyRun ./alata horizon:snapshot and check that its scheduled command is running.
Workers repeatedly restartInspect service logs for task import errors or memory-limit exits before adjusting worker settings.

Configuration Reference

HorizonConfig keys

KeyDefaultPurpose
prefix"taskiq-horizon:"Namespace for job history and commands. Use a distinct prefix for each application and environment; share it across that application's worker servers.
name""Display name suffix shown in the dashboard title/header.
path"horizon"Route path the dashboard is mounted under (e.g. "horizon", "ops/horizon").
proxy_path""External proxy path prefix for the dashboard's router (e.g. "/admin") when served behind a path-rewriting proxy.
redis_url"redis://localhost:6379/0"Redis connection for dashboard history, metrics, and worker commands.
trimTrimSettings()How long (in minutes) to keep job records: recent, pending, completed, recent_failed, failed, monitored.
silenced / silenced_tags[]Task names / tags to hide from the main job lists (they land in the Silenced tab).
metricsHorizonMetricsConfig()Number of snapshots to retain for each job and queue (default 24).
waits{"default": 60}Per-queue wait-time thresholds in seconds before a long-wait event fires.
memory_limit512Memory (MB) the master process may consume before a graceful restart is requested.
environments{}{environment: {supervisor_name: SupervisorOptions}} — the supervisor layout per environment.

SupervisorOptions

Each supervisor manages one queue — or a comma-separated set of queues — with its own scaling and resource limits:

OptionDefaultPurpose
queue"default"Queue name, or comma-separated list ("default,high,low").
balance"auto"Balancing mode: "auto", "simple", or "false" (see below).
min_processes1Minimum target per queue when balancing, or for the shared pool when balancing is disabled.
max_processes10Maximum total worker processes across this supervisor's queues.
memory128Memory limit (MB) per worker process before it is recycled.
timeout60Grace period in seconds for workers to drain before forced termination; not a per-job execution timeout.
balance_cooldown3Seconds between autoscaling adjustments.
balance_max_shift1Maximum processes added/removed per adjustment.
auto_scale_by_num_jobsFalseScale on queue length instead of projected time-to-clear.
auto_scaling_strategy"time"The default strategy weighs each queue by time to clear (queue length × recent average runtime).
broker_path""Import path of your broker, e.g. "bootstrap.broker:broker" — what each worker process loads.
worker_args[]Extra worker options, such as --max-async-tasks. Job discovery uses the application's queue configuration.

Balancing modes

  • auto (default) — each queue gets its own worker pool, and the autoscaler continuously shifts processes between pools based on each queue's projected time-to-clear (or queue length, with auto_scale_by_num_jobs=True), within min_processes/max_processes. A busy high queue borrows workers from an idle low queue.
  • simple — each queue gets its own pool and processes are split evenly between them; no autoscaling.
  • "false" — a single pool of workers consumes the comma-separated queue list in the order given, so earlier queues act as higher priority.

For balanced queues, max_processes must be at least number of queues × min_processes so every queue can receive its minimum allocation.

worker_args is where per-worker concurrency lives: "--max-async-tasks", "25" caps how many async tasks a single worker process runs simultaneously. Total concurrency is roughly processes × max async tasks.

On this page