@workflow/core 5.0.0-beta.15 → 5.0.0-beta.17

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.
@@ -1,23 +1,27 @@
1
1
  ---
2
2
  title: Idempotency
3
- description: Ensure operations can be safely retried without producing duplicate side effects.
3
+ description: Make step retries safe and coordinate duplicate workflow starts with hook tokens.
4
4
  type: conceptual
5
- summary: Prevent duplicate side effects when retrying operations in steps.
5
+ summary: Use step IDs for retry-safe external calls, and route duplicate workflow-start requests through deterministic hook tokens.
6
6
  prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
9
9
  - /docs/foundations/errors-and-retries
10
+ - /docs/foundations/starting-workflows
11
+ - /docs/foundations/hooks
10
12
  ---
11
13
 
12
- Idempotency is a property of an operation that ensures it can be safely retried without producing duplicate side effects.
14
+ Idempotency is a property of an operation that ensures repeated attempts have the same effect as a single attempt.
15
+
16
+ In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency coordinates duplicate requests that try to start the same workflow.
17
+
18
+ ## Step Idempotency
13
19
 
14
20
  In distributed systems (calling external APIs), it is not always possible to ensure an operation has only been performed once just by seeing if it succeeds.
15
21
  Consider a payment API that charges the user $10, but due to network failures, the confirmation response is lost. When the step retries (because the previous attempt was considered a failure), it will charge the user again.
16
22
 
17
23
  To prevent this, many external APIs support idempotency keys. An idempotency key is a unique identifier for an operation that can be used to deduplicate requests.
18
24
 
19
- ## The core pattern: use the step ID as your idempotency key
20
-
21
25
  Every step invocation has a stable `stepId` that stays the same across retries.
22
26
  Use it as the idempotency key when calling third-party APIs.
23
27
 
