workflow 5.0.0-beta.5 → 5.0.0-beta.50

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.
Files changed (256) hide show
  1. package/README.md +68 -23
  2. package/dist/api-workflow.d.ts +1 -1
  3. package/dist/api-workflow.d.ts.map +1 -1
  4. package/dist/api-workflow.js +1 -1
  5. package/dist/api.d.ts +3 -3
  6. package/dist/api.d.ts.map +1 -1
  7. package/dist/api.js +5 -7
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +6 -1
  11. package/dist/internal/builtins.d.ts +20 -3
  12. package/dist/internal/builtins.d.ts.map +1 -1
  13. package/dist/internal/builtins.js +68 -4
  14. package/dist/internal/errors.d.ts +1 -1
  15. package/dist/internal/errors.d.ts.map +1 -1
  16. package/dist/internal/errors.js +2 -2
  17. package/dist/nest-builder.d.ts +2 -0
  18. package/dist/nest-builder.d.ts.map +1 -0
  19. package/dist/nest-builder.js +2 -0
  20. package/dist/nest-vercel-builder.d.ts +2 -0
  21. package/dist/nest-vercel-builder.d.ts.map +1 -0
  22. package/dist/nest-vercel-builder.js +2 -0
  23. package/dist/observability.d.ts +1 -1
  24. package/dist/observability.js +2 -2
  25. package/dist/runtime.d.ts +2 -1
  26. package/dist/runtime.d.ts.map +1 -1
  27. package/dist/runtime.js +4 -1
  28. package/docs/ai/chat-session-modeling.mdx +29 -26
  29. package/docs/ai/defining-tools.mdx +6 -7
  30. package/docs/ai/human-in-the-loop.mdx +11 -11
  31. package/docs/ai/index.mdx +50 -45
  32. package/docs/ai/message-queueing.mdx +16 -16
  33. package/docs/ai/meta.json +1 -0
  34. package/docs/ai/resumable-streams.mdx +40 -28
  35. package/docs/ai/sleep-and-delays.mdx +10 -10
  36. package/docs/ai/streaming-updates-from-tools.mdx +6 -6
  37. package/docs/api-reference/index.mdx +24 -0
  38. package/docs/api-reference/meta.json +8 -0
  39. package/docs/api-reference/vitest/index.mdx +9 -15
  40. package/docs/api-reference/workflow/create-hook.mdx +89 -10
  41. package/docs/api-reference/workflow/create-webhook.mdx +16 -15
  42. package/docs/api-reference/workflow/define-hook.mdx +35 -33
  43. package/docs/api-reference/workflow/fatal-error.mdx +30 -8
  44. package/docs/api-reference/workflow/fetch.mdx +14 -10
  45. package/docs/api-reference/workflow/get-step-metadata.mdx +2 -2
  46. package/docs/api-reference/workflow/get-workflow-metadata.mdx +3 -3
  47. package/docs/api-reference/workflow/get-writable.mdx +7 -7
  48. package/docs/api-reference/workflow/index.mdx +4 -1
  49. package/docs/api-reference/workflow/retryable-error.mdx +1 -1
  50. package/docs/api-reference/workflow/set-attributes.mdx +61 -0
  51. package/docs/api-reference/workflow/sleep.mdx +4 -4
  52. package/docs/api-reference/workflow-ai/durable-agent.mdx +48 -86
  53. package/docs/api-reference/workflow-ai/index.mdx +3 -3
  54. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +67 -24
  55. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +26 -12
  56. package/docs/api-reference/workflow-api/get-run.mdx +43 -8
  57. package/docs/api-reference/workflow-api/index.mdx +6 -10
  58. package/docs/api-reference/workflow-api/resume-hook.mdx +73 -12
  59. package/docs/api-reference/workflow-api/resume-webhook.mdx +11 -9
  60. package/docs/api-reference/workflow-api/start.mdx +60 -13
  61. package/docs/api-reference/workflow-astro/index.mdx +18 -0
  62. package/docs/api-reference/workflow-astro/meta.json +4 -0
  63. package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
  64. package/docs/api-reference/workflow-errors/entity-conflict-error.mdx +4 -4
  65. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
  66. package/docs/api-reference/workflow-errors/hook-not-found-error.mdx +8 -8
  67. package/docs/api-reference/workflow-errors/index.mdx +88 -0
  68. package/docs/api-reference/workflow-errors/meta.json +6 -0
  69. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +68 -0
  70. package/docs/api-reference/workflow-errors/run-expired-error.mdx +2 -2
  71. package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
  72. package/docs/api-reference/workflow-errors/step-not-registered-error.mdx +5 -5
  73. package/docs/api-reference/workflow-errors/throttle-error.mdx +2 -2
  74. package/docs/api-reference/workflow-errors/too-early-error.mdx +2 -2
  75. package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
  76. package/docs/api-reference/workflow-errors/workflow-not-registered-error.mdx +5 -6
  77. package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +6 -6
  78. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +5 -5
  79. package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
  80. package/docs/api-reference/workflow-errors/workflow-run-not-found-error.mdx +4 -4
  81. package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
  82. package/docs/api-reference/workflow-errors/workflow-world-error.mdx +8 -8
  83. package/docs/api-reference/workflow-globals.mdx +14 -10
  84. package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
  85. package/docs/api-reference/workflow-nest/index.mdx +31 -0
  86. package/docs/api-reference/workflow-nest/meta.json +9 -0
  87. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
  88. package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
  89. package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
  90. package/docs/api-reference/workflow-next/with-workflow.mdx +39 -17
  91. package/docs/api-reference/workflow-nitro/index.mdx +60 -0
  92. package/docs/api-reference/workflow-nuxt/index.mdx +48 -0
  93. package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
  94. package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
  95. package/docs/api-reference/workflow-observability/index.mdx +62 -0
  96. package/docs/api-reference/workflow-observability/meta.json +11 -0
  97. package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
  98. package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
  99. package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
  100. package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
  101. package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
  102. package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
  103. package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +11 -14
  104. package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
  105. package/docs/api-reference/workflow-runtime/index.mdx +41 -0
  106. package/docs/api-reference/workflow-runtime/meta.json +12 -0
  107. package/docs/api-reference/workflow-runtime/set-world.mdx +51 -0
  108. package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +43 -0
  109. package/docs/api-reference/workflow-runtime/world/analytics.mdx +315 -0
  110. package/docs/api-reference/workflow-runtime/world/index.mdx +60 -0
  111. package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
  112. package/docs/api-reference/workflow-runtime/world/queue.mdx +88 -0
  113. package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +98 -34
  114. package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +8 -8
  115. package/docs/api-reference/workflow-serde/index.mdx +1 -2
  116. package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +3 -4
  117. package/docs/api-reference/workflow-serde/workflow-serialize.mdx +8 -8
  118. package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
  119. package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
  120. package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
  121. package/docs/api-reference/workflow-vite/index.mdx +18 -0
  122. package/docs/api-reference/workflow-vite/meta.json +4 -0
  123. package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
  124. package/docs/changelog/attributes-mvp.mdx +380 -0
  125. package/docs/changelog/batched-event-writes.mdx +79 -0
  126. package/docs/changelog/eager-processing.mdx +110 -436
  127. package/docs/changelog/index.mdx +4 -2
  128. package/docs/changelog/lazy-event-creation.md +127 -0
  129. package/docs/changelog/lazy-hook-resume.mdx +78 -0
  130. package/docs/changelog/meta.json +11 -1
  131. package/docs/changelog/resilient-resume.mdx +32 -0
  132. package/docs/changelog/resilient-start.mdx +33 -285
  133. package/docs/changelog/step-message-ownership.mdx +360 -0
  134. package/docs/changelog/turbo-mode.md +87 -0
  135. package/docs/comparisons/index.mdx +66 -0
  136. package/docs/comparisons/meta.json +11 -0
  137. package/docs/comparisons/workflow-sdk-vs-aws-agentcore.mdx +55 -0
  138. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +111 -0
  139. package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +71 -0
  140. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +102 -0
  141. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +123 -0
  142. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +104 -0
  143. package/docs/configuration/build-and-diagnostics.mdx +70 -0
  144. package/docs/configuration/cli-and-web-ui.mdx +241 -0
  145. package/docs/configuration/framework-options.mdx +165 -0
  146. package/docs/configuration/index.mdx +32 -0
  147. package/docs/configuration/meta.json +12 -0
  148. package/docs/configuration/runtime-tuning.mdx +376 -0
  149. package/docs/configuration/worlds.mdx +313 -0
  150. package/docs/cookbook/advanced/child-workflows.mdx +211 -264
  151. package/docs/cookbook/advanced/meta.json +6 -1
  152. package/docs/cookbook/advanced/publishing-libraries.mdx +65 -56
  153. package/docs/cookbook/advanced/serializable-steps.mdx +28 -20
  154. package/docs/cookbook/advanced/upgrading-workflows.mdx +199 -0
  155. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +27 -19
  156. package/docs/cookbook/agent-patterns/durable-agent.mdx +14 -142
  157. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +30 -22
  158. package/docs/cookbook/common-patterns/batching.mdx +18 -14
  159. package/docs/cookbook/common-patterns/idempotency.mdx +41 -53
  160. package/docs/cookbook/common-patterns/rate-limiting.mdx +8 -4
  161. package/docs/cookbook/common-patterns/saga.mdx +23 -19
  162. package/docs/cookbook/common-patterns/scheduling.mdx +34 -22
  163. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +29 -25
  164. package/docs/cookbook/common-patterns/timeouts.mdx +26 -21
  165. package/docs/cookbook/common-patterns/webhooks.mdx +10 -6
  166. package/docs/cookbook/common-patterns/workflow-composition.mdx +30 -27
  167. package/docs/cookbook/index.mdx +22 -21
  168. package/docs/cookbook/integrations/ai-sdk.mdx +85 -47
  169. package/docs/cookbook/integrations/chat-sdk.mdx +50 -33
  170. package/docs/cookbook/integrations/sandbox.mdx +62 -45
  171. package/docs/deploying.mdx +95 -0
  172. package/docs/errors/abort-signal-timeout-in-workflow.mdx +16 -12
  173. package/docs/errors/corrupted-event-log.mdx +29 -18
  174. package/docs/errors/deployment-mismatch.mdx +71 -0
  175. package/docs/errors/fetch-in-workflow.mdx +11 -7
  176. package/docs/errors/hook-conflict.mdx +69 -13
  177. package/docs/errors/index.mdx +2 -36
  178. package/docs/errors/node-js-module-in-workflow.mdx +9 -5
  179. package/docs/errors/replay-divergence.mdx +27 -0
  180. package/docs/errors/run-expired.mdx +85 -0
  181. package/docs/errors/runtime-decryption-failed.mdx +77 -0
  182. package/docs/errors/serialization-failed.mdx +44 -12
  183. package/docs/errors/start-invalid-workflow-function.mdx +9 -5
  184. package/docs/errors/step-executed-multiple-times.mdx +23 -0
  185. package/docs/errors/step-not-registered.mdx +6 -6
  186. package/docs/errors/timeout-in-workflow.mdx +12 -8
  187. package/docs/errors/webhook-invalid-respond-with-value.mdx +18 -18
  188. package/docs/errors/webhook-response-not-sent.mdx +20 -16
  189. package/docs/errors/workflow-not-registered.mdx +5 -5
  190. package/docs/foundations/cancellation.mdx +31 -32
  191. package/docs/foundations/errors-and-retries.mdx +42 -11
  192. package/docs/foundations/hooks.mdx +64 -35
  193. package/docs/foundations/idempotency.mdx +244 -12
  194. package/docs/foundations/index.mdx +1 -23
  195. package/docs/foundations/meta.json +2 -1
  196. package/docs/foundations/serialization.mdx +21 -22
  197. package/docs/foundations/starting-workflows.mdx +106 -30
  198. package/docs/foundations/streaming.mdx +107 -59
  199. package/docs/foundations/versioning.mdx +263 -0
  200. package/docs/foundations/workflows-and-steps.mdx +9 -9
  201. package/docs/getting-started/astro.mdx +22 -18
  202. package/docs/getting-started/express.mdx +15 -11
  203. package/docs/getting-started/fastify.mdx +15 -11
  204. package/docs/getting-started/hono.mdx +15 -11
  205. package/docs/getting-started/index.mdx +10 -3
  206. package/docs/getting-started/meta.json +3 -1
  207. package/docs/getting-started/nestjs.mdx +87 -20
  208. package/docs/getting-started/next.mdx +22 -16
  209. package/docs/getting-started/nitro.mdx +22 -18
  210. package/docs/getting-started/nuxt.mdx +15 -11
  211. package/docs/getting-started/python.mdx +135 -40
  212. package/docs/getting-started/react-router/index.mdx +33 -0
  213. package/docs/getting-started/react-router/meta.json +5 -0
  214. package/docs/getting-started/react-router/v7.mdx +237 -0
  215. package/docs/getting-started/react-router/v8.mdx +232 -0
  216. package/docs/getting-started/sveltekit.mdx +20 -16
  217. package/docs/getting-started/tanstack-start.mdx +17 -13
  218. package/docs/getting-started/vite.mdx +15 -11
  219. package/docs/how-it-works/cancellation.mdx +63 -63
  220. package/docs/how-it-works/code-transform.mdx +83 -67
  221. package/docs/how-it-works/encryption.mdx +30 -26
  222. package/docs/how-it-works/event-sourcing.mdx +98 -34
  223. package/docs/how-it-works/framework-integrations.mdx +96 -337
  224. package/docs/how-it-works/understanding-directives.mdx +22 -22
  225. package/docs/internal/index.mdx +6 -4
  226. package/docs/internal/meta.json +6 -1
  227. package/docs/internal/nitro-native-build.mdx +38 -0
  228. package/docs/internal/nitro-web-ui.mdx +24 -0
  229. package/docs/internal/serializable-abort-controller.mdx +7 -7
  230. package/docs/meta.json +3 -2
  231. package/docs/observability/attributes.mdx +134 -0
  232. package/docs/observability/index.mdx +32 -10
  233. package/docs/observability/meta.json +1 -1
  234. package/docs/observability/retention.mdx +93 -0
  235. package/docs/observability/tracing.mdx +124 -0
  236. package/docs/testing/index.mdx +36 -36
  237. package/docs/testing/server-based.mdx +10 -10
  238. package/docs/whats-new.mdx +186 -0
  239. package/package.json +17 -14
  240. package/docs/api-reference/workflow-api/world/index.mdx +0 -58
  241. package/docs/api-reference/workflow-api/world/meta.json +0 -4
  242. package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
  243. package/docs/api-reference/workflow-api/world/queue.mdx +0 -86
  244. package/docs/deploying/building-a-world.mdx +0 -251
  245. package/docs/deploying/index.mdx +0 -95
  246. package/docs/deploying/meta.json +0 -4
  247. package/docs/deploying/world/local-world.mdx +0 -84
  248. package/docs/deploying/world/meta.json +0 -4
  249. package/docs/deploying/world/postgres-world.mdx +0 -224
  250. package/docs/deploying/world/vercel-world.mdx +0 -179
  251. package/docs/migration-guides/index.mdx +0 -34
  252. package/docs/migration-guides/meta.json +0 -9
  253. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +0 -363
  254. package/docs/migration-guides/migrating-from-inngest.mdx +0 -314
  255. package/docs/migration-guides/migrating-from-temporal.mdx +0 -318
  256. package/docs/migration-guides/migrating-from-trigger-dev.mdx +0 -337
