Skip to content

Concepts

Workflows

A workflow is a task whose awaited steps are recorded. It calls other tasks, waits on batches of child runs, sleeps and waits for events for up to 7 days, and resumes after a restart from the last finished step.

On this page

A workflow is a recorded function#

You write a workflow as an ordinary async function. Each awaited ctx call is a step: Bok Joy records it and its result in Postgres.

const DAY = 24 * 60 * 60 * 1000; // A workflow: each awaited ctx call is a recorded step.export async function trial({userId}, ctx) {  const mail = (template, key) =>    ctx.callTask('email.send', {userId, template}, key);   await mail('trial-started', 'welcome');   // Two days pass. The run holds no worker meanwhile.  await ctx.sleep(2 * DAY, 'two-days');   // One heavy step on a bigger machine.  const usage = await ctx.callTask('usage.report', {userId}, {    key: 'usage',    machine: 'medium-2x',  });   // Up to five days for the user to upgrade.  const upgrade = await ctx.waitEvent('upgraded', 5 * DAY, 'upgraded');  if (upgrade.timed_out) {    await mail('trial-ending', 'last-call');    return {upgraded: false, usage};  }  return {upgraded: true, plan: upgrade.payload.plan, usage};}

Register it with "kind": "workflow":

JSON
{"id": "trial.flow", "kind": "workflow", "runtime": "node", "entrypoint": "tasks/trial.mjs", "handler": "trial"}

In Python, a workflow handler must be async def, because its steps are awaited.

How a workflow runs#

When a workflow reaches a step it has not recorded yet, its attempt ends with the status suspended, and the run waits for that step. Bok Joy then runs the child tasks, starts the timer or waits for the event. No worker is held while it waits.

When the step finishes, the workflow runs again in a new attempt, from the top. This time each step it already took returns its recorded result at once, without running again, until the code reaches the next new step. This is replay.

So a restart, a lost worker or a deploy never loses progress: the next attempt replays the finished steps and carries on. A suspension is not a failure and never counts against max_attempts.

Steps#

NodePythonWaits forResult
ctx.callTask(task, input, options?)await ctx.call_task(task, input, key=None, *, machine=None)A child run of another taskThe child's output
ctx.triggerAndWait(task, input?, options?)await ctx.trigger_and_wait(task, input=None, key=None, *, machine=None, concurrency_key=None)A child run of another taskThe child's result, whether it failed or not
ctx.batchTriggerAndWait(task, items, options?)await ctx.batch_trigger_and_wait(task, items, key=None)1 to 1,000 child runs of one task{runs}, one result per item
ctx.sleep(duration_ms, key?)await ctx.sleep(duration_ms, key=None)A durable timer, 0 ms to 7 daysnull
ctx.waitEvent(event, timeout_ms?, key?)await ctx.wait_event(event, timeout_ms=60000, key=None)A named event, 1 ms to 7 days{timed_out, payload}

In Node, the third argument of callTask is a key string or {key, machine}. triggerAndWait takes {key, machine, concurrencyKey}, and batchTriggerAndWait takes {key}.

A child is always a task ("kind": "task"), never another workflow. It runs the same deployment as the workflow, in the same environment, with the same placement and variables. Pass machine to size one child differently from its task's own size (Machine sizes).

Call a task#

callTask starts a child run and returns its output.

A child that fails, after its own retries, fails the workflow too: the error reaches the run as child <id> failed: .... Cancelling a child the workflow is waiting on fails the workflow the same way. To handle a failed child in the workflow instead, wait for it with triggerAndWait.

Sleep#

ctx.sleep waits for a duration. The deadline is stored when the step starts, so a replay keeps the original deadline instead of starting the wait over.

Wait for an event#

ctx.waitEvent waits for an event with a name, sent to this run. It resolves to one of two shapes:

JSON
{"timed_out": false, "payload": {"plan": "pro"}}{"timed_out": true, "payload": null}

The default timeout is 60 seconds, so pass the one you mean. An event sent before the workflow asks for it is kept, and the wait takes it at once. With several events of one name, each wait takes the oldest unclaimed one. Send events shows how to send one.

Wait for children#

ctx.triggerAndWait starts one child run and waits for it. ctx.batchTriggerAndWait starts up to 1,000 at once and waits for all of them. They have Trigger.dev's names and result shapes.

