dddramatiq
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 firstsend_task,run_task_syncorget_cron_jobs. - Actors are async functions: a sync actor on the broker makes
setup_tasks()raiseTypeErrorwith its name. An actor is wrapped once, by the facade that set it up first. - Define the actors in a module of the tasks package and export them from its
__init__.py. A scheduler gets a cron job as a reference,<module>:<actor>.send, and APScheduler cannot resolve one whose module is a package__init__.py. - 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 aScopedRegistryfrom 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,Noneleft out. The registry must hold a pydantic model. List it after the manager.TaskLoggingMiddleware(max_result_log_size=1000)logsStarted task <name>, thenFinished task <name>withresultwhen there is one, orFailed task <name>witherror, 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. ARetryis 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 on boot and then at an interval, 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.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dddramatiq-0.0.2.tar.gz | 14.8 kB | With provenance | Details for dddramatiq-0.0.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dddramatiq-0.0.2-py3-none-any.whl | Python 3 | none | any | Details for dddramatiq-0.0.2-py3-none-any.whl |
Total release size: 33.6 kB
Release files / dddramatiq-0.0.2.tar.gz
| Download URL | dddramatiq-0.0.2.tar.gz |
|---|---|
| Size | 14.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f74f3d674747d2152ce297d7751e56702f2023096a5ea07d5602ca63e85346ac
|
|
BLAKE2b-256 checksum How to use checksums |
36e553fb36d67a0541c066d6b2b880ee1b6793be400ef56dd2bb54bd70e1d9cd
|
| 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 logRelease files / dddramatiq-0.0.2-py3-none-any.whl
| Download URL | dddramatiq-0.0.2-py3-none-any.whl |
|---|---|
| Size | 18.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ca52210208369809182f3069d2f3ea8ec3064f0078b3977a6924c70ac0c967a1
|
|
BLAKE2b-256 checksum How to use checksums |
12ff7f0ff5c8cb451f11b01f1df994b88057f6024ea36dcbf94474122a728244
|
| 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 logSecurity for dddramatiq 0.0.2
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.
Attestation for dddramatiq-0.0.2.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 logA 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.