@@ -5,6 +5,10 @@ type: guide
5
5
  summary: Run a sequence of steps where each registers a compensation. If any step throws a FatalError, compensations execute in reverse order to restore consistency.
6
6
  ---
7
7
 
8
+ <CopyPrompt
9
+ text="Implement a saga-style workflow. Import `FatalError` from `workflow`. In the exported &quot;use workflow&quot; function, keep a compensation stack such as `const compensations: Array<() => Promise<void>> = []`. For each forward side effect, create a &quot;use step&quot; helper, await it, then push the matching compensation &quot;use step&quot; helper onto the stack. Throw `FatalError` for permanent business failures and normal errors for retryable failures. In the workflow catch block, run compensations in reverse order with `for (const compensate of compensations.reverse()) await compensate()`, then rethrow or return a failed status. Make each compensation idempotent. Verify successful completion, a fatal failure after multiple steps, and a replay/retry during rollback."
10
+ />
11
+
8
12
  Use the saga pattern when a business transaction spans multiple services and you need automatic rollback if any step fails. Each forward step registers a compensation, and on failure the workflow unwinds them in reverse order.
9
13
 
10
14
  ## When to use this
@@ -16,8 +20,8 @@ Use the saga pattern when a business transaction spans multiple services and you
16
20
  ## How it works