Unlike callTask, they never fail the workflow for a failed child. Each child comes back as a result for the workflow to check.

// A workflow that waits on child runs: one thumbnail per image, then a page.export async function thumbnails({albumId, imageIds}, ctx) {  const made = [];  const failed = [];   // A batch starts 1 to 100 children, so a longer list goes in chunks.  for (let start = 0; start < imageIds.length; start += 100) {    const chunk = imageIds.slice(start, start + 100);    const {runs} = await ctx.batchTriggerAndWait(      'image.thumbnail',      chunk.map((imageId) => ({payload: {imageId}})),      {key: `thumbnails-${start / 100}`},    );    // A failed child is a result, not an exception.    for (const run of runs) {      if (run.ok) made.push(run.output.url);      else failed.push({id: run.id, error: run.error.message});    }  }   // One more child. unwrap() returns its output, or throws if it failed.  const page = await ctx.triggerAndWait('album.publish', {albumId, thumbnails: made}, {    key: 'publish',    machine: 'small-2x',  }).unwrap();   return {made: made.length, failed, page};}

While a workflow waits for its children, it holds no worker and no queue slot. The children run like any other runs, as many at once as your workers and queue limits allow.

Results#

Each child comes back in one of two shapes:

JSON
{"ok": true, "id": "0b9a7c1e-5d3f-4e2a-9c8b-7a6f5e4d3c2b", "taskIdentifier": "image.thumbnail", "output": {"url": "t/img-0.png"}}{"ok": false, "id": "4c2e8f6a-1b3d-4f5e-8a7c-9d0e1f2a3b4c", "taskIdentifier": "image.thumbnail", "error": {"name": "RunFailedError", "message": "corrupt image"}}
  • A failed child has a RunFailedError, whose message is the child's error. It is recorded when the child fails for good, once its own max_attempts are used or at once on AbortTaskRunError, not at a failure it retries.
  • A cancelled child has a RunCancelledError.
  • unwrap() returns a completed child's output, and throws SubtaskUnwrapError for any other. The error has taskId, runId and cause, the result's error (Python: task_id, run_id and cause). Left uncaught, it fails the attempt like any other error.

In Node, call unwrap() on the result, or on the promise as the example does. In Python, a result is a dict with the properties ok, id, task_identifier, output and error, and unwrap().

batchTriggerAndWait returns {runs}: one result per item, in the order of the items. The step ends when the last child finishes.

Batches#

Each item is {payload, options}, and options is optional. It takes machine and concurrencyKey (Python: concurrency_key) for that one child, and key and scope (see One child for the environment).

  • 1 to 1,000 items. A longer list throws before anything starts. Split it into chunks, each a step with its own key, as the example does.
  • Inputs up to 10 MiB together. Each item's payload is at most 3 MiB of JSON, and a batch's payloads at most 10 MiB together. A batch over either fails the attempt before any child starts.
  • All or none. The children start together, in one transaction. If one cannot start, for example because its task is not in the deployment, none does, and the attempt fails with the reason.
  • One task per batch. To wait on children of several tasks, run one batch per task, one after another.
  • Counted in the run tree. Each child counts toward the tree's limit of 10,000 triggered and batched runs by default. A batch that would pass it starts nothing, and the attempt fails with the reason. A batch of 1,000 uses a tenth of it.

One child for the environment#

By default each wait starts its own child. Pass scope: 'environment' with a key (Python: scope="environment"), and the key names one child of the task across every run in the environment, as a key from Trigger.dev's idempotencyKeys.create does. One key used for two tasks starts two children. The first workflow that waits with the key starts the child. Every other workflow that waits with it waits on that same child, while it runs or after it finished, and gets the same result. The child runs once.

JavaScript
const report = await ctx.triggerAndWait('report.build', {day}, {key: `report:${day}`, scope: 'environment'});

