workflow 5.2.3 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +1 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +1 -1
- package/dist/internal/errors.d.ts +1 -1
- package/dist/internal/errors.d.ts.map +1 -1
- package/dist/internal/errors.js +2 -2
- package/docs/api-reference/workflow/create-hook.mdx +8 -0
- package/docs/api-reference/workflow/fetch.mdx +6 -0
- package/docs/api-reference/workflow-api/get-hook-by-token.mdx +5 -1
- package/docs/api-reference/workflow-api/get-run.mdx +4 -0
- package/docs/api-reference/workflow-api/resume-hook.mdx +58 -2
- package/docs/api-reference/workflow-api/start.mdx +64 -1
- package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +6 -3
- package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +68 -0
- package/docs/api-reference/workflow-errors/index.mdx +6 -0
- package/docs/api-reference/workflow-errors/meta.json +2 -0
- package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +2 -0
- package/docs/api-reference/workflow-errors/workflow-start-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-world-error.mdx +12 -1
- package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -1
- package/docs/changelog/eager-processing.mdx +2 -0
- package/docs/changelog/index.mdx +1 -0
- package/docs/changelog/lazy-event-creation.md +1 -1
- package/docs/changelog/meta.json +1 -0
- package/docs/changelog/spec-9.mdx +4019 -0
- package/docs/changelog/turbo-mode.md +4 -0
- package/docs/configuration/runtime-tuning.mdx +61 -2
- package/docs/configuration/worlds.mdx +12 -0
- package/docs/cookbook/advanced/child-workflows.mdx +2 -2
- package/docs/cookbook/common-patterns/batching.mdx +3 -1
- package/docs/cookbook/common-patterns/idempotency.mdx +11 -12
- package/docs/errors/fetch-in-workflow.mdx +7 -1
- package/docs/foundations/errors-and-retries.mdx +6 -0
- package/docs/foundations/hooks.mdx +3 -1
- package/docs/foundations/idempotency.mdx +190 -60
- package/docs/how-it-works/event-sourcing.mdx +6 -0
- package/docs/whats-new.mdx +3 -1
- package/docs/worlds/building-a-world.mdx +28 -3
- package/docs/worlds/local.mdx +6 -0
- package/docs/worlds/postgres.mdx +211 -145
- package/docs/worlds/upgrading-to-v5.mdx +7 -1
- package/docs/worlds/vercel.mdx +11 -5
- package/package.json +11 -11
|
@@ -85,3 +85,7 @@ We decided **not** to ship it, for two reasons:
|
|
|
85
85
|
2. **Divergent branches from non-durable results.** Advancing past a step before its result is durable lets the workflow commit to a forward path that a crash-and-redeliver can re-decide differently. A `Promise.race([B, C])` resolved by local timing can pick `B`, run `D(B)`, then crash before `step_completed_B` is durable. The redelivery may re-resolve to `C`, so `D` executed against a winner the durable history never records. The same shape appears for a branch on a non-deterministic step output (`B(v1)` runs, crash, redelivery commits `B(v2)`). Idempotency doesn't cover these because `D(B)`/`D(C)` and `B(v1)`/`B(v2)` are *different* operations, not retries of one. A "run ahead only while at most one result is undurable" gate would contain the race case (a race needs ≥2 concurrent undurable steps) but not the non-deterministic-output case, and that residual hazard plus the re-execution blast radius outweighed the gain.
|
|
86
86
|
|
|
87
87
|
So turbo deliberately stops at forced-optimistic *start* and awaits each `step_completed` before moving on: re-execution after a crash stays deterministic (each step re-runs against the same durable inputs) and bounded (roughly one step, not the whole chain). The idea is recorded here in case a future change (e.g. a determinism signal on steps, or deterministic race resolution) makes run-ahead safe enough to revisit.
|
|
88
|
+
|
|
89
|
+
## Spec 9 runs
|
|
90
|
+
|
|
91
|
+
This page describes turbo on spec 8 runs, the default. The experimental spec 9 runtime has its own turbo path, and runs ahead of durable writes within bounds that address the two reasons above. See [Turbo](/docs/changelog/spec-9#turbo) and [Run-ahead](/docs/changelog/spec-9#run-ahead) on the spec 9 page.
|
|
@@ -168,6 +168,19 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
168
168
|
- Default: `3`
|
|
169
169
|
- Clamp: `1` to `16`
|
|
170
170
|
- Number of newly-created steps one invocation runs inline in parallel before queueing the rest.
|
|
171
|
+
- Steps started beside an awaited hook registration (`hook.getConflict()`) count against the same cap. They are held for the pass that observes the registration and then run inline on it, so the registration still precedes them; only the steps past the cap are queued.
|
|
172
|
+
|
|
173
|
+
### `WORKFLOW_INLINE_EARLY_ADVANCE`
|
|
174
|
+
|
|
175
|
+
- Default: enabled
|
|
176
|
+
- Spec 8 runs on the Node.js VM engine only (not QuickJS, and not spec 9 runs). When one inline step of a parallel batch completes or fails while its siblings are still running, the invocation replays the workflow right away instead of waiting for the slowest sibling. A branch of a `Promise.all` can then start its next step without waiting for the other branches.
|
|
177
|
+
- Steps still running stay owned by the invocation that started them. They count against `WORKFLOW_MAX_INLINE_STEPS`, so fewer new steps run inline while they run. A branch that fans out while its siblings still run queues the steps past the remaining slots as background steps.
|
|
178
|
+
- When the workflow returns or throws while one of its inline steps is still running (for example a `Promise.race` loser), the run completes or fails right away. That step gets only its current attempt: the invocation lets its body finish, and the bundled Worlds record its `step_completed`, `step_failed` or `step_retrying` after the run's terminal event, but a retry is never run, so a step whose attempt fails retryably stays pending. This matches what happens when a `sleep()` or hook wins a race. `run_completed` or `run_failed` is therefore not always the last event of a run. With this setting off, the run waits for the loser and its retries. The `workflow.inline.running_at_terminal` and `workflow.inline.discarded_outcomes` span attributes, and an info log, report these steps.
|
|
179
|
+
- A step that retries, is throttled, or leaves stream writes unflushed waits for its whole batch, as with this setting off.
|
|
180
|
+
- Branches whose steps were queued because the batch exceeded `WORKFLOW_MAX_INLINE_STEPS` still advance only when the last pending step of the batch completes.
|
|
181
|
+
- When the invocation hands the run off (its replay budget or inline window is spent), it waits for every inline step still running first, so branches advance in lockstep at that point, as with this setting off. An info log marks the hand-off.
|
|
182
|
+
- `workflow.inline.early_advances` counts early replays and `workflow.inline.slots_held_back` counts steps queued because running steps held the inline slots.
|
|
183
|
+
- Set `0` or `false` to wait for every inline step of a batch before replaying.
|
|
171
184
|
|
|
172
185
|
### `WORKFLOW_TURBO`
|
|
173
186
|
|
|
@@ -187,7 +200,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
187
200
|
|
|
188
201
|
- Default: enabled
|
|
189
202
|
- Node.js VM engine only. Keeps the suspended workflow VM alive across inline steps within one invocation, so each iteration of the inline loop appends only the newly written events instead of replaying the whole event log in a fresh VM. QuickJS manages its own retained inline loop independently of this setting.
|
|
190
|
-
- A step- or attribute-driven suspension can keep the VM retained even when hooks or waits are open or created at the same boundary. Hook- or wait-only suspensions park the invocation because nothing in the current delivery can advance them, with one exception: when the hook's own create is what the workflow is waiting on (a `hook.getConflict()` awaiter, or a create whose token is already claimed), the invocation resumes the retained VM over the committed `hook_created` or `hook_conflict` instead of re-invoking through the queue. Any replay divergence falls back to a full replay.
|
|
203
|
+
- A step- or attribute-driven suspension can keep the VM retained even when hooks or waits are open or created at the same boundary. Hook- or wait-only suspensions park the invocation because nothing in the current delivery can advance them, with one exception: when the hook's own create is what the workflow is waiting on (a `hook.getConflict()` awaiter, or a create whose token is already claimed), the invocation resumes the retained VM over the committed `hook_created` or `hook_conflict` instead of re-invoking through the queue, and runs the steps started at that same boundary on the pass after it. Any replay divergence falls back to a full replay.
|
|
191
204
|
- Step inputs made of plain data (objects, arrays, primitives) and standard built-ins (`Map`, `Set`, `Date`, `RegExp`, typed arrays, `ArrayBuffer`, `URL`, `Headers`) keep the VM retained. Patching or polyfilling built-in prototypes doesn't change that because serialization never calls them. A boundary falls back to a full replay only when serializing its arguments runs code the workflow controls, such as a getter, a proxy, or a custom class serializer, or computes an `Error`'s stack trace.
|
|
192
205
|
- Set `0` or `false` to replay the Node.js workflow from scratch in a fresh VM on every iteration.
|
|
193
206
|
|
|
@@ -241,7 +254,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
241
254
|
- Set `0` to opt out and always replay the full event log.
|
|
242
255
|
- Like `WORKFLOW_VM`, the policy is stamped into the run's `executionContext` at start, so a run keeps the snapshot policy it started with. Runs started with `WORKFLOW_VM=quickjs` are stamped with this value, or the default when unset. Runs without a stamped policy use the handler's value, or the default. `start()` rejects an invalid value. An invalid value on the workflow handler disables snapshotting with a warning.
|
|
243
256
|
- Runs stamped with `workflowVm: "quickjs"` and a positive threshold are exempt from the default [per-run event limit](/docs/errors/max-events-exceeded) on the Local and Vercel Worlds.
|
|
244
|
-
- A snapshot can only be restored by the exact QuickJS engine build that captured it. On Vercel, runs keep executing on the deployment they started on, so deploys don't affect in-flight snapshots. If your deployment serves in-flight runs from new code (for example, a self-hosted rolling update), an upgrade that changes the embedded engine makes every in-flight run fall back to a full replay at its next resume, all at once, before re-snapshotting at its next qualifying suspension. Plan for that one-time replay load when upgrading.
|
|
257
|
+
- A snapshot can only be restored by the exact QuickJS engine build that captured it. On Vercel, runs keep executing on the deployment they started on, so deploys don't affect in-flight snapshots. If your deployment serves in-flight runs from new code (for example, a self-hosted rolling update), an upgrade that changes the embedded engine or the snapshot format makes every in-flight run fall back to a full replay at its next resume, all at once, before re-snapshotting at its next qualifying suspension. Plan for that one-time replay load when upgrading.
|
|
245
258
|
|
|
246
259
|
What a snapshot contains, and how it is protected:
|
|
247
260
|
|
|
@@ -419,3 +432,49 @@ These variables are primarily for tests, debugging, or unusual deployments.
|
|
|
419
432
|
- Clamp-down only: it never raises the World's limit, and it applies even when the World supplies none. With no World limit and no override, nothing is enforced.
|
|
420
433
|
- The Local and Vercel Worlds both supply a limit; the Local World defaults to 25,000 and is configurable with [`WORKFLOW_MAX_EVENTS`](/docs/configuration/worlds#workflow_max_events). The Vercel World's ceiling is documented under [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits).
|
|
421
434
|
- QuickJS runs with snapshotting are exempt from the World's default limit, but this override still applies to them.
|
|
435
|
+
|
|
436
|
+
## Spec 9 (experimental)
|
|
437
|
+
|
|
438
|
+
Everything above describes spec 8 runs, the default. The experimental spec 9 runtime is opt-in with `WORKFLOW_SPEC_VERSION=9`, reads some of the settings above differently, and adds the settings below. See [Settings and behaviour on spec 9 runs](/docs/changelog/spec-9#settings-and-behaviour-on-spec-9-runs) for each one in full.
|
|
439
|
+
|
|
440
|
+
### `WORKFLOW_SPEC_VERSION`
|
|
441
|
+
|
|
442
|
+
- Default: unset. New runs use spec version 8, or 6 with [`WORKFLOW_SEALED_LOG=0`](#workflow_sealed_log), which this setting takes precedence over.
|
|
443
|
+
- `9` creates spec 9 runs on a World that declares the in-band fence (the Vercel, Local and Postgres Worlds do). `6` to `8` select that version. A run keeps the version it was created with.
|
|
444
|
+
- Upgrade every deployment and process that shares the World before setting it, and do not roll back below this release once spec 9 runs exist. See [Opting in](/docs/changelog/spec-9#opting-in).
|
|
445
|
+
|
|
446
|
+
### `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS`
|
|
447
|
+
|
|
448
|
+
- Default: `2000`
|
|
449
|
+
- Log-tail poll interval of a busy orchestrator while no live event feed covers the run. `0` turns polling off.
|
|
450
|
+
|
|
451
|
+
### `WORKFLOW_ORCHESTRATOR_FEED_POLL_INTERVAL_MS`
|
|
452
|
+
|
|
453
|
+
- Default: `10000`
|
|
454
|
+
- Log-tail poll interval while the World's live event feed is up.
|
|
455
|
+
|
|
456
|
+
### `WORKFLOW_ORCHESTRATOR_LINGER_MS`
|
|
457
|
+
|
|
458
|
+
- Default: `30000`
|
|
459
|
+
- How long an orchestrator with nothing left to run stays live on the event feed while the run waits on an open hook or a background step. `0` turns it off.
|
|
460
|
+
|
|
461
|
+
### `WORKFLOW_ORCHESTRATOR_READ_TIMEOUT_MS`
|
|
462
|
+
|
|
463
|
+
- Default: `5000`
|
|
464
|
+
- Deadline for one incremental read of the event log before the orchestrator sends it again. `0` turns the deadline off.
|
|
465
|
+
|
|
466
|
+
### `WORKFLOW_INLINE_STEP_DEADLINE_MARGIN_MS`
|
|
467
|
+
|
|
468
|
+
- Default: `60000`
|
|
469
|
+
- How long before the inline window ends the orchestrator stops starting inline steps.
|
|
470
|
+
|
|
471
|
+
### `WORKFLOW_OPTIMISTIC_BACKGROUND_START`
|
|
472
|
+
|
|
473
|
+
- Default: unset
|
|
474
|
+
- `1` or `true` starts a background step's body before its `step_started` commits. Use only when background step bodies are idempotent.
|
|
475
|
+
|
|
476
|
+
### `WORKFLOW_RUN_AHEAD_DEPTH`
|
|
477
|
+
|
|
478
|
+
- Default: `10`
|
|
479
|
+
- Clamp: `0` to `16`
|
|
480
|
+
- How many inline step outcomes may be unconfirmed at once while the orchestrator runs ahead of its writes. `0` disables run-ahead.
|
|
@@ -154,6 +154,7 @@ The Postgres World is a self-hosted durable backend for long-running server proc
|
|
|
154
154
|
- Environment variable: `WORKFLOW_POSTGRES_JOB_PREFIX`
|
|
155
155
|
- Default: `workflow_`
|
|
156
156
|
- Prefix for Graphile Worker job names.
|
|
157
|
+
- Use a distinct prefix for each application that shares a database. `start()` re-enqueues only the active runs created under this prefix, plus runs created by earlier versions, which have no prefix. See [`WORKFLOW_POSTGRES_JOB_PREFIX`](/worlds/postgres#workflow_postgres_job_prefix).
|
|
157
158
|
|
|
158
159
|
### `queueConcurrency`
|
|
159
160
|
|
|
@@ -176,6 +177,16 @@ The Postgres World is a self-hosted durable backend for long-running server proc
|
|
|
176
177
|
- Set to `true` only when the application awaits `world.close()` before closing its workflow HTTP server and caller-owned pool.
|
|
177
178
|
- Prevents Graphile Worker's default handler from terminating the process before the application's remaining cleanup finishes.
|
|
178
179
|
|
|
180
|
+
### `jobLockStaleSeconds`
|
|
181
|
+
|
|
182
|
+
- Environment variable: `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`
|
|
183
|
+
- Default: `0` (off)
|
|
184
|
+
- Seconds a running delivery's job lock may go unrenewed before another process releases the job for redelivery. When set, a running delivery renews its lock, so this bounds how long the job of a process that died stays locked.
|
|
185
|
+
- `30` is a good value when more than one process shares the database. Use the same value on every process, and keep it well above the longest a process can block its event loop.
|
|
186
|
+
- `0` leaves recovery to Graphile Worker's fixed 4 hour reset and to restarts.
|
|
187
|
+
- Off by default because of rolling upgrades. A process on an earlier version neither renews its locks nor fences its acknowledgement on the lock holder, so while it shares the database with a process that has this on, its deliveries that run longer than the window are redelivered, and finishing one can delete the redelivered job.
|
|
188
|
+
- To turn it on, set the same value on every process that shares the database once all of them run a version that includes this option. See [Postgres World: `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](/worlds/postgres#workflow_postgres_job_lock_stale_seconds).
|
|
189
|
+
|
|
179
190
|
### `maxPoolSize`
|
|
180
191
|
|
|
181
192
|
- Environment variable: `WORKFLOW_POSTGRES_MAX_POOL_SIZE`
|
|
@@ -253,6 +264,7 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
|
|
|
253
264
|
- CLI flag: none
|
|
254
265
|
- Default: `https://api.vercel.com/v1/workflow`
|
|
255
266
|
- Workflow API proxy URL for external tooling.
|
|
267
|
+
- The Vercel World doesn't follow HTTP redirects, so the URL must answer directly. A `3xx` response fails the request.
|
|
256
268
|
|
|
257
269
|
### `WORKFLOW_SEQUENTIAL_REPLAYS`
|
|
258
270
|
|
|
@@ -21,7 +21,7 @@ Child workflows are the right choice when:
|
|
|
21
21
|
- **You need isolated failure boundaries**: A failing child should not abort unrelated work. The parent decides how to handle failures.
|
|
22
22
|
- **You want large fan-out**: Spawning 50 or 500 children is practical because each runs on its own infrastructure. The parent still pays for each spawn, so start them in chunks rather than all at once (see [Chunked spawning](#fan-out-pattern-chunked-spawning)).
|
|
23
23
|
- **You need per-item observability**: Each child workflow has its own run ID, status, and event log for monitoring.
|
|
24
|
-
- **
|
|
24
|
+
- **You want to bound each run's event log**: Splitting work gives each child a separate event log. On the default runtime, a growing log can add replay overhead and reach the [per-run event limit](/worlds/vercel#per-run-limits). [QuickJS](/docs/configuration/runtime-tuning#workflow_vm) is an alternative for long single runs: it reduces replay overhead and exempts eligible runs from the default event cap. Choose child workflows when separate run histories or failure boundaries also help your application.
|
|
25
25
|
|
|
26
26
|
For simpler cases where steps share a single event log, use [direct await composition](/cookbook/common-patterns/workflow-composition#direct-await-flattening) instead.
|
|
27
27
|
|
|
@@ -307,7 +307,7 @@ async function startAndWaitWithRetries(
|
|
|
307
307
|
- **Export wrapped children at module scope**: The SDK registers `"use workflow"` functions statically, so a runtime higher-order function returned from `withChildCompletionHook()` cannot be passed to `start()`.
|
|
308
308
|
- **Use stable hook keys**: Document IDs, job IDs, or indexes prevent token collisions between parallel children in one parent run.
|
|
309
309
|
- **Use chunked spawning for large batches**: Starting 500 children at once can create a large burst of work. Break the work into chunks of 10–50.
|
|
310
|
-
- **Watch the parent's log too**:
|
|
310
|
+
- **Watch the parent's log too**: The parent records events for spawning and collecting every child. On the default runtime, count those events against the parent's [event limit](/worlds/vercel#per-run-limits) and consider another layer of intermediate runs if needed. QuickJS with snapshotting reduces replay overhead and exempts eligible parent runs from the default event cap, but does not reduce their event count or remove payload and storage limits.
|
|
311
311
|
- **Account for each child's retry semantics**: Steps inside child workflows retry independently. The parent sees the final `{ status, value | error }` payload from the hook.
|
|
312
312
|
- **Use `deploymentId: "latest"` when children should run on the most recent deployment**: See [Versioning](/docs/foundations/versioning) for the full model and the [`start()` API reference](/docs/api-reference/workflow-api/start#using-deploymentid-latest) for compatibility considerations.
|
|
313
313
|
|
|
@@ -99,7 +99,9 @@ async function processRecord(record: Record): Promise<string> {
|
|
|
99
99
|
|
|
100
100
|
- **Use `Promise.allSettled` instead of `Promise.all`**: Use this pattern when you want to continue even if some items fail. `Promise.all` rejects on the first failure, while `allSettled` waits for everything and identifies failures.
|
|
101
101
|
- **Tune batch size to your downstream API limits**: If the API allows 10 concurrent requests, use `batchSize: 10`.
|
|
102
|
-
- **Batching bounds concurrency, not
|
|
102
|
+
- **Batching bounds concurrency, not total event count**: Every record processed in its own step adds events to the same [event log](/docs/how-it-works/event-sourcing#how-fast-a-log-grows), regardless of batch size.
|
|
103
|
+
- **Consider using the QuickJS engine for long-running batches**: [Set `WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to use the experimental QuickJS runtime, which compresses and snapshots the event log and only loads events since the last snapshot on resume. This reduces replay overhead as the log grows and exempts eligible runs from the default [per-run event limit](/worlds/vercel#per-run-limits) ([`MAX_EVENTS_EXCEEDED`](/docs/errors/max-events-exceeded)). It does not reduce event count or speed up the work inside each step.
|
|
104
|
+
- **Choose the retry and run boundaries you need**: Keep one step per record when independent retries and visibility matter. To write fewer events, process multiple records within each step and make the grouped work idempotent, since a retry can repeat the whole group. Use a [child workflow](/cookbook/advanced/child-workflows) per batch when you need separate run histories and failure boundaries.
|
|
103
105
|
- **Add pacing with `sleep()`**: Add a delay between batches to respect rate limits. The sleep is durable and survives cold starts.
|
|
104
106
|
- **Treat each `processRecord` call as an independent step**: If one call fails, it retries up to three times without affecting other items in the batch.
|
|
105
107
|
|
|
@@ -59,30 +59,29 @@ See [Step Idempotency](/docs/foundations/idempotency#step-idempotency) for why `
|
|
|
59
59
|
|
|
60
60
|
## Run idempotency
|
|
61
61
|
|
|
62
|
-
For duplicate workflow-start requests, derive a hook token from your domain key
|
|
62
|
+
For duplicate workflow-start requests, derive a hook token from your domain key and pass it to `start()`. Exactly one run owns the token, and a duplicate start throws `HookConflictError` naming the owner instead of creating a run:
|
|
63
63
|
|
|
64
64
|
```typescript
|
|
65
|
-
import {
|
|
66
|
-
import {
|
|
65
|
+
import { start } from "workflow/api";
|
|
66
|
+
import { HookConflictError } from "workflow/errors";
|
|
67
67
|
import { processOrder } from "./workflows/process-order";
|
|
68
68
|
|
|
69
69
|
export async function POST(request: Request) {
|
|
70
70
|
const { orderId } = await request.json();
|
|
71
|
-
const token = `order:${orderId}`;
|
|
72
71
|
|
|
73
72
|
try {
|
|
74
|
-
const
|
|
75
|
-
|
|
73
|
+
const run = await start(processOrder, [orderId], {
|
|
74
|
+
hook: { token: `order:${orderId}` }, // [!code highlight]
|
|
75
|
+
});
|
|
76
|
+
return Response.json({ runId: run.runId, reused: false });
|
|
76
77
|
} catch (error) {
|
|
77
|
-
if (!
|
|
78
|
+
if (!HookConflictError.is(error)) throw error;
|
|
79
|
+
return Response.json({ runId: error.conflictingRunId, reused: true }); // [!code highlight]
|
|
78
80
|
}
|
|
79
|
-
|
|
80
|
-
const run = await start(processOrder, [orderId]); // [!code highlight]
|
|
81
|
-
return Response.json({ runId: run.runId, reused: false });
|
|
82
81
|
}
|
|
83
82
|
```
|
|
84
83
|
|
|
85
|
-
The
|
|
84
|
+
The run's start Hook can be resumed as soon as `start()` returns, so a duplicate request that carries data can `resumeHook()` the owner on a conflict, and the workflow reads it with `createHook({ token })`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for the full pattern, retention, and World support, and for coordinating inside the workflow with `hook.getConflict()` on Worlds without atomic start Hooks.
|
|
86
85
|
|
|
87
86
|
## Key APIs
|
|
88
87
|
|
|
@@ -92,4 +91,4 @@ The workflow should create the deterministic hook and check `await hook.getConfl
|
|
|
92
91
|
- [`createHook()`](/docs/api-reference/workflow/create-hook): Creates a hook with an optional deterministic token.
|
|
93
92
|
- [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token): Finds the hook that owns a token.
|
|
94
93
|
- [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes the active hook when the duplicate request carries data.
|
|
95
|
-
- [`start()`](/docs/api-reference/workflow-api/start): Starts a new workflow run.
|
|
94
|
+
- [`start()`](/docs/api-reference/workflow-api/start): Starts a new workflow run, at most once per `hook.token`.
|
|
@@ -77,7 +77,7 @@ export async function chatWorkflow(prompt: string) {
|
|
|
77
77
|
This is the most common scenario - using AI SDK functions that make HTTP requests:
|
|
78
78
|
|
|
79
79
|
```typescript lineNumbers
|
|
80
|
-
import { generateText
|
|
80
|
+
import { generateText } from "ai";
|
|
81
81
|
import { fetch } from "workflow"; // [!code highlight]
|
|
82
82
|
|
|
83
83
|
export async function aiWorkflow(userMessage: string) {
|
|
@@ -89,12 +89,18 @@ export async function aiWorkflow(userMessage: string) {
|
|
|
89
89
|
const response = await generateText({
|
|
90
90
|
model: "spacexai/grok-4.6",
|
|
91
91
|
prompt: userMessage,
|
|
92
|
+
maxRetries: 0, // [!code highlight]
|
|
92
93
|
});
|
|
93
94
|
|
|
94
95
|
return response.text;
|
|
95
96
|
}
|
|
96
97
|
```
|
|
97
98
|
|
|
99
|
+
#### AI SDK limitations in workflow functions
|
|
100
|
+
|
|
101
|
+
- **Set `maxRetries: 0`.** When a provider returns a retryable status such as 429 or 5xx, the AI SDK waits with `setTimeout` before it retries, and [timers are not available in workflow functions](/docs/errors/timeout-in-workflow). With the default `maxRetries`, the run fails with a timer error instead of the provider's error. To retry these calls, put the `generateText()` call inside a step function, which the workflow retries on failure.
|
|
102
|
+
- **Streaming is not supported.** `streamText()` and other streaming calls pipe the response through web streams, which are not available in workflow functions. Use [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent), or call `streamText()` inside a step function.
|
|
103
|
+
|
|
98
104
|
### Direct API calls
|
|
99
105
|
|
|
100
106
|
You can also use the fetch step function directly for your own HTTP requests:
|
|
@@ -170,6 +170,8 @@ On Vercel, backend connection failures and interrupted event streams use the exi
|
|
|
170
170
|
|
|
171
171
|
The SDK also replaces its shared events connection pool after repeated HTTP/2 session failures, and retries event-log reads whose HTTP/2 stream the backend resets. An events request that receives no response data for 60 seconds fails and is retried instead of stalling the invocation. Invalid backend URLs, including unsupported protocols and embedded credentials, fail immediately. Fetch requests to blocked ports or with unsupported headers (such as `Expect`) also fail without retrying. Interrupted event writes retain their existing retries; caller cancellations do not trigger another write.
|
|
172
172
|
|
|
173
|
+
Writing to a stream forwarded from another run looks up that run's encryption key first. A transient lookup failure (a connection error, a timeout, an HTTP `429`, or a `5xx`) uses the step's retry policy. Any other lookup failure, such as an HTTP `404` when the owner run no longer exists, fails the step without retrying, with a `EncryptionKeyLookupError` whose `cause` is the original failure.
|
|
174
|
+
|
|
173
175
|
A connection failure does not prove that the backend rejected a write: it may have accepted it before the response was lost. Continue to make step side effects [idempotent](/docs/foundations/idempotency).
|
|
174
176
|
|
|
175
177
|
Failed-run logs include the underlying error causes and their codes, exposing socket, DNS, or TLS errors behind messages such as `TypeError: fetch failed`. If a cause cannot be read, the log includes `[unavailable cause]` and the run can still be recorded as failed.
|
|
@@ -272,3 +274,7 @@ export async function placeOrderSaga(orderId: string) {
|
|
|
272
274
|
}
|
|
273
275
|
}
|
|
274
276
|
```
|
|
277
|
+
|
|
278
|
+
## Spec 9 (experimental)
|
|
279
|
+
|
|
280
|
+
The experimental spec 9 runtime retries steps differently: a failed step is retried after about a second by default on its one queue message, and a `maxRetries = 0` step whose invocation dies after it started fails instead of running again. See [Retries on spec 9 runs](/docs/changelog/spec-9#retries).
|
|
@@ -112,7 +112,9 @@ export async function orderWorkflow(orderId: string) {
|
|
|
112
112
|
}
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
-
Calling `createHook()` on its own does not register the hook; registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies.
|
|
115
|
+
Calling `createHook()` on its own does not register the hook; registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies. A run started with [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) already owns its token: `createHook({ token })` with that token binds to the run's start Hook, and `getConflict()` resolves `null` without suspending.
|
|
116
|
+
|
|
117
|
+
Awaiting the registration costs one write, not a round trip through the queue: the invocation that commits the registration is the one that carries on past the awaiter, and it runs the steps the workflow started beside the awaiter — as in `await Promise.all([hook.getConflict(), prepare()])` — in that same invocation, once the registration is recorded. That covers the steps the invocation runs inline; a fan-out wider than the free inline slots ([`WORKFLOW_MAX_INLINE_STEPS`](/docs/configuration/runtime-tuning#workflow_max_inline_steps), less any inline steps the invocation is still running) queues the rest alongside the hook, so await `hook.getConflict()` before the step when the ordering itself matters. See [`createHook()`](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
|
|
116
118
|
|
|
117
119
|
### Custom tokens for deterministic hooks
|
|
118
120
|
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Idempotency
|
|
3
|
-
description: Make step retries safe and
|
|
3
|
+
description: Make step retries safe, and start a workflow run at most once per key with start({ hook }).
|
|
4
4
|
type: conceptual
|
|
5
|
-
summary: Use step IDs for retry-safe external calls, and
|
|
5
|
+
summary: Use step IDs for retry-safe external calls, and pass a deterministic hook token to start() so a duplicate request is refused or routed to the run that owns it.
|
|
6
6
|
prerequisites:
|
|
7
7
|
- /docs/foundations/workflows-and-steps
|
|
8
8
|
related:
|
|
@@ -13,7 +13,7 @@ related:
|
|
|
13
13
|
|
|
14
14
|
Idempotency is a property of an operation that ensures repeated attempts have the same effect as a single attempt.
|
|
15
15
|
|
|
16
|
-
In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency
|
|
16
|
+
In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency makes duplicate requests start the same workflow run only once.
|
|
17
17
|
|
|
18
18
|
## Step idempotency
|
|
19
19
|
|
|
@@ -57,11 +57,190 @@ Why this works:
|
|
|
57
57
|
|
|
58
58
|
Step idempotency protects side effects **inside** a workflow run. Run idempotency answers a different question: if the same API request is sent twice, should it create one workflow run or two?
|
|
59
59
|
|
|
60
|
-
|
|
60
|
+
Workflow uses a [Hook](/docs/foundations/hooks) token as the idempotency key. Pick a token from your domain, such as an order ID, invoice ID, import ID, or request ID, and pass it to `start()`.
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
### Start a run once per key
|
|
63
63
|
|
|
64
|
-
|
|
64
|
+
```typescript title="app/api/orders/route.ts" lineNumbers
|
|
65
|
+
import { start } from "workflow/api";
|
|
66
|
+
import { HookConflictError } from "workflow/errors";
|
|
67
|
+
import { processOrder } from "./workflows/process-order";
|
|
68
|
+
|
|
69
|
+
export async function POST(request: Request) {
|
|
70
|
+
const { orderId } = await request.json();
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
const run = await start(processOrder, [orderId], {
|
|
74
|
+
hook: { token: `order:${orderId}` }, // [!code highlight]
|
|
75
|
+
});
|
|
76
|
+
return Response.json({ runId: run.runId, duplicate: false });
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (!HookConflictError.is(error)) throw error;
|
|
79
|
+
return Response.json({ runId: error.conflictingRunId, duplicate: true }); // [!code highlight]
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`start({ hook })` admits the run and creates its **start Hook** in one atomic step. Exactly one run owns the token. A duplicate `start()` with the same token throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) with the owner's `conflictingRunId`. The duplicate never becomes a run, and none of its code runs.
|
|
85
|
+
|
|
86
|
+
### Start or route to the owner
|
|
87
|
+
|
|
88
|
+
A duplicate request often carries data the owner should receive, such as a follow-up message in a chat. Since the start Hook exists from the moment the run is admitted, you can resume it right away on a conflict, even before the owner starts executing:
|
|
89
|
+
|
|
90
|
+
```typescript title="app/api/orders/route.ts" lineNumbers
|
|
91
|
+
import { resumeHook, start } from "workflow/api";
|
|
92
|
+
import { HookConflictError, HookNotFoundError } from "workflow/errors";
|
|
93
|
+
import { processOrder } from "./workflows/process-order";
|
|
94
|
+
|
|
95
|
+
export async function POST(request: Request) {
|
|
96
|
+
const { orderId, note } = await request.json();
|
|
97
|
+
const token = `order:${orderId}`;
|
|
98
|
+
|
|
99
|
+
let owner: string | undefined;
|
|
100
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
101
|
+
try {
|
|
102
|
+
const run = await start(processOrder, [orderId, note], { hook: { token } });
|
|
103
|
+
return Response.json({ runId: run.runId, started: true });
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (!HookConflictError.is(error)) throw error;
|
|
106
|
+
owner = error.conflictingRunId;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
const hook = await resumeHook(token, { note }); // [!code highlight]
|
|
111
|
+
return Response.json({ runId: hook.runId, started: false });
|
|
112
|
+
} catch (error) {
|
|
113
|
+
// The owner's Hook is no longer resumable (it ended, or disposed its
|
|
114
|
+
// start Hook): try to start again, which may take the token.
|
|
115
|
+
if (!HookNotFoundError.is(error)) throw error; // [!code highlight]
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Still refused: a finished owner holds the token for its retention, or
|
|
120
|
+
// the owner is a candidate that was admitted but never became a run.
|
|
121
|
+
throw new Error(`Run ${owner} holds ${token}; it can't be started or resumed`);
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Every caller either starts the run, delivers its payload to the owner, or learns which run holds the token. While the owner's start Hook is open, the loop needs at most two calls. A `HookNotFoundError` after a conflict means the owner's Hook is no longer resumable: the owner ended, or [disposed its start Hook](#take-care-with-the-start-hooks-lifecycle). The next `start()` may then take the token, or be refused again: by a finished owner that still holds it for its retention, or by another caller that started first.
|
|
126
|
+
|
|
127
|
+
If the token has a [retention](#keep-the-token-after-the-run-ends), a finished owner keeps refusing new starts until the retention passes, and its Hook can no longer be resumed, so the loop above gives up after its attempts and names that run. Use `getRun(owner)` to tell the caller what the finished run returned.
|
|
128
|
+
|
|
129
|
+
### Receive the payloads in the workflow
|
|
130
|
+
|
|
131
|
+
To read the payloads, call `createHook()` in the workflow with the same token:
|
|
132
|
+
|
|
133
|
+
```typescript title="workflows/process-order.ts" lineNumbers
|
|
134
|
+
import { createHook } from "workflow";
|
|
135
|
+
|
|
136
|
+
type OrderUpdate = { note: string; done?: boolean };
|
|
137
|
+
declare function recordNote(orderId: string, note: string): Promise<void>; // @setup
|
|
138
|
+
|
|
139
|
+
export async function processOrder(orderId: string, note: string) {
|
|
140
|
+
"use workflow";
|
|
141
|
+
|
|
142
|
+
await recordNote(orderId, note);
|
|
143
|
+
|
|
144
|
+
const updates = createHook<OrderUpdate>({ token: `order:${orderId}` }); // [!code highlight]
|
|
145
|
+
for await (const update of updates) {
|
|
146
|
+
await recordNote(orderId, update.note);
|
|
147
|
+
if (update.done) break;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
- `createHook({ token })` with the run's start token returns a handle bound to the start Hook. It doesn't register a new Hook, so it adds no step, and `await hook.getConflict()` resolves `null`.
|
|
153
|
+
- Payloads resumed before the workflow opens the Hook are kept, and are delivered in order once it does.
|
|
154
|
+
- If the workflow never opens it, the token was only an idempotency key. The run completes normally, and unread payloads are simply left unread.
|
|
155
|
+
- `metadata` and `experimental_minRetention` belong on `start({ hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to this `createHook()` throws.
|
|
156
|
+
|
|
157
|
+
### Keep the token after the run ends
|
|
158
|
+
|
|
159
|
+
The start Hook follows the ordinary Hook lifecycle, like a `createHook()` in the run. Without a retention, the token is released when the run ends, and a later `start()` with the token is admitted as a new run.
|
|
160
|
+
|
|
161
|
+
To refuse late duplicates too, set `experimental_minRetention`. It accepts the same duration string, milliseconds, or `Date` as [`createHook({ experimental_minRetention })`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends), and a duration counts from `start()`:
|
|
162
|
+
|
|
163
|
+
```typescript lineNumbers
|
|
164
|
+
import { start } from "workflow/api";
|
|
165
|
+
import { processOrder } from "./workflows/process-order";
|
|
166
|
+
declare const orderId: string; // @setup
|
|
167
|
+
|
|
168
|
+
const run = await start(processOrder, [orderId, ""], {
|
|
169
|
+
hook: {
|
|
170
|
+
token: `order:${orderId}`,
|
|
171
|
+
experimental_minRetention: "30 days", // [!code highlight]
|
|
172
|
+
metadata: { orderId },
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
The run owns the token until it ends, even if the retention passes first. After the run ends, and until the retention passes:
|
|
178
|
+
|
|
179
|
+
- a duplicate `start()` throws `HookConflictError` naming the finished owner;
|
|
180
|
+
- [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) still returns the Hook, with the `start()` metadata;
|
|
181
|
+
- `resumeHook()` throws `HookNotFoundError`, because a finished run can't receive payloads.
|
|
182
|
+
|
|
183
|
+
There is no default retention.
|
|
184
|
+
|
|
185
|
+
Cancelling the owner ends the run, so it releases the token too, once any retention has passed.
|
|
186
|
+
|
|
187
|
+
### Take care with the start Hook's lifecycle
|
|
188
|
+
|
|
189
|
+
<Callout type="warn">
|
|
190
|
+
The run holds its token only while its start Hook does. Disposing the start Hook, with `hook.dispose()` or when a `using` declaration in an inner scope ends, releases the token at once, as it does for any Hook. A later `start()` with the token is then admitted as a new run, even while this one is still running, and `experimental_minRetention` no longer applies: it only holds the token after a run that ends without disposing the Hook.
|
|
191
|
+
</Callout>
|
|
192
|
+
|
|
193
|
+
Open the start Hook with `const`, as in the examples above, and let the run's end release it. After disposing it, the run can call `createHook({ token })` again for a new Hook, but only if no other run has taken the token in the meantime; otherwise `getConflict()` names that run.
|
|
194
|
+
|
|
195
|
+
### Dispose the start Hook with `using`
|
|
196
|
+
|
|
197
|
+
`using` disposes a Hook when its scope ends, which reads well when the workflow only needs the payloads for part of its work:
|
|
198
|
+
|
|
199
|
+
```typescript title="workflows/process-order.ts" lineNumbers
|
|
200
|
+
import { createHook } from "workflow";
|
|
201
|
+
|
|
202
|
+
type OrderUpdate = { note: string; done?: boolean };
|
|
203
|
+
declare function recordNote(orderId: string, note: string): Promise<void>; // @setup
|
|
204
|
+
declare function shipOrder(orderId: string): Promise<void>; // @setup
|
|
205
|
+
|
|
206
|
+
export async function processOrder(orderId: string, note: string) {
|
|
207
|
+
"use workflow";
|
|
208
|
+
|
|
209
|
+
{
|
|
210
|
+
using updates = createHook<OrderUpdate>({ token: `order:${orderId}` }); // [!code highlight]
|
|
211
|
+
for await (const update of updates) {
|
|
212
|
+
await recordNote(orderId, update.note);
|
|
213
|
+
if (update.done) break;
|
|
214
|
+
}
|
|
215
|
+
} // The start Hook is disposed here, and the token is released.
|
|
216
|
+
|
|
217
|
+
await shipOrder(orderId);
|
|
218
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Disposing the start Hook ends the run's idempotency: from the end of that block, another `start()` with the token is admitted while this run ships the order. Use it when that is what you want. To keep duplicates out for the whole run, use `const`. A `using` at the top level of the workflow function disposes the Hook only as the run returns, but with a retention it releases the token then instead of holding it.
|
|
222
|
+
|
|
223
|
+
### When `start()` can't confirm the outcome
|
|
224
|
+
|
|
225
|
+
If `start({ hook })` can't confirm whether its candidate run was queued or admitted, for example because the World timed out, it throws [`WorkflowStartError`](/docs/api-reference/workflow-errors/workflow-start-error) with the candidate's `runId`. The outcome is unknown, not failed. Retrying with the same token is safe: the retry either becomes the owner, or is refused with a `HookConflictError` naming the owner. Inside a workflow, the `start()` step retries it on its own.
|
|
226
|
+
|
|
227
|
+
### World support
|
|
228
|
+
|
|
229
|
+
`start({ hook })` requires a World that supports atomic start Hooks (`capabilities.atomicStartHook`), and Hook retention when you set `experimental_minRetention`. Otherwise `start()` throws before it enqueues anything.
|
|
230
|
+
|
|
231
|
+
| World | Support |
|
|
232
|
+
| --- | --- |
|
|
233
|
+
| [Local World](/worlds/local) | Supported. |
|
|
234
|
+
| [Postgres World](/worlds/postgres) | Opt in with [`WORKFLOW_POSTGRES_EXPERIMENTAL_START_HOOK=1`](/worlds/postgres#workflow_postgres_experimental_start_hook), after applying migration `0028_add_start_hook_admissions` (required for every Postgres World on this version, with or without the flag). Stop workers running a previous version first. |
|
|
235
|
+
| [Vercel World](/worlds/vercel) | Opt in with [`WORKFLOW_VERCEL_EXPERIMENTAL_START_HOOK=1`](/worlds/vercel#workflow_vercel_experimental_start_hook), which needs a backend that supports start Hooks. |
|
|
236
|
+
|
|
237
|
+
See [`start()`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) for the full option reference.
|
|
238
|
+
|
|
239
|
+
### Coordinate inside the workflow
|
|
240
|
+
|
|
241
|
+
On a World without atomic start Hooks, or when a run should decide for itself how to treat a duplicate, coordinate with `createHook()` and `getConflict()` in the workflow instead. Hook tokens are unique while active: if another run already owns the token, `await hook.getConflict()` resolves with a `Run` handle for the owner, and awaiting the hook rejects with [`HookConflictError`](/docs/errors/hook-conflict).
|
|
242
|
+
|
|
243
|
+
Create the hook near the beginning of the workflow, and check `await hook.getConflict()` before calling any step. Awaiting it suspends the workflow to commit the registration; steps called before that suspension start alongside it, so a duplicate run that learns of the conflict later may already have started them. See [Registering a hook before a step uses it](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
|
|
65
244
|
|
|
66
245
|
```typescript lineNumbers
|
|
67
246
|
import { createHook } from "workflow";
|
|
@@ -96,62 +275,15 @@ export async function processOrder(orderId: string): Promise<OrderResult> {
|
|
|
96
275
|
}
|
|
97
276
|
```
|
|
98
277
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
Outside the workflow, try to resume the hook first. If the hook is not registered yet, start the workflow and retry the resume until the new run creates the hook:
|
|
102
|
-
|
|
103
|
-
```typescript lineNumbers
|
|
104
|
-
import { resumeHook, start } from "workflow/api";
|
|
105
|
-
import { HookNotFoundError } from "workflow/errors";
|
|
106
|
-
import { processOrder } from "./workflows/process-order";
|
|
107
|
-
|
|
108
|
-
type OrderRequest = { confirmed: boolean };
|
|
109
|
-
|
|
110
|
-
async function resumeOrder(token: string, payload: OrderRequest) {
|
|
111
|
-
for (let attempt = 0; attempt < 5; attempt++) {
|
|
112
|
-
try {
|
|
113
|
-
return await resumeHook(token, payload); // [!code highlight]
|
|
114
|
-
} catch (error) {
|
|
115
|
-
if (!HookNotFoundError.is(error)) throw error;
|
|
116
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
throw new Error("Order workflow did not register its hook in time");
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export async function POST(request: Request) {
|
|
124
|
-
const { orderId, confirmed } = await request.json();
|
|
125
|
-
const token = `order:${orderId}`;
|
|
126
|
-
const payload = { confirmed };
|
|
127
|
-
|
|
128
|
-
try {
|
|
129
|
-
const hook = await resumeHook(token, payload); // [!code highlight]
|
|
130
|
-
return Response.json({ runId: hook.runId, reused: true });
|
|
131
|
-
} catch (error) {
|
|
132
|
-
if (!HookNotFoundError.is(error)) throw error;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
const run = await start(processOrder, [orderId]); // [!code highlight]
|
|
136
|
-
const resumed = await resumeOrder(token, payload);
|
|
137
|
-
|
|
138
|
-
// A concurrent request's run may have won the race between `start()` // [!code highlight]
|
|
139
|
-
// and hook registration. The resume always reaches the actual active // [!code highlight]
|
|
140
|
-
// owner, so compare run IDs instead of waiting for this run to finish. // [!code highlight]
|
|
141
|
-
return Response.json({ // [!code highlight]
|
|
142
|
-
runId: resumed.runId, // [!code highlight]
|
|
143
|
-
reused: resumed.runId !== run.runId, // [!code highlight]
|
|
144
|
-
}); // [!code highlight]
|
|
145
|
-
}
|
|
146
|
-
```
|
|
278
|
+
Outside the workflow, try `resumeHook()` first, and on `HookNotFoundError` call `start()` and retry the resume until the new run registers its hook.
|
|
147
279
|
|
|
148
280
|
<Callout type="warn">
|
|
149
|
-
|
|
281
|
+
Unlike `start({ hook })`, this doesn't stop a duplicate from becoming a run. Two concurrent requests can both see "no hook yet" and each call `start()`. The losing run is still created, queued, and started, and returns once `getConflict()` resolves with the owner. The route can detect it by comparing the resumed hook's `runId` with the run it started.
|
|
150
282
|
</Callout>
|
|
151
283
|
|
|
152
|
-
|
|
284
|
+
The token becomes available when its workflow ends, unless you set `experimental_minRetention` on `createHook()`. See [`createHook()` minimum retention](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends).
|
|
153
285
|
|
|
154
|
-
|
|
286
|
+
#### Conflict-handling strategies
|
|
155
287
|
|
|
156
288
|
Some workflow systems resolve duplicate IDs with a fixed, pre-declared policy, typically a static choice between rejecting the new execution, deferring to the existing one, or terminating it. Workflow has no policy enum. `hook.getConflict()` hands the duplicate run the conflicting `Run` itself, and the policy is ordinary code, including policies that inspect state before deciding, which static configuration can't express.
|
|
157
289
|
|
|
@@ -302,9 +434,7 @@ export async function processOrderNewestWins(orderId: string) {
|
|
|
302
434
|
|
|
303
435
|
A run started at a Workflow spec version below 8, including runs started by older SDK releases, can't be taken from. In that case the forced Hook rejects with `HookConflictError`, as it would without `experimental_force`.
|
|
304
436
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
Because this pattern uses hooks for idempotency, duplicate requests can also inject additional data and steer the existing run. The route example above uses `resumeHook()` for that: if the hook already exists, the duplicate request resumes the active workflow; if the hook is not registered yet, the route starts the workflow and retries `resumeHook()` so the payload is not dropped.
|
|
437
|
+
[`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) before `start()` is only an advisory pre-check in this pattern: the lookup and `start()` are not atomic, so the workflow should still check `hook.getConflict()`.
|
|
308
438
|
|
|
309
439
|
## Related docs
|
|
310
440
|
|
|
@@ -129,6 +129,8 @@ While a hook is active, its token is reserved and cannot be used by other workfl
|
|
|
129
129
|
|
|
130
130
|
When a workflow ends, its hooks can no longer be resumed. They are normally removed, and their tokens become available again. With `experimental_minRetention`, a hook remains readable, and its token remains unavailable until retention ends. A `hook_disposed` event removes the hook and makes its token available immediately.
|
|
131
131
|
|
|
132
|
+
A hook disposed as the workflow returns or throws, such as one declared with `using` in the workflow function's top-level scope, is released by the run's `run_completed` or `run_failed` event, so the log records no separate `hook_disposed`. Disposing a hook that uses `experimental_minRetention` still records one, because it releases the token before retention ends.
|
|
133
|
+
|
|
132
134
|
See [Hooks and webhooks](/docs/foundations/hooks) for more on how hooks and webhooks work.
|
|
133
135
|
|
|
134
136
|
### Wait lifecycle
|
|
@@ -381,3 +383,7 @@ Step-to-step overhead (STSO) measures the time the runtime adds between two step
|
|
|
381
383
|
<MetricVideo metric="stso" />
|
|
382
384
|
|
|
383
385
|
See [Step-to-step overhead](/docs/performance#step-to-step-overhead-stso) on the Performance page for how it's measured and the latest results.
|
|
386
|
+
|
|
387
|
+
## Spec 9 (experimental)
|
|
388
|
+
|
|
389
|
+
The experimental spec 9 runtime writes the same event types with a different model: one orchestrator per run writes every decision behind an in-band fence, step and wait events are plain appends, and an inline step is created by its first `step_started`. See [The event log on spec 9 runs](/docs/changelog/spec-9#the-event-log).
|