Aviary
Cluster

Node worker

Author and run a store-less Node worker with @dudousxd/durable-worker — the JS counterpart to the Python client. Register @Step/@Workflow bodies on a DurableWorkerRuntime and drive them with runRedisWorker, with fixed or adaptive concurrency.

@dudousxd/durable-worker is the standalone Node worker SDK — the JavaScript twin of the Python client. It runs steps (and whole workflows) in a store-less process that owns no engine and no database: it consumes tasks off the broker, replays or executes, and publishes results back. The engine stays the sole owner of durable state, recovery and timers. This is the building block behind both the store-less tenant worker and the co-located worker — reach for it directly when you want a worker without the full NestJS module (a script, a purpose-built pod, a sidecar), or when you want to understand what those roles start under the hood.

pnpm add @dudousxd/durable-worker bullmq ioredis

Module or SDK?

If your worker is already a NestJS app, you usually don't touch this package directly — DurableModule.forRoot({ topology: 'tenant', partition, connection }) discovers your @Workflow/@Step and starts the runner for you (see Roles & config). Use @dudousxd/durable-worker when you want the raw runtime with no module, or a second worker loop inside an existing process.

The runtime + a runner

A worker is two pieces: a DurableWorkerRuntime (the pure routing core — it holds your registered workflows and steps) and a runner (runRedisWorker) that wires it to Redis. Register bodies, then start the runner:

worker.ts
import { DurableWorkerRuntime, runRedisWorker } from '@dudousxd/durable-worker';

const runtime = new DurableWorkerRuntime()
  // A step, routed by name — the same name a workflow's ctx.step('payments.charge-card', …) calls.
  .registerStep('payments.charge-card', async (input: { orderId: string; amountCents: number }) => {
    const res = await stripe.charge(input.orderId, input.amountCents);
    return { chargeId: res.id };
  })
  // A whole workflow, replayed turn-by-turn against the history the engine sends.
  .registerWorkflow('pipeline', async (ctx, input: { id: string }) => {
    const rows = await ctx.step('ingestion', { key: `/${input.id}/data.csv` });
    await ctx.sleep('1m');
    return { rows };
  });

const worker = await runRedisWorker({
  runtime,
  connection: { host: '127.0.0.1', port: 6379 }, // same Redis the engine's BullMQTransport uses
});

// on SIGTERM: await worker.close();  — drains + stops every queue and pub/sub

runRedisWorker starts one BullMQ Worker per registered name (workflows ∪ steps, deduped) — there's no single hand-declared "group" queue. Each name gets its own queue, so the engine's ctx.step('payments.charge-card', …) or a dispatched pipeline turn is routed to exactly the worker that registered it. The queue name is the routing; nothing else to declare.

It's the same wire as Python

A Node worker and a Python worker speak the identical JSON wire over the identical Redis queues — so you can mix them freely on one control plane (see Cross-ecosystem interop). Everything on the Python page about the connection model, at-least-once delivery, idempotency, and cooperative cancellation applies here too.

Step-only vs workflow-authoring

DurableWorkerRuntime composes a StepWorker (runs remote steps → StepResult) and a WorkflowWorker (replays workflow turns → WorkflowDecision). Both are pure and transport-free — processTask(task) is a function of the task, so you can unit-test either without a broker:

import { StepWorker, WorkflowWorker } from '@dudousxd/durable-worker';

const steps = new StepWorker().register('reserve', (input) => reserve(input));
const result = await steps.processTask(task); // { status: 'completed', output, startedAt, … }

const workflows = new WorkflowWorker().register('checkout', async (ctx, input) => {
  await ctx.step('reserve', input);
  return { ok: true };
});
const decision = await workflows.processTask(workflowTask); // { status: 'continue' | 'completed' | …, commands }

A step handler receives (input, log) — the log is a step-event sink that rides back on the result (log.info(...), sub-process outcomes). An unknown name never throws the consumer down: it returns a failed result/decision with a clear message, so a misconfigured worker is a recorded failure, not a crash.

Authoring a workflow: the ctx

A registered workflow receives a WorkflowContext that implements the engine's WorkflowCtx, so a body written against WorkflowCtx runs unchanged here. Each op is keyed by a deterministic seq: a completed op replays its recorded result instead of re-running, and changing the op sequence under an in-flight run throws NondeterminismError rather than diverging silently.