In a batch, give the item a key and the scope in its options. A child that ctx.trigger started with the key in that scope counts too.

  • The key must ask for the same child. If the key already started a child of the task with another machine, input or concurrency key, the attempt fails with the reason. To start a new child, use another key. Two items of one batch with one key must match each other too. Then they share one child. A retry from failure is the exception for a child its failed run, or an earlier retry of it, started: it takes that child whatever its input. So is the child a wait started: when that wait runs again on the workflow's next attempt, it takes its child whatever its input, such as data it read again.
  • Only new children count. A child that already exists takes no room in the run tree's limit and needs no worker.
  • A finished child stays finished. A later wait with the key gets its result, failed or not. Wait with a new key to run it again, or retry the workflow from failure.
  • The child belongs to the first workflow. Cancelling that workflow cancels the child, and every other workflow waiting on it gets a RunCancelledError result.
  • It needs a key of your own. Without one the SDK throws. A default key like call:0 names a position, which would join unrelated workflows to one child.
  • It needs a current control plane and agent. With an older one the wait throws and names the upgrade. It never starts a child of its own instead.

In the Trigger.dev dialect, a made key of 64 characters waits in the environment's scope. A batch's items get keys made in the run's scope from the batch key and their index, as Trigger.dev makes them, so the same batch key in another workflow starts that workflow's own children.

Code before a wait runs again#

The attempt ends at the wait. When the children finish, the run replays from the top, so the code before the wait runs again, as it does before any step.

A replay checks a wait for children against history. What happens when its input or items changed depends on its key:

  • With its default key (call:0, batch:1), the wait replays only unchanged. A changed input or list fails the attempt with a nondeterminism error that names the step and says to pass an explicit key. A default key names only a position. In a loop over ["A", "B"] that reads ["B", "A"] on replay, it would hand A's result to B.
  • With an explicit key, the recorded results stand. No child starts again, and the workflow carries on with them. The result says so: drifted is true, and a batch's result also has items, the items its runs were started for, in the same order. The run records a replay.drift event for that step, once, naming what changed. durable-compute watch prints it.

A different task or key is Nondeterminism at command N either way.

Pass an explicit key per call in loops, and per batch over data that can change between attempts. A list from outside, such as a database query, can change: a replay may read rows the first attempt did not see, or read them in another order. If your code pairs runs with its own list, check drifted and pair them with items instead. To start children for new rows, give them a new step with a new key. To keep a list from changing between replays, read it in a child task: its output is recorded.

JavaScript
for (const org of orgs) {  const result = await ctx.triggerAndWait('org.sync', {org}, {key: `sync:${org}`});} const {runs, drifted, items} = await ctx.batchTriggerAndWait('org.sync', orgs.map(org => ({payload: {org}})), {key: 'sync-all'});const synced = (drifted ? items.map(item => item.payload.org) : orgs).filter((org, i) => runs[i].ok);

In Python, result.drifted is a property, and a drifted batch's return has the keys "drifted" and "items".

Cancel and retry#

  • Cancelling the workflow cancels every child it waits on, running or queued, and every run below them, except the hook runs that run their lifecycle hooks.
  • Cancelling one child gives it a RunCancelledError result. The rest of its batch keeps going.
  • Children retry on their own. A failing child retries up to its task's max_attempts before its result is recorded.
  • A retried workflow keeps its results. If the workflow's attempt fails after a wait, the retry replays the recorded results. No child runs twice.

In a plain task#

In a Node task that is not a workflow, ctx.triggerAndWait and ctx.batchTriggerAndWait hold the task until its children finish. This is a held wait, as on self-hosted Trigger.dev. The task's process keeps running and the wait returns where it was called, so the code before it runs once. The results have the same shape as in a workflow. ctx.callTask, ctx.sleep and ctx.waitEvent stay workflow steps.

  • A held task gives back its slots. While it waits, its slot on the machine, its queue's and its project's are free for its children. When the children finish, it continues once its queue and project have room, ahead of the runs queued behind it.
  • It keeps its process and its memory. So a machine holds only a few waiting tasks of one project at a time. Past that it starts only the children they wait on, until waits end.
  • Held time is not run time. It does not count toward the task's timeout_ms. A task may be held for at most 24 hours in all. Past that its attempt stops and is not retried, and its children keep running.
  • One wait at a time. A second wait while one is held, such as Promise.all around two waits, throws. Wait on many children at once with ctx.batchTriggerAndWait, which takes 0 to 1,000 items here.
  • A crash starts over. If the task's process dies while it waits, its next attempt runs from the top. A child started with a key is not started again: the retry waits on that child. Without a key, the retry starts new children.
  • Cancelling the task cancels its children.