17
21
 
18
22
  1. Each forward step does work and registers a compensation function.
19
- 2. If any step throws `FatalError`, the catch block runs compensations in reverse (LIFO) order to restore consistency.
20
- 3. Regular errors are retried automatically (up to 3x by default). Use `FatalError` only for permanent failures where retrying won't help.
23
+ 2. If any step throws `FatalError`, the catch block runs compensations in reverse, or last in, first out (LIFO), order to restore consistency.
24
+ 3. Regular errors are retried automatically, up to three times by default. Use `FatalError` only for permanent failures where retrying won't help.
21
25
 
22
26
  ## Pattern
23
27
 
@@ -49,7 +53,7 @@ export async function subscriptionUpgradeSaga(accountId: string, seats: number)
49
53
  const entitlementId = await provisionSeats(accountId, seats);
50
54
  compensations.push(() => deprovisionSeats(accountId, entitlementId)); // [!code highlight]
51
55
 
52
- // No compensation — notifications are fire-and-forget
56
+ // No compensation: notifications are fire-and-forget
53
57
  await sendConfirmation(accountId, invoiceId, entitlementId);
54
58
 
55
59
  return { status: "completed" };
@@ -66,7 +70,7 @@ export async function subscriptionUpgradeSaga(accountId: string, seats: number)
66
70
 
67
71
  ### Step functions
68
72
 
69
- Each step is a `"use step"` function with full Node.js access (fetch, fs, npm packages). Forward steps do the work and throw `FatalError` on permanent failure; compensation steps undo it and must be idempotent — safe to call multiple times if the workflow restarts mid-rollback.
73
+ Each step is a `"use step"` function with full Node.js access (fetch, fs, npm packages). Forward steps do the work and throw `FatalError` on permanent failure; compensation steps undo it and must be idempotent: safe to call multiple times if the workflow restarts mid-rollback.
70
74
 
71
75
  ```typescript
72
76
  import { FatalError } from "workflow";
@@ -118,7 +122,7 @@ async function sendConfirmation(
118
122
  });
119
123
  }
120
124
 
121
- // Compensation steps — must be idempotent
125
+ // Compensation steps: must be idempotent
122
126
 
123
127
  async function releaseSeats(accountId: string, reservationId: string): Promise<void> {
124
128
  "use step";
@@ -147,7 +151,7 @@ async function deprovisionSeats(accountId: string, entitlementId: string): Promi
147
151
 
148
152
  ### Streaming step progress (optional)
149
153
 
150
- Use `getWritable()` to stream progress events to a UI so users can see each step execute in real time.
154
+ Use `getWritable()` to stream progress events to a user interface (UI) so users can see each step execute in real time.
151
155
 
152
156
  ```typescript
153
157
  import { FatalError } from "workflow";
@@ -200,7 +204,7 @@ export async function subscriptionUpgradeSaga(accountId: string, seats: number)
200
204
  compensations.push({ name: "Deprovision Seats", execute: () => deprovisionSeats(accountId, entitlementId) });
201
205
  await emit({ type: "step_done", step: "Provision Seats", detail: entitlementId });
202
206
 
203
- // No compensation — notifications are fire-and-forget
207
+ // No compensation: notifications are fire-and-forget
204
208
  await emit({ type: "step_start", step: "Send Confirmation" });
205
209
  await sendConfirmation(accountId, invoiceId, entitlementId);
206
210
  await emit({ type: "step_done", step: "Send Confirmation", detail: "sent" });
@@ -227,21 +231,21 @@ export async function subscriptionUpgradeSaga(accountId: string, seats: number)
227
231
  ## Adapting to your use case
228
232
 
229
233
  - Replace the step functions with real API calls. Each `"use step"` function has full Node.js access.
230
- - Add or remove steps as needed — the pattern scales to any number of steps.
231
- - Make compensations idempotent — they may be retried if the workflow restarts mid-rollback.
232
- - The `emit()` calls and `SagaEvent` type are optional — remove them if you don't need real-time UI progress.
234
+ - Add or remove steps as needed; the pattern scales to any number of steps.
235
+ - Make compensations idempotent, since they may be retried if the workflow restarts mid-rollback.
236
+ - The `emit()` calls and `SagaEvent` type are optional; remove them if you don't need real-time UI progress.
233
237
 
234
238
  ## Tips
235
239
 
236
- - **Use `FatalError` for permanent failures.** Regular errors trigger automatic retries (up to 3 by default). Throw `FatalError` when retrying won't help (e.g., insufficient funds, invalid input).
237
- - **Make compensations idempotent.** If a compensation step is retried, it should produce the same result. Check whether the resource was already released before releasing it again.
238
- - **Compensation steps are also `"use step"` functions.** This makes them durable — if the workflow restarts mid-rollback, it resumes where it left off.
239
- - **Capture values in closures carefully.** Use block-scoped variables or copy values before pushing compensations to avoid referencing stale state.
240
- - **Notifications don't need compensations.** Fire-and-forget steps like sending emails or Slack messages typically don't register a compensation.
240
+ - **Use `FatalError` for permanent failures**: Regular errors trigger automatic retries, up to three times by default. Throw `FatalError` when retrying won't help, such as for insufficient funds or invalid input.
241
+ - **Make compensations idempotent**: If a compensation step is retried, it should produce the same result. Check whether the resource was already released before releasing it again.
242
+ - **Use `"use step"` functions for compensation steps**: This makes them durable. If the workflow restarts during rollback, it resumes where it left off.
243
+ - **Capture values in closures carefully**: Use block-scoped variables or copy values before pushing compensations to avoid referencing stale state.
244
+ - **Skip compensations for notifications**: Fire-and-forget steps such as sending emails or Slack messages typically don't register a compensation.
241
245
 
242
246
  ## Key APIs
243
247
 