The wire-expressible subset is supported:

OpMeaning
ctx.step(nameOrRef, input, opts?)Dispatch a durable step (routed by name, any language) and await it. Always engine-scheduled. Its retries/backoff/timeoutMs apply, see below.
ctx.sleep(duration)Durable timer ('30s', '2h', or ms) — the run suspends, the engine resumes it.
ctx.sleepUntil(when)Durable timer to an absolute Date or epoch ms.
ctx.waitForSignal(token, { timeoutMs? })Suspend until engine.signal(token, payload) arrives; returns the payload. With timeoutMs, throws SignalTimeoutError once the deadline passes, as in-process.
ctx.waitForEvent(name, { match?, timeoutMs? })Suspend until engine.publishEvent(name, payload) publishes a payload that matches (buffered events included).
ctx.waitForAny(name, conditions)Whichever signal, timer or child comes first.
ctx.child(workflow, input)Start a tracked child run and await its output.
ctx.startChild(workflow, input, opts?)Start a child run without awaiting it; returns its run id. childId and priority apply.
ctx.all(workflow, inputs)Start N children of the same workflow in parallel, await all.
ctx.continueAsNew(input)Complete this run and continue it as <runId>~N on a clean history.
ctx.setEvent(key, value)Publish a value engine.getEvent(runId, key) reads.
ctx.gather([[name, body], …])Run N local step bodies concurrently in one turn, await all (worker-only extension).
ctx.now() / ctx.sideEffect(fn)Deterministic capture — recorded once, replayed thereafter.
ctx.localStep(name, fn, options?)Run fn on the worker and record its result once. retries, the backoff and compensate apply as in-process, see below.

Everything else on WorkflowCtx — transaction, callEntity, signalEntity, waitForRun, task, breakpoint, webhook, onUpdate, patched, upsertSearchAttributes, and startChild with a version or parentClose — has no command on the remote protocol yet, so each throws UnsupportedOnThinWorker naming the op. Run such a workflow in-process on the engine instead.

Step policy

retries, backoff, backoffMs, backoffMaxMs, jitter and timeoutMs, from the per-call opts or the @Step({ ... }) declaration (the call wins field by field), travel on the step's call decision and the control plane applies them with the in-process rules:

  • without timeoutMs, a failed attempt is dispatched again after its backoff, up to retries attempts in total, unless the handler marked the error non-retryable (retryable: false);
  • with timeoutMs, an attempt that returns no result within the window is dispatched again, up to retries attempts, and then fails with error.code: 'remote_step_timeout'. A failure the handler reports is final, as in-process.

Local step policy

ctx.localStep's options apply on the worker with the in-process rules, through the same retry loop the engine runs:

  • retries is the total number of attempts. A failed attempt waits its backoff (backoff, backoffMs, backoffMaxMs, jitter) and runs again; a FatalError is never retried.
  • When the attempts run out, the step is recorded failed with the last attempt's error, its code and details intact and the checkpoint's attempts set, and the run fails with that error.
  • The wait between attempts is an in-process sleep inside the turn, as it is in-process, not a durable timer: a worker that dies mid-backoff has its turn replayed, and the step starts again from attempt 1. Keep local-step backoffs short; a long wait belongs on a dispatched ctx.step.
  • A compensate closure is registered when its step completes, and again whenever a later turn replays it. When a turn fails, the worker runs the registered undos in reverse before it reports the failure, each tried up to compensationRetries times (a DurableWorkerRuntime and WorkflowWorker option, default 1), and records each as a compensate:<step> step, as the engine does. A failing undo is recorded and skipped; the run keeps its original error. A cancelled run does not unwind local compensations on the worker. Under NestJS the worker takes the module's compensationRetries, with a @dudousxd/durable-worker from this release on; an older one ignores it and tries each undo once.
  • The undo records reach the engine only with the failed turn's decision, so on the worker an unwind is at least once: a crash mid-unwind or a lost decision redelivers the turn, and every undo runs again. Write compensations to be idempotent.

Feature negotiation

