@upstash/workflow 1.4.0 → 1.5.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.
Files changed (223) hide show
  1. package/README.md +9 -0
  2. package/astro.d.mts +19 -2
  3. package/astro.d.ts +19 -2
  4. package/astro.js +670 -159
  5. package/astro.mjs +1 -1
  6. package/{chunk-DRHEHWMS.mjs → chunk-J3PXPHSB.mjs} +828 -317
  7. package/cloudflare.d.mts +17 -2
  8. package/cloudflare.d.ts +17 -2
  9. package/cloudflare.js +670 -159
  10. package/cloudflare.mjs +1 -1
  11. package/docs/agents/examples.mdx +8 -0
  12. package/docs/agents/features.mdx +374 -0
  13. package/docs/agents/getting-started.mdx +139 -0
  14. package/docs/agents/overview.mdx +40 -0
  15. package/docs/agents/patterns/evaluator-optimizer.mdx +72 -0
  16. package/docs/agents/patterns/orchestrator-workers.mdx +95 -0
  17. package/docs/agents/patterns/parallelization.mdx +77 -0
  18. package/docs/agents/patterns/prompt-chaining.mdx +84 -0
  19. package/docs/basics/best-practices/at-least-one-step.mdx +57 -0
  20. package/docs/basics/best-practices/business-logic-in-steps.mdx +52 -0
  21. package/docs/basics/best-practices/deterministic-code.mdx +132 -0
  22. package/docs/basics/best-practices/idempotency.mdx +38 -0
  23. package/docs/basics/best-practices/nested-context-methods.mdx +38 -0
  24. package/docs/basics/best-practices/overview.mdx +35 -0
  25. package/docs/basics/best-practices/promise-any.mdx +9 -0
  26. package/docs/basics/best-practices/return-step-results.mdx +80 -0
  27. package/docs/basics/best-practices/workflow-limits.mdx +62 -0
  28. package/docs/basics/client/cancel.mdx +137 -0
  29. package/docs/basics/client/dlq/callback.mdx +21 -0
  30. package/docs/basics/client/dlq/delete.mdx +120 -0
  31. package/docs/basics/client/dlq/list.mdx +96 -0
  32. package/docs/basics/client/dlq/restart.mdx +164 -0
  33. package/docs/basics/client/dlq/resume.mdx +167 -0
  34. package/docs/basics/client/logs.mdx +139 -0
  35. package/docs/basics/client/notify.mdx +79 -0
  36. package/docs/basics/client/trigger.mdx +139 -0
  37. package/docs/basics/client/waiters.mdx +31 -0
  38. package/docs/basics/client.mdx +40 -0
  39. package/docs/basics/how.mdx +65 -0
  40. package/docs/basics/serve/advanced.mdx +435 -0
  41. package/docs/basics/serve.mdx +142 -0
  42. package/docs/changelog.mdx +174 -0
  43. package/docs/examples/allInOne.mdx +377 -0
  44. package/docs/examples/authWebhook.mdx +567 -0
  45. package/docs/examples/customRetry.mdx +309 -0
  46. package/docs/examples/customerOnboarding.mdx +230 -0
  47. package/docs/examples/dynamicWorkflow.mdx +203 -0
  48. package/docs/examples/eCommerceOrderFulfillment.mdx +281 -0
  49. package/docs/examples/imageProcessing.mdx +339 -0
  50. package/docs/examples/paymentRetry.mdx +438 -0
  51. package/docs/examples/waitForEvent.mdx +201 -0
  52. package/docs/features/dlq/callback.mdx +42 -0
  53. package/docs/features/dlq/delete.mdx +29 -0
  54. package/docs/features/dlq/restart.mdx +33 -0
  55. package/docs/features/dlq/resume.mdx +37 -0
  56. package/docs/features/dlq.mdx +39 -0
  57. package/docs/features/failure-callback.mdx +102 -0
  58. package/docs/features/failureFunction/advanced.mdx +36 -0
  59. package/docs/features/failureFunction/reliability.mdx +33 -0
  60. package/docs/features/flow-control/monitor.mdx +22 -0
  61. package/docs/features/flow-control/parallelism.mdx +45 -0
  62. package/docs/features/flow-control/rate-period.mdx +46 -0
  63. package/docs/features/flow-control.mdx +164 -0
  64. package/docs/features/invoke/serveMany.mdx +109 -0
  65. package/docs/features/invoke.mdx +39 -0
  66. package/docs/features/notify.mdx +127 -0
  67. package/docs/features/parallel-steps.mdx +41 -0
  68. package/docs/features/retries/prevent-retries.mdx +140 -0
  69. package/docs/features/retries.mdx +93 -0
  70. package/docs/features/wait-for-event.mdx +104 -0
  71. package/docs/features/wait.mdx +44 -0
  72. package/docs/features/webhooks.mdx +116 -0
  73. package/docs/getstarted.mdx +200 -0
  74. package/docs/howto/cancel.mdx +50 -0
  75. package/docs/howto/changes.mdx +33 -0
  76. package/docs/howto/configure.mdx +42 -0
  77. package/docs/howto/failures.mdx +185 -0
  78. package/docs/howto/get-token.mdx +18 -0
  79. package/docs/howto/local-development/development-server.mdx +130 -0
  80. package/docs/howto/local-development/local-tunnel.mdx +73 -0
  81. package/docs/howto/middlewares.mdx +263 -0
  82. package/docs/howto/migrations.mdx +335 -0
  83. package/docs/howto/multi-region.mdx +107 -0
  84. package/docs/howto/parallel-runs.mdx +52 -0
  85. package/docs/howto/readonly-token.mdx +19 -0
  86. package/docs/howto/realtime/basic.mdx +315 -0
  87. package/docs/howto/realtime/human-in-the-loop.mdx +454 -0
  88. package/docs/howto/redact-fields.mdx +61 -0
  89. package/docs/howto/retry-now.mdx +41 -0
  90. package/docs/howto/schedule.mdx +104 -0
  91. package/docs/howto/security.mdx +143 -0
  92. package/docs/howto/singleton.mdx +137 -0
  93. package/docs/howto/start.mdx +69 -0
  94. package/docs/howto/use-webhooks.mdx +256 -0
  95. package/docs/integrations/aisdk.mdx +316 -0
  96. package/docs/integrations/anthropic.mdx +51 -0
  97. package/docs/integrations/datadog.mdx +69 -0
  98. package/docs/integrations/openai.mdx +87 -0
  99. package/docs/integrations/prometheus.mdx +65 -0
  100. package/docs/integrations/resend.mdx +82 -0
  101. package/docs/llms-txt.mdx +4 -0
  102. package/docs/openapi.yaml +2944 -0
  103. package/docs/pricing.mdx +22 -0
  104. package/docs/quickstarts/astro.mdx +185 -0
  105. package/docs/quickstarts/cloudflare-workers.mdx +190 -0
  106. package/docs/quickstarts/express.mdx +190 -0
  107. package/docs/quickstarts/fastapi.mdx +282 -0
  108. package/docs/quickstarts/flask.mdx +282 -0
  109. package/docs/quickstarts/hono.mdx +221 -0
  110. package/docs/quickstarts/nextjs-fastapi.mdx +147 -0
  111. package/docs/quickstarts/nextjs-flask.mdx +147 -0
  112. package/docs/quickstarts/nuxt.mdx +169 -0
  113. package/docs/quickstarts/platforms.mdx +78 -0
  114. package/docs/quickstarts/solidjs.mdx +161 -0
  115. package/docs/quickstarts/svelte.mdx +170 -0
  116. package/docs/quickstarts/tanstack-start.mdx +205 -0
  117. package/docs/quickstarts/vercel-nextjs.mdx +233 -0
  118. package/docs/roadmap.mdx +8 -0
  119. package/docs/sdk/workflow-js.mdx +4 -0
  120. package/docs/sdk/workflow-py.mdx +4 -0
  121. package/docs/steps/api.mdx +64 -0
  122. package/docs/steps/call.mdx +183 -0
  123. package/docs/steps/cancel.mdx +25 -0
  124. package/docs/steps/createWebhook.mdx +40 -0
  125. package/docs/steps/invoke.mdx +100 -0
  126. package/docs/steps/notify.mdx +105 -0
  127. package/docs/steps/run.mdx +150 -0
  128. package/docs/steps/sleep.mdx +97 -0
  129. package/docs/steps/sleepUntil.mdx +88 -0
  130. package/docs/steps/waitForEvent.mdx +60 -0
  131. package/docs/steps/waitForWebhook.mdx +78 -0
  132. package/docs/steps.mdx +108 -0
  133. package/docs/troubleshooting/general.mdx +331 -0
  134. package/docs/troubleshooting/vercel.mdx +82 -0
  135. package/express.d.mts +19 -2
  136. package/express.d.ts +19 -2
  137. package/express.js +670 -159
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +19 -2
  140. package/h3.d.ts +19 -2
  141. package/h3.js +670 -159
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +17 -2
  144. package/hono.d.ts +17 -2
  145. package/hono.js +670 -159
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +50 -21
  148. package/index.d.ts +50 -21
  149. package/index.js +686 -171
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +40 -2
  152. package/nextjs.d.ts +40 -2
  153. package/nextjs.js +670 -159
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +16 -2
  157. package/react-router.d.ts +16 -2
  158. package/react-router.js +670 -159
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CG3BFvO3.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-iJF1IUXk.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +10 -1
  163. package/solidjs.d.ts +10 -1
  164. package/solidjs.js +670 -159
  165. package/solidjs.mjs +1 -1
  166. package/src/platforms/astro.ts +84 -0
  167. package/src/platforms/cloudflare.ts +127 -0
  168. package/src/platforms/express.ts +147 -0
  169. package/src/platforms/h3.ts +105 -0
  170. package/src/platforms/hono.ts +103 -0
  171. package/src/platforms/nextjs.ts +193 -0
  172. package/src/platforms/react-router.ts +92 -0
  173. package/src/platforms/solidjs.ts +59 -0
  174. package/src/platforms/svelte.ts +99 -0
  175. package/src/platforms/tanstack.ts +96 -0
  176. package/src/src/client/dlq.ts +387 -0
  177. package/src/src/client/filter-types.ts +166 -0
  178. package/src/src/client/index.ts +350 -0
  179. package/src/src/client/types.ts +501 -0
  180. package/src/src/client/utils.ts +307 -0
  181. package/src/src/constants.ts +82 -0
  182. package/src/src/context/api/anthropic.ts +58 -0
  183. package/src/src/context/api/base.ts +52 -0
  184. package/src/src/context/api/index.ts +24 -0
  185. package/src/src/context/api/openai.ts +125 -0
  186. package/src/src/context/api/resend.ts +57 -0
  187. package/src/src/context/auto-executor.ts +707 -0
  188. package/src/src/context/context.ts +681 -0
  189. package/src/src/context/index.ts +1 -0
  190. package/src/src/context/provider.ts +37 -0
  191. package/src/src/context/steps.ts +965 -0
  192. package/src/src/error.ts +203 -0
  193. package/src/src/index.ts +13 -0
  194. package/src/src/middleware/default-callbacks.ts +20 -0
  195. package/src/src/middleware/index.ts +2 -0
  196. package/src/src/middleware/logging.ts +39 -0
  197. package/src/src/middleware/manager.ts +148 -0
  198. package/src/src/middleware/middleware.ts +46 -0
  199. package/src/src/middleware/types.ts +72 -0
  200. package/src/src/qstash/headers.ts +397 -0
  201. package/src/src/qstash/step-config.ts +268 -0
  202. package/src/src/qstash/submit-steps.ts +284 -0
  203. package/src/src/serve/authorization.ts +118 -0
  204. package/src/src/serve/index.ts +475 -0
  205. package/src/src/serve/multi-region/handlers.ts +225 -0
  206. package/src/src/serve/multi-region/utils.ts +88 -0
  207. package/src/src/serve/options.ts +241 -0
  208. package/src/src/serve/serve-many.ts +117 -0
  209. package/src/src/serve/utils.ts +11 -0
  210. package/src/src/types.ts +590 -0
  211. package/src/src/utils.ts +141 -0
  212. package/src/src/workflow-parser.ts +472 -0
  213. package/src/src/workflow-requests.ts +575 -0
  214. package/svelte.d.mts +17 -2
  215. package/svelte.d.ts +17 -2
  216. package/svelte.js +670 -159
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +15 -2
  219. package/tanstack.d.ts +15 -2
  220. package/tanstack.js +670 -159
  221. package/tanstack.mjs +1 -1
  222. package/{types-CekOpKvz.d.ts → types-CrgK5P6p.d.mts} +372 -32
  223. package/{types-CekOpKvz.d.mts → types-CrgK5P6p.d.ts} +372 -32
