alata.
Digging Deeper

Queues

Create background jobs, dispatch them, and run workers with retries and failure tracking.

Queues let you send email, generate reports, and process files in the background. Create a job, dispatch it from your application, and run a worker to process it.

Getting started

For a first queue, use your application's configured database:

.env
QUEUE_CONNECTION=database

Run the migrations and create a job:

Terminal
./alata migrate
./alata make:job SendWelcomeEmail

Database queues work with PostgreSQL, MySQL, and SQLite. You can also use Redis or SQS.

Creating jobs

The generator creates app/jobs/send_welcome_email.py. Put the work in handle():

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


class SendWelcomeEmail(ShouldQueue):
    async def handle(self, user_id: int) -> None:
        # Load the user and send their welcome email.
        ...

Both async def handle() and def handle() are supported. Declare job inputs as arguments to handle(). Pass IDs and other JSON-compatible values; load the records you need inside the job.

Automatic discovery

Jobs in app/jobs/ and decorated functions in app/tasks/ are available to workers automatically, including subfolders. For a nested job, run:

./alata make:job Billing/GenerateInvoice

To add another package, update config/queue.py:

QUEUE_CONFIG["task_modules"] = [
    "app.jobs",
    "app.tasks",
    "app.billing.jobs",
]

The same configuration applies to Horizon and scheduled jobs.

Dispatching jobs

Call dispatch() from an async handler or service:

from app.jobs.send_welcome_email import SendWelcomeEmail

await SendWelcomeEmail.dispatch(user_id=42)

With database, Redis, or SQS queues, this queues the job and lets the caller continue. Start a worker to execute it.

Write jobs so that running them again is safe. For example, check whether an invoice has already been sent before sending it again. A job can run more than once after a failure or interruption.

Queue selection

Send a job to a named queue:

await SendWelcomeEmail.on_queue("emails").dispatch(user_id=42)

Or set a default on the class:

class SendWelcomeEmail(ShouldQueue):
    queue = "emails"

    async def handle(self, user_id: int) -> None:
        ...

on_queue() overrides the class default for one dispatch. Run a worker listening to the same queue:

./alata queue:listen --queue=emails

Running workers

Local development

Use queue:listen while developing:

Terminal
./alata queue:listen

It runs one worker and reloads when you change Python code. Keep it running in a separate terminal alongside ./alata serve. Stop it with Ctrl+C. Restart it manually after changing environment variables or installing dependencies.

Select queues with --queue:

./alata queue:listen --queue=high,default,low

Redis and database workers check queues in the order given. SQS accepts one queue per worker command.

Production

Use queue:work for long-running workers:

./alata queue:work
./alata queue:work --queue=high,default,low --workers=4
OptionDefaultPurpose
--queueConfigured queueQueue to process, or a priority list for Redis and database queues.
--workers2Number of worker processes.
--reloadOffRun one worker with code reload for development, like queue:listen.

Both commands accept -v for debug logging. Without --queue, they use QUEUE_NAME, or SQS_QUEUE_NAME for SQS.

Restart production workers after deploying code changes. Use your process manager to keep them running, or Horizon for worker management and a dashboard. See deployment.

Configuration

Choose a connection in .env. Additional settings live in config/queue.py.

ConnectionUse
databaseQueue jobs using PostgreSQL, MySQL, or SQLite, without a separate queue service.
redisQueue jobs using a running Redis service.
sqsQueue jobs using AWS SQS.
syncExecute jobs immediately; the caller waits for them to finish. Useful for tests and simple local runs.
nullDiscard dispatched jobs. Useful when background work should be disabled.

queue:listen and queue:work require database, redis, or sqs. The sync and null connections do not use workers.

Run ./alata migrate to enable batching and failed-job tracking on any connection.

The database connection

.env
QUEUE_CONNECTION=database
QUEUE_NAME=default
QUEUE_RETRY_AFTER=3600

Run ./alata migrate before starting a worker. Set QUEUE_RETRY_AFTER higher than your longest job's runtime so a slow job is not picked up by another worker while it is still running.

The Redis connection

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

Set REDIS_QUEUE_URL if queues should use a different Redis service from the rest of the application. Set REDIS_QUEUE_RESULT_URL to store results separately. Configure a working Redis URL before starting a worker; without a URL, jobs run immediately in the calling process.

The SQS connection

.env
QUEUE_CONNECTION=sqs
SQS_QUEUE_NAME=default
AWS_REGION=us-east-1