@@ -27,7 +31,7 @@ import { getStepMetadata } from "workflow";
27
31
  async function chargeUser(userId: string, amount: number) {
28
32
  "use step";
29
33
 
30
- const { stepId } = getStepMetadata();
34
+ const { stepId } = getStepMetadata(); // [!code highlight]
31
35
 
32
36
  // Example: Stripe-style idempotency key
33
37
  // This guarantees only one charge is created even if the step retries
@@ -49,14 +53,235 @@ Why this works:
49
53
  - **Stable across retries**: `stepId` does not change between attempts.
50
54
  - **Globally unique per step**: Fulfills the uniqueness requirement for an idempotency key.
51
55
 
52
- ## Best practices
56
+ ## Run idempotency
57
+
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
+
60
+ Because [hooks](/docs/foundations/hooks) already ensure globally unique active tokens, Workflow can use the same mechanism to coordinate duplicate requests while a run is active.
61
+
62
+ Use a hook token as the idempotency key for an active workflow run. Hook tokens are globally unique while they are active: if another run tries to create a hook with the same token, the runtime records a conflict, `hook.getConflict()` resolves with a `Run` handle for the run that owns the token, and the hook rejects with [`HookConflictError`](/docs/errors/hook-conflict) when the workflow awaits or iterates its payload.
63
+
64
+ The token should come from your domain, such as an order ID, invoice ID, import ID, or request ID. Create the hook near the beginning of the workflow and check `await hook.getConflict()` before doing duplicate-sensitive work that depends on owning the active token. Calling `createHook()` alone does not register the hook — awaiting `getConflict()` suspends the workflow to commit the registration.
65
+
66
+ ```typescript lineNumbers
67
+ import { createHook } from "workflow";
68
+
69
+ type OrderRequest = { confirmed: boolean };
70
+ type OrderResult =
71
+ | { status: "processed" | "cancelled" }
72
+ | { status: "duplicate"; runId: string };
73
+ declare function chargeOrder(orderId: string): Promise<void>; // @setup
74
+
75
+ export async function processOrder(orderId: string): Promise<OrderResult> {
76
+ "use workflow";
77
+
78
+ using request = createHook<OrderRequest>({ // [!code highlight]
79
+ token: `order:${orderId}`, // [!code highlight]
80
+ }); // [!code highlight]
81
+
82
+ const conflict = await request.getConflict(); // [!code highlight]
83
+ if (conflict) { // [!code highlight]
84
+ // Another active run already owns this order's token. // [!code highlight]
85
+ return { status: "duplicate" as const, runId: conflict.runId }; // [!code highlight]
86
+ } // [!code highlight]
87
+
88
+ const { confirmed } = await request;
89
+
90
+ if (!confirmed) {
91
+ return { status: "cancelled" as const };
92
+ }
93
+
94
+ await chargeOrder(orderId);
95
+ return { status: "processed" as const };
96
+ }
97
+ ```
98
+
99
+ The runtime creates the hook atomically. At most one active hook can own `order:${orderId}`, so duplicate workflow runs converge on one active owner. A duplicate run observes `getConflict()` resolving with the owner's `Run` and returns before it reaches `chargeOrder()`. The conflicting run's accessors (`status`, `returnValue`, `cancel()`, …) are durable steps, so the duplicate run can do more than report the owner — see [conflict-handling strategies](#conflict-handling-strategies) below.
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
+ ```
147
+
148
+ <Callout type="warn">
149
+ This avoids creating a new run only after the first run has registered its hook. Because `start()` returns before the run body executes and calls `createHook()`, two concurrent requests can both observe "no hook yet" and each call `start()`. The race is resolved inside the workflow body, where the losing run observes `getConflict()` resolving with the active owner and returns without doing duplicate-sensitive work — and the route detects it by comparing the resumed hook's `runId` against the run it just started, without waiting for either run to finish. A native API for atomically starting a run and registering a hook is in the works. Until then, model recovery inside the workflow by checking `hook.getConflict()`.
150
+ </Callout>
151
+
152
+ This is active-run coordination. When the workflow completes and disposes the hook, the token can be used again. If a duplicate request after completion must return the original result instead of starting fresh work, persist that completed result under the same domain key.
153
+
154
+ ### Conflict-handling strategies
155
+
156
+ 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
+
158
+ The example above implements **reject the duplicate**: return the owner's `runId` and let the caller decide. Other common strategies:
159
+
160
+ **Adopt the owner's result.** Wait for the active run to finish and return its result, so callers cannot tell which run did the work:
161
+
162
+ ```typescript lineNumbers
163
+ import { createHook } from "workflow";
164
+
165
+ type OrderRequest = { confirmed: boolean };
166
+ declare function processOwnedOrder(orderId: string): Promise<{ status: string }>; // @setup
167
+
168
+ export async function processOrder(orderId: string) {
169
+ "use workflow";
170
+
171
+ using request = createHook<OrderRequest>({
172
+ token: `order:${orderId}`,
173
+ });
174
+
175
+ const conflict = await request.getConflict();
176
+ if (conflict) {
177
+ // Callers get the same result regardless of which run did the work.
178
+ return await conflict.returnValue; // [!code highlight]
179
+ }
180
+
181
+ return await processOwnedOrder(orderId);
182
+ }
183
+ ```
184
+
185
+ **Inspect the owner before deciding.** Branch on the owner's live state:
186
+
187
+ ```typescript lineNumbers
188
+ import { createHook } from "workflow";
189
+
190
+ type OrderRequest = { confirmed: boolean };
191
+ declare function processOwnedOrder(orderId: string): Promise<{ status: string }>; // @setup
192
+
193
+ export async function processOrder(orderId: string) {
194
+ "use workflow";
195
+
196
+ using request = createHook<OrderRequest>({
197
+ token: `order:${orderId}`,
198
+ });
199
+
200
+ const conflict = await request.getConflict();
201
+ if (conflict) {
202
+ const status = await conflict.status; // [!code highlight]
203
+ if (status === "running") {
204
+ return { status: "duplicate" as const, runId: conflict.runId };
205
+ }
206
+ // Owner already reached a terminal state; its hook will be released.
207
+ }
208
+
209
+ return await processOwnedOrder(orderId);
210
+ }
211
+ ```
212
+
213
+ **Signal the owner instead of doing the work.** The duplicate run knows the token, so it can deliver this run's input to the owner's hook from a step:
214
+
215
+ ```typescript lineNumbers
216
+ import { createHook } from "workflow";
217
+ import { resumeHook } from "workflow/api";
218
+
219
+ type OrderRequest = { confirmed: boolean };
220
+
221
+ async function forwardToOwner(token: string, payload: OrderRequest) {
222
+ "use step";
223
+ await resumeHook(token, payload); // [!code highlight]
224
+ }
225
+
226
+ export async function processOrder(orderId: string, confirmed: boolean) {
227
+ "use workflow";
228
+
229
+ const token = `order:${orderId}`;
230
+ using request = createHook<OrderRequest>({ token });
231
+
232
+ const conflict = await request.getConflict();
233
+ if (conflict) {
234
+ await forwardToOwner(token, { confirmed }); // [!code highlight]
235
+ return { status: "forwarded" as const, runId: conflict.runId };
236
+ }
237
+
238
+ // ... own the token and do the work
239
+ }
240
+ ```
241
+
242
+ **Supersede the owner.** Newest-wins: cancel the active run, then claim the released token. Cancellation disposes the owner's hooks; the retry loop covers the window where that disposal has not propagated yet:
243
+
244
+ ```typescript lineNumbers
245
+ import { createHook } from "workflow";
246
+
247
+ type OrderRequest = { confirmed: boolean };
248
+ declare function chargeOrder(orderId: string): Promise<void>; // @setup
249
+
250
+ export async function processOrderNewestWins(orderId: string) {
251
+ "use workflow";
252
+
253
+ const token = `order:${orderId}`;
254
+
255
+ for (let attempt = 0; attempt < 3; attempt++) {
256
+ using request = createHook<OrderRequest>({ token });
257
+
258
+ const conflict = await request.getConflict();
259
+ if (!conflict) {
260
+ // Token claimed — this run is now the owner.
261
+ const { confirmed } = await request;
262
+ if (confirmed) {
263
+ await chargeOrder(orderId);
264
+ }
265
+ return { status: "processed" as const };
266
+ }
267
+
268
+ await conflict.cancel(); // [!code highlight]
269
+ }
270
+
271
+ throw new Error(`Could not claim ${token} after cancelling the owner`);
272
+ }
273
+ ```
274
+
275
+ If duplicate requests should only reuse the active run without sending data, use [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) as an advisory pre-check before calling `start()`. The workflow should still check `hook.getConflict()`, because the lookup and `start()` are not atomic.
53
276
 
54
- - **Always provide idempotency keys to external side effects that are not idempotent** inside steps (payments, emails, SMS, queues).
55
- - **Prefer `stepId` as your key**; it is stable across retries and unique per step.
56
- - **Keep keys deterministic**; avoid including timestamps or attempt counters.
57
- - **Handle 409/conflict responses** gracefully; treat them as success if the prior attempt completed.
277
+ 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.
58
278
 
59
279
  ## Related docs
60
280
 
61
281
  - Learn about retries in [Errors & Retrying](/docs/foundations/errors-and-retries)
62
282
  - API reference: [`getStepMetadata`](/docs/api-reference/workflow/get-step-metadata)
283
+ - API reference: [`createHook()`](/docs/api-reference/workflow/create-hook)
284
+ - API reference: [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token)
285
+ - API reference: [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook)
286
+ - API reference: [`start()`](/docs/api-reference/workflow-api/start)
287
+ - Learn about deterministic hook tokens in [Hooks](/docs/foundations/hooks)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workflow/core",
3
- "version": "5.0.0-beta.15",
3
+ "version": "5.0.0-beta.17",
4
4
  "description": "Core runtime and engine for Workflow SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -89,15 +89,18 @@
89
89
  "semver": "7.7.4",
90
90
  "ulid": "~3.0.1",
91
91
  "zod": "4.3.6",
92
- "@workflow/errors": "5.0.0-beta.7",
92
+ "@workflow/errors": "5.0.0-beta.8",
93
93
  "@workflow/serde": "5.0.0-beta.2",
94
- "@workflow/utils": "5.0.0-beta.3",
95
- "@workflow/world": "5.0.0-beta.9",
96
- "@workflow/world-local": "5.0.0-beta.16",
97
- "@workflow/world-vercel": "5.0.0-beta.14"
94
+ "@workflow/utils": "5.0.0-beta.4",
95
+ "@workflow/world": "5.0.0-beta.10",
96
+ "@workflow/world-local": "5.0.0-beta.18",
97
+ "@workflow/world-vercel": "5.0.0-beta.16"
98
98
  },
99
99
  "devDependencies": {
100
100
  "@opentelemetry/api": "1.9.0",
101
+ "@opentelemetry/context-async-hooks": "1.30.1",
102
+ "@opentelemetry/core": "1.30.1",
103
+ "@opentelemetry/sdk-trace-base": "1.30.1",
101
104
  "@types/debug": "4.1.12",
102
105
  "@types/node": "22.19.0",
103
106
  "@types/seedrandom": "3.0.8",