Roles & config
The topology preset on DurableModule.forRoot, the RunGateway surface every shape shares, and layered tenant authentication for a store-less fleet.
Which shape a process takes is inferred from the options you give it. The
topology option on DurableModule.forRoot names the role instead: 'standalone' (the default),
'control-plane' or 'tenant', the same words Agora uses. It validates the two axes that otherwise
read as synonyms, namespace (the operator's poll scope) and partition (a worker's queue suffix),
and TypeScript rejects a store on a tenant. Omit it and inference behaves as 'standalone'.
The configs
Omit topology (or set topology: 'standalone') and you get the default: an operator that owns the
store and runs every @Workflow on the inline fast path.
DurableModule.forRoot({
store,
transport: new EventEmitterTransport(), // or BullMQ for cross-process
})Add a connection and the same process keeps the store but moves execution onto a co-located BullMQ
consumer — every @Workflow becomes group-served instead of inline.
Any role that sets connection executes bodies through @dudousxd/durable-worker, which is an
optional peer — pnpm add @dudousxd/durable-worker bullmq ioredis alongside the module. An
operator that only owns a store never loads it and does not need it installed.
What topology validates
Each check is named after the axis it protects, and runs at forRoot/forRootAsync resolution time:
topology | Requires | Forbids | Notes |
|---|---|---|---|
'standalone' (default) | store or connection; a store needs transport | nothing | The role is inferred from store/connection, as in the tabs above. |
'control-plane' | store and (transport or transports) | tenantToken (type only) | partition is optional and becomes the control plane's namespace. Omit it on a deployed control plane (it then drives every tenant); set it to scope a self-contained local stack to its own runs while sharing a broker with a deployed cluster. Setting namespace too is allowed only when it equals partition; a mismatch throws. |
'tenant' | partition and connection | store, namespace, verifyTenant | store is a compile error. partition is the tenant this process serves and acts as. |
The check exists for the case plain inference can't catch: an app that sets both namespace (meant
for the operator) and partition (meant for a worker) on one instance because the two options read
as near-synonyms. topology forces you to pick one role and rejects the other role's axis outright,
with an error message that explains why. What each axis actually partitions is
Tenancy.
Migrating from the object form
topology used to be an object. It is now a string, and the nested tenant moved to partition:
// Before
DurableModule.forRoot({ topology: { role: 'control-plane', tenant: 'davi-local' }, store, transport });
DurableModule.forRoot({ topology: { role: 'tenant', tenant: 'acme-corp' }, connection });
// After
DurableModule.forRoot({ topology: 'control-plane', partition: 'davi-local', store, transport });
DurableModule.forRoot({ topology: 'tenant', partition: 'acme-corp', connection });The object form throws at boot with this hint. Nothing on the wire changed, so a migrated process keeps talking to processes that have not been upgraded yet, and to Agora and Python processes.
The shared surface: RunGateway
Every shape binds exactly one RunGateway, and the role picks the implementation. An operator with a
store reads its store directly (StoreRunGateway). A store-less pod binds a ProxyRunGateway that
round-trips every call over the transport to the control plane, which reads its store and answers.
This is what makes application code portable across shapes. Your controllers and the
dashboard call the same interface either way, so a pod moving from
single-process to store-less changes only its forRoot — no controller code, and the identical
DurableDashboardModule mounts on both.
@Controller('runs')
export class RunsController {
constructor(private readonly gateway: RunGateway) {} // inject by type — the class is its own token
@Get(':id')
async show(@Param('id') id: string) {
return (await this.gateway.getRunDetail(id)) ?? {};
}
}| Verb | Purpose |
|---|---|
topology() | this pod's role, plus its tenant when store-less. Synchronous — no round-trip. |
getRunDetail(runId, options?) | one run plus its step timeline and child ids, or null. With { summarizeFansOver: n }, every fan wider than n comes back as a FanSummary in fans instead of its members, and children is capped at 200 with childCount as the total. Unset returns the full detail. |
getFanMembers?(runId, group, query) | optional — one page { items, total } of a fan's members; query is { offset?, limit?, failedOnly? } (limit defaults to 100, at most 500) |
getRun?(runId) | optional — the run alone, without its timeline |
listRuns(query) | a filtered listing (status, workflow, tag, namespace, search attributes), each row optionally carrying what a suspended run is parked on |
runFacets(query) | whole-set counts grouped by (status, origin) — exact even when the listing is paginated |
runValueFacets(axis, query, opts?) | the distinct values of one filter axis (tag, tenant, origin, workflow, search-attribute key or value) with counts — what fills a console's pickers |
waitingFor(runIds) | bulk-resolve what each of an arbitrary set of runs is parked on |
workerHealth() | queue backlog and live worker heartbeats per group; scoped to the requester's own groups over a tenant proxy |
cancel(runId, opts?) | cancel a run, with { compensate: true } to run its saga undo first |
retry(runId) / continue(runId) | re-drive a failed run, or push a dead one one step further |
retryWithInput(runId, input) | fix-and-replay: a fresh run from corrected input, keeping the original's namespace |
redispatchPending(runId) | re-enqueue every remote step still pending — the operator escape hatch for a lost dispatch |
subscribe(runId, onEvent) | live-tail one run's lifecycle events; returns the unsubscribe |
Tune the proxy round-trip with runGatewayTimeoutMs (default 10_000). It is ignored on an
operator, which is bound to the store-backed gateway.
Wide fans over the gateway
The dashboard asks getRunDetail(id, { summarizeFansOver: 50 }) and pages a fan with
getFanMembers (see Wide fans). StoreRunGateway
implements both, plus getRun. On a store-less pod, ProxyRunGateway forwards the detail options
in its getRunDetail request and sends getFanMembers and getRun request kinds. getRun answers
the run alone, so a caller that only needs a run's status (a cancel check, say) does not ship the
whole timeline over the wire. The control plane's
responder checks that the requesting tenant owns the run before it pages the fan, as it does
before every run-scoped verb, so a tenant cannot page another tenant's fan. A control plane older
than the tenant still serves both. See Rolling upgrades.
If you implement RunGateway yourself:
summarizeFansOveris a hint. A gateway that ignores it returns the full detail, and the console renders every member as before.getFanMembersis optional. Without it, the dashboard'sGET runs/:id/fans/:groupanswers 404, so a summarized fan can be drawn but not expanded. Core exportssummarizeTimeline,summarizeFan,pageFanandchildIdsOf, so a gateway that already loads the checkpoints can implement both in a few lines, the wayStoreRunGatewaydoes.getRunis optional. The ownership check uses it to read only the run row; without it, the check falls back togetRunDetail, which reads every checkpoint of the run.
cancel on a store-less pod: same verb, two objects, opposite answers. Injecting
WorkflowEngine there gets you a start-only client — start publishes a start message over the
wire, but cancel, deleteRun, resume, signal, signalWithStart and publishEvent reject with
a named tenantUnsupported(...) error, because they reach for a store the pod does not have. The
RunGateway above has no such problem: its cancel is a wire request the control plane answers
against its store, so it works on every shape.
That is why the table lists cancel as a working verb. It is RunGateway.cancel that works;
WorkflowEngine.cancel is the one that rejects. Inject RunGateway in anything that has to run on
more than one shape, and you never meet the distinction.
What a tenant gets
A tenant's workflows run on the tenant's worker, but the control plane orchestrates them. These basics behave as on a standalone app:
- Class statics.
MyWorkflow.start(input, opts)works on a tenant. It publishes the start to the control plane through the same start-only clientWorkflowEngineinjects.MyWorkflow.execute()outside a workflow still throws there, because waiting on a run needs the store. - Start options.
version,priority,startAtandconcurrencytravel with the start and the control plane applies them: the run is stamped with the priority, waits for itsstartAt, counts against the quota, and starts only on a live worker that declares the pinned version. A start the quota refuses is recorded as afailedrun witherror.code: 'concurrency_limit'. The tenant caller has already returned, so the refusal has to be stored where you can find it by run id. A start whose input the control plane's own registration rejects is stored the same way, with'invalid_input'. @Workflowoptions declared on the tenant. The control plane knows a tenant's workflow by name only, so the tenant carries its options:- Evaluated by the tenant, on each start. An
inputschema andvalidateInputreject a bad input instart()itself, before anything is sent. Asingletonkey and a defaultconcurrencyquota are functions of the input, so the tenant evaluates them and sends the result with the start. The control plane stamps the runsingleton:<partition>/<key>(namespaced, so two tenants using the same key never share a slot) and admits it like a local singleton, on every turn. - Announced by its workers. Static
tags,executionTimeoutand the singletonlimitride on the worker's registration (WorkflowRegistration.options). The control plane merges the tags into each run, cancels a run that outlives the timeout (execution_timeout), and admits a singleton key up to the limit. When replicas disagree (a rolling deploy), the worker that started last wins, as for schedules. - Precedence. A per-start option beats the workflow's (
opts.concurrencyover@Workflow({ concurrency }); starttagsare merged with the workflow's). A registration of the workflow on the control plane itself (register,registerRemote, a@Workflowthere) beats anything the tenant announces: the announced options apply only to a workflow the control plane serves by convention. - Not carried.
searchAttributesschemas are checked wherectx.upsertSearchAttributesruns.debounce/batchcoalescing needs the control plane's accumulator: a tenant's ownpublishEventstarts such a subscriber once per event, with a warning. A start that does not come from the tenant (a control-planeengine.startby name) has no singleton key to stamp; a tenant schedule of a singleton workflow class does, evaluated once against the schedule's input.
- Evaluated by the tenant, on each start. An
signal,signalWithStartandpublishEventfrom tenant code. They go to the control plane as run requests over the tenant'stransport(theProxyRunGatewaychannel), scoped to the tenant's own partition:engine.signal(token, payload, { id })resumes the run of this partition waiting ontoken, and resolvesnullwhen none waits. Unlike on a control plane it is not buffered for a wait opened later: another partition's run could open it. A run of another partition waiting on the token reads as nobody.engine.signalWithStart(workflow, input, runId, { token, payload })starts the run in this partition (with the same options and policy asstart) unless it exists, then signals it. The signal is buffered until the run waits only when the token contains the run id (a run-scoped token like`${runId}:add`, the patternsignalWithStartis for); another token is delivered only to a run of this partition already waiting on it. A run id or a waiting run that belongs to another partition is refused withcross-tenant.engine.publishEvent(name, payload, { id })starts this app's ownonEventsubscribers (theirwhereandinputapplied here) through the start path, asevt:<id>:<workflow>, and has the control plane resume the runs of this partition waiting on the event. Nothing is buffered.- Without
transporton the tenant'sDurableModulethese reject, naming it.
@DeadLetterhandlers and interceptors. A tenant's inline@DeadLetter()method is registered on its worker as<name>.dlq, and the worker announces it as the workflow's dead-letter route (else thedeadLetterWorkflowreference, else the tenant's module-leveldeadLetterWorkflow). When a run of that workflow dead-letters on the control plane, the control plane starts the route in the run's partition, asdlq:<runId>with theDeadLetterpayload, so the handler runs on the tenant. With no live worker it waitsblockedlike any tenant start. The control plane's owndeadLetterWorkflowdefault stands aside for a workflow whose workers announce a route.@StepInterceptor()providers on a tenant wrap every step its workers run (workflowis''in the invocation: a dispatched step does not carry it).- Entities stay on the control plane. An entity's state is a run on the store and its
@Onhandlers run in the engine that owns that store, which a tenant does not have. An@Entityprovider on a tenant fails at boot, naming the entity. - A start is never lost. When no worker serves the workflow yet (the tenant pod is down, rolling
or not deployed), the control plane creates the run
blockedwitherror.code: 'no_live_worker'and starts it once a worker is live. It checks everyblockedPollMs, backing off to once a minute for a run that has waited long. Liveness is read through a registry snapshot up to 30 seconds old, so a worker that just booted is noticed within that window. Such a run is never dead-lettered for waiting; cancel it to drop it. A start the control plane fails to create (a store error) is put back on the start queue and retried with a delay that doubles up to a minute, for about an hour. Redelivery is safe: a run id is started once, and a start sent without one gets its id before the first attempt. - A dead worker does not hang its run. A workflow turn dispatched to a worker carries a re-drive
deadline:
remoteAdvanceSilenceMswhen you set it, elsereconcileMs(5 minutes by default). The worker's run heartbeat (every 5 seconds while it replays the turn) pushes it forward. If the worker dies holding the turn, the control plane sends the turn again once the deadline passes, to any live worker on the partition.reconcileMs: 0withremoteAdvanceSilenceMsunset keeps the old unbounded wait. - Workflow code runs as it does standalone. A
@Step({ retries, backoff, timeoutMs })(or the same options onctx.step) is retried, backed off and timed out by the control plane with the in-process rules, andctx.sleepUntil,ctx.waitForSignal(token, { timeoutMs }),ctx.waitForEvent, fire-and-forgetctx.startChild,ctx.continueAsNewandctx.setEventwork in tenant code. A child or continuation stays on the tenant's partition. See the worker ctx for the full list. - Not yet in tenant code:
ctx.patched,ctx.upsertSearchAttributes,ctx.waitForRun,ctx.transaction, entities,ctx.task,ctx.breakpoint,ctx.webhook,ctx.onUpdate, andstartChildwithversionorparentClose. Each throwsUnsupportedOnThinWorkernaming the op.
Schedules on a tenant
A tenant has no store, so it cannot fire the schedules you declare on it. Its workers announce them
instead, and the control plane adopts them as persisted schedules and fires them:
DurableModule.forRoot({
connection: process.env.REDIS_URL,
partition: 'acme',
schedules: [{ key: 'daily-digest', workflow: DigestWorkflow, cron: '0 8 * * *' }],
});- Announced on the worker descriptor. Each tenant worker publishes its app's schedules on the
descriptor it already beats into the worker registry, under the same wire tenant its starts carry
(the partition, or its
tenantToken, which a control plane withverifyTenantverifies; an announcement that fails verification is ignored). A producer-only process (consumers: false) publishes no descriptor, so declare schedules on the processes that run the app's workers. It warns if you don't. - Adopted per app. Every 15 seconds a driving control-plane instance (one at a time with
@nestjs/locks) reads the live descriptors and keeps one persisted schedule per announced key, with idapp:<partition>:<key>, namespace<partition>and the tagschedule:announced. Two apps with the same key never collide. Any number of replicas announcing the same set write nothing after the first sync, and each window still starts one run (its run id issched:app:<partition>:<key>:<window>). - The newest deploy wins. When live workers of one app disagree on a key (a rolling deploy changed
its cron), the worker that started last wins. A changed definition is re-applied like
upsert: its history is kept and its next fire is recomputed from now. - Removed means paused, not deleted. A schedule that no live worker of its app announces any more is marked unannounced, and paused ("withdrawn") once it has stayed that way for the grace period, 10 minutes by default. The grace period starts only once the old pods are out of the registry: a pod that shut down cleanly leaves at once, a pod that died expires within about a minute. The history stays, and announcing it again (a rollback) resumes it. Nothing is withdrawn while the app has no live worker, or only workers on an SDK that does not announce schedules, so an outage never pauses your schedules.
- Fired through the tenant start path. A window starts its run exactly like a tenant start. With no
live worker of the app (the tenant is down, or mid-deploy), the run waits
blockedwitherror.code: 'no_live_worker'and starts once a worker is live, instead of the window being lost. Windows that come due while that run still waits are folded into it, so an app that comes back after an outage finds one run per schedule waiting, the boundcatchup: 'latest'gives.overlap: 'skip'holds as on any schedule (a waiting run is in flight).backfillis not carried over: an announced schedule catches up one window at most. - Owned by the control plane. Announced schedules show on the console's Schedules page with their
app, and pause, resume and run now work on them. A pause made there survives the next
deploys. A change of the app's own
pausedflag does apply. Deleting one is undone by the next sync while the app still announces it: pause it, or remove it from the app. - Configuration.
announcedScheduleson the control plane'sDurableModule: on by default with a store that persists schedules and a transport that reads worker descriptors (BullMQ);{ syncMs, graceMs }tunes it andfalseturns it off. It does not needpersistedSchedules: with that off, the poll fires only the adopted schedules. A schedule'snamespaceis ignored on a tenant, whose runs always belong to its own partition.
A remote step that a dead worker took with it is a separate case. remoteRedispatchMs re-sends
it, and stays off by default because it re-runs a step that was only slow. See
Retries.
A worker on an SDK that does not send run heartbeats (the TypeScript and Python workers do) is
re-sent any turn that takes longer than reconcileMs. Set remoteAdvanceSilenceMs above your
longest turn if you run one.
Rolling upgrades
Tenant pods and the control plane can be upgraded in either order. While they are on different releases, run detail keeps working in both directions:
| Tenant | Control plane | What happens |
|---|---|---|
| 0.47.2+ | 0.46.x or older | The old responder ignores the detail options and has no getFanMembers. ProxyRunGateway sees the full detail come back without fans and summarizes it on the tenant. A getFanMembers gets no data from an old responder, so the proxy reads the full detail and pages the fan out of it. Both fallbacks happen on that reply, with no timeout wait. A getRun gets no data either, so the proxy takes the run out of the full detail. |
| 0.47.0 or 0.47.1 | 0.46.x or older | These tenants have no fallback: run detail comes back unsummarized and fan pages answer 404. Upgrade the control plane first, or move the tenants straight to 0.47.2. |
| 0.46.x or older | 0.47.0+ | An old proxy never sends detail options or getFanMembers. The new responder answers its requests exactly as before: a full detail, and the same ownership checks. |
Starts follow the same rule: a field one side does not know is ignored.
| Tenant | Control plane | What happens to a start |
|---|---|---|
| this release | older | The old control plane ignores version, priority, startAt and concurrency and starts the newest version at once. A start with no live worker is dropped, as before. MyWorkflow.start() works on the tenant either way. |
| older | this release | The start carries no options and runs as before. A start with no live worker now waits blocked instead of being dropped, and a turn whose worker dies is re-driven after reconcileMs. |
The @Workflow options, dead-letter routes and run requests of this release follow it as well:
| Tenant | Control plane | What happens |
|---|---|---|
| this release | older | The old control plane ignores options, deadLetter and a start's singleton: no announced tags, timeout or singleton gate, and a dead run goes to the control plane's own default, as before. The input schema and the default quota still apply, since the tenant evaluates them. signal gets no answer it knows (the oldest responders reply with nothing) and rejects unsupported-request, as do signalWithStart and publishEvent; publishEvent starts the tenant's own subscribers first. |
| older | this release | The old worker announces no options or route, so nothing new applies and its dead runs go to the control plane's default. Its signal, signalWithStart and publishEvent reject on the tenant, as before. |
this release, on an older @dudousxd/durable-worker | any | @StepInterceptor() providers are not applied, with a warning at boot; a start's singleton key is not sent. |
Schedules follow it too. The announcement is an optional descriptor field.
| Tenant | Control plane | What happens to the tenant's schedules |
|---|---|---|
| this release | older | The old control plane ignores the field: the schedules do not fire, as before. Nothing breaks. |
| older | this release | The old worker announces nothing, so nothing is adopted for it and nothing is withdrawn. While a rolling deploy runs old and new workers of one app side by side, the new workers' announcement is the one applied. |
Workflow code follows feature negotiation: the control plane lists the decisions it applies on each workflow task it sends.
| Tenant | Control plane | What happens to tenant workflow code |
|---|---|---|
| this release | older | A step declared with retries, backoff or a timeout, and sleepUntil, a timed waitForSignal, waitForEvent, startChild, continueAsNew, fail the run with error.code: 'control_plane_unsupported' naming the op, instead of running without their semantics. Everything else runs as before. Upgrade the control plane first. |
| older | this release | Unchanged: an older worker never sends the new decisions, and a step decision without a policy runs once, as before. |
After a control plane answers that it does not know getFanMembers (or getRun), the proxy pages fans locally
for the next minute before it asks again. The control plane can be several pods behind one queue,
mid-upgrade themselves, and a reply does not say which pod sent it. So the proxy treats the whole
control plane as old until that minute is up. The result is the same either way. Only the cost
changes: the old path moves every checkpoint of the run over the wire, so on a run with a very wide
fan, finish upgrading the control plane soon.
From 0.47.2 on, a responder answers a request kind it does not know with an error whose code is
unsupported-request, without touching the store. The next new verb can fall back the same way on a
control plane that does not have it. A responder whose gateway throws replies with that error, so a
tenant no longer waits out runGatewayTimeoutMs for an answer that will never come.
Layered tenant authentication
The tenant on a wire request is a claim. Without authentication the
isolation boundary is meaningless — any pod could
ask for any tenant's runs. Durable stacks two layers:
Prefix / network baseline
Each tenant runs on a segmented transport prefix/namespace behind a Redis/network ACL, so a pod can only reach its own prefix. No application code.
Signed token on top
Each tenant pod carries a secret-signed token. The control plane verifies the signature and derives
the tenant from the token, ignoring any tenant in the request body — defense in depth.
Both sides are optional and off by default. Turn the second layer on with verifyTenant on the
control plane and tenantToken on each tenant pod:
import { hmacTenantVerifier, signTenantToken } from '@dudousxd/nestjs-durable';
// Mint the token a tenant pod presents (once, e.g. in your provisioning script). The pod carries
// only the token, never the secret. `ttlMs` makes it expire, so a captured token stops replaying:
const token = signTenantToken('acme-corp', process.env.DURABLE_TENANT_SECRET!, { ttlMs: 86_400_000 });
// Control plane: verify it. A secret LIST makes rotation a two-step deploy — verify with
// [next, current] first, then re-mint tokens with `next` at leisure.
DurableModule.forRoot({
topology: 'control-plane',
store,
transport,
verifyTenant: hmacTenantVerifier([process.env.DURABLE_TENANT_SECRET_NEXT!, process.env.DURABLE_TENANT_SECRET!]),
});
// Tenant pod: present it. A function is called before every request, so a short-lived token can be
// re-minted or fetched from a secret store without a restart.
DurableModule.forRoot({
topology: 'tenant',
partition: 'acme-corp',
connection: process.env.REDIS_URL,
tenantToken: process.env.DURABLE_TENANT_TOKEN!, // or: () => fetchTenantToken()
});A token provider runs before the request is sent, and the request's timeout starts only once it has resolved: the deadline covers the control plane's round trip, not the provider. A provider that rejects fails the request.
The token travels in the existing tenant field of every RunRequest and StartRunMessage, so
the wire shape does not change. It is <claim>.<base64url(HMAC-SHA256(secret, claim))>, where the
claim is the tenant name, optionally followed by .exp<epochMs> when minted with ttlMs. The live-tail
channel stays keyed by the partition, never the token.
With a verifier configured, the control plane:
- answers a run request whose token is missing, tampered, expired or signed with another secret with
{ ok: false, error: { message: 'invalid or unauthorized tenant token', code: 'unauthorized' } }, before any run is touched.ProxyRunGatewayrejects with aRunGatewayErrorwhosecodeisunauthorized(cross-tenantfor a run owned by another tenant), soerr.codeis typed; - drops such a start-run without creating a run (logged; the start channel has no reply);
- scopes every accepted request to the tenant derived from the token, never the wire claim;
- turns a verifier that throws into an error reply, so the tenant never waits out its timeout.
Bring your own verifier for asymmetric or issued tokens (your own JWTs, an OIDC provider):
verifyTenant takes a function ({ token, tenant }) => { tenant, capabilities? } | null (sync or
async), or a class or object implementing TenantVerifierContract, and tenantToken takes a class or
object implementing TenantCredentialsContract. Authenticate tenants
has full working classes. capabilities is carried on the verified identity but not enforced yet:
a verified tenant can call every verb, scoped to its own namespace.
Without verifyTenant the wire tenant is trusted verbatim — any process with broker access can
list, cancel and start runs as any tenant (prefix/network isolation only). An explicit
topology: 'control-plane' without a verifier therefore logs a warning when its responder
starts. A standalone operator (no topology, role inferred from store) boots silently, because an app
that never serves tenants has nothing to protect there.
The scheme is byte-compatible with Agora (@adonis-agora/durable): a token minted by either side
verifies on the other, and the unauthorized reply is identical. See
interop.
The control plane is the trust boundary for these proxied requests: it forces listRuns to the
requester's own tenant (no cross-tenant enumeration), validates run.namespace === tenant on every
runId-bearing verb (anti-IDOR), and rejects unknown verbs and tampered tokens.
Next steps
- Tenancy — what
namespaceandpartitionpartition, and the rules that keep a tenant's runs on the tenant's own pool. - Handshake & capability negotiation — keep a mixed fleet version-safe.
- Cross-ecosystem interop — add Python and Adonis workers.
Topologies
Run durable in one process, split the control plane from the workers, or spread store-less thin workers per tenant — the same engine over the same wire, selected by which options a process is given.
Authenticate tenants
Prove which tenant a store-less process is. Write a verifier for the control plane and a credentials source for the tenant, with your own JWTs, any OIDC provider, or a shared HMAC secret.