Configure AWS credentials through your environment or an IAM role. Optional settings include SQS_QUEUE_URL, SQS_RESULT_BUCKET for storing results in S3, and SQS_ENDPOINT_URL for local services such as LocalStack.

Retries

ShouldQueue jobs retry failures automatically. Set application defaults in .env:

QUEUE_MAX_RETRIES=3
QUEUE_RETRY_DELAY=60

QUEUE_MAX_RETRIES is the total number of attempts, including the first. QUEUE_RETRY_DELAY is the pause between failed attempts, in seconds.

Override either setting on a job:

class SendWelcomeEmail(ShouldQueue):
    max_retries = 5
    retry_delay = 10

    async def handle(self, user_id: int) -> None:
        ...

Set max_retries = 1 to attempt the job once.

The failed callback

Add failed() to react when a job has no attempts left. It receives the exception and the original job arguments:

class SendWelcomeEmail(ShouldQueue):
    async def handle(self, user_id: int) -> None:
        ...

    async def failed(self, exception: BaseException, user_id: int) -> None:
        # Record the failed delivery or notify your team.
        ...

The callback can be synchronous or async. Use the supplied arguments to identify the failed work.

Results

Keep the returned task handle when you need the job's return value:

from app.jobs.generate_report import GenerateReport

task = await GenerateReport.dispatch(report_id=42)
result = await task.wait_result(timeout=30)
result.raise_for_error()
report_url = result.return_value

Return JSON-compatible values from jobs. Result storage must be configured for your connection. Database results expire after 24 hours by default; change result_ttl in the database queue configuration if you need them longer.

Job batches

Dispatch a group of jobs and run callbacks when the group finishes:

from alata.queue.batch import Batch, job
from app.jobs.import_chunk import ImportChunk
from app.jobs.notify_import import NotifyImport

batch = await (
    Batch.create(
        "Import customers",
        [job(ImportChunk, chunk_id=chunk_id) for chunk_id in chunk_ids],
    )
    .then(job(NotifyImport, message="Import finished"))
    .catch(job(NotifyImport, message="Import had failures"))
    .finally_(job(NotifyImport, message="Import ended"))
    .dispatch()
)

batch_id = batch.record.id
  • then() runs after every job succeeds.
  • catch() runs when the batch finishes with at least one permanently failed job.
  • finally_() runs when the batch finishes, regardless of the outcome.

Retries finish before a job is counted as failed. Callback jobs should also be safe to run more than once. Use Horizon to inspect batch progress and retry failures.

Pruning old batches

./alata queue:prune-batches
./alata queue:prune-batches --hours=48 --unfinished=168

By default, finished or cancelled batches are kept for 24 hours and unfinished batches for 72 hours. Schedule this command from your console kernel.

Failed jobs

Inspect jobs that have permanently failed:

./alata queue:failed
./alata queue:failed --limit=50

Retry one job using the UUID shown in the list, or retry all failed jobs:

./alata queue:retry <uuid>
./alata queue:retry --all

Retried jobs return to their original queue with a fresh allowance of attempts. Once queued successfully, they are removed from the failed-job list.

Delete all saved failure records with:

./alata queue:flush

Horizon cleanup

If Horizon shows jobs abandoned by a worker that stopped unexpectedly, run:

./alata queue:prune-orphans

This marks jobs older than QUEUE_RETRY_AFTER as failed in Horizon. The generated console schedule already runs it hourly; keep the scheduler running.

Defining tasks

You can also use decorated functions in app/tasks/:

app/tasks/report_tasks.py
from bootstrap.broker import broker


@broker.task(
    task_name="reports:generate",
    retry_on_error=True,
    max_retries=3,
    retry_delay=10,
)
async def generate_report(report_id: int) -> None:
    ...

Both synchronous and async functions are supported. Set retry_on_error=True to enable retries for decorated tasks. task_name gives the task a stable name if you later move the function.

Dispatch the task with .kiq():

from app.tasks.report_tasks import generate_report

await generate_report.kiq(report_id=42)

Choose a queue for one dispatch:

await generate_report.kicker().with_labels(queue_name="reports").kiq(report_id=42)

To retry only selected exceptions, add types_of_exceptions=[TimeoutError, ConnectionError] to the decorator. To handle permanent failure, define a function named generate_report_failed(exception, report_id) in the same module, or use @failed_handler(generate_report) from alata.queue.retry_middleware.

Job classes and decorated functions can be used together, including in batches and scheduled jobs.

On this page