In Python, a wait in a plain task throws, and the error says to declare the task with "kind": "workflow". So does a wait in a lifecycle hook. On a private worker whose agent is older than held waits, a Node wait throws too, and the error names the upgrade. A task deploy finds in build.dirs becomes a workflow when the manifest names it in build.workflows. A workflow's attempt ends at the wait and frees its machine. To start a child without waiting for it, use ctx.trigger in any task.

In a workflow, ctx.triggerAndWait and ctx.batchTriggerAndWait end the attempt by throwing. So a catch around one runs in each attempt that stops there, and a finally around one runs in every attempt that reaches it. The Trigger.dev style triggerAndWait and batchTriggerAndWait from @bokjoy/sdk/trigger end the attempt without throwing. Their catch never runs for the wait, and a finally around one runs only in the attempts that get past it. See Waiting on child runs.

callTask or triggerAndWait#

callTasktriggerAndWait
ReturnsThe child's outputThe child's result. unwrap() gives the output.
A failed or cancelled childFails the workflowReturns ok: false. The workflow carries on.
Replayed with a changed inputNondeterminism at command NWith an explicit key, the recorded result stands, marked drifted. With its default key, a nondeterminism error.
Concurrency keyNoneconcurrencyKey

Keys#

Each step has a key. Without one, the SDK makes <type>:<index>, such as call:0, batch:1 or wait_event:2. A replay compares every step it takes, its key included, with what was recorded at that position.

Give your steps explicit keys, as the examples do. A key names what a step means, and it makes a mismatch after a code change obvious in the run's history. A wait for children needs one to replay with a changed input (Code before a wait runs again).

Rules for replay#

A workflow must take the same steps, in the same order, every time it replays. If a replay takes a different step where history has a recorded one, the run fails with Nondeterminism at command N at once, without using its other attempts: they would replay the same code. The same goes for a workflow that returns before reaching every recorded step. Bok Joy never guesses which step you meant.

  • Do side effects in tasks. Send email, charge cards and write to databases in child tasks. Code between steps runs again on every replay.
  • Keep time and randomness out of decisions. Date.now(), Math.random() and random.random() change between replays. Compute them in a task and use its recorded result.
  • One step at a time. Await each step before the next. Running two at once, for example with Promise.all or asyncio.gather, fails with Parallel durable operations are not supported. To wait on many children at once, start them in one batch.
  • Deploys do not reach running workflows. A run keeps its deployment, so new code applies to new runs only. To apply a fix to a workflow that failed, retry it from failure.

Retry from failure#

When a workflow fails, fix the cause, deploy, and retry it from failure. A new run starts with the same payload on the environment's current deployment, linked to the failed run. It reuses the steps that succeeded before the failure and runs the rest:

  • Every step before the first failure is reused. A completed call, a sleep that passed, an event that arrived and a batch whose children all came back ok keep their recorded results. Nothing in them runs again.
  • The step that failed runs again. A failed call starts a new child, and a wait that timed out waits again.
  • A batch keeps the children that came back ok. Only the items whose child failed or was cancelled start new children. Each item is compared on its own: an unchanged item at the same position keeps its result. The step's result has every item's result, in item order.
  • A key finds what the failed run started. A key in the environment's scope names the same child in the retry as in the failed run. If that child succeeded, or is still running, the retry takes it as it is, even when the fix changed the step's input, as Trigger.dev returns a key's run whatever the payload. To run it again, use another key. This holds for a child the failed run started, or an earlier retry of it. A child that another workflow started, or that the retry started itself, needs the same input as always, and with another input the step fails with an error that says to use another key.
  • A shared child that failed runs again for a wait. Where a step waits with a key in the environment's scope that names a child that failed or was cancelled, the retry starts a new child in its place, with the input the retry passes. Retries of several workflows that waited on it share that one new child. The shared child stays as it was, so other workflows that wait with its key still get its result.
  • A trigger that does not wait never runs a failed child again. It takes the child its key names as it is, in a retry as outside one, so the ID it returns is always that child's. To run it again, trigger with a new key.
  • A trigger names the failed run's child. ctx.trigger in the run's own scope makes its child's ID from the first run's ID and the key. So a trigger the failed run sent before it failed starts nothing again: the retry takes that child as it is, whatever its input, and gets its ID back. A key that names a child of another task is refused, as always. Without a key, the nth trigger of a task uses trigger:<task>:<n>, so a fix that adds a trigger of another task shifts nothing. A fix that adds a trigger of the same task before its others shifts that task's later triggers. The added trigger then takes the first one's child, and the run records a trigger.reused event that names the key. Give a trigger that must happen once a key of its own.
  • Every step after the failed one runs again. Even one that is the same as the failed run's: the step that failed may return something else this time, so a result recorded after it could be out of date.
  • The failed run is unchanged. Its page lists its retries, and the new run links back to it.
  • The retry runs its own lifecycle hooks. The failed run's onFailure ran when it failed, and does not run again.