244
- - [`"use workflow"`](/docs/api-reference/workflow/use-workflow) -- declares the orchestrator function
245
- - [`"use step"`](/docs/api-reference/workflow/use-step) -- declares step functions with full Node.js access
246
- - [`FatalError`](/docs/api-reference/workflow/fatal-error) -- non-retryable error that triggers compensation
247
- - [`getWritable()`](/docs/api-reference/workflow/get-writable) -- streams data from workflows for real-time UI updates
248
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions): Declares the orchestrator function.
249
+ - [`"use step"`](/docs/foundations/workflows-and-steps#step-functions): Declares step functions with full Node.js access.
250
+ - [`FatalError`](/docs/api-reference/workflow/fatal-error): Represents a non-retryable error that triggers compensation.
251
+ - [`getWritable()`](/docs/api-reference/workflow/get-writable): Streams data from workflows for real-time UI updates.
@@ -5,17 +5,25 @@ type: guide
5
5
  summary: Schedule future actions with durable sleep that survives cold starts, and race sleeps against hooks to let external events cancel the workflow early.
6
6
  ---
7
7
 
8
- Workflow's `sleep()` is durable — it survives cold starts, restarts, and deployments. Combined with `defineHook()` and `Promise.race()`, it becomes the foundation for interruptible scheduled workflows like drip campaigns, reminders, and timed sequences.
8
+ <CopyPrompt
9
+ text="Create an interruptible scheduled workflow. Import `defineHook` and `sleep` from `workflow`. Define a cancellation hook such as `export const cancelDrip = defineHook<{ reason?: string }>()`. In an exported workflow function with &quot;use workflow&quot;, create the hook once, send the first message in a &quot;use step&quot; helper, then `await Promise.race([sleep(&quot;2d&quot;).then(() => false), cancelHook.then(() => true)])` before each delayed action. If the hook wins, return a canceled status; if sleep wins, continue to the next step. Add an API route that calls `cancelDrip.resume(runIdOrToken, { reason })` or `resumeHook()` from `workflow/api`. Verify scheduled delivery, cancellation before sleep completes, and resume after server restart."
10
+ />
11
+
12
+ Workflow's `sleep()` is durable: it survives cold starts, restarts, and deployments. Combined with `defineHook()` and `Promise.race()`, it becomes the foundation for interruptible scheduled workflows like drip campaigns, reminders, and timed sequences.
13
+
14
+ <Callout type="info">
15
+ Scheduled workflows are still pinned to the deployment that started them. If you are building recurring or indefinitely running schedules that should adopt newer code over time, see [Versioning](/docs/foundations/versioning) for the explicit `deploymentId: "latest"` continuation pattern.
16
+ </Callout>
9
17
 
10
18
  ## When to use this
11
19
 
12
- - Sending emails on a schedule (drip campaigns, onboarding sequences, reminders)
13
- - Waiting for a deadline but allowing early cancellation
14
- - Any pattern where "do X, wait N hours, then do Y" needs to be both reliable and interruptible
20
+ - Sending emails on a schedule, such as drip campaigns, onboarding sequences, or reminders
21
+ - Waiting for a deadline while allowing early cancellation
22
+ - Reliable, interruptible patterns that perform one action, wait for a specified time, and then perform another action
15
23
 
16
24
  ## Drip campaign with cancellation
17
25
 
18
- A drip campaign sends emails at intervals, sleeping between each. Each sleep races against a cancellation hook — if an external event fires the hook (e.g. user converts, unsubscribes), the campaign stops immediately.
26
+ A drip campaign sends emails at intervals, sleeping between each message. Each sleep races against a cancellation hook. If an external event fires the hook, such as when a user converts or unsubscribes, the campaign stops immediately.
19
27
 
20
28
  ```typescript
21
29
  import { defineHook, sleep } from "workflow";
@@ -97,29 +105,33 @@ export async function POST(req: Request) {
97
105
 
98
106
  ## How it works
99
107
 
100
- 1. **Durable sleep** — `sleep("2d")` persists through restarts at zero compute cost. The workflow resumes precisely when the timer fires.
101
- 2. **Hook creation** — `cancelDrip.create({ token })` registers a hook that resolves when any external system calls `.resume()` with the same token.
102
- 3. **Race** — `Promise.race([sleep(...), hook])` blocks until either the timer fires or the hook is resumed, whichever comes first.
103
- 4. **Fresh hooks per window** — after a sleep completes normally, the previous hook instance is consumed. A new `.create()` call registers a fresh hook for the next sleep window, reusing the same token.
108
+ 1. **Durable sleep**: `sleep("2d")` persists through restarts at zero compute cost. The workflow resumes when the timer fires.
109
+ 2. **Hook creation**: `cancelDrip.create({ token })` registers a hook that resolves when any external system calls `.resume()` with the same token.
110
+ 3. **Race**: `Promise.race([sleep(...), hook])` blocks until either the timer fires or the hook is resumed, whichever comes first.
111
+ 4. **Fresh hooks per window**: After a sleep completes normally, the previous hook instance is consumed. A new `.create()` call registers a fresh hook for the next sleep window, reusing the same token.
112
+
113
+ <Callout type="info">
114
+ Deterministic hook tokens can also serve as the idempotency point for scheduled runs. If duplicate schedule starts would send duplicate campaigns or reminders, create a hook with a token derived from the campaign key near the beginning of the workflow and route retries through that hook. If two scheduled starts race, the duplicate run can detect the conflict early with `await hook.getConflict()`, which resolves with the active owner so the duplicate can defer to it. See [Idempotency](/docs/foundations/idempotency).
115
+ </Callout>
104
116
 
105
117
  ## Adapting to your use case
106
118
 
107
- - **Change durations** — replace `"2d"` with any duration string (`"1h"`, `"7d"`, `"30m"`) or a `Date` object for absolute times.
108
- - **Add more steps** — the pattern scales to any number of email-then-sleep pairs.
109
- - **Snooze instead of cancel** — resolve the hook with a `snooze` payload and sleep again: `sleep(new Date(Date.now() + payload.snoozeMs))`.
110
- - **Timeout any operation** — the same `Promise.race(sleep, work)` pattern works for adding deadlines to slow steps.
111
- - **Real providers** — swap the `sendEmail` step body for Resend, Postmark, or any HTTP API. The `"use step"` function has full Node.js access.
119
+ - **Change durations**: Replace `"2d"` with any duration string (`"1h"`, `"7d"`, or `"30m"`) or a `Date` object for absolute times.
120
+ - **Add more steps**: The pattern scales to any number of email-then-sleep pairs.
121
+ - **Snooze instead of cancel**: Resolve the hook with a `snooze` payload and sleep again with `sleep(new Date(Date.now() + payload.snoozeMs))`.
122
+ - **Set a timeout for any operation**: Use the same `Promise.race(sleep, work)` pattern to add deadlines to slow steps.
123
+ - **Use production providers**: Replace the `sendEmail` step body with Resend, Postmark, or any HTTP API. The `"use step"` function has full Node.js access.
112
124
 
113
125
  ## Tips
114
126
 
115
- - **`sleep()` accepts** duration strings (`"1d"`, `"2h"`, `"30s"`), milliseconds, or `Date` objects for sleeping until a specific time.
116
- - **Durable means durable.** A `sleep("7d")` workflow costs nothing while sleeping — no compute, no memory.
117
- - **Use `sleep()` in workflow context only.** Step functions cannot call `sleep()` directly. If a step needs a delay, use `setTimeout` inside the step.
127
+ - **Pass supported values to `sleep()`**: Use duration strings (`"1d"`, `"2h"`, or `"30s"`), milliseconds, or `Date` objects for sleeping until a specific time.
128
+ - **Sleeping consumes no compute or memory**: A workflow waiting on `sleep("7d")` consumes no compute or memory while sleeping.
129
+ - **Use `sleep()` only in workflow context**: Step functions cannot call `sleep()` directly. If a step needs a delay, use `setTimeout` inside the step.
118
130
 
119
131
  ## Key APIs
120
132
 
121
- - [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
122
- - [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions that run with full Node.js access
123
- - [`sleep()`](/docs/api-reference/workflow/sleep) — durable wait (survives restarts, zero compute cost)
124
- - [`defineHook()`](/docs/api-reference/workflow/define-hook) — creates a typed hook that external systems can fire
125
- - [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — races sleep against hooks for interruptible waits
133
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps): Marks the orchestrator function.
134
+ - [`"use step"`](/docs/foundations/workflows-and-steps): Marks functions that run with full Node.js access.
135
+ - [`sleep()`](/docs/api-reference/workflow/sleep): Provides a durable wait that survives restarts with zero compute cost.
136
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook): Creates a typed hook that external systems can fire.
137
+ - [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race): Races sleep against hooks for interruptible waits.
@@ -1,22 +1,26 @@
1
1
  ---
2
2
  title: Sequential & Parallel Execution
3
- description: Compose steps with familiar async/await patterns — sequential await, Promise.all, and Promise.race.
3
+ description: Compose steps with familiar async/await patterns, sequential await, Promise.all, and Promise.race.
4
4
  type: guide
5
- summary: Workflows are just async functions, so all the standard composition primitives (await, Promise.all, Promise.race) apply unchanged — including racing webhooks against durable sleeps.
5
+ summary: Workflows are plain async functions, so all the standard composition primitives (await, Promise.all, Promise.race) apply unchanged, including racing webhooks against durable sleeps.
6
6
  related:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  - /cookbook/common-patterns/timeouts
9
9
  - /cookbook/common-patterns/scheduling
10
10
  ---
11
11
 
12
- Workflows are written in plain async/await — there's no new control-flow API to learn. Sequential awaits chain steps that depend on each other, `Promise.all` runs independent steps in parallel, and `Promise.race` returns whichever finishes first. These compose with workflow primitives like [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) since those are also just promises.
12
+ <CopyPrompt
13
+ text="Compose these workflow steps with standard async/await patterns. In the exported &quot;use workflow&quot; function, chain dependent &quot;use step&quot; calls with sequential `await`; run independent steps concurrently by starting them without `await` and awaiting `Promise.all([...])`; and use `Promise.race([...])` to act on whichever promise settles first. These compose with durable primitives: race a step or a webhook from `createWebhook()` against `sleep()` from `workflow` for deadlines. Keep every step input and output serializable, and remember `Promise.race` does not cancel the losing branch (it keeps running), so side-effectful losers need idempotency keys. Verify sequential ordering, parallel execution, and both race outcomes."
14
+ />
15
+
16
+ Workflows are written in plain async/await: there's no new control-flow API to learn. Sequential awaits chain steps that depend on each other, `Promise.all` runs independent steps in parallel, and `Promise.race` returns whichever finishes first. These compose with workflow primitives like [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) since those are also promises.
13
17
 
14
18
  ## When to use this
15
19
 
16
- - **Pipelines** — each step depends on the previous step's output (validate → process → store)
17
- - **Independent fan-out** — fetch multiple resources or perform multiple actions that don't depend on each other
18
- - **Race conditions** — return as soon as one of N operations completes (timeout, first-responder, deadline)
19
- - **Mixing primitives** — running steps, sleeps, and webhooks side-by-side in the same control-flow expression
20
+ - **Pipelines**: Each step depends on the previous step's output (validate → process → store).
21
+ - **Independent fan-out**: Fetch multiple resources or perform multiple actions that don't depend on each other.
22
+ - **Race conditions**: Return as soon as one operation completes, such as for a timeout, first responder, or deadline.
23
+ - **Mixing primitives**: Run steps, sleeps, and webhooks side by side in the same control-flow expression.
20
24
 
21
25
  ## Pattern
22
26
 
@@ -64,7 +68,7 @@ export async function fetchUserData(userId: string) {
64
68
 
65
69
  ### Race with `Promise.race`
66
70
 
67
- `Promise.race` resolves as soon as the first promise settles. Since [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) return promises, they compose naturally — for example, waiting for a webhook callback with a deadline:
71
+ `Promise.race` resolves as soon as the first promise settles. Since [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) return promises, they compose naturally. For example, waiting for a webhook callback with a deadline:
68
72
 
69
73
  ```typescript lineNumbers
70
74
  import { sleep, createWebhook } from "workflow";
@@ -86,11 +90,11 @@ export async function runExternalTask(userId: string) {
86
90
  }
87
91
  ```
88
92
 
89
- For racing operations against deadlines specifically (timeouts), see the dedicated [Timeouts](/cookbook/common-patterns/timeouts) recipe — it covers result discrimination, `FatalError` semantics, and the "loser keeps running" caveat.
93
+ For racing operations against deadlines specifically (timeouts), see the dedicated [Timeouts](/cookbook/common-patterns/timeouts) recipe, which covers result discrimination, `FatalError` semantics, and the "loser keeps running" caveat.
90
94
 
91
95
  ### Combining sequential, parallel, and durable primitives
92
96
 
93
- Most real workflows combine all three. Here's a simplified version of the [birthday card generator demo](https://github.com/vercel/workflow-examples/tree/main/birthday-card-generator) — sequential card generation, parallel RSVP fan-out, non-blocking webhook collection, and a durable sleep until the birthday:
97
+ Most workflows combine all three patterns. The following simplified version of the [birthday card generator demo](https://github.com/vercel/workflow-examples/tree/main/birthday-card-generator) uses sequential card generation, parallel invitation-response fan-out, non-blocking webhook collection, and a durable sleep until the birthday:
94
98
 
95
99
  ```typescript lineNumbers
96
100
  import { createWebhook, sleep, type Webhook } from "workflow";
@@ -132,24 +136,24 @@ export async function birthdayWorkflow(
132
136
 
133
137
  ## How it works
134
138
 
135
- 1. **`await` is durable.** When the workflow awaits a step, the runtime persists the step's input, suspends the workflow, runs the step, and replays the workflow with the step's result on resume. The same applies to `sleep()` and `createWebhook()`.
136
- 2. **`Promise.all` runs steps concurrently.** Each promise in the array is suspended on its own and the workflow resumes only when all have settled. Failures propagate — if any promise rejects, the whole `Promise.all` rejects.
137
- 3. **`Promise.race` resolves on the first settle.** The losing promises keep running in the background but their results are discarded by the workflow.
138
- 4. **All primitives are promises.** `sleep("1 day")` and `createWebhook()` return promises, so they compose with `Promise.all` / `Promise.race` exactly like steps do — this is what makes patterns like "race a webhook against a 24-hour deadline" a one-liner.
139
+ 1. **`await` is durable**: When the workflow awaits a step, the runtime persists the step's input, suspends the workflow, runs the step, and replays the workflow with the step's result on resume. The same applies to `sleep()` and `createWebhook()`.
140
+ 2. **`Promise.all` runs steps concurrently**: Each promise in the array is suspended on its own, and the workflow resumes only when all have settled. If any promise rejects, the whole `Promise.all` rejects.
141
+ 3. **`Promise.race` resolves when the first promise settles**: The losing promises keep running in the background, but the workflow discards their results.
142
+ 4. **All primitives are promises**: `sleep("1 day")` and `createWebhook()` return promises, so they compose with `Promise.all` and `Promise.race` like steps do. This behavior enables patterns such as racing a webhook against a 24-hour deadline.
139
143
 
140
144
  ## Adapting to your use case
141
145
 
142
- - **Replace `Promise.all` with `Promise.allSettled`** when partial failures should not abort the rest. You'll get an array of `{ status, value | reason }` instead of throwing on the first rejection.
143
- - **Bound the parallelism** — `Promise.all` over 1000 items will fan out 1000 concurrent steps. If your downstream APIs can't handle that, batch the array into chunks (see [Batching](/cookbook/common-patterns/batching)).
144
- - **Add a deadline to any race** — pair the operation with `sleep("30s").then(() => "timeout" as const)` and check the discriminated result. See [Timeouts](/cookbook/common-patterns/timeouts).
145
- - **Mix steps and hooks in a race** — wait for an external signal *or* a deadline *or* a step result, all in the same `Promise.race`. The first one to resolve wins.
146
+ - **Replace `Promise.all` with `Promise.allSettled`**: Use this option when partial failures shouldn't abort the remaining operations. You'll get an array of `{ status, value | reason }` instead of an error on the first rejection.
147
+ - **Bound the parallelism**: `Promise.all` over 1,000 items will fan out 1,000 concurrent steps. If your downstream APIs can't handle that, batch the array into chunks (see [Batching](/cookbook/common-patterns/batching)).
148
+ - **Add a deadline to any race**: Pair the operation with `sleep("30s").then(() => "timeout" as const)` and check the discriminated result. See [Timeouts](/cookbook/common-patterns/timeouts).
149
+ - **Mix steps and hooks in a race**: Wait for an external signal, a deadline, or a step result in the same `Promise.race`. The first promise to resolve wins.
146
150
 
147
151
  ## Key APIs
148
152
 
149
- - [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
150
- - [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions with full Node.js access
151
- - [`sleep()`](/docs/api-reference/workflow/sleep) — durable sleep that survives restarts
152
- - [`createWebhook()`](/docs/api-reference/workflow/create-webhook) — webhook URL the workflow can race against
153
- - [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) — wait for all promises
154
- - [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — wait for the first to settle
155
- - [`Promise.allSettled()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) — wait for all, including failures
153
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps): Marks the orchestrator function.
154
+ - [`"use step"`](/docs/foundations/workflows-and-steps): Marks functions with full Node.js access.
155
+ - [`sleep()`](/docs/api-reference/workflow/sleep): Provides durable sleep that survives restarts.
156
+ - [`createWebhook()`](/docs/api-reference/workflow/create-webhook): Provides a webhook URL that the workflow can race against.
157
+ - [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all): Waits for all promises.
158
+ - [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race): Waits for the first promise to settle.
159
+ - [`Promise.allSettled()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled): Waits for all promises, including failures.
@@ -2,7 +2,7 @@
2
2
  title: Timeouts
3
3
  description: Add deadlines to slow operations by racing them against a durable sleep.
4
4
  type: guide
5
- summary: Use `Promise.race` with `sleep()` to bound the time any step, hook, or webhook is allowed to take — and recover gracefully when the deadline fires first.
5
+ summary: Use `Promise.race` with `sleep()` to bound the time any step, hook, or webhook is allowed to take, and recover gracefully when the deadline fires first.
6
6
  related:
7
7
  - /docs/api-reference/workflow/sleep
8
8
  - /docs/foundations/hooks
@@ -10,14 +10,18 @@ related:
10
10
  - /cookbook/common-patterns/webhooks
11
11
  ---
12
12
 
13
- A common requirement is bounding how long a workflow waits for something to finish — a slow step, an external webhook, a human approval. Race the operation against a durable `sleep()` with `Promise.race()` — whichever finishes first wins, and the loser keeps running but its result is ignored.
13
+ <CopyPrompt
14
+ text="Add a deadline to this slow workflow operation. Import `sleep` from `workflow`. In the exported &quot;use workflow&quot; function, race the operation against a durable sleep: `await Promise.race([slowStep(...), deadline(&quot;10m&quot;)])`, where `deadline` is a helper that awaits `sleep(duration)` and returns a sentinel value or throws. Branch on the winner: continue normally on success, run the fallback or compensation path on timeout. Use the same pattern to bound hooks and webhooks. `Promise.race` does not cancel the loser (the underlying step keeps running), so pass an `AbortSignal` into the step for cooperative cancellation and make non-idempotent side effects retry-safe with idempotency keys. Verify the fast path, the timeout path, and side-effect safety when the loser completes late."
15
+ />
16
+
17
+ Workflows often need to limit how long they wait for a slow step, an external webhook, or human approval. Race the operation against a durable `sleep()` with `Promise.race()`. The first operation to finish wins, while the other keeps running and its result is ignored.
14
18
 
15
19
  ## When to use this
16
20
 
17
- - **Slow steps** — bound the time spent waiting on third-party APIs, model calls, or expensive computation
18
- - **External callbacks** — give webhooks a deadline so the workflow doesn't hang forever waiting for an event that may never arrive
19
- - **Human approvals** — auto-decline or escalate when a hook isn't resumed within a window
20
- - **Polling loops** — give an outer poll-until-ready loop an overall budget
21
+ - **Slow steps**: bound the time spent waiting on third-party APIs, model calls, or expensive computation
22
+ - **External callbacks**: give webhooks a deadline so the workflow doesn't hang forever waiting for an event that may never arrive
23
+ - **Human approvals**: auto-decline or escalate when a hook isn't resumed within a window
24
+ - **Polling loops**: give an outer poll-until-ready loop an overall budget
21
25
 
22
26
  ## Pattern
23
27
 
@@ -46,7 +50,7 @@ export async function processWithTimeout(data: string) {
46
50
 
47
51
  ### Timeout on a webhook
48
52
 
49
- The same pattern works for any promise — including hooks and webhooks. Here a webhook waits for an external service to call back, with a hard deadline of 7 days:
53
+ The same pattern works for any promise, including hooks and webhooks. Here a webhook waits for an external service to call back, with a hard deadline of 7 days:
50
54
 
51
55
  ```typescript lineNumbers
52
56
  import { sleep, createWebhook } from "workflow";
@@ -74,26 +78,27 @@ export async function waitForApproval(requestId: string) {
74
78
 
75
79
  ## How it works
76
80
 
77
- 1. **Durable sleep** — `sleep("30s")` persists through restarts at zero compute cost. The workflow resumes precisely when the timer fires.
78
- 2. **Race** — `Promise.race([work, sleep(...)])` returns the value of whichever promise resolves first. The loser keeps running in the background but its result is ignored by the workflow.
79
- 3. **Discriminated result** — tagging the sleep branch with a sentinel value (`"timeout" as const`, `{ timedOut: true }`) lets TypeScript narrow the result and pick the right branch.
80
- 4. **Throw to fail the workflow** — inside a workflow function, throwing an `Error` exits the run with that error. Use `FatalError` inside steps; throw plain errors inside workflows.
81
+ 1. **Durable sleep**: `sleep("30s")` persists through restarts at zero compute cost. The workflow resumes precisely when the timer fires.
82
+ 2. **Race**: `Promise.race([work, sleep(...)])` returns the value of whichever promise resolves first. The loser keeps running in the background but its result is ignored by the workflow.
83
+ 3. **Discriminated result**: tagging the sleep branch with a sentinel value (`"timeout" as const`, `{ timedOut: true }`) lets TypeScript narrow the result and pick the right branch.
84
+ 4. **Throw to fail the workflow**: inside a workflow function, throwing an `Error` exits the run with that error. Use `FatalError` inside steps; throw plain errors inside workflows.
81
85
 
82
86
  <Callout type="warn">
83
- **The losing operation keeps running.** `Promise.race` doesn't cancel — when the sleep wins, the underlying step (or model call, or HTTP request) continues to completion in the background. This is fine for idempotent reads but matters when the operation has side effects or costs money. Pass an `AbortSignal` into the step to cancel it cooperatively — see the [Cancellation Guide](/docs/foundations/cancellation) for patterns.
87
+ **The losing operation keeps running.** `Promise.race` doesn't cancel: when the sleep wins, the underlying step (or model call, or HTTP request) continues to completion in the background. This is fine for idempotent reads but matters when the operation has side effects or costs money. Pass an `AbortSignal` into the step to cancel it cooperatively, and use idempotency keys for non-idempotent side effects. See the [Cancellation Guide](/docs/foundations/cancellation) and [Idempotency](/docs/foundations/idempotency) for patterns.
84
88
  </Callout>
85
89
 
86
90
  ## Adapting to your use case
87
91
 
88
- - **Different durations** — `sleep()` accepts duration strings (`"30s"`, `"5m"`, `"7 days"`), milliseconds, or `Date` objects for absolute deadlines.
89
- - **Soft timeout (retry)** — instead of throwing, loop and retry with a fresh `Promise.race` and a backoff.
90
- - **Soft timeout (fallback)** — return a default value when the timer wins instead of throwing: `if (result === "timeout") return cachedFallback`.
91
- - **Combine with cancellation** — race three promises: the operation, a deadline `sleep()`, and a cancellation hook. See the [Scheduling cookbook](/cookbook/common-patterns/scheduling) for the cancellation half of this pattern.
92
- - **Per-step deadlines** — wrap each step in its own `Promise.race` for independent budgets, or use a single outer race for an overall workflow deadline.
92
+ - **Different durations**: `sleep()` accepts duration strings (`"30s"`, `"5m"`, `"7 days"`), milliseconds, or `Date` objects for absolute deadlines.
93
+ - **Soft timeout (retry)**: instead of throwing, loop and retry with a fresh `Promise.race` and a backoff.
94
+ - **Soft timeout (fallback)**: return a default value when the timer wins instead of throwing: `if (result === "timeout") return cachedFallback`.
95
+ - **Combine with cancellation**: race three promises: the operation, a deadline `sleep()`, and a cancellation hook. See the [Scheduling cookbook](/cookbook/common-patterns/scheduling) for the cancellation half of this pattern.
96
+ - **Per-step deadlines**: wrap each step in its own `Promise.race` for independent budgets, or use a single outer race for an overall workflow deadline.
93
97
 
94
98
  ## Key APIs
95
99
 
96
- - [`sleep()`](/docs/api-reference/workflow/sleep) — durable wait (survives restarts, zero compute cost)
97
- - [`createWebhook()`](/docs/api-reference/workflow/create-webhook) — create a webhook URL the workflow can race against
98
- - [`defineHook()`](/docs/api-reference/workflow/define-hook) — typed hook for in-process cancellation
99
- - [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — race operations against deadlines
100
+ - [`sleep()`](/docs/api-reference/workflow/sleep): durable wait (survives restarts, zero compute cost)
101
+ - [`createWebhook()`](/docs/api-reference/workflow/create-webhook): create a webhook URL the workflow can race against
102
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook): typed hook for in-process cancellation
103
+ - [Idempotency](/docs/foundations/idempotency): protect side effects that may keep running after a timeout
104
+ - [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race): race operations against deadlines
@@ -2,9 +2,13 @@
2
2
  title: Webhooks & External Callbacks
3
3
  description: Receive HTTP callbacks from external services, process them durably, and respond inline.
4
4
  type: guide
5
- summary: Create webhook endpoints that your workflow can await, process incoming requests in steps, and respond to the caller — all within durable workflow context.
5
+ summary: Create webhook endpoints that your workflow can await, process incoming requests in steps, and respond to the caller, all within durable workflow context.
6
6
  ---
7
7
 
8
+ <CopyPrompt
9
+ text="Implement durable webhook handling for this workflow. Use `createWebhook()` from `workflow` inside the &quot;use workflow&quot; function when the workflow needs a generated callback URL. Use `createWebhook({ respondWith: &quot;manual&quot; })` when the workflow must validate the request before sending an HTTP response. Await the webhook request, pass the `RequestWithResponse` into a &quot;use step&quot; function for validation and side effects, and call `request.respondWith(Response.json(...))` on every code path. Race the webhook against `sleep()` for deadlines and throw `FatalError` for permanent timeout/failure paths. For fixed public callbacks or large payloads, use `defineHook()` plus `resumeHook()` from `workflow/api` and pass only a token or blob reference into the hook payload. Verify success response, invalid response, timeout, duplicate callback, and large-payload behavior."
10
+ />
11
+
8
12
  Use webhooks when external services push events to your application via HTTP callbacks. The workflow creates a webhook URL, suspends with zero compute cost, and resumes when a request arrives.
9
13
 
10
14
  ## When to use this
@@ -13,7 +17,7 @@ Use webhooks when external services push events to your application via HTTP cal
13
17
  - Waiting for third-party verification or processing results
14
18
  - Any integration where an external system calls you back asynchronously
15
19
 
16
- ## Pattern: Processing webhook events
20
+ ## Pattern: processing webhook events
17
21
 
18
22
  Create a webhook with manual response control, then iterate over incoming requests:
19
23
 
@@ -73,7 +77,7 @@ async function processEvent(
73
77
  }
74
78
  ```
75
79
 
76
- ## Pattern: Async request-reply with timeout
80
+ ## Pattern: async request-reply with timeout
77
81
 
78
82
  Submit a request to an external service, pass it your webhook URL, then race the callback against a deadline:
79
83
 
@@ -124,7 +128,7 @@ async function processCallback(
124
128
  }
125
129
  ```
126
130
 
127
- ## Pattern: Large payload by reference
131
+ ## Pattern: large payload by reference
128
132
 
129
133
  When payloads are too large to serialize into the event log, pass a lightweight reference (a "claim check") instead. Use a hook to signal when the data is ready:
130
134
 
@@ -139,7 +143,7 @@ export async function importLargeFile(importId: string) {
139
143
  // Suspend until the external system signals the blob is uploaded
140
144
  const { blobToken } = await blobReady.create({ token: `upload:${importId}` }); // [!code highlight]
141
145
 
142
- // Process by reference -- the full payload never enters the event log
146
+ // Process by reference. The full payload never enters the event log.
143
147
  await processBlob(blobToken);
144
148
 
145
149
  return { importId, blobToken, status: "indexed" };
@@ -173,7 +177,7 @@ export async function POST(request: Request) {
173
177
  - **`for await` on a webhook** lets you process multiple events from the same URL. Use `break` to stop listening after a terminal event.
174
178
  - **Webhooks auto-generate URLs** at `/.well-known/workflow/v1/webhook/:token`. Pass this URL to external services.
175
179
  - **Race webhooks against `sleep()`** for deadlines. If the callback doesn't arrive in time, the workflow can take a fallback action.
176
- - **For large payloads**, use a hook + reference token instead of passing the data through the workflow. The event log serializes all step inputs/outputs, so large payloads hurt performance.
180
+ - **For large payloads**, use a hook and reference token instead of passing the data through the workflow. The event log serializes all step inputs and outputs, so large payloads hurt performance.
177
181
 
178
182
  ## Key APIs
179
183
 
@@ -2,25 +2,30 @@
2
2
  title: Workflow Composition
3
3
  description: Call workflows from other workflows by direct await (flatten into the parent) or background spawn via start() (separate run).
4
4
  type: guide
5
- summary: Compose workflows two ways — direct await flattens the child into the parent's event log, while background spawn via start() runs the child as an independent run.
5
+ summary: Compose workflows two ways. Direct await flattens the child into the parent's event log, while background spawn via start() runs the child as an independent run.
6
6
  related:
7
7
  - /cookbook/advanced/child-workflows
8
+ - /cookbook/common-patterns/idempotency
8
9
  - /docs/api-reference/workflow-api/start
9
10
  - /docs/api-reference/workflow-api/get-run
10
11
  ---
11
12
 
12
- Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or wants to fire the child off as an independent run (background spawn). For massive fan-out with polling and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
13
+ <CopyPrompt
14
+ text="Compose these workflows. For direct composition, `await` the child workflow function from the parent &quot;use workflow&quot; function: the child's steps flatten into the parent's event log and run as a single run sharing the parent's lifecycle. For independent background work, spawn the child with `start()` from `workflow/api` called directly in the workflow (in v5, `start()` is step-backed and records a deterministic step boundary) and return `run.runId` so callers can track it with `getRun()`. Choose flattening when the parent needs the child's result; choose background spawn when the child should have its own run, retries, and lifetime. Keep all inputs and outputs serializable. Verify flattened execution, background spawn with a separate runId, and replay determinism."
15
+ />
16
+
17
+ Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or starts the child as an independent run (background spawn). For large fan-out operations with hook-based waiting and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
13
18
 
14
19
  ## When to use this
15
20
 
16
- - **Direct await** — the parent needs the child's result before continuing, and you want a single unified event log
17
- - **Background spawn** — the parent doesn't need to wait, and you want the child to be observable as a separate run with its own `runId`
21
+ - **Direct await**: the parent needs the child's result before continuing, and you want a single unified event log
22
+ - **Background spawn**: the parent doesn't need to wait, and you want the child to be observable as a separate run with its own `runId`
18
23
 
19
24
  ## Pattern
20
25
 
21
26
  ### Direct await (flattening)
22
27
 
23
- Call a child workflow with `await` and the child's steps execute inline within the parent — they appear in the parent's event log as if you'd called them directly.
28
+ Call a child workflow with `await` and the child's steps execute inline within the parent. They appear in the parent's event log as if you'd called them directly.
24
29
 
25
30
  ```typescript lineNumbers
26
31
  declare function sendEmail(userId: string): Promise<void>; // @setup
@@ -53,7 +58,7 @@ The parent waits for the child to finish before continuing. Both functions share
53
58
 
54
59
  ### Background spawn via `start()`
55
60
 
56
- To run a child workflow independently without blocking the parent, call [`start()`](/docs/api-reference/workflow-api/start) from a step. This launches the child as a separate workflow run with its own `runId`.
61
+ To run a child workflow independently without blocking the parent, call [`start()`](/docs/api-reference/workflow-api/start) from the parent workflow. This launches the child as a separate workflow run with its own `runId`.
57
62
 
58
63
  ```typescript lineNumbers
59
64
  import { start } from "workflow/api";
@@ -62,37 +67,34 @@ declare function generateReport(reportId: string): Promise<void>; // @setup
62
67
  declare function fulfillOrder(orderId: string): Promise<{ id: string }>; // @setup
63
68
  declare function sendConfirmation(orderId: string): Promise<void>; // @setup
64
69
 
65
- async function triggerReportGeneration(reportId: string) {
66
- "use step"; // [!code highlight]
67
-
68
- const run = await start(generateReport, [reportId]); // [!code highlight]
69
- return run.runId;
70
- }
71
-
72
70
  export async function processOrder(orderId: string) {
73
71
  "use workflow";
74
72
 
75
73
  const order = await fulfillOrder(orderId);
76
74
 
77
- const reportRunId = await triggerReportGeneration(orderId); // [!code highlight]
75
+ const reportRun = await start(generateReport, [orderId]); // [!code highlight]
78
76
 
79
77
  await sendConfirmation(orderId);
80
78
 
81
- return { orderId, reportRunId };
79
+ return { orderId, reportRunId: reportRun.runId };
82
80
  }
83
81
  ```
84
82
 
85
- The parent continues immediately after `start()` returns. The child runs independently and can be monitored separately using the returned `runId` (e.g., via [`getRun()`](/docs/api-reference/workflow-api/get-run)).
83
+ The parent continues immediately after `start()` returns. The child runs independently and can be monitored separately using the returned `runId`, such as through [`getRun()`](/docs/api-reference/workflow-api/get-run).
84
+
85
+ <Callout type="info">
86
+ Each background spawn creates a separate run. If duplicate requests must route to one active child workflow, have the child create a deterministic hook token from the business key and use that hook as the idempotency point. If concurrent starts race, the losing child can detect the conflict early with `await hook.getConflict()`, which resolves with the active owner so the child can point callers at it. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
87
+ </Callout>
86
88
 
87
89
  <Callout type="info">
88
- If you want the child workflow to run on the latest deployment rather than the current one, pass [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest) in the `start()` options. This is currently a Vercel-specific feature. Be aware that the child workflow's function name, file path, argument types, and return type must remain compatible across deployments — renaming the function or changing its location will change the workflow ID, and modifying expected inputs or outputs can cause serialization failures.
90
+ If you want the child workflow to run on the latest deployment rather than the current one, pass [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest) in the `start()` options. See [Versioning](/docs/foundations/versioning) for the full model. This is currently a Vercel-specific feature, and other Worlds may map the concept to their own deployment runtimes. Be aware that the child workflow's function name, file path, argument types, and return type must remain compatible across deployments. Renaming the function or changing its location will change the workflow ID, and modifying expected inputs or outputs can cause serialization failures.
89
91
  </Callout>
90
92
 
91
93
  ## How it works
92
94
 
93
- 1. **Direct await flattens.** When a workflow function awaits another workflow function, the child's `"use workflow"` directive is treated as inline — the child's steps emit into the parent's event log and share the parent's run ID.
94
- 2. **`start()` mints a new run.** The child gets its own `runId`, its own event log, and its own retry boundary. The parent only sees the `runId` returned by `start()`.
95
- 3. **`start()` must be called from a step.** Calling `start()` directly from a workflow function is not allowed — wrap it in a `"use step"` function. This keeps the spawn deterministic across replays.
95
+ 1. **Direct await flattens the child workflow**: When a workflow function awaits another workflow function, the child's `"use workflow"` directive is treated as inline. The child's steps emit into the parent's event log and share the parent's run ID.
96
+ 2. **`start()` creates a new run**: The child gets its own `runId`, event log, and retry boundary. The parent only sees the `runId` returned by `start()`.
97
+ 3. **`start()` can run inside workflows**: In v5, `start()` is step-backed, so it can be called directly from a workflow function and still records a deterministic step boundary in the event log.
96
98
 
97
99
  ## Choosing between the two modes
98
100
 
@@ -106,13 +108,14 @@ If you want the child workflow to run on the latest deployment rather than the c
106
108
 
107
109
  ## Adapting to your use case
108
110
 
109
- - **Spawn many children at once** — call `start()` in a loop inside a step. For more advanced fan-out (chunking, polling, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
110
- - **Wait for a background child to finish** — combine `start()` with `getRun()` polling. The [Child Workflows](/cookbook/advanced/child-workflows) page covers the full polling loop.
111
- - **Pass results back from background children** — the spawn step returns the `runId`; later, a poll step uses `getRun(runId).returnValue` to fetch the final result.
111
+ - **Spawn many children at once**: call `start()` in a loop from the workflow. For more advanced fan-out (chunking, hook-based waiting, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
112
+ - **Wait for a background child to finish**: combine `start()` with a completion hook the child resumes when done. The [Child Workflows](/cookbook/advanced/child-workflows) page covers the recommended `startAndWait()` pattern.
113
+ - **Pass results back from background children**: the wrapped child resumes the parent's hook in `finally` with `{ status, value | error }`; the parent awaits the hook instead of polling `getRun().status`.
112
114
 
113
115
  ## Key APIs
114
116
 
115
- - [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
116
- - [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions with full Node.js access
117
- - [`start()`](/docs/api-reference/workflow-api/start) — spawn a child workflow as a separate run
118
- - [`getRun()`](/docs/api-reference/workflow-api/get-run) — retrieve a workflow run's status and return value
117
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps): marks the orchestrator function
118
+ - [`"use step"`](/docs/foundations/workflows-and-steps): marks functions with full Node.js access
119
+ - [`start()`](/docs/api-reference/workflow-api/start): spawn a child workflow as a separate run
120
+ - [`getRun()`](/docs/api-reference/workflow-api/get-run): retrieve a workflow run's status and return value
121
+ - [Idempotency](/docs/foundations/idempotency): deduplicate step side effects and workflow starts