Event-driven workflows
publishEvent(name, payload) starts every @Workflow({ onEvent }) subscriber and resumes any run parked on ctx.waitForEvent — with optional debounce/batch coalescing for bursty sources.
Not every workflow starts from a direct start call, and not every wait is for a signal aimed at
one specific run. Events are name-based pub/sub layered on top of the same suspend machinery:
engine.publishEvent(name, payload) can start a fresh run of any workflow subscribed to that
name, and can resume any in-flight run parked on ctx.waitForEvent(name) — in one call, fanning
out to as many runs as care about it.
Publishing an event
Call engine.publishEvent(name, payload, opts?) — or WorkflowService.publishEvent, the same
method exposed for DI — from anywhere: a controller, another workflow's step, a queue consumer.
@Controller('webhooks')
export class BillingWebhookController {
constructor(private readonly workflows: WorkflowService) {}
@Post('payment-settled')
async onPaymentSettled(@Body() body: { orderId: string; amount: number }) {
const touched = await this.workflows.publishEvent('payment.settled', body);
return { touched };
}
}publishEvent does two things, and returns the sum of how many runs it touched:
- Resumes every in-flight run currently parked on
ctx.waitForEvent(name, { match })whosematchthe payload satisfies — fan-out, unlike a signal's point-to-point token. - Starts a fresh run of every workflow registered with
onEvent: [name](via@Workflow({ onEvent })or@OnDurableEvent), passingpayloadas that run's input.
Publishing is idempotent per subscriber: pass opts.id to dedupe redeliveries of the same
logical event. Each started run gets the id evt:<id>:<workflow>, so redelivering the same id
finds the existing run instead of starting a second one. Omit id and the engine generates a fresh
uuid per publish, so every call starts its subscribers exactly once.
A subscriber whose input schema or validateInput rejects the payload simply never starts — it does not block the
other subscribers or the waiters being resumed.
Starting a workflow from an event
Subscribe a @Workflow to one or more event names with onEvent, or the equivalent
@OnDurableEvent(...) class decorator — the two are merged, so you can use whichever reads better,
or both:
@Workflow({ name: 'send-welcome', version: '1', onEvent: ['user.registered'] })
export class SendWelcomeWorkflow {
constructor(private readonly mailer: MailerService) {}
async run(ctx: WorkflowCtx, input: { email: string }) {
await ctx.step(this.mailer.sendWelcome, input.email);
return { sent: true };
}
}// Equivalent, class-decorator form — merges with any `onEvent` array on the same class.
@OnDurableEvent('user.registered', 'user.invited')
@Workflow({ name: 'audit-signup', version: '1' })
export class AuditSignupWorkflow {
async run(_ctx: WorkflowCtx, input: { email: string }) {
/* ... */
}
}The decorator is named OnDurableEvent — not OnEvent — because @nestjs/event-emitter exports an
@OnEvent of its own, and in an app using both libraries an auto-import picking the wrong one fails
silently in either direction.
The next time anyone calls publishEvent('user.registered', { email }), both workflows above start
a fresh run with { email } as input. A publish can resume waiters and start subscribers in the
same call — the returned count covers both.
Filtering with where, shaping with input
An onEvent entry can be { event, where, input } instead of a bare name. where(payload) runs
when the event is published and decides whether this workflow starts for it. input(payload) builds
the started run's input; without it, the run gets the payload as is. It works in
@Workflow({ onEvent }) and @OnDurableEvent(...) alike:
@OnDurableEvent({
event: 'order.placed',
where: (o) => (o as Order).total > 1000,
input: (o) => ({ orderId: (o as Order).id }),
})
@Workflow({ name: 'review-large-order', version: '1' })
export class ReviewLargeOrderWorkflow { /* ... */ }A where that throws counts as "no", and the engine logs a warning naming the subscriber. Both
functions are TypeScript, so they only apply to subscriptions registered in TypeScript.
Reacting to another workflow finishing
When a run settles, the engine publishes it as a lifecycle event: run.completed:<workflow>
when it completes, run.failed:<workflow> when it ends failed, cancelled or dead. Subscribe with
@OnWorkflowCompleted / @OnWorkflowFailed, and the workflow that finished never has to know who
reacts to it:
@OnWorkflowCompleted(IngestionWorkflow, {
where: (e) => e.input.type === 'mvr',
input: (e) => ({ baseId: e.input.baseId }),
})
@Workflow({ name: 'refresh-summaries', version: '1' })
export class RefreshSummariesWorkflow {
async run(ctx: WorkflowCtx, input: { baseId: string }) { /* ... */ }
}Without input, the subscriber receives the WorkflowLifecycleEvent itself: the settled run's id,
input, output (or error and status), tags and search attributes, read from the store after it
settled. Type it with LifecycleEventOf<typeof IngestionWorkflow>. Prefer input when the
subscriber needs a few fields: it lets an existing workflow subscribe with its own input shape, and
keeps the settled run's whole input and output out of the new run's row.
With a class ref, the decorator type-checks the subscriber: where and input see the source's
input and output types, and the decorated workflow's run must accept the event (or what input
returns), or the decorator does not compile. A name instead of a class (for a workflow from another
runtime) is not checked. You can also use the event names directly in onEvent, through
runCompletedEvent(name) / runFailedEvent(name).
@OnWorkflowFailed starts on all three endings by default. Narrow it with statuses, for example
to page on failures but not on an operator's cancel:
@OnWorkflowFailed(IngestionWorkflow, { statuses: ['failed', 'dead'] })Child runs publish too: a subscriber of IngestionWorkflow starts for every ingestion an etl
workflow runs as a child, not only for the ones started directly. Filter with where if it should
not.
Python subscribers
A Python workflow subscribes the same way,
with @worker.workflow("notify", on_workflow_completed="ingest"), on_workflow_failed=... or a
plain on_event=[...]. The worker announces the events in its descriptor (subscribes), and an
engine that publishes one starts the workflow by name on its live worker group, with the event
payload as its input and the same deterministic id (evt:<runId>:completed:notify). An announced
subscriber that is also registered on the engine is started once, through the local registration.
One that a Node engine announces is left to that engine, so its where and input still apply.
An announced subscriber has no where and no input: the announcement carries only the event
name, and those functions run in the publishing process. Filter in the Python body instead, and
return early for an event it should ignore. An engine with no live worker group of the
subscriber's name leaves the event owed, for an instance that has one, rather than reporting it as
failed.
Delivery
Each settled run starts each subscriber exactly once, including when the subscriber is registered on some instances only (a rolling deploy, or a workflow that lives on one worker):
-
The terminal status write also tags the run
durable:lifecycle:pending, plus onedurable:lifecycle:owed:<subscriber>tag per subscriber the event is owed to, in the same update. The subscribers are the ones registered on the engine settling the run and the ones the rest of the fleet announces, in two ways:- The subscription registry, in the state store. Every engine with
onEventsubscriptions keeps one run of the internal__lifecycle_registryworkflow (id__lifecycle_registry:<instanceId>, statuscompleted, its subscriptions ininput), refreshed every 10 seconds by the timer poller and counted as live for 35 seconds. It works with every transport (BullMQ, db, SQS, event emitter) and with none. - Worker descriptors. On a transport that reads them fleet-wide (BullMQ), each worker's
descriptor lists the events each workflow subscribes to (
subscribes); a Python worker announces its subscriptions only this way.
The engine reads both at most once every 5 seconds (the registry a page of 1000 rows at a time, to the end). The terminal write never waits for that read: it uses the last one, and starts a new one in the background when it is older than 5 seconds.
- The subscription registry, in the state store. Every engine with
-
When the engine settling the run has no usable read yet (it just booted) or its last read failed, the terminal write tags the run
durable:lifecycle:pendingalone: the owed set is unresolved. The first publish with a good read (the live one, or the sweep on any instance) resolves it to every subscriber of the run's namespace that has not started, coalesced or failed from it, writes their owed tags and goes on as below. Until then an instance starts only its own subscribers that do not debounce or batch, and the run stays unresolved. -
The owed set is scoped to the settled run's namespace. A run of namespace
acmeis owed to the subscribers announced foracme(registry runs ofacmeengines, descriptors servingacmeby theirnamespaceor@acmegroup) and to those of engines with no namespace, never to another tenant's. An engine with no namespace publishes every namespace's settled runs, so its own subscribers apply to the runs of every namespace, whichever engine settles them; a namespaced engine's apply to its namespace only. The registry run records which it is (engineNamespace,nullfor no namespace), since both kinds of engine keep it underdefault. -
Right after, the engine starts the subscribers it has, drops their owed tags and records one
durable:triggered:<subscriber>tag per run it started, or onedurable:coalesced:<subscriber>tag per subscriber whose debounce/batch accumulator it routed the event into.durable:lifecycle:pendinggoes with the last owed tag. -
Every publish of a run (live, sweep, heal, republish, orphan drop) holds the run's lease while it reads the run's tags, starts subscribers and writes the tags back, so publishers on several instances update them one at a time and never overwrite each other. A publish that cannot take the lease within about 1.5 seconds gives up: the live one leaves the run to the sweep, the sweep moves on until its next tick.
run.triggeredandrun.trigger_failedcome from the publish whose write recorded them, so a run that two instances publish reports each subscriber once. -
The timer poller's lifecycle sweep runs on every instance. It finds a run still marked (after a 30s grace for the live publish) and starts the owed subscribers that instance has, so a subscriber registered only elsewhere is started there. A process that died before publishing is covered the same way. The subscriber's run id is deterministic (
evt:<runId>:completed:<subscriber>), so a second publish starts nothing new. -
The sweep reads marked runs a page (
limit, 100) at a time and skips the ones it cannot act on, until it has published to (or dropped orphans of) 100 runs or examined 1000. Runs owed only to subscribers other instances have cannot fill its window and hold back the ones it can publish. -
The sweep also heals runs settled in the last 2 minutes (
LIFECYCLE_HEAL_WINDOW_MS) that missed a subscriber the fleet announced only after the settling engine last read the announcements (a subscriber coming up during a rolling deploy). For each subscription it first saw in that window, it reads the recently settled runs of the source workflow (updatedAfter, at most 100 per workflow) and publishes to each subscriber a run has no owed, triggered, coalesced or failed tag for, as if it had been owed: started where the sweeping instance has it, owed to the instances that do otherwise. A subscriber that comes up more than 2 minutes after a run settled is a backfill: republish the run (below). -
An owed subscriber that no live worker announces and the sweeping instance does not have is dropped 24 hours after the run settled (
LIFECYCLE_ORPHAN_MS), counting only announcements for the run's namespace, and reported asrun.trigger_failed(subscriber <name> is not registered on any live worker), so a removed subscriber does not keep the run marked forever. -
Retention never prunes a run still carrying
durable:lifecycle:pending, so a short retention window cannot delete it before its event is published.
A subscriber that cannot start, because its where threw or its start failed (its validateInput
rejected the input, for example), is reported as run.trigger_failed on the settled run and is not
retried. The same update that drops its owed tag tags the run durable:trigger_failed:<subscriber>
(LIFECYCLE_TRIGGER_FAILED_TAG_PREFIX; the orphan drop does too), so the run detail lists it as
failed; the message is carried only by the event. Republish it once it is fixed (below): a
successful start removes the tag.
An engine writes its registry run from the timer poller, so only an instance that drives runs
(drive not false) announces its subscriptions. A subscriber registered only on a dashboard-only
or API-only instance is owed the event only by runs that instance settles itself.
The registry runs are engine bookkeeping: retention never prunes them (they carry
durable:lifecycle:registry), recovery and the timer sweeps leave them alone, and the dashboard's
run lists, counts and pickers leave them out unless you filter on __lifecycle_registry by name. Any
engine's sweep deletes the ones not refreshed for 10 minutes, so a scaled-down instance leaves
nothing behind.
A run marked only durable:lifecycle:pending, with no owed tags, is unresolved (see above), and so
is a run settled before the owed tags existed: both resolve to every subscriber the fleet has for the
run's namespace, which includes every subscriber the publishing instance has.
A continue-as-new handoff is not a completion: only the last run of the chain publishes. Nothing is marked, read or published for a workflow nobody subscribes to.
Republishing
engine.republishLifecycle(target) (also workflowService.republishLifecycle) publishes settled
runs again, without needing the marker: to backfill a subscriber added after the runs settled, or to
retry one that failed to start. Subscribers already started from a run are not started again.
// Every completed ingestion of the last week, for the new `refresh-summaries` only.
await workflowService.republishLifecycle({
workflow: 'ingestion',
kind: 'completed',
since: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
subscriber: 'refresh-summaries',
});
// → { runs: 112, started: 112, failed: [] }
// One run, every subscriber that has not started from it.
await workflowService.republishLifecycle({ runId: 'ingest-42' });The workflow form reads at most limit settled runs (default 1000), a page at a time; since and
until bound when they settled. Subscribers registered on the calling instance are started there.
A subscriber only another worker has is owed the event again (the run is re-marked), and the sweep
on that worker starts it. A republish publishes only to subscribers of the run's lifecycle event in
its namespace: a subscriber that is not one is reported in failed, and is never written as owed.
limit must be a positive integer. A debounced or batched subscriber starts no run of its own id, so
its durable:coalesced:<subscriber> tag stands for that run: a republish sends it the event when the
run has no such tag (a coalescing subscriber added later is backfilled like any other), and again
only when its start failed.
Through the tenant proxy, a republish by a tenant is refused (RunGatewayError coded bad-request,
HTTP 400 from the dashboard) when limit is not a positive integer or subscriber does not
subscribe to the workflow in the tenant's namespace, and a limit above 1000 is lowered to 1000.
The dashboard offers the same on a settled run whose workflow has subscribers ("Republish lifecycle
event"), and the CLI as durable lifecycle:republish --workflow ingestion --since 2026-11-01 --subscriber refresh-summaries (or --run <id>), with a config that exports the engine.
Following the link
The two runs are linked both ways, without being parent and child: cancelling or retrying one does not touch the other.
- Dashboard: the settled run's header lists the runs it
triggered:, and the started run shows which run it wasstarted when this run completed:(orfailed:). - Code:
workflowService.triggeredRuns(runId)returns the started runs' ids, read from the settled run'sdurable:triggered:*tags, so any instance can answer it.lifecycleSourceOf(run)returns the run that started one, read from its id. Build an id withlifecycleRunId(sourceRunId, 'completed', 'refresh-summaries'). - Events: the engine emits
run.triggeredon the settled run (nameis the subscriber,triggeredRunIdthe run it started) andrun.trigger_failedfor a subscriber it could not start. The OTel metrics count both (runs.triggered,runs.triggerFailed, andtriggeredBySubscriberby workflow and subscriber), and Telescope shows them in the runs' trails. - Traces: with
attachDurableOtel, the started run's span links to the settled run's span. - Dashboard workflow page:
#/workflow/<name>lists who starts when the workflow settles and who starts it (see the dashboard). In code,engine.workflowLifecycle(name).
A subscriber that debounces or batches its events has no run of its own per settled run, so it gets a
run.triggered event and a durable:coalesced:<subscriber> tag (LIFECYCLE_COALESCED_TAG_PREFIX,
read with coalescedSubscribersOf(tags)) but no durable:triggered:* link. Its accumulator counts each settled run's
event once (the event carries the source run's id, and the accumulator remembers the last 1000 ids
across bursts), so a run published twice never counts twice in a debounce or a batch.
Coalescing bursts: debounce and batch
A source that fires many events in quick succession — a stream of file uploads, a chatty webhook —
usually shouldn't start one run per event. debounce and batch coalesce an onEvent subscription
so the workflow starts once per burst instead:
export interface WorkflowOptions {
// ...
/** Start one run only once events have been quiet for this long (resets on each event), with the
* LAST payload. */
debounce?: string | number;
/** Start one run with ALL payloads (`{ events: [...] }`) once maxSize is reached or `within`
* elapses from the first event. */
batch?: { maxSize: number; within: string | number };
}Both are built the same way under the hood: instead of starting the target workflow directly, the
engine routes each published event into a per-workflow accumulator — a long-lived built-in
workflow (__evt_debounce / __evt_batch, registered once at engine construction) that collects
payloads via signalWithStart, then startChilds the real target once, and finally continueAsNews
to re-arm itself for the next burst.
debounce — "reindex at most once a minute"
@Workflow({
name: 'reindex-search',
version: '1',
onEvent: ['catalog.item-changed'],
debounce: '1m',
})
export class ReindexSearchWorkflow {
constructor(private readonly search: SearchService) {}
async run(ctx: WorkflowCtx, lastChange: { itemId: string }) {
// Runs once the catalog has been quiet for a minute, with only the LAST change payload.
await ctx.step(this.search.reindex, lastChange);
}
}Every catalog.item-changed publish resets the quiet-window clock; the accumulator only fires
ReindexSearchWorkflow once nothing new has arrived for the debounce window ('1m'), and the run
it starts receives the last payload published during the burst — earlier ones in the same burst
are discarded. Three publishes within the window produce exactly one run, carrying the last payload.
batch — "process uploads in batches"
@Workflow({
name: 'process-uploads',
version: '1',
onEvent: ['upload.completed'],
batch: { maxSize: 100, within: '10s' },
})
export class ProcessUploadsWorkflow {
constructor(private readonly ingest: IngestService) {}
async run(ctx: WorkflowCtx, batch: { events: Array<{ fileId: string }> }) {
await ctx.step(this.ingest.processBatch, batch.events);
}
}The accumulator collects payloads as upload.completed is published and fires
ProcessUploadsWorkflow as soon as either condition is met: maxSize events have arrived, or
within has elapsed since the first one in the batch — whichever comes first. The target's input is
always { events: [...] } — the full array of payloads collected in that batch, in publish order:
three hit events with maxSize: 3 produce one run with { events: [{ n: 1 }, { n: 2 }, { n: 3 }] }.
debounce and batch are mutually exclusive per workflow, and both are declared once on the
@Workflow (or via the plain WorkflowOptions). Their windows (debounce: '30s', or the within
of a batch) accept the same duration strings as ctx.sleep.
Coalescing per key
A workflow coalesces all its triggers into one accumulator, so a burst for one key would swallow
another key's. key gives each distinct key its own accumulator, and so its own run. It receives the
subscriber's input (after the subscription's input mapping) and returns a string; any string works,
it is escaped into the accumulator's run id.
@OnWorkflowCompleted / @OnWorkflowFailed take it as debounce: { windowMs, key } or
batch: { maxSize, windowMs, key }. Several ingestion runs of the same base finishing close together
start one summary refresh per base:
@OnWorkflowCompleted(IngestionWorkflow, {
input: (e) => ({ baseId: e.input.baseId }),
debounce: { windowMs: '30s', key: (input) => input.baseId },
})
@Workflow({ name: 'refresh-summaries', version: '1' })
export class RefreshSummariesWorkflow {
async run(ctx: WorkflowCtx, input: { baseId: string }) { /* ... */ }
}key is typed with the subscriber's input: the return type of input, so it needs no cast. It runs
when the event is routed, before any run exists, so it receives exactly what input builds, not what
the subscriber's own @Workflow({ input }) schema parses that to (unlike the singleton and
concurrency keys, which read the parsed value). With batch, the subscriber's run takes
{ events: TInput[] }, which the decorator type-checks. The option sets the workflow's coalescing,
so it applies to every event the workflow subscribes to. A subscription takes debounce or batch,
not both, and a workflow whose @Workflow({ debounce | batch }) says something different fails at
registration. Two decorators on one workflow must declare the same settings: their keys are
compared by source text, so the same arrow written on both matches, while keys written differently
fail at decoration even when they compute the same thing. Without a decorator, pass key in the engine's eventBatch:
engine.register(name, version, fn, { onEvent, eventBatch: { mode: 'debounce', windowMs, key } }).
Waiting for an event mid-run
Where onEvent starts a new run, ctx.waitForEvent<TPayload>(name, opts?) lets an already
running workflow suspend until a matching event arrives, then resume with its payload:
@Workflow({ name: 'order', version: '1' })
export class OrderWorkflow {
async run(ctx: WorkflowCtx, input: { orderId: string }) {
await ctx.step(this.orders.markAwaitingPayment, input.orderId);
// Suspends with zero compute until a `payment.settled` publish whose payload has this orderId.
const payment = await ctx.waitForEvent<{ amount: number }>('payment.settled', {
match: { orderId: input.orderId },
timeoutMs: 24 * 60 * 60 * 1000, // 1 day
});
return { orderId: input.orderId, paid: payment.amount };
}
}match is an optional subset of the payload that must deep-equal for this waiter to be resumed —
engine.publishEvent lists every waiter registered for name, and only signals the ones whose
match keys equal the corresponding payload values. Omit match and the waiter is a broadcast:
it resumes on any payload published under that name. With match, a publish only reaches the runs
it concerns — two OrderWorkflow runs waiting on different orderIds each resume only from the
payment.settled publish carrying their own id.
Pass { timeoutMs } to bound the wait — same shape as ctx.waitForSignal: if the deadline passes
first, the call throws SignalTimeoutError instead of waiting forever. Omit it to wait indefinitely,
consuming zero compute either way. The
same determinism cost as any bounded wait applies: an unbounded waitForEvent consumes one logical
position, a bounded one consumes two (deadline + wait) — see the note under
Timeouts.
Under the hood, waitForEvent is a waitForSignal whose token encodes the event name and the
match criteria (base64-encoded so they never collide with the token's : delimiter) —
engine.publishEvent finds candidate waiters by listing every token with that name's prefix, then
checks each one's decoded match against the payload before signalling it.
Waiting for another run to finish
ctx.waitForRun(runId, opts?) suspends until any run settles, not only a child of this one, and
resumes with its WorkflowLifecycleEvent: status, plus output on a completed run or error on
one that failed, was cancelled or died. Use it to depend on work started elsewhere, such as an
ingestion an upload handler started:
@Workflow({ name: 'monthly-report', version: '1' })
export class MonthlyReportWorkflow {
async run(ctx: WorkflowCtx, input: { ingestionRunId: string }) {
const ingestion = await ctx.waitForRun(IngestionWorkflow, input.ingestionRunId, {
timeoutMs: '6h',
});
if (ingestion.status !== 'completed') return { skipped: ingestion.error?.message };
// `ingestion.output` is typed by IngestionWorkflow's run().
return ctx.step(this.reports.build, { rows: ingestion.output?.rows ?? 0 });
}
}- Passing the workflow class first types the event as
LifecycleEventOf<typeof IngestionWorkflow>;ctx.waitForRun<TOutput>(runId)takes the output type directly. - A run that already settled resolves at once. A run that continues as new settles when the last run of its chain does.
timeoutMs(ms or a duration string) throwsSignalTimeoutErrorwhen it passes first, likewaitForEvent. A run id that does not exist fails with a non-retryablerun <id> not found.- The result is recorded in this run's history, so a replay returns the same event even if the target run was changed or deleted since.
It is a signal waiter whose token embeds the target and this call's position
(runwait:<targetRunId>#<runId>#<seq>). Every settle resumes the waiters on that run; the timer
poller's lifecycle sweep also delivers to waiters whose run settled without resuming them (a crash in
between, or a continue-as-new chain that ended). Only TS workflows that run in the engine can call it;
the thin worker throws UnsupportedOnThinWorker.
Events vs signals vs updates
All three suspend a run with zero compute until something external resumes it, but they differ in addressing and delivery:
| Addressing | Delivery | Typical use | |
|---|---|---|---|
Event (ctx.waitForEvent / engine.publishEvent) | Name + optional match filter | Fan-out — one publish can resume many waiters and start many onEvent subscribers | Something happened that any number of runs (or none yet) might care about — a domain event, a webhook that many orders could be waiting on |
Signal (ctx.waitForSignal / engine.signal) | Exact token you choose | Point-to-point — resumes at most one waiter, buffered if it arrives early | A wakeup aimed at one specific run; see Sleep & signals |
Update (ctx.onUpdate / engine.update) | Run-scoped name | Point-to-point, with a validator that can reject before the run is touched | Steering one specific run with a rejectable business rule; see Queries & updates |
An event is a signal with the addressing inverted: a signal's token is chosen by the caller to hit
one run, while an event's name is a stable, shared channel that any number of runs can subscribe
to (by parking on waitForEvent) or be created by (via onEvent) — match narrows a broadcast
down to the runs a given publish actually concerns. Reach for an update instead when the caller
needs synchronous, validated rejection of a bad delivery — events and signals both always land.
Durable entities
Keyed, long-lived virtual objects — @Entity + @On declare per-key state and its operations; ctx.callEntity/signalEntity or EntityService drive them, serialized per key, exactly once.
Queries & updates
Reading a live run's state with ctx.setEvent + engine.getEvent (side-effect-free queries), and steering it with ctx.onUpdate + engine.registerUpdateValidator + engine.update (validated, Temporal-style updates that can be rejected before they touch the run).