Every Python team eventually hits the same wall: an endpoint that used to respond in milliseconds now drags through image resizing, third-party calls, or a slow report, and users start refreshing the page. Moving that work off the request cycle is the fix, but the usual task frameworks punish you with a dozen knobs you must set correctly or lose messages. It is widely recognized that many teams abandon their first queue not because queuing is hard, but because the defaults surprise them.
dramatiq, by Bogdan Popa, takes a different stance: a small set of strong defaults — actors, middleware, at-least-once delivery — arranged so an engineer can read the whole library in an afternoon. The default branch is master, and the checkout behind this tour identifies itself as version 2.2.1 in the package initializer. Rather than paraphrase the documentation, this post walks the actual tree, from the decorator you touch first to the thread that finally calls your function.
The tour covers the public API, the message envelope, both production brokers, the worker runtime, and the middleware stack that adds retries, timeouts, and metrics. Two diagrams anchor the walk: an overview of module relationships, and a detail view that adds the test broker, the Lua dispatch scripts, and the results subsystem.
Overview of dramatiq's module layout on master: the public API re-exports a compact core, two broker implementations satisfy one abstract interface, and the worker runtime talks to both through middleware hooks.
Reading the overview from left to right:
- Actor, L49 — wraps your callable and stores its queue name, priority, and options; a duplicate actor name raises a
ValueErrorat line 74. - actor, L239 — the decorator: validates queue names against a regex (line 295) and rejects undeclared options (line 302) before touching the broker.
- get_broker, L36 — the global broker accessor; tries RabbitMQ first, falls back to Redis when AMQP dependencies are missing.
- Message, L64 — a frozen dataclass: queue, actor, args, kwargs, options, a UUID id (line 83), and a millisecond timestamp (line 84).
- Worker, L61 — the runtime hub that fans messages from consumer threads onto worker threads through one shared priority queue.
- WorkerThread, L492 — the execution side: no network I/O, it only pops work items and calls actors (line 560).
- Retries, L37 — automatic retries with exponential backoff; twenty attempts, a 15-second floor, and a seven-day cap by default.
- TimeLimit, L46 — cancels runaway actors by raising asynchronous exceptions inside worker threads.
- Results, L28 — the opt-in middleware that stores actor return values in a result backend.
The detail view adds what the overview hides: the in-memory stub broker for tests, the Lua script that keeps Redis operations atomic, the individual middlewares, and the result backend hierarchy.
The actor decorator: registration as validation
The decorator does more than its name suggests. Its inner function defaults the actor name to the function’s own (line 294 of actor.py), then validates the queue name against _queue_name_re (line 42), which demands a leading letter or underscore. Next, line 302 diffs your options against everything the broker’s middleware declared, and raises a ValueError asking whether you forgot to add middleware — configuration errors surface at declaration time, not at 2 a.m. The Actor class stays thin: the constructor stores metadata and calls broker.declare_actor, and line 78 wraps coroutine functions with async_to_sync (line 56 of dramatiq/asyncio.py) so an async def actor looks synchronous to the runtime. Class-based fans get GenericActor (line 50 of dramatiq/generic.py), registered per subclass through a metaclass.
Inside the worker: two thread roles and one priority queue
A Worker starts eight worker threads by default (line 85 of worker.py) and prefetches min(worker_threads * 2, 65535) regular messages (line 95) but up to worker_threads * 1000 delayed ones (line 98), because far-future ETAs would otherwise starve the consumer. Each declared queue gets its own ConsumerThread (line 272), spawned by a tiny internal middleware reacting to after_declare_queue.
The two thread roles are deliberately split. ConsumerThread owns the network: it calls broker.consume in a loop, parks eta messages on a per-queue delay queue, and pushes everything else onto the shared PriorityQueue as a _WorkQueueItem — a frozen, slotted dataclass (line 255) whose ordering key combines the actor’s priority with a monotonic enqueue time, keeping equal-priority messages roughly FIFO. WorkerThread (line 492) owns execution only: its process_message (line 542) resolves the actor and calls it with actor(*message.args, **message.kwargs) (line 560), then hands the proxy back to the originating consumer for ack or nack (line 400), each wrapped in middleware signals. Shutdown at line 141 stops executors first so broker heartbeats keep flowing, then requeues every in-memory unacknowledged message before closing connections.
From quick fix to durable design
Small decisions across the tree show what production traffic taught the maintainers. The message envelope is a frozen dataclass (lines 63 to 64 of message.py) with a UUID message_id default factory (line 83) and a millisecond message_timestamp (line 84); decode failures are wrapped into a DecodeError carrying the raw bytes (line 107), so a corrupt payload is diagnosable rather than silently swallowed. The Redis broker then copies every enqueue with a fresh redis_message_id (lines 163 to 170 of brokers/redis.py) because the same Message is re-enqueued on each retry and Redis needs a unique list member per attempt.
The RabbitMQ broker keeps three physical queues per logical queue — base, .DQ delay, and .XQ dead-letter — declared together at lines 301 to 303 of brokers/rabbitmq.py, with the suffix rules in common.py at lines 141 to 171. Dead letters live seven days by default (DEAD_MESSAGE_TTL, line 39) and enqueues retry up to MAX_ENQUEUE_ATTEMPTS = 6 (line 43) before surfacing a connection error. Retries ships with max_retries=20 (line 75 of middleware/retries.py), a 15-second backoff floor (line 30), and a seven-day cap (line 34) computed by compute_backoff from common.py. Even the time-limit machinery is a lesson: the ten-minute default (line 67 of middleware/time_limit.py) is enforced by _CtypesTimeoutManager (line 100), which raises TimeLimitExceeded through raise_thread_exception — a ctypes call to PyThreadState_SetAsyncExc at line 85 of dramatiq/threading.py — with the honest caveat, right in the docstring, that such exceptions fire only when the thread next acquires the GIL and can never cancel a system call.
What the brokers actually do
Both production brokers implement one small contract from broker.py: consume returns a Consumer iterator (line 195), whose ack (line 340) removes a message and whose nack (line 349) dead-letters it, while MessageProxy (line 385) wraps each message so exceptions can be stuffed into it (line 405) for middleware to inspect. get_broker (line 36) builds a RabbitmqBroker pointed at 127.0.0.1:5672 with a five-second heartbeat (lines 51 to 61) and only falls back to RedisBroker on ImportError — the fallback is about installed dependencies, not reachability.
The Redis broker’s interesting machinery is atomicity. Enqueue tags each message (lines 166 to 180), routes delayed ones onto the .DQ queue with an eta option, and delegates list manipulation to dispatch.lua, whose prologue at lines 45 to 69 binds the namespace, per-worker ack keys, heartbeats, and the dead-letter TTL before fetch, ack, and requeue run in a single EVAL. Maintenance is probabilistic: _should_do_maintenance (line 238) rolls a random number per command so cleanup spreads across workers instead of stampeding at boot. For tests, StubBroker (line 34 of brokers/stub.py) implements the same interface in memory with a blocking join. If you pair dramatiq with the Redis instance most deployments already run, read the broker’s key layout before adding your own instrumentation, because everything it touches is namespaced under that scheme.
Middleware everywhere
Middleware is the extension mechanism, and the default stack assembled at line 56 of middleware/__init__.py wires six of them in a fixed order — AgeLimit, TimeLimit, ShutdownNotifications, Callbacks, and Retries are the ones you meet most often. The Middleware base class (line 39 of middleware/middleware.py) defines paired before_* and after_* hooks for declaration, enqueue, processing, and acknowledgement, and the broker’s emit helpers (lines 111 to 127 of broker.py) run after-hooks in reverse, so unwinding mirrors setup. A hook that raises SkipMessage (line 33) drops the message; AgeLimit does exactly that (line 54 of middleware/age_limit.py) once current_millis() - message.message_timestamp exceeds max_age (line 51).
Observability ships the same way: the Prometheus middleware registers counters like dramatiq_messages_total with queue and actor labels (lines 67 to 72 of middleware/prometheus.py) and exposes them on port 9191 (line 39) in the text format the Prometheus scraper expects, so a worker fleet becomes monitorable without touching actor code. Results are middleware too — Results (line 28 of results/middleware.py) persists return values for actors declared with store_results=True, backed by a ResultBackend whose Redis implementation lives in results/backends/redis.py. The runtime defends against misuse as well: when an actor returns a value with no results middleware present, WorkerThread logs a suggestion (lines 563 to 571 of worker.py), guarded by an lru_cache check at line 635 so the scan happens once per broker.
Honest Limits
The threading model has real constraints. Worker threads are OS threads, so CPU-bound actors serialize on the GIL; the intended answer is horizontal processes via the CLI’s --processes option, which defaults to the machine’s CPU count (line 187 of cli.py) while --threads stays at 8 (line 194). Time limits cannot cancel system calls, as the docstring admits, so a stuck network call still needs broker-side timeouts as a backstop. The results subsystem ships only Redis, memcached, and stub backends — no database backend exists in the tree — and the deprecated MessageProxy ordering (line 427 of broker.py) plus the ConnectionError alias warning (line 94 of the package initializer) both announce removal in version 3.0.0, so pin your version before upgrading. A gevent-flavored launcher exists in bin/dramatiq-gevent, but it changes concurrency semantics in ways this tour does not cover.
Testing, by contrast, is a strong point: Enjoyed this post? Never miss out on future posts by following us StubBroker with its blocking join was designed for pytest suites — enqueue, broker.join, assert on side effects, no sleeps. The CLI also exits with distinct codes from RET_OK through RET_PIDFILE (lines 57 to 61 of cli.py) so process managers can tell an import failure from a broker connection failure, and the optional file watcher (line 12 of dramatiq/watcher.py) restarts workers on source changes during development. Read the source with the two diagrams open side by side: after one pass, the middleware list at line 56 reads less like configuration and more like the table of contents for everything the runtime can do.