The new run replays from the top like any workflow, so the code between steps runs again. The steps before the failure are its history. If the fixed code takes one of them differently, with another input for example, or no longer takes it, the retry runs that step and every later one itself instead of reusing them. A fix can change any step. This needs the fix deployed with the sdk folder from this release: with an older copy, a step the fix changed fails the retry with Nondeterminism at command N, and every trigger the failed run sent starts again. A run of a deployment made before this release triggered with the old default keys, trigger:<n>. A retry of it on a new deployment matches none of them, so its triggers without a key start again. Triggers with a key of your own keep their children.

The retry is a new run with an ID of its own, so a key you build from the run's ID changes. ctx.firstRunId (Python: ctx.first_run_id) names the failed run instead, and for a retry of a retry the first run of the chain. In any other run it is the run's own ID. Build keys from it to keep them in a retry. A key from idempotencyKeys.create with its default scope, 'run', is already made from it, so a step the failed run took with such a key replays unchanged and nothing it started starts again. A key made with the scope 'attempt' is the retry's own. On a worker whose agent is too old to pass the first run on, a workflow that reads ctx.firstRunId, makes a 'run' key or triggers in its own scope throws an error that says to rebuild the worker. The SDK never uses the retry's own ID in its place, which would start the failed run's children again. A plain task is never a retry, so there it uses the run's own ID. In Python the error is FirstRunMissingError, an AttributeError, so hasattr(ctx, "first_run_id") is false.

Retry from failure in the console, from a failed workflow run's page (next to Replay run, which starts from scratch) or for many runs on Bulk actions. Once a run has a retry, its page links to the retry instead, and Bulk actions leaves it out, so the console starts one retry per failed run. A cancelled retry does not count: the run can be retried again, and its page says that its last retry was cancelled. If someone retried the run after the page loaded, the click starts nothing: the page refreshes and says why. Bulk actions does the same for each run. From code, call runs.retryFromFailure. From a terminal, run durable-compute retry-from-failure RUN_ID.

Only a failed workflow run can be retried from failure. A plain task has no steps, so replay it instead. When the reused steps would no longer fit in the 16 MiB an attempt receives next to the input and the environment's current variables, the retry is refused and nothing starts.

Limits#

  • A workflow records at most 1,024 steps. The next one fails the attempt with workflow history limit exceeded. A batch is one step, however many children it starts.
  • A batch starts 1 to 1,000 children of one task. Their inputs are at most 10 MiB of JSON together.
  • Sleeps and event waits last at most 7 days (604,800,000 ms).
  • A child's input is at most 3 MiB of JSON, as any payload, and its output at most 10 MiB.
  • A workflow's recorded steps hold at most 256 MiB of JSON in all. A step whose command would pass it fails the attempt before any child starts. A result that would pass it fails the workflow at once. Both errors name the step. Every replay reads every recorded step again, so keep large data out of steps where you can.
  • An attempt receives the workflow's input, its environment variables and every recorded step in at most 16 MiB. A step's inputs and results over 512 KiB are stored out of line, and so are the largest of the rest once the recorded steps pass 1 MiB. They follow it one at a time, as the replay reaches them, and do not count. A step whose command would not fit with the rest fails the attempt before any child starts. A result that would not fit fails the workflow at once. Both errors name the step.
  • Strings in a step's input, such as a batch item's payload, cannot hold the NUL character (\u0000). The SDK throws before the step starts, naming the method.
  • The task's timeout_ms applies to each attempt: the code between steps, not the time spent waiting.

Limits lists every number.