The newer decisions (callPolicy, sleepUntil, waitSignalTimeout, waitEvent, spawnChild, continueAsNew) are negotiated. A control plane lists the ones it applies on every workflow task it dispatches (WorkflowTask.features, exported as REMOTE_WORKFLOW_FEATURES). When a body reaches an op whose feature is missing (the control plane is older than the worker), the turn fails with UnsupportedByControlPlane (error.code: 'control_plane_unsupported', naming the op and the feature) instead of sending a command that would be rejected or silently ignored. A step declared with a policy counts: on an older control plane it fails the turn rather than running without its retries. Upgrade the control plane first. An older worker against a newer control plane keeps working: it never sends the new commands, and a call without a policy behaves as before.

ctx.setEvent needs no feature: it is recorded as an ordinary step every control plane applies.

Concurrency: fixed or adaptive

By default a runner processes one task per queue at a time (concurrency: 1). Raise it so a fanned-out batch (the N steps of a gather, say) runs in parallel instead of serially. Total parallelism is concurrency × distinct names × replicas.

await runRedisWorker({
  runtime,
  connection,
  concurrency: 8, // up to 8 in-flight tasks per subscribed queue, per process
});

You can normalise a concurrency option yourself with the exported resolveConcurrency(opt) (a bare number or undefined → { mode: 'fixed', fixed }; 'adaptive'/{ mode: 'adaptive', … } → { mode: 'adaptive', adaptive } with every default applied), and drive an AdaptiveController directly if you're building your own runner loop.

Runner options

OptionDefaultNotes
runtime—The DurableWorkerRuntime holding the registered workflows + steps.
connection—ioredis connection options (or an IORedis instance) — the same shape BullMQTransport takes. Point it at the engine's Redis.
prefix'durable'Key prefix namespacing the durable queues. Must match the engine's BullMQTransport prefix.
partitionnoneIsolation suffix — every per-name queue token becomes <name>@<partition>, so an operator can route a tenant's runs to this worker. Distinct from prefix. Omit / '' / 'default' = a bare, byte-identical single-tenant token.
instanceIdts-<hostname>-<pid>Stable id for this process in heartbeats/control keys.
concurrency1Tasks per subscribed queue — a number, 'adaptive', or { mode: 'adaptive', … } (above).
lockDuration5 minBullMQ job-lock duration. Generous by design so a long workflow turn never lapses its lock mid-run and gets redelivered. It is also how long a task held by a worker that died waits before BullMQ can redeliver it, so lower it to recover sooner.
stalledIntervalBullMQ's (30 s)How often each Worker checks its queue for stalled jobs. Sent only when set.
maxStalledCountBullMQ's (1)How many times a job may stall before BullMQ fails it for good. Sent only when set.
await runRedisWorker({
  runtime,
  connection: process.env.REDIS_URL,
  prefix: 'durable',        // must equal BullMQTransport({ prefix })
  partition: 'acme-corp',   // this worker serves the acme-corp tenant's queues (<name>@acme-corp)
  instanceId: 'orders-worker-1',
  concurrency: 'adaptive',
});

The runner also, best-effort, subscribes to the <prefix>-control channel for cooperative cancellation, streams each local step's lifecycle live, and stamps a TTL'd liveness heartbeat per subscribed queue — none of which can block the worker from starting or processing. All of it mirrors the Python SDK byte-for-byte.

Starting runs without a database (startRun)

A store-less worker has no engine to call engine.start on. To request a new run from the control plane over the broker, use startRun — it publishes a StartRunMessage onto <prefix>-start-run, which the control plane turns into a durable run:

import { startRun } from '@dudousxd/durable-worker';

await startRun(connection, {
  tenant: 'acme-corp',
  workflow: 'pipeline',
  input: { id: 'order-42' },
  runId: 'run-order-42', // supply your own for idempotent, at-least-once-safe redelivery
});

Pass your own runId for idempotency

startRun sits at the head of a retryable, at-least-once BullMQ path (queue add → consumer → engine). It passes your runId through verbatim and never mints one in its place — because substituting a fresh id per delivery would make a redelivered startRun create a second run. Omit runId and the control plane mints one, but a redelivery of that specific call is then not idempotent. Always supply your own runId when you need idempotent redelivery. For high-frequency callers, hold a BullMQTransport and call transport.dispatchStartRun directly instead of the one-shot startRun.

See also

On this page