Skip to main content

dddramatiq

pypi downloads versions codecov license

Dramatiq helpers: a task facade with actor middlewares, cron tasks and broker middlewares for health checks, metrics and async shutdown

Installation

Install the library using pip:

pip install dddramatiq

Development

The project runs entirely in Docker. Requires Docker and Fabric on the host:

fab build      # build the dev image
fab tests      # run pytest
fab linters    # run ruff (with --fix), ty and complexipy
fab shell      # IPython inside the container
fab bash       # bash inside the container

This project was generated from dd-lib-stub; run uvx copier update to pull in template updates.

Compatibility

Python 3.11 to 3.15. What changed in each release, breaking changes included, is in the GitHub releases.

Depends on dramatiq>=2.0,<2.3, prometheus-client>=0.20,<1, sentry-sdk>=2.12,<4, dddesign>=2.1.2,<3, ddutils>=0.4.0,<0.5.0 and pydantic>=2.1,<3. The tests run on dramatiq's stub broker, no Redis or RabbitMQ is needed.

Package What is in it
dddramatiq.facade BaseDramatiqFacade: finds the task modules, wraps the actors, sends tasks, lists the cron jobs
dddramatiq.actor_middlewares Layers around every actor: log properties, Sentry tags, start and finish logs
dddramatiq.decorators cron, the mark of a periodic actor
dddramatiq.middlewares Broker middlewares: AsyncShutdown, HealthCheck, PrometheusMetrics

Actors are async functions. dramatiq runs them on one event loop per worker process, the thread its AsyncIO middleware manages, so AsyncIO() must be in the broker's middleware list.

Facade

One facade per application is the door to its tasks. A subclass says where the task modules are; the instance imports them, wraps every actor in the actor middlewares and sends tasks by name, so the code that enqueues a task never imports the module that defines it.

import dramatiq
from dramatiq.brokers.redis import RedisBroker
from dramatiq.middleware import AsyncIO

from dddramatiq.actor_middlewares import LogPropertiesManagerMiddleware, SentryTagsMiddleware, TaskLoggingMiddleware
from dddramatiq.facade import BaseDramatiqFacade
from dddramatiq.middlewares import AsyncShutdown, HealthCheck, PrometheusMetrics

broker = RedisBroker(
    url='redis://localhost/0',
    middleware=[AsyncIO(), PrometheusMetrics(), HealthCheck(), AsyncShutdown(close_connections)],
)
dramatiq.set_broker(broker)


class DramatiqFacade(BaseDramatiqFacade):
    base_dir = '/app/src'                                   # where the pattern is looked up
    module_pattern = 'app.*.infrastructure.ports.tasks'     # dotted, `*` for one package
    actor_middlewares = (                                   # the first one is the outermost
        LogPropertiesManagerMiddleware(log_properties_registry),
        SentryTagsMiddleware(log_properties_registry),
        TaskLoggingMiddleware(),
    )


dramatiq_facade_impl = DramatiqFacade()
# app/order_context/infrastructure/ports/tasks/__init__.py
import dramatiq

from dddramatiq.decorators import cron


@dramatiq.actor(queue_name='orders', max_retries=3)
async def order_create_task(order_id: int) -> None: ...


@cron('*/5 * * * *')
@dramatiq.actor
async def order_expire_periodic_task() -> None: ...
Method What it does
setup_tasks() Imports every module the pattern matches and wraps every actor of the broker in the actor middlewares. Runs once; what the worker and the scheduler call on start
send_task(task_name, *args, delay=None, **kwargs) Enqueues a message for the actor with its queue, priority and options. delay is keyword only, milliseconds or a timedelta; everything else goes to the task
run_task_sync(task_name, *args, **kwargs) Runs the actor in place, through the middlewares, and returns its result. Needs the event loop thread of AsyncIO, so it works inside a worker; elsewhere dramatiq raises RuntimeError
get_cron_jobs() Yields (job_path, crontab, job_name) for every actor marked with @cron
broker The global broker, dramatiq.get_broker()
  • The arguments of a task are passed through JSON before they are sent or run, so an actor always gets what a real broker would deliver: a tuple arrives as a list, and a value JSON cannot carry raises TypeError.
  • A process that never called setup_tasks(), a script or a test, gets it on the first send_task, run_task_sync or get_cron_jobs.
  • Actors are async functions: a sync actor on the broker makes setup_tasks() raise TypeError with its name. An actor is wrapped once, by the facade that set it up first.
  • Declare the facade in a module that imports no task: importing it costs nothing, and the tasks are imported when the process sets them up.
dramatiq_facade_impl.send_task('order_create_task', order_id)
dramatiq_facade_impl.send_task('order_create_task', order_id=order_id, delay=timedelta(minutes=5))

A scheduler turns the cron jobs into triggers. With APScheduler:

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger

scheduler = BlockingScheduler()
dramatiq_facade_impl.setup_tasks()
for job_path, crontab, job_name in dramatiq_facade_impl.get_cron_jobs():
    scheduler.add_job(job_path, trigger=CronTrigger.from_crontab(crontab, timezone='UTC'), name=job_name)

Actor middlewares

A BaseActorMiddleware is a layer around the coroutine of every actor: __call__(call_next, *args, **kwargs) gets the next layer and the arguments of the run.

from dddramatiq.actor_middlewares import BaseActorMiddleware


class TimingMiddleware(BaseActorMiddleware):
    async def __call__(self, call_next, *args, **kwargs):
        started = time.monotonic()
        try:
            return await call_next(*args, **kwargs)
        finally:
            logger.info({'message': 'Task took', 'seconds': time.monotonic() - started})
  • LogPropertiesManagerMiddleware(log_properties_registry) enters the scope of a ScopedRegistry from ddutils for the run: the log properties are created on enter and removed when the run is over, failed or not. The registry and its model are the application's.
  • SentryTagsMiddleware(log_properties_registry) tags the Sentry scope of the run with the properties, nested fields flattened with dots, None left out. The registry must hold a pydantic model. List it after the manager.
  • TaskLoggingMiddleware(max_result_log_size=1000) logs Started task <name>, then Finished task <name> with result when there is one, or Failed task <name> with error, each a dict with the scalar arguments of the run under the names of their parameters. A result whose repr is longer than the limit is logged by its type and size. A failure is a warning without the traceback: dramatiq logs the error itself, and a second ERROR record would be a second event in Sentry. A Retry is not logged as a failure.

Broker middlewares

AsyncShutdown

Runs coroutines on the event loop of the worker when the worker shuts down, after the actors have finished: closing the async clients that live in that loop. Place it after AsyncIO(); without the loop it raises RuntimeError.

middleware=[AsyncIO(), ..., AsyncShutdown(kafka_producer_factory.close, redis_client_factory.close)]

HealthCheck

A liveness endpoint for a worker. Every worker process checks itself, all its worker threads are alive and its event loop answers, and writes the moment to a file; one more process, forked by dramatiq, serves /livez, /readyz and /startupz: 200 while every worker pinged recently, 503 with the reasons otherwise.

Environment variable Default Meaning
DRAMATIQ_HEALTH_PORT 9192 Port of the endpoint
DRAMATIQ_HEALTH_PING_INTERVAL 10 Seconds between the checks of a worker process
DRAMATIQ_HEALTH_STALE_THRESHOLD 60 Seconds after which a ping is stale and the worker unhealthy

The settings are environment variables because the server is a process of its own that dramatiq starts by the import path of the function; the built-in Prometheus middleware is configured the same way.

PrometheusMetrics

dramatiq's Prometheus middleware plus two metrics. Use it instead of the built-in one.

Metric Type What it counts
dramatiq_messages_enqueued_total Counter Messages enqueued, retries excluded
dramatiq_message_queue_time_milliseconds Histogram Time from enqueue to the start of processing, first attempts only, delayed messages excluded

The metrics exist in worker processes only, where dramatiq boots the middleware: a message enqueued by a web server or a scheduler is not counted by dramatiq_messages_enqueued_total, one enqueued by an actor is. The queue time is measured for every message, wherever it was enqueued.

Metadata

Release files for dddramatiq 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dddramatiq 0.0.1
File Size Uploaded Provenance Actions
dddramatiq-0.0.1.tar.gz 14.6 kB With provenance Details for dddramatiq-0.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dddramatiq 0.0.1
File Interpreter ABI Platform Actions
dddramatiq-0.0.1-py3-none-any.whl Python 3 none any Details for dddramatiq-0.0.1-py3-none-any.whl

Total release size: 33.2 kB

Release files / dddramatiq-0.0.1.tar.gz

Download URL dddramatiq-0.0.1.tar.gz
Size 14.6 kB
Tags Source
SHA-256 checksum
How to use checksums
6b0f6499b84467c0d873e44fb19c03349861f4c95e2e3134add1c280be9a8b43
BLAKE2b-256 checksum
How to use checksums
02c26fb0cc967d03b6d4fa66de14a764468cabd9c9abaebed8d164b348a966f3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Release files / dddramatiq-0.0.1-py3-none-any.whl

Download URL dddramatiq-0.0.1-py3-none-any.whl
Size 18.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
82c0757655ab6ce6720896692cf736c16a6e447c21b31e3852e18df3341ff294
BLAKE2b-256 checksum
How to use checksums
ce207d6f52bd4089c809940f13daf27a7bbaafdfc2f1abf48cb82efa2f032436
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Security for dddramatiq 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for dddramatiq-0.0.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page