BullMQ / Redis
The queue-backed transport for cross-process and cross-language steps. Each step name gets its own tasks queue; results return on a shared results queue. Run one instance engine-side, one per worker.
@dudousxd/nestjs-durable-transport-bullmq carries steps over BullMQ/Redis — the path for steps
that run in another process or another language (e.g. a Python worker).
pnpm add @dudousxd/nestjs-durable-transport-bullmq bullmqHow it compares to the other transports: see Choosing a transport.
How it works
ctx.stepdispatches a task to a per-name queue:<prefix>-tasks-<name>[@<partition>].- A worker registered for that step name consumes it, runs the handler, and adds the result to the
shared
<prefix>-resultsqueue. - The engine-side instance consumes results and checkpoints them.
Run one instance engine-side (consumes results) and one per worker process (registers its handlers, and dispatches on the transport):
const transport = new BullMQTransport({ connection: { host: 'localhost', port: 6379 } });
DurableModule.forRoot({ store, transport });const transport = new BullMQTransport({
connection: { host: 'localhost', port: 6379 },
partition: 'payments', // optional isolation suffix — omit for a single-tenant deployment
});
transport.handle('payments.charge-card', async (input) => ({ chargeId: await charge(input) }));Concurrency
concurrency controls how many tasks this instance runs at once from each of its per-name task
queues (the BullMQ Worker's own concurrency). It takes three forms:
- a fixed number — always runs exactly that many in parallel. Defaults to
1(one task at a time). 'adaptive'— anAdaptiveControllerself-tunes the limit from a latency gradient, a RAM brake, and backpressure (errors/stalls), instead of you guessing a number.{ mode: 'adaptive', ... }— adaptive with overrides (min,max,start,ramCeilingPct,cpuCeilingPct,tickMs). The defaults aremin: 1,max: 32,start: min,ramCeilingPct: 85, no CPU ceiling, andtickMs: 2000. To pin the limit instead, pass a plain number.
A number that is not finite or is out of range falls back to its default: a fixed value, min,
max, start or tickMs below 1 (or NaN, Infinity) uses the default, and so does a
ramCeilingPct of 0 or less. A bad cpuCeilingPct turns the CPU ceiling off. A fractional count
is rounded down.
Watch an adaptive worker breathe — spike the load and it grows into its headroom; fire the RAM brake and it backs off before memory melts:
concurrency: 'adaptive': the worker's slot count breathes — it grows into the dashed headroom while backlog builds and latency stays healthy, and the RAM brake slams it down before memory melts, recovering once pressure clears. The live limit is what the worker heartbeats as WorkerStatus (see the Telescope Workers panel).const transport = new BullMQTransport({
connection: { host: 'localhost', port: 6379 },
concurrency: { mode: 'adaptive', min: 2, max: 32, ramCeilingPct: 85 },
});Total parallelism across a fleet is concurrency × replicas. Only adaptive mode runs a control
loop; a fixed limit never moves and runs no timer. Either mode publishes its live status — current
limit, in-flight count, RSS, CPU, throughput, p95 and (adaptive) the last adjustment — on the
worker's heartbeat as a WorkerStatus. Throughput is completions per minute over the trailing
minute, so an idle worker's reading decays and drops to 0 once a minute passes with no completion. See Flow control
for the full set of tunables and how the Telescope Workers dashboard renders it.
Result concurrency
concurrency governs the task queues a worker consumes. The engine side consumes the shared
<prefix>-results queue and works on up to 512 results at once per instance. Handing a result over
is cheap: the engine settles one run's waiting results together, so the more of a wide fan's results
are in flight, the fewer writes settle them. There is nothing to tune for wide fans.
Results of the same run are settled in batches: the results of a run that arrive while one batch
is being written go into the next (up to 256), which claims their checkpoints with one
settleCheckpointsIfPending call. A step fan's join barrier is checked only by a batch with none of the
fan's results queued behind it, so under a backlog it is read about once per instance rather than
once per batch. A batch resumes the run at most once, and each result is acknowledged only after its
batch commits. The turn a batch triggers waits for the previous turn of that run on this instance. A
run never gets two concurrent turns from one instance, and different runs proceed in parallel. The
engine applies the same ordering to any transport that delivers results concurrently, including the
in-process ones.
resultConcurrency raises the per-instance limit above 512; a lower value has no effect. A value
that is not a finite number of at least 1 is ignored; a fractional value is rounded down.
A step fan's tasks are enqueued with addBulk, 500 jobs a call.
Result delivery
A worker publishes step results in batches while an engine consumes them: the results that finish
while one batch is being published go out together in the next (up to 256), as one job on the
<prefix>-results-batch queue. An idle worker publishes each result as soon as it finishes; a busy
one publishes one job per batch instead of one per step, which halves the Redis commands a step costs
(about 64 to 37 in a 40,000-step fan). A step's task job completes only once the batch carrying its
result is on the queue, so a crash never loses a result. A batch that fails to publish goes out one
result per job.
A worker sends batches only once a live consumer is reading <prefix>-results-batch (it rereads that
every 5 seconds through BullMQ's worker list, and any error reading it answers no). Otherwise each
result is its own job on <prefix>-results, which every engine consumes, so a fleet mid-upgrade, an
or an older engine loses nothing. The Python worker does the same from durable-worker 0.27; older
releases publish one result per job on <prefix>-results, which every engine still reads.
A result job whose handler throws (a store error at peak load, say) is retried up to 5 times with exponential backoff starting at 500 ms. A result that still fails is kept in the results queue for 24 hours instead of being removed, and the transport logs that it gave up on it, with the step and run ids.
Priority
Per-call priority on ctx.step follows the engine's convention: higher wins. BullMQ's own job
priority is the opposite — lower numbers run first — so the transport translates one into the other
before enqueuing, keeping "higher = more urgent" true end-to-end regardless of transport. Leave
priority unset for the default FIFO ordering.
Namespace
namespace segments every queue/stream/key this instance touches, so a single Redis can host
several isolated deployments — e.g. one per developer — without crosstalk. Leave it unset (or
"default") for production: names stay byte-identical to the un-namespaced scheme. Any other value
inserts a -<namespace> segment into every name. See Tenancy for the
operator/tenant model this enables.
Run queue
The engine queues the runs it starts or wakes on <prefix>-runs (<prefix>-runs-<namespace> for an
engine scoped to a namespace), and every driving instance consumes it, 256 at once. A start's job id
is start-<runId>-<key> (: escaped as %3A), where the key names the pending state it is for:
a start re-sent for that state is not queued twice, and a run that went pending again is a new
job even while the earlier one is being handled. A wake has no job id, so none is dropped. A fan's
children go in addBulk writes of up to 500, and a run's priority maps onto the job's as for a
step. A job held by an instance that went down is redelivered by BullMQ's stalled check. The job ids
are the same as adonis-agora-durable's.
Crash recovery
A worker that crashes or stalls mid-step never produces a StepResult, so without help the step's
checkpoint would stay pending forever. BullMQTransport closes that gap automatically:
BullMQ's own stalled-check (run by a peer worker's Worker) marks a crashed/stalled task job
failed, and a Worker.on('failed') listener bridges that into a synthetic failed StepResult —
so the engine settles the checkpoint as failed and its normal durable retry re-dispatches the
step. A handler business error is unaffected: runStepHandler already turns it into a
successful job carrying a failed StepResult, so there's no double-publish.
No configuration needed on your part — dispatch() sets removeOnFail: { age: 24h } on every
task job (overriding the default immediate removeOnFail) so a failed job's payload survives long
enough for the bridge to read the runId/seq/stepId it needs, before BullMQ garbage-collects
it.
The bridge lives in the consumer, not the queue. A worker in another language consumes the
same queues, and the bridge only exists where somebody implemented it: the TypeScript transport
here, and the Python durable-worker (from the release that ships its own failed listener —
earlier versions had none, so a Python fleet's steps orphaned where a Node fleet's did not). If
you run a worker on an SDK without it, treat the checkpoint as unsettled and rely on the engine's
remoteRedispatchMs self-heal below.
Residual gaps, both of which the engine's opt-in remoteRedispatchMs self-heal covers (see
Retries):
- if the only worker for a queue crashes and never restarts, no peer's stalled-check ever runs, so nothing settles the checkpoint;
- if the consuming SDK has no failure bridge, the job's terminal failure is never turned into a result.
See also Recovering a lost remote step dispatch.
Producer-only processes
A BullMQ Worker starts fetching the moment it is created, and the task, results, decisions,
step-events, start-run and run-request queues each hand a job to ONE consumer. A process that boots
the module without being a worker — a CLI command, a REPL, a migration or seed script — would
compete with the real fleet: it claims jobs it then dies holding, and takes results meant for the
long-lived engines. Make it a pure producer:
DurableModule.forRoot({ store, transport, drive: false, consumers: false });consumers: false calls transport.deferConsumers() before the engine subscribes, and starts no
co-located or thin worker consumer. The process still dispatches and starts runs; the jobs wait on
the queues for the fleet, and it is not advertised as a live worker. transport.startConsumers()
starts the parked consumers later, if the process turns out to be a worker after all. Outside the
module, construct the transport with deferConsumers: true (or call deferConsumers() before any
handle() / onResult()). Pub/sub (heartbeats, control, run replies, tenant events) is broadcast
and is not parked.
Grouped task queues
By default every handler has its own queue (<P>-tasks-<token>), consumed by its own BullMQ
Worker with its own blocking connection. Each idle worker re-polls its queue every drainDelay
and runs a stalled-job check every stalledInterval, so a process with 85 @Step handlers polls
85 queues and holds 85+ connections while nothing happens.
taskQueues: 'grouped' puts every step handler of a partition on ONE queue:
new BullMQTransport({ connection, taskQueues: 'grouped' })- The queue is
<P>-taskgroup, or<P>-taskgroup@<partition>for a partitioned token. It is the AdonisJS durable lib's grouped queue (same name, same job shape), so both fleets can share it. - One
Workerconsumes it and routes each job to its handler by the routing token in the job (group). The API does not change:handle(),dispatch()and results work as before. - Each handler keeps its own
concurrencylimit (fixed or adaptive) through an in-process limiter. The shared worker runs two limits' worth of slots per handler; a job of a handler at its limit waits in-process (its lock keeps renewing), and past one limit's worth of waiters it goes back to the queue with a growing delay, so one handler's backlog never starves the others.stepTimeoutMs, stalled-job recovery and the terminal-failure bridge apply as before. Priority still orders the shared queue, but under contention it is weaker than per-handler: jobs waiting in-process for a handler slot are served first in, first out, and a job handed back re-enters by its due time, so a high-priority job can wait behind earlier lower-priority jobs of the same handler. - Every process consuming a partition's grouped queue must register the handlers dispatched to it. A job for a handler the process lacks goes back to the queue (delayed 10 s) for another process. It is logged, and logged again every 5 minutes with how many bounced since, so a handler nothing serves keeps showing up.
- Workflow tasks (
dispatchWorkflowTask) stay on<P>-tasks-<token>: their consumers here (@dudousxd/durable-workerand the Python worker) read per-handler queues. groupHealth()reports the handler's share of the shared queue (from a sample of up to 500 jobs,depthSampledwhen it did not cover the queue), the shared queue's name and total (queue,queueDepth), and what still waits on the handler's own queue (drainingDepth). The dashboard counts a shared queue once per partition and marks it.
Measured with 85 handlers in one worker process plus one engine (registry legacy switches off, 60 s
idle window): 43.6 commands/s and 179 connections per-handler, 1.5 commands/s and 9 connections
grouped (23.3 and 0.9 commands/s with stalledInterval: 120_000). A 3-step run cost 326 commands
per-handler and 259 grouped.
Switching layouts
Dispatchers and step workers of a fleet must agree on the layout, which a rolling deploy cannot
guarantee. taskQueueDrain covers the gap: a process also consumes the OTHER layout's queues of the
handlers it serves while they hold jobs (waiting, delayed, prioritized, paused, or active under a
worker that died). In 'grouped' mode that is the per-handler queues (on by default); in
'per-handler' mode it is the grouped queue (off by default, turn it on for a rollback). Each
interval (60 s) costs one batched EXISTS while those queues are all empty, plus one EXISTS per
queue while any holds jobs; a drain worker starts only on a queue that holds jobs and stops once it
is empty.
- Deploy
taskQueues: 'grouped'to the workers and the engines. Jobs already on per-handler queues, and jobs older engines still dispatch there, are drained by the grouped workers. - To roll back, deploy
taskQueues: 'per-handler'withtaskQueueDrain: true, so the jobs left on the grouped queue still run.
Python and @dudousxd/durable-worker step handlers only consume per-handler queues: keep
'per-handler' while any of them serves steps this fleet dispatches.
Worker registry
Workers advertise which handler queues they consume (liveness plus live status), their
handshake descriptor, and, for an engine running workflow bodies
in-process, that it consumes the run queue. All of it lives in one Redis hash per prefix,
<P>-workers:instances, with one field per instance listing every token it serves. A worker writes
its field once per 10 s beat, whatever its number of handlers. A process reads the whole hash with
one HGETALL and reuses it for 30 s across every reader: the dashboard's Workers page, convention
routing (listWorkerGroups), the announced-workflow directory and the descriptors read before a
dispatch. Before the engine parks a run blocked it reads the hash again, so a worker that joined
inside those 30 s is never missed. A process sees its own entries at once. The hash has a TTL, and
every writer deletes other writers' expired fields (a crashed process). A clean close() removes
the instance's field at once.
The layout is the AdonisJS durable lib's, byte for byte, so a NestJS fleet and an Adonis fleet on one Redis see each other's workers.
Before this version workers wrote one key per handler (<P>-worker-heartbeat:<token>:<instance>,
<P>-worker-descriptor:<token>:<instance>), and readers found them with SCAN. A SCAN visits every
key of the db however few match, so on a Redis holding BullMQ jobs that walk was most of the
registry's cost. For a rolling upgrade both sides of the old layout are kept, behind two switches:
new BullMQTransport({
connection,
workerRegistry: {
legacyWrites: true, // default; false once every reader runs this version
legacyWriteIntervalMs: 30_000, // default
legacyScan: true, // default; false once every writer runs this version
legacyScanIntervalMs: 60_000, // default
connection: { ...redisOptions, db: 2 }, // optional: keep the registry hash on another db
},
})legacyWriteskeeps writing the per-instance keys (and the per-token hashes older Adonis versions read) everylegacyWriteIntervalMs, living three intervals.legacyScankeeps reading the per-instance keys of writers that never write the hash (an older version, and the Python worker, which still writes per-instance keys): ONESCANwalk shared by every reader of the process, at most once perlegacyScanIntervalMs. After the first walk readers get the last walk at once while the next one runs in the background, so a Python worker that just started can take up to a minute to appear.
workerRegistry.connection takes the same forms as connection and holds the registry hashes; the
per-instance keys stay on connection. Every process of the fleet must use the same value.
Measured with 85 handlers, one engine polling the Workers view every 5 s, and 40 000 unrelated keys
in the db: 424 512 SCAN calls a minute and 7 293 commands/s before; 5 SCAN calls a minute and
158 commands/s with the defaults; no SCAN and 150 commands/s with both switches off (the rest is
the per-group queue counts and BullMQ's own polling).
Upgrading a fleet
- Deploy this version everywhere (transport,
@dudousxd/durable-worker), with the defaults. Its workers still write what older readers read, and its readers still read older workers. - Once every process that reads the registry runs this version (engines, dashboards, Adonis
control planes on 1.0.0-rc.32 or later), set
legacyWrites: falseon the workers. - Once every process that writes the registry writes the hash (no Python worker, no older
NestJS or Adonis worker shares the Redis), set
legacyScan: falseon the readers. They then never walk the keyspace. Keep it on while Python workers share the Redis.
Control plane & tenant protocol
Every onDecision and onResult handler registered on one transport gets every decision and every
result, over a single consumer each. Two engines sharing a transport is safe: an engine settles a
result by claiming the step's still-pending checkpoint, so an engine that doesn't know the run does
nothing, and over one store only one engine wins the claim.
Beyond Transport, BullMQTransport also implements ControlPlane — cross-instance broadcast for
lifecycle events and cancellation — and carries the tenant start-run / run-request / run-reply
/ tenant-event protocol a store-less tenant worker uses to proxy runs through an operator. See
Tenancy for the full model.
Options
| Option | Description |
|---|---|
connection | ioredis connection options, an IORedis instance, or a redis:// / rediss:// URL (host, port, credentials, db and TLS are read from it; query parameters are refused). |
deferConsumers | Start with every point-to-point consumer parked until startConsumers(). See Producer-only processes. Defaults to false. |
partition | Optional isolation suffix appended to every one of this instance's per-name queues (<name>@<partition>). Omit for a single-tenant deployment. |
prefix | Namespaces the queues. Defaults to durable. |
namespace | Logical deployment namespace segmenting every queue/stream/key. See Namespace above. |
instanceId | Stable id for this worker process, stamped into its heartbeats/liveness keys. Defaults to ts-<hostname>-<pid>. |
concurrency | Fixed number, 'adaptive', or { mode: 'adaptive', ... }. See Concurrency above. Defaults to 1. |
resultConcurrency | The most step results this instance handles at once from the results queue, when above the built-in 512. One run's results still resume it in order. See Result concurrency. |
drainDelay | Seconds each BullMQ worker blocks on an empty queue before polling it again. A new job wakes the worker at once (BullMQ's marker) and a delayed job's due time shortens the block, so this only sets how often idle queues are re-polled (a BZPOPMIN and a moveToActive script per queue). Closing is not held up by it. Defaults to 30 (BullMQ's own default is 5). |
stalledInterval | Milliseconds between each worker's stalled-job checks (one script per queue). Raising it lowers idle Redis load and delays recovering a job whose worker died. Defaults to BullMQ's 30 000. |
taskQueues | 'per-handler' (default) or 'grouped': one queue per handler, or one shared queue per partition. See Grouped task queues. |
taskQueueDrain | While switching layouts, also consume the other layout's queues of the handlers this process serves until they are empty. true / false / { intervalMs } (default 60_000). Defaults to true with 'grouped', false with 'per-handler'. |
workerRegistry | { legacyWrites?, legacyWriteIntervalMs?, legacyScan?, legacyScanIntervalMs?, connection? }: what the worker registry still writes and reads for older versions, and an optional separate connection for its hash. See Worker registry. Defaults to { legacyWrites: true, legacyWriteIntervalMs: 30_000, legacyScan: true, legacyScanIntervalMs: 60_000 }. |
The payload is the documented RemoteTask / StepResult JSON, so a non-Node worker on the same
queues interoperates — that's exactly how the Python worker plugs in.
Choosing a transport
A capability matrix of every transport (BullMQ, SQS, SQL, event-emitter, in-memory) checked against the source, the known limitations of each, and which one to pick.
AWS SQS
The queue-backed transport on AWS SQS. Same RemoteTask/StepResult contract as BullMQ — tasks go to a per-group queue, results return on a shared queue — so Node and Python workers interoperate.