@@ -0,0 +1,39 @@
1
+ ---
2
+ title: Workflow Invoke Overview
3
+ sidebarTitle: "Overview"
4
+ ---
5
+
6
+ You can start another workflow run inside a workflow and await its execution to complete.
7
+ This allows to orchestrate multiple workflows together without external synchronization.
8
+
9
+ When you use `context.invoke`, invoking workflow will wait until the invoked workflow finishes before running the next step.
10
+
11
+ ```typescript
12
+ const {
13
+ body, // response from the invoked workflow
14
+ isFailed, // whether the invoked workflow was canceled
15
+ isCanceled // whether the invoked workflow failed
16
+ } = await context.invoke(
17
+ "analyze-content",
18
+ {
19
+ workflow: analyzeContent,
20
+ body: "test",
21
+ header: {...}, // headers to pass to anotherWorkflow (optional)
22
+ retries, // number of retries (optional, default: 3)
23
+ flowControl, // flow control settings (optional)
24
+ workflowRunId // workflowRunId to set (optional)
25
+ }
26
+ )
27
+ ```
28
+
29
+ You can return a response from a workflow, which will be delivered to invoker workflow run.
30
+
31
+ <Frame caption="You can navigate between the invoker and invoked workflow runs on the dashboard">
32
+ <img src="/img/workflow/invoke.png" alt="You can navigate between the invoker and invoked workflow runs on the dashboard" />
33
+ </Frame>
34
+
35
+ <Note>
36
+ You cannot create an infinite chain of workflow invocations. If you set up an 'invoke loop' where workflows continuously invoke each other, the process will fail once it reaches a depth of 100.
37
+ </Note>
38
+
39
+
@@ -0,0 +1,127 @@
1
+ ---
2
+ title: "Notify"
3
+ ---
4
+
5
+ You can notify all the workflow runs waiting for a specific event ID.
6
+ There are two ways to send a notify request.
7
+
8
+
9
+ ## Notify within Workflow
10
+
11
+ Notifies other workflows waiting for a specific event from within a workflow.
12
+
13
+ <CodeGroup>
14
+ ```typescript TypeScript
15
+ import { serve } from "@upstash/workflow/nextjs";
16
+
17
+ export const { POST } = serve<string>(async (context) => {
18
+ const { orderId, processingResult } = context.requestPayload;
19
+
20
+ await context.run("process-order", async () => {
21
+ // ...
22
+ })
23
+
24
+ const { notifyResponse } = await context.notify(
25
+ "notify-processing-complete",
26
+ `order-${orderId}`,
27
+ {
28
+ orderId,
29
+ status: "completed",
30
+ result: processingResult,
31
+ completedAt: new Date().toISOString()
32
+ }
33
+ );
34
+
35
+ });
36
+ ```
37
+
38
+ </CodeGroup>
39
+
40
+ ## External Notification
41
+
42
+ You can also notify workflows from external systems using the Workflow Client:
43
+
44
+ <CodeGroup>
45
+ ```typescript TypeScript
46
+ import { Client } from "@upstash/workflow";
47
+
48
+ const client = new Client({ token: "<WORKFLOW_TOKEN>" });
49
+
50
+ await client.notify({
51
+ eventId: "order-completed-123",
52
+ eventData: {
53
+ orderId: "123",
54
+ status: "completed",
55
+ deliveryTime: "2 days",
56
+ trackingNumber: "TRK123456"
57
+ }
58
+ });
59
+ ```
60
+
61
+ </CodeGroup>
62
+
63
+ ## Lookback Functionality
64
+
65
+ By default, if you call `notify` before a workflow reaches its `waitForEvent` step, the notification will be lost (race condition). To prevent this, you can provide a `workflowRunId` parameter which enables **lookback** - the notification will be stored and delivered even if sent before the wait step.
66
+
67
+ This is particularly useful when:
68
+ - You trigger a workflow and immediately want to send it an event
69
+ - You have concurrent operations where timing is unpredictable
70
+ - You want to eliminate race conditions in your event-driven workflows
71
+
72
+ <CodeGroup>
73
+ ```typescript TypeScript
74
+ import { Client } from "@upstash/workflow";
75
+
76
+ const client = new Client({ token: "<WORKFLOW_TOKEN>" });
77
+
78
+ // Trigger a workflow and get its run ID
79
+ const { workflowRunId } = await client.trigger({
80
+ url: "https://your-app.com/api/process-order",
81
+ body: { orderId: "123" }
82
+ });
83
+
84
+ // Immediately notify it with lookback enabled
85
+ // The notification will be delivered even if the workflow
86
+ // hasn't reached waitForEvent yet
87
+ await client.notify({
88
+ eventId: "payment-verified",
89
+ eventData: { verified: true, amount: 100 },
90
+ workflowRunId: workflowRunId, // Enables lookback
91
+ });
92
+ ```
93
+
94
+ </CodeGroup>
95
+
96
+ The same also applies to `context.notify` by passing the `workflowRunId` as the fourth argument:
97
+
98
+ <CodeGroup>
99
+ ```typescript TypeScript
100
+ import { serve } from "@upstash/workflow/nextjs";
101
+
102
+ export const { POST } = serve<string>(async (context) => {
103
+ const { orderId, processingResult } = context.requestPayload;
104
+
105
+ await context.run("process-order", async () => {
106
+ // ...
107
+ })
108
+
109
+ const { notifyResponse } = await context.notify(
110
+ "notify-processing-complete",
111
+ `order-${orderId}`,
112
+ {
113
+ orderId,
114
+ status: "completed",
115
+ result: processingResult,
116
+ completedAt: new Date().toISOString()
117
+ },
118
+ "targetWorkflowRunId" // Enables lookback
119
+ );
120
+
121
+ });
122
+ ```
123
+ </CodeGroup>
124
+
125
+ <Note>
126
+ When using lookback with `workflowRunId`, the notification is targeted to a specific workflow run rather than all waiters with that event ID.
127
+ </Note>
@@ -0,0 +1,41 @@
1
+ ---
2
+ title: "Parallel Steps"
3
+ ---
4
+
5
+ Upstash Workflow supports executing multiple steps in parallel.
6
+
7
+ Since each step returns a `Promise`, you can execute multiple steps concurrently by using `Promise.all()`.
8
+ This behavior works out of the box. No additional configuration is required.
9
+
10
+ ```typescript app/api/workflow/route.ts
11
+ import { serve } from "@upstash/workflow/nextjs";
12
+ import { checkInventory, brewCoffee, printReceipt } from "@/utils";
13
+
14
+ export const { POST } = serve(async (context) => {
15
+
16
+ // 👇 Execute steps in parallel
17
+ const [coffeeBeansAvailable, cupsAvailable, milkAvailable] =
18
+ await Promise.all([
19
+ context.run("check-coffee-beans", () => checkInventory("coffee-beans")),
20
+ context.run("check-cups", () => checkInventory("cups")),
21
+ context.run("check-milk", () => checkInventory("milk")),
22
+ ]);
23
+
24
+ });
25
+ ```
26
+
27
+ The results of the parallel steps are available as usual once awaited.
28
+
29
+ The dashboard visualizes parallel execution as shown below:
30
+
31
+ <Frame caption="The workflow executes three steps in parallel">
32
+ <img src="/img/workflow/parallel_steps.png" alt="Parallel workflow steps diagram" />
33
+ </Frame>
34
+
35
+ You can also await different step types together. For example, you can run a `context.call()` and a `context.run()` in parallel.
36
+
37
+ <Warning>
38
+ Whether executing sequentially or in parallel, you should always
39
+ <code>await</code> all promises in a workflow.
40
+ Leaving promises unawaited may cause unexpected behavior.
41
+ </Warning>
@@ -0,0 +1,140 @@
1
+ ---
2
+ title: "Prevent Retries"
3
+ ---
4
+
5
+ It is recommended to enable retries for workflow runs to improve reliability.
6
+
7
+ However, in some cases, you may want to stop execution immediately when an error occurs, without causing additional retries.
8
+ Upstash Workflow provides several mechanisms to terminate workflow execution gracefully.
9
+
10
+ ## Using `WorkflowNonRetryableError`
11
+
12
+ `WorkflowNonRetryableError` lets you explicitly fail a workflow without entering the retry cycle.
13
+
14
+ When thrown, the workflow run is marked as failed, which:
15
+ - Triggers the failure function (if defined)
16
+ - Sends the workflow run to the DLQ
17
+
18
+ ```ts TypeScript highlight={7}
19
+ export const { POST } = serve<{ topic: string }>(async (context) => {
20
+ const payload = context.requestPayload
21
+
22
+ const isExists = await context.run("is-user-exists", () => { ... });
23
+
24
+ if (!isExists) {
25
+ throw new WorkflowNonRetryableError("The user does not exists!")
26
+ }
27
+ })
28
+ ```
29
+
30
+ ## Using `context.cancel()`
31
+
32
+ You can cancel a workflow run explicitly from inside the workflow.
33
+
34
+ When canceled, the run is labeled as canceled instead of failed. This means:
35
+ - The failure handler will **NOT** be triggered
36
+ - The workflow will **NOT** be sent to the DLQ
37
+
38
+ <CodeGroup>
39
+ ```typescript highlight={10-11} TypeScript
40
+ export const { POST } = serve<{ orderId: string }>(async (context) => {
41
+ const { orderId } = context.requestPayload;
42
+
43
+ // Check if order is still valid
44
+ const orderStatus = await context.run("check-order-status", async () => {
45
+ return await getOrderStatus(orderId);
46
+ });
47
+
48
+ if (orderStatus === "cancelled") {
49
+ // Stop execution gracefully without error
50
+ await context.cancel();
51
+ return;
52
+ }
53
+
54
+ // Continue processing if order is valid
55
+ await context.run("process-order", async () => {
56
+ return await processOrder(orderId);
57
+ });
58
+ });
59
+ ```
60
+
61
+ ```python Python
62
+ @serve.post("/graceful-cancellation")
63
+ async def graceful_cancellation(context: AsyncWorkflowContext[dict]) -> None:
64
+ order_id = context.request_payload["order_id"]
65
+
66
+ async def _check_order_status():
67
+ return await get_order_status(order_id)
68
+
69
+ # Check if order is still valid
70
+ order_status = await context.run("check-order-status", _check_order_status)
71
+
72
+ if order_status == "cancelled":
73
+ # Stop execution gracefully without error
74
+ await context.cancel()
75
+ return
76
+
77
+ # Continue processing if order is valid
78
+ async def _process_order():
79
+ return await process_order(order_id)
80
+
81
+ await context.run("process-order", _process_order)
82
+ ```
83
+ </CodeGroup>
84
+
85
+ ## Using conditional execution
86
+
87
+ You can also use guard conditions to skip certain steps and exit early, without throwing errors or canceling the workflow.
88
+
89
+ In this case, the workflow run completes successfully because no error was raised.
90
+ <CodeGroup>
91
+ ```typescript TypeScript highlight={10-11}
92
+ export const { POST } = serve<{ data: any }>(async (context) => {
93
+ const { data } = context.requestPayload;
94
+
95
+ // Check if order is still valid
96
+ const orderStatus = await context.run("check-order-status", async () => {
97
+ return await getOrderStatus(orderId);
98
+ });
99
+
100
+ if (orderStatus === "not-found") {
101
+ // Stop execution without error
102
+ return;
103
+ }
104
+
105
+ // Continue processing if order is valid
106
+ await context.run("process-order", async () => {
107
+ return await processOrder(orderId);
108
+ });
109
+ });
110
+ ```
111
+
112
+ ```python Python
113
+ @serve.post("/conditional-execution")
114
+ async def conditional_execution(context: AsyncWorkflowContext[dict]) -> None:
115
+ data = context.request_payload["data"]
116
+
117
+ async def _validate_data():
118
+ return validate_input_data(data)
119
+
120
+ # Validate data first
121
+ validation_result = await context.run("validate-data", _validate_data)
122
+
123
+ if not validation_result["is_valid"]:
124
+ # Log the validation failure
125
+ async def _log_validation_failure():
126
+ await log_validation_error(validation_result["errors"])
127
+
128
+ await context.run("log-validation-failure", _log_validation_failure)
129
+
130
+ # Stop execution without error
131
+ return
132
+
133
+ # Only execute if validation passes
134
+ async def _process_valid_data():
135
+ return await process_data(data)
136
+
137
+ await context.run("process-valid-data", _process_valid_data)
138
+ ```
139
+ </CodeGroup>
140
+
@@ -0,0 +1,93 @@
1
+ ---
2
+ title: Workflow Retries Overview
3
+ sidebarTitle: "Overview"
4
+ ---
5
+
6
+ Upstash Workflow provides an automatic retry mechanism to improve reliability and make workflows resilient against temporary failures.
7
+ Workflow automatically handles transient errors such as network issues or service unavailability.
8
+
9
+ ## How Retries Work
10
+
11
+ When a step fails, Upstash Workflow automatically retries the failed step with configurable retry attempts and delay strategy.
12
+ This allows temporary issues to resolve without manual intervention.
13
+
14
+ <Frame caption="A failing step is automatically retried three times by default">
15
+ <img src="/img/workflow/automatic_retry.png" alt="A failing step is automatically retried three times by default" />
16
+ </Frame>
17
+
18
+ By default, the retry count is set to **3**, and an **exponential backoff** delay strategy is used.
19
+
20
+ ```javascript Default Backoff Algorithm
21
+ // n = how many times this request has been retried
22
+ delay = min(86400, e ** (2.5*n)) // in seconds
23
+ ```
24
+
25
+ | Retry Attempt | Algorithm | Delay |
26
+ |---------------|--------------|--------|
27
+ | 1 | $$e^{2.5}$$ | 12s |
28
+ | 2 | $$e^5$$ | 2m28s |
29
+ | 3 | $$e^{7.5}$$ | 30m8s |
30
+ | 4+ | $$86400$$ | 24h |
31
+
32
+ ## Configuration
33
+
34
+ You can configure retry behavior when starting a new workflow run.
35
+
36
+ ### Configure Retry Attempt Count
37
+
38
+ You can specify how many times a step should be retried upon failure.
39
+
40
+ ```typescript Configure Retry Attempt Count
41
+ import { Client } from "@upstash/workflow";
42
+
43
+ const client = new Client({ token: "<QSTASH_TOKEN>" })
44
+
45
+ const { workflowRunId } = await client.trigger({
46
+ url: "https://<YOUR_WORKFLOW_ENDPOINT>/<YOUR-WORKFLOW-ROUTE>",
47
+ retries: 3
48
+ })
49
+ ```
50
+
51
+ ### Configure Retry Delay Strategy
52
+
53
+ Retry delay is the time to wait before trying again after a failure. You can define a custom retry delay strategy.
54
+
55
+ The delay is defined as a math expression that is calculated on every retry.
56
+ The expression can use the `retried` variable, which represents how many times the step has already retried (starting from 0).
57
+
58
+ To apply a constant delay, you can simply provide a fixed value.
59
+
60
+ The expression must return the delay in **milliseconds**.
61
+
62
+ ```typescript Configure Retry Delay Strategy
63
+ import { Client } from "@upstash/workflow";
64
+
65
+ const client = new Client({ token: "<QSTASH_TOKEN>" })
66
+
67
+ const { workflowRunId } = await client.trigger({
68
+ url: "https://<YOUR_WORKFLOW_ENDPOINT>/<YOUR-WORKFLOW-ROUTE>",
69
+ retries: 3,
70
+ retryDelay: "(1 + retried) * 1000"
71
+ })
72
+ ```
73
+
74
+ ### Configure Retries for a Single Step
75
+
76
+ The retry configuration of a run applies to all of its steps. You can override it for a single `context.run`
77
+ step by passing `retries` and `retryDelay` as the third argument:
78
+
79
+ ```typescript Configure Retries for a Single Step
80
+ export const { POST } = serve(async (context) => {
81
+ await context.run(
82
+ "call flaky service",
83
+ () => callFlakyService(),
84
+ {
85
+ retries: 5,
86
+ retryDelay: "1000",
87
+ }
88
+ );
89
+ });
90
+ ```
91
+
92
+ Any field left unset falls back to the configuration the run was triggered with.
93
+ The step-level options can be combined with [step-level flow control](/workflow/features/flow-control#step-level-flow-control).
@@ -0,0 +1,104 @@
1
+ ---
2
+ title: Workflow Wait for Event Overview
3
+ sidebarTitle: "Overview"
4
+ ---
5
+
6
+ Wait for Event feature that allows you to pause workflow execution until an external event occurs.
7
+
8
+ This feature enables you to build asynchronous workflows that can wait for user interactions, external system responses, or any other events without consuming compute resources.
9
+
10
+ ## How Wait for Event Works
11
+
12
+ When you use `context.waitForEvent()` in your workflow, Upstash Workflow automatically pauses execution and waits for an external notification to resume.
13
+ This happens without keeping your serverless function running, making it cost-effective and reliable for event-driven workflows.
14
+
15
+ Each waiter has a timeout duration to wait for the event and then fires automatically.
16
+
17
+ <Note>
18
+ Wait for Event timeouts have limits based on your pricing plan:
19
+ - **Free**: Maximum timeout of 7 days
20
+ - **Pay-as-you-go**: Maximum timeout of 1 year
21
+ - **Fixed pricing**: Custom timeouts (no limit)
22
+ </Note>
23
+
24
+ ## Race Condition Between Wait and Notify
25
+
26
+ A race condition can occur when `notify` is called before `waitForEvent` is executed.
27
+ In this scenario, the notification will be sent but no workflow will be waiting to receive it, causing the event to be lost.
28
+
29
+ ### Solutions
30
+
31
+ There are three ways to handle race conditions:
32
+
33
+ 1. **Use lookback with `workflowRunId`** (Recommended for targeted notifications)
34
+ 2. **Use [Webhooks](/workflow/features/webhooks)** (Recommended for general use)
35
+ 3. **Check and retry** (Manual approach)
36
+
37
+ #### Option 1: Lookback with workflowRunId
38
+
39
+ When you know which specific workflow run should receive the notification, you can provide a `workflowRunId` to enable lookback. The notification will be stored and delivered even if sent before `waitForEvent`:
40
+
41
+ <CodeGroup>
42
+ ```typescript TypeScript
43
+ import { Client } from "@upstash/workflow";
44
+
45
+ const client = new Client({ token: "<WORKFLOW_TOKEN>" });
46
+
47
+ // Trigger a workflow
48
+ const { workflowRunId } = await client.trigger({
49
+ url: "https://your-app.com/api/process-order",
50
+ body: { orderId: "123" }
51
+ });
52
+
53
+ // Immediately notify with lookback - no race condition!
54
+ await client.notify({
55
+ eventId: "payment-verified",
56
+ eventData: { verified: true },
57
+ workflowRunId: workflowRunId, // Enables lookback
58
+ });
59
+ ```
60
+ </CodeGroup>
61
+
62
+ #### Option 2: Use Webhooks
63
+
64
+ [Webhooks](/workflow/features/webhooks) have built-in lookback and are safer against timing issues for general event handling.
65
+
66
+ #### Option 3: Check and Retry
67
+
68
+ Alternatively, you can check the response of the `notify` operation and retry if needed:
69
+
70
+ <CodeGroup>
71
+ ```typescript TypeScript
72
+ import { Client } from "@upstash/workflow";
73
+
74
+ const client = new Client({ token: "<WORKFLOW_TOKEN>" });
75
+
76
+ const result = await client.notify({
77
+ eventId,
78
+ eventData,
79
+ });
80
+
81
+ // `result` is a list with one entry per notified workflow
82
+ if (result.length > 0) {
83
+ console.log(`Notified ${result.length} workflows`);
84
+ } else {
85
+ // If no workflows were waiting, wait and retry once
86
+ console.log("No workflows waiting, retrying in 5 seconds...");
87
+ await new Promise((resolve) => setTimeout(resolve, 5000));
88
+
89
+ const retryResult = await client.notify({
90
+ eventId,
91
+ eventData,
92
+ });
93
+ console.log(`Retry notified ${retryResult.length} workflows`);
94
+ }
95
+ ```
96
+ </CodeGroup>
97
+
98
+ ## Selecting an Event ID
99
+
100
+ When a workflow run waits on an event ID, it's appended to a list of waiters for the event ID.
101
+
102
+ When a notify request is sent, all workflow runs waiting for that event are notified sequentially.
103
+ To avoid heavy notify operations, it’s recommended to use unique event IDs instead of generic ones.
104
+ For example, instead of waiting on `user-sent-verification`, wait the workflow on `user-{userId}-sent-verification` event.
@@ -0,0 +1,44 @@
1
+ ---
2
+ title: "Wait"
3
+ ---
4
+
5
+ You can pause a workflow run with the `waitForEvent` step. An event is uniquely identified by event ID.
6
+
7
+ The workflow will resume when the matching event is published.
8
+
9
+ `waitForEvent` supports configurable timeouts to prevent workflows from waiting indefinitely.
10
+ When a timeout occurs, the returned object includes `timeout: true`, allowing you to handle the failure case gracefully (for example, cancel an order, notify the user, or retry later).
11
+
12
+ <Tip>
13
+ If no timeout is specified, the default is **7 days**.
14
+ </Tip>
15
+
16
+ <CodeGroup>
17
+ ```typescript TypeScript
18
+ import { serve } from "@upstash/workflow/nextjs";
19
+
20
+ export const { POST } = serve<string>(async (context) => {
21
+ const { orderId, userEmail } = context.requestPayload;
22
+
23
+ // Wait for order processing completion
24
+ const { eventData, timeout } = await context.waitForEvent(
25
+ "wait-for-order-processing",
26
+ `order-${orderId}`,
27
+ {
28
+ timeout: "1d" // 1 day timeout
29
+ }
30
+ );
31
+
32
+ if (timeout) {
33
+ // Handle timeout scenario
34
+ await context.run("handle-timeout", async () => {
35
+ return await handleOrderTimeout(orderId, userEmail);
36
+ });
37
+ return;
38
+ }
39
+
40
+ });
41
+ ```
42
+
43
+ </CodeGroup>
44
+