workflow 5.0.0-beta.1 → 5.0.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/api-workflow.d.ts +1 -1
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +2 -2
- package/dist/api.d.ts +5 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +14 -2
- package/dist/astro.js +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/builtins.d.ts +17 -0
- package/dist/internal/builtins.d.ts.map +1 -1
- package/dist/internal/builtins.js +65 -1
- package/dist/internal/class-serialization.js +1 -1
- package/dist/internal/errors.js +1 -1
- package/dist/nest.js +1 -1
- package/dist/next.cjs +1 -1
- package/dist/nitro.js +1 -1
- package/dist/nuxt.js +1 -1
- package/dist/observability.d.ts +1 -1
- package/dist/observability.js +2 -2
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2 -2
- package/dist/stdlib.js +1 -1
- package/dist/sveltekit.js +1 -1
- package/dist/typescript-plugin.cjs +1 -1
- package/dist/vite.js +1 -1
- package/dist/workflow.js +1 -1
- package/docs/ai/index.mdx +6 -5
- package/docs/ai/resumable-streams.mdx +1 -1
- package/docs/api-reference/vitest/index.mdx +28 -1
- package/docs/api-reference/workflow/create-webhook.mdx +37 -18
- package/docs/api-reference/workflow/experimental-set-attributes.mdx +63 -0
- package/docs/api-reference/workflow/get-workflow-metadata.mdx +34 -0
- package/docs/api-reference/workflow/index.mdx +3 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +0 -4
- package/docs/api-reference/workflow-ai/index.mdx +0 -5
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +0 -4
- package/docs/api-reference/workflow-api/start.mdx +5 -4
- package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
- package/docs/api-reference/workflow-next/with-workflow.mdx +34 -2
- package/docs/changelog/attributes-mvp.mdx +368 -0
- package/docs/changelog/eager-processing.mdx +595 -0
- package/docs/changelog/index.mdx +2 -1
- package/docs/cookbook/advanced/child-workflows.mdx +313 -0
- package/docs/cookbook/advanced/meta.json +9 -0
- package/docs/cookbook/advanced/publishing-libraries.mdx +336 -0
- package/docs/cookbook/advanced/serializable-steps.mdx +147 -0
- package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +156 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +154 -0
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +255 -0
- package/docs/cookbook/agent-patterns/meta.json +4 -0
- package/docs/cookbook/common-patterns/batching.mdx +105 -0
- package/docs/cookbook/common-patterns/idempotency.mdx +107 -0
- package/docs/cookbook/common-patterns/meta.json +15 -0
- package/docs/cookbook/common-patterns/rate-limiting.mdx +228 -0
- package/docs/cookbook/common-patterns/saga.mdx +247 -0
- package/docs/cookbook/common-patterns/scheduling.mdx +129 -0
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +99 -0
- package/docs/cookbook/common-patterns/webhooks.mdx +185 -0
- package/docs/cookbook/common-patterns/workflow-composition.mdx +111 -0
- package/docs/cookbook/index.mdx +38 -0
- package/docs/cookbook/integrations/ai-sdk.mdx +383 -0
- package/docs/cookbook/integrations/chat-sdk.mdx +307 -0
- package/docs/cookbook/integrations/meta.json +4 -0
- package/docs/cookbook/integrations/sandbox.mdx +520 -0
- package/docs/cookbook/meta.json +5 -0
- package/docs/deploying/building-a-world.mdx +1 -1
- package/docs/deploying/world/local-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +6 -4
- package/docs/deploying/world/vercel-world.mdx +3 -1
- package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
- package/docs/errors/hook-conflict.mdx +56 -4
- package/docs/errors/index.mdx +3 -0
- package/docs/errors/runtime-decryption-failed.mdx +77 -0
- package/docs/errors/start-invalid-workflow-function.mdx +1 -1
- package/docs/foundations/cancellation.mdx +460 -0
- package/docs/foundations/errors-and-retries.mdx +7 -3
- package/docs/foundations/index.mdx +3 -3
- package/docs/foundations/meta.json +3 -2
- package/docs/foundations/serialization.mdx +78 -42
- package/docs/foundations/starting-workflows.mdx +6 -2
- package/docs/foundations/versioning.mdx +263 -0
- package/docs/getting-started/astro.mdx +6 -0
- package/docs/getting-started/index.mdx +13 -7
- package/docs/getting-started/meta.json +3 -1
- package/docs/getting-started/nestjs.mdx +8 -0
- package/docs/getting-started/next.mdx +5 -3
- package/docs/getting-started/nitro.mdx +22 -0
- package/docs/getting-started/python.mdx +165 -0
- package/docs/getting-started/sveltekit.mdx +6 -0
- package/docs/getting-started/tanstack-start.mdx +241 -0
- package/docs/how-it-works/cancellation.mdx +287 -0
- package/docs/how-it-works/code-transform.mdx +2 -2
- package/docs/how-it-works/event-sourcing.mdx +2 -2
- package/docs/how-it-works/meta.json +2 -1
- package/docs/internal/index.mdx +19 -0
- package/docs/internal/meta.json +5 -0
- package/docs/internal/serializable-abort-controller.mdx +148 -0
- package/docs/meta.json +1 -0
- package/docs/migration-guides/index.mdx +34 -0
- package/docs/migration-guides/meta.json +9 -0
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +358 -0
- package/docs/migration-guides/migrating-from-inngest.mdx +304 -0
- package/docs/migration-guides/migrating-from-temporal.mdx +313 -0
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +328 -0
- package/docs/observability/attributes.mdx +66 -0
- package/docs/observability/index.mdx +9 -1
- package/docs/observability/meta.json +1 -1
- package/package.json +14 -13
- package/docs/foundations/common-patterns.mdx +0 -265
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Human-in-the-Loop
|
|
3
|
+
description: Pause an AI agent to wait for human approval, then resume based on the decision.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Use defineHook with the tool call ID to suspend an agent for human approval, with an optional timeout.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
Use this pattern when an AI agent needs human confirmation before performing a consequential action like booking, purchasing, or publishing. The workflow suspends without consuming resources until the human responds.
|
|
9
|
+
|
|
10
|
+
## When to use this
|
|
11
|
+
|
|
12
|
+
- Booking confirmations where users must approve before charges are made
|
|
13
|
+
- Content publishing gates where an editor must sign off
|
|
14
|
+
- Any agent action where the cost of getting it wrong justifies a human check
|
|
15
|
+
- Actions with side effects that can't be easily undone
|
|
16
|
+
|
|
17
|
+
## Pattern
|
|
18
|
+
|
|
19
|
+
Create a typed hook using `defineHook()`. When the agent calls the approval tool, the tool emits a custom data part to the stream so the client can render approval controls, then creates a hook and suspends. An API route resumes the hook with the decision.
|
|
20
|
+
|
|
21
|
+
### Workflow
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
25
|
+
import { defineHook, sleep, getWritable } from "workflow";
|
|
26
|
+
import { z } from "zod";
|
|
27
|
+
import type { ModelMessage, UIMessageChunk } from "ai";
|
|
28
|
+
|
|
29
|
+
// Exported so the approval API route can call .resume()
|
|
30
|
+
export const bookingApprovalHook = defineHook({ // [!code highlight]
|
|
31
|
+
schema: z.object({
|
|
32
|
+
approved: z.boolean(),
|
|
33
|
+
comment: z.string().optional(),
|
|
34
|
+
}),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
async function searchFlights({ from, to, date }: {
|
|
38
|
+
from: string;
|
|
39
|
+
to: string;
|
|
40
|
+
date: string;
|
|
41
|
+
}) {
|
|
42
|
+
"use step";
|
|
43
|
+
const res = await fetch(
|
|
44
|
+
`https://api.example.com/flights?from=${from}&to=${to}&date=${date}`
|
|
45
|
+
);
|
|
46
|
+
return res.json();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function confirmBooking({ flightId, passenger }: {
|
|
50
|
+
flightId: string;
|
|
51
|
+
passenger: string;
|
|
52
|
+
}) {
|
|
53
|
+
"use step";
|
|
54
|
+
const res = await fetch("https://api.example.com/bookings", {
|
|
55
|
+
method: "POST",
|
|
56
|
+
body: JSON.stringify({ flightId, passenger }),
|
|
57
|
+
});
|
|
58
|
+
return res.json();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Stream a custom data part so the client can render the approval UI.
|
|
62
|
+
// This MUST run before the hook suspends the workflow — otherwise
|
|
63
|
+
// the tool-invocation won't appear in the stream until the tool returns,
|
|
64
|
+
// and the client would have no way to show approval buttons.
|
|
65
|
+
async function emitApprovalRequest(details: {
|
|
66
|
+
flightId: string;
|
|
67
|
+
passenger: string;
|
|
68
|
+
price: number;
|
|
69
|
+
toolCallId: string;
|
|
70
|
+
}) {
|
|
71
|
+
"use step";
|
|
72
|
+
const writer = getWritable<UIMessageChunk>().getWriter();
|
|
73
|
+
try {
|
|
74
|
+
await writer.write({
|
|
75
|
+
type: "data-approval-needed", // [!code highlight]
|
|
76
|
+
id: details.toolCallId,
|
|
77
|
+
data: details,
|
|
78
|
+
} as UIMessageChunk);
|
|
79
|
+
} finally {
|
|
80
|
+
writer.releaseLock();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Stream the resolution so the client can update the approval card.
|
|
85
|
+
async function emitApprovalResolved(details: {
|
|
86
|
+
toolCallId: string;
|
|
87
|
+
result: string;
|
|
88
|
+
}) {
|
|
89
|
+
"use step";
|
|
90
|
+
const writer = getWritable<UIMessageChunk>().getWriter();
|
|
91
|
+
try {
|
|
92
|
+
await writer.write({
|
|
93
|
+
type: "data-approval-resolved", // [!code highlight]
|
|
94
|
+
id: details.toolCallId,
|
|
95
|
+
data: details,
|
|
96
|
+
} as UIMessageChunk);
|
|
97
|
+
} finally {
|
|
98
|
+
writer.releaseLock();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// No "use step" — hooks are workflow-level primitives
|
|
103
|
+
async function requestBookingApproval(
|
|
104
|
+
{ flightId, passenger, price }: {
|
|
105
|
+
flightId: string;
|
|
106
|
+
passenger: string;
|
|
107
|
+
price: number;
|
|
108
|
+
},
|
|
109
|
+
{ toolCallId }: { toolCallId: string }
|
|
110
|
+
) {
|
|
111
|
+
// Emit to the stream before suspending so the UI can show buttons
|
|
112
|
+
await emitApprovalRequest({ flightId, passenger, price, toolCallId }); // [!code highlight]
|
|
113
|
+
|
|
114
|
+
const hook = bookingApprovalHook.create({ token: toolCallId });
|
|
115
|
+
|
|
116
|
+
// Race: human decision vs. timeout
|
|
117
|
+
const result = await Promise.race([
|
|
118
|
+
hook.then((payload) => ({ type: "decision" as const, ...payload })),
|
|
119
|
+
sleep("24h").then(() => ({ type: "timeout" as const, approved: false as const })),
|
|
120
|
+
]);
|
|
121
|
+
|
|
122
|
+
if (result.type === "timeout") {
|
|
123
|
+
const msg = "Booking request expired.";
|
|
124
|
+
await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
|
|
125
|
+
return msg;
|
|
126
|
+
}
|
|
127
|
+
if (!result.approved) {
|
|
128
|
+
const msg = `Rejected: ${result.comment || "No reason given"}`;
|
|
129
|
+
await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
|
|
130
|
+
return msg;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const booking = await confirmBooking({ flightId, passenger });
|
|
134
|
+
const msg = `Booked! Confirmation: ${booking.confirmationId}`;
|
|
135
|
+
await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
|
|
136
|
+
return msg;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export async function bookingAgent(messages: ModelMessage[]) {
|
|
140
|
+
"use workflow";
|
|
141
|
+
|
|
142
|
+
const agent = new DurableAgent({
|
|
143
|
+
model: "anthropic/claude-haiku-4.5",
|
|
144
|
+
instructions: "You help book flights. Always request approval before booking.",
|
|
145
|
+
tools: {
|
|
146
|
+
searchFlights: {
|
|
147
|
+
description: "Search for available flights",
|
|
148
|
+
inputSchema: z.object({
|
|
149
|
+
from: z.string().describe("Departure airport code"),
|
|
150
|
+
to: z.string().describe("Arrival airport code"),
|
|
151
|
+
date: z.string().describe("Travel date (YYYY-MM-DD)"),
|
|
152
|
+
}),
|
|
153
|
+
execute: searchFlights,
|
|
154
|
+
},
|
|
155
|
+
requestBookingApproval: {
|
|
156
|
+
description: "Request human approval before booking a flight",
|
|
157
|
+
inputSchema: z.object({
|
|
158
|
+
flightId: z.string().describe("Flight ID to book"),
|
|
159
|
+
passenger: z.string().describe("Passenger name"),
|
|
160
|
+
price: z.number().describe("Total price"),
|
|
161
|
+
}),
|
|
162
|
+
execute: requestBookingApproval,
|
|
163
|
+
},
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
await agent.stream({
|
|
168
|
+
messages,
|
|
169
|
+
writable: getWritable<UIMessageChunk>(),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### Approval API route
|
|
175
|
+
|
|
176
|
+
The approval route imports the hook definition and calls `.resume()` with the tool call ID as the token:
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
import { bookingApprovalHook } from "@/app/workflows/booking-agent";
|
|
180
|
+
|
|
181
|
+
export async function POST(req: Request) {
|
|
182
|
+
const { toolCallId, approved, comment } = await req.json();
|
|
183
|
+
|
|
184
|
+
await bookingApprovalHook.resume(toolCallId, { approved, comment }); // [!code highlight]
|
|
185
|
+
|
|
186
|
+
return Response.json({ success: true });
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Client rendering
|
|
191
|
+
|
|
192
|
+
Listen for `data-approval-needed` and `data-approval-resolved` custom data parts in the message stream. The approval tool invocation itself won't appear until the tool returns, so the custom data parts are the mechanism for showing and updating the approval UI.
|
|
193
|
+
|
|
194
|
+
```tsx
|
|
195
|
+
// Scan all messages for the resolution
|
|
196
|
+
const approvalResult = messages
|
|
197
|
+
.flatMap((m) => m.parts)
|
|
198
|
+
.find((p) => p.type === "data-approval-resolved")
|
|
199
|
+
?.data?.result;
|
|
200
|
+
|
|
201
|
+
// In your message parts loop:
|
|
202
|
+
{message.parts.map((part, i) => {
|
|
203
|
+
if (part.type === "data-approval-needed") { // [!code highlight]
|
|
204
|
+
const { flightId, passenger, price, toolCallId } = part.data;
|
|
205
|
+
if (approvalResult) {
|
|
206
|
+
return <div key={i}>Result: {approvalResult}</div>;
|
|
207
|
+
}
|
|
208
|
+
return (
|
|
209
|
+
<div key={i} className="rounded-lg border p-4 space-y-3">
|
|
210
|
+
<div className="text-sm">
|
|
211
|
+
<div>Flight: {flightId}</div>
|
|
212
|
+
<div>Passenger: {passenger}</div>
|
|
213
|
+
<div>Price: ${price}</div>
|
|
214
|
+
</div>
|
|
215
|
+
<div className="flex gap-2">
|
|
216
|
+
<button onClick={() => approve(toolCallId)}>Approve</button> {/* [!code highlight] */}
|
|
217
|
+
<button onClick={() => reject(toolCallId)}>Reject</button> {/* [!code highlight] */}
|
|
218
|
+
</div>
|
|
219
|
+
</div>
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
// Hide the requestBookingApproval tool-invocation part
|
|
223
|
+
if (part.type === "tool-invocation" &&
|
|
224
|
+
part.toolInvocation.toolName === "requestBookingApproval") {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
// ... other part types
|
|
228
|
+
})}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
## How it works
|
|
232
|
+
|
|
233
|
+
1. **`defineHook()` with schema** — creates a typed hook with Zod validation. The approval payload is validated before the workflow receives it.
|
|
234
|
+
2. **`toolCallId` as token** — the approval tool uses the tool call ID as the hook token, naturally linking the hook to the specific tool invocation.
|
|
235
|
+
3. **`emitApprovalRequest` step** — writes a `data-approval-needed` custom data part to the stream *before* the hook suspends. Without this, the client would never see the approval controls because tool invocations don't stream until the tool returns.
|
|
236
|
+
4. **No `"use step"` on the approval tool** — the tool runs at the workflow level because `defineHook().create()` is a workflow primitive. It calls step functions (`emitApprovalRequest`, `emitApprovalResolved`, `confirmBooking`) for I/O.
|
|
237
|
+
5. **`Promise.race` with sleep** — the approval races against a durable timeout. If nobody responds, the workflow continues with an expiration message.
|
|
238
|
+
6. **`emitApprovalResolved` step** — writes the outcome to the stream so the client can update the card immediately, without waiting for the tool-invocation result.
|
|
239
|
+
|
|
240
|
+
## Adapting to your use case
|
|
241
|
+
|
|
242
|
+
- **Change the approval schema** — add fields like `reason`, `amount`, `reviewerEmail` to match your domain.
|
|
243
|
+
- **Multiple approval gates** — the pattern works for any number of tools. Each tool creates its own hook with its own `toolCallId`.
|
|
244
|
+
- **Escalation** — if the first approver doesn't respond, use `sleep()` + another hook to escalate to a backup reviewer.
|
|
245
|
+
- **Adjust timeout** — use `"24h"` for production, shorter durations for demos.
|
|
246
|
+
- **Workflow-level vs step tools** — tools that use `sleep()`, `defineHook()`, or other workflow primitives must NOT use `"use step"`. Tools with only I/O (API calls, DB queries) should use `"use step"` for retries.
|
|
247
|
+
|
|
248
|
+
## Key APIs
|
|
249
|
+
|
|
250
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
251
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — declares step functions with retries
|
|
252
|
+
- [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook with schema validation
|
|
253
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep) — durable timeout for approval expiry
|
|
254
|
+
- [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream custom data parts from steps
|
|
255
|
+
- [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — durable agent with tool definitions
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Batching & Parallel Processing
|
|
3
|
+
description: Process large collections in parallel batches with failure isolation between groups.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Split items into fixed-size batches, process each batch concurrently with Promise.allSettled, and pace batches with sleep to avoid overloading downstream services.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
Use batching when you need to process a large list of items in parallel while controlling concurrency. Items are split into fixed-size batches, each batch runs concurrently, and failures in one batch don't affect others.
|
|
9
|
+
|
|
10
|
+
## When to use this
|
|
11
|
+
|
|
12
|
+
- Bulk data imports (contacts, orders, products from a CSV)
|
|
13
|
+
- Processing hundreds or thousands of items against external APIs
|
|
14
|
+
- Calling rate-limited APIs where you need to control concurrency
|
|
15
|
+
- Any fan-out where you want failure isolation between groups
|
|
16
|
+
|
|
17
|
+
## How it works
|
|
18
|
+
|
|
19
|
+
1. Records are split into fixed-size batches.
|
|
20
|
+
2. Each batch runs in parallel via `Promise.allSettled` — failures in one record don't affect others.
|
|
21
|
+
3. A `sleep()` between batches paces requests to avoid overloading downstream services.
|
|
22
|
+
4. After all batches, a summary is returned with succeeded/failed counts.
|
|
23
|
+
|
|
24
|
+
## Pattern
|
|
25
|
+
|
|
26
|
+
The workflow splits records into chunks, processes each chunk concurrently, tracks results per batch, and returns a final tally.
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { sleep } from "workflow";
|
|
30
|
+
|
|
31
|
+
type Record = { name: string; email: string; role: string };
|
|
32
|
+
|
|
33
|
+
declare function processRecord(record: Record): Promise<string>; // @setup
|
|
34
|
+
|
|
35
|
+
export async function batchImport(records: Record[], batchSize: number) {
|
|
36
|
+
"use workflow";
|
|
37
|
+
|
|
38
|
+
let totalSucceeded = 0;
|
|
39
|
+
let totalFailed = 0;
|
|
40
|
+
|
|
41
|
+
for (let i = 0; i < records.length; i += batchSize) {
|
|
42
|
+
const batch = records.slice(i, i + batchSize);
|
|
43
|
+
|
|
44
|
+
// Run batch in parallel — failures are isolated per record
|
|
45
|
+
const outcomes = await Promise.allSettled( // [!code highlight]
|
|
46
|
+
batch.map((record) => processRecord(record))
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
for (let j = 0; j < outcomes.length; j++) {
|
|
50
|
+
if (outcomes[j].status === "fulfilled") {
|
|
51
|
+
totalSucceeded++;
|
|
52
|
+
} else {
|
|
53
|
+
totalFailed++;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Pace between batches to avoid overloading downstream
|
|
58
|
+
if (i + batchSize < records.length) {
|
|
59
|
+
await sleep("1s"); // [!code highlight]
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return { total: records.length, succeeded: totalSucceeded, failed: totalFailed };
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Step function
|
|
68
|
+
|
|
69
|
+
Each record is processed in its own step with full Node.js access and automatic retries.
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
type Record = { name: string; email: string; role: string };
|
|
73
|
+
|
|
74
|
+
async function processRecord(record: Record): Promise<string> {
|
|
75
|
+
"use step";
|
|
76
|
+
const res = await fetch(`https://api.example.com/contacts`, {
|
|
77
|
+
method: "POST",
|
|
78
|
+
body: JSON.stringify(record),
|
|
79
|
+
});
|
|
80
|
+
if (!res.ok) throw new Error(`Failed to import ${record.email}`);
|
|
81
|
+
const { id } = await res.json();
|
|
82
|
+
return id;
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Adapting to your use case
|
|
87
|
+
|
|
88
|
+
- Replace the `Record` type with your actual data shape (orders, images, products, etc.).
|
|
89
|
+
- Replace `processRecord()` with your real import logic — DB upserts, API calls, file processing.
|
|
90
|
+
- Tune `batchSize` and the `sleep()` duration to match your downstream rate limits.
|
|
91
|
+
- Add or remove tracking as needed — the pattern works with any item type.
|
|
92
|
+
|
|
93
|
+
## Tips
|
|
94
|
+
|
|
95
|
+
- **Use `Promise.allSettled` over `Promise.all`** when you want to continue even if some items fail. `Promise.all` rejects on the first failure; `allSettled` waits for everything and tells you what failed.
|
|
96
|
+
- **Tune batch size to your downstream API limits.** If the API allows 10 concurrent requests, use `batchSize: 10`.
|
|
97
|
+
- **Add pacing with `sleep()`** between batches to respect rate limits. The sleep is durable — it survives cold starts.
|
|
98
|
+
- **Each `processRecord` call is an independent step.** If one fails, it retries up to 3 times without affecting other items in the batch.
|
|
99
|
+
|
|
100
|
+
## Key APIs
|
|
101
|
+
|
|
102
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) -- marks the orchestrator function
|
|
103
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps) -- marks functions that run with full Node.js access
|
|
104
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep) -- pacing delay between batches
|
|
105
|
+
- [`Promise.allSettled()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) -- runs items in parallel, isolating failures
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Idempotency
|
|
3
|
+
description: Ensure external side effects happen exactly once, even when steps are retried or workflows are replayed.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Use step IDs as idempotency keys for external APIs like Stripe so that retries and replays don't create duplicate charges.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
Workflow steps can be retried (on failure) and replayed (on cold start). If a step calls an external API that isn't idempotent, retries could create duplicate charges, send duplicate emails, or double-process records. Use idempotency keys to make these operations safe.
|
|
9
|
+
|
|
10
|
+
## When to use this
|
|
11
|
+
|
|
12
|
+
- Charging a payment (Stripe, PayPal)
|
|
13
|
+
- Sending transactional emails or SMS
|
|
14
|
+
- Creating records in external systems where duplicates are harmful
|
|
15
|
+
- Any step that has side effects in systems you don't control
|
|
16
|
+
|
|
17
|
+
## Pattern: Step ID as idempotency key
|
|
18
|
+
|
|
19
|
+
Every step has a unique, deterministic `stepId` available via `getStepMetadata()`. Pass this as the idempotency key to external APIs:
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { getStepMetadata } from "workflow";
|
|
23
|
+
|
|
24
|
+
declare function createCharge(customerId: string, amount: number): Promise<{ id: string }>; // @setup
|
|
25
|
+
declare function sendReceipt(customerId: string, chargeId: string): Promise<void>; // @setup
|
|
26
|
+
|
|
27
|
+
export async function chargeCustomer(customerId: string, amount: number) {
|
|
28
|
+
"use workflow";
|
|
29
|
+
|
|
30
|
+
const charge = await createCharge(customerId, amount);
|
|
31
|
+
await sendReceipt(customerId, charge.id);
|
|
32
|
+
|
|
33
|
+
return { customerId, chargeId: charge.id, status: "completed" };
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Step function with idempotency key
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
import { getStepMetadata } from "workflow";
|
|
41
|
+
|
|
42
|
+
async function createCharge(
|
|
43
|
+
customerId: string,
|
|
44
|
+
amount: number
|
|
45
|
+
): Promise<{ id: string }> {
|
|
46
|
+
"use step";
|
|
47
|
+
|
|
48
|
+
const { stepId } = getStepMetadata(); // [!code highlight]
|
|
49
|
+
|
|
50
|
+
// Stripe uses the idempotency key to deduplicate requests.
|
|
51
|
+
// If this step is retried, Stripe returns the same charge.
|
|
52
|
+
const charge = await fetch("https://api.stripe.com/v1/charges", {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: {
|
|
55
|
+
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
|
|
56
|
+
"Idempotency-Key": stepId, // [!code highlight]
|
|
57
|
+
},
|
|
58
|
+
body: new URLSearchParams({
|
|
59
|
+
amount: String(amount),
|
|
60
|
+
currency: "usd",
|
|
61
|
+
customer: customerId,
|
|
62
|
+
}),
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
if (!charge.ok) {
|
|
66
|
+
const error = await charge.json();
|
|
67
|
+
throw new Error(`Charge failed: ${error.message}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return charge.json();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function sendReceipt(customerId: string, chargeId: string): Promise<void> {
|
|
74
|
+
"use step";
|
|
75
|
+
|
|
76
|
+
const { stepId } = getStepMetadata();
|
|
77
|
+
|
|
78
|
+
await fetch("https://api.example.com/receipts", {
|
|
79
|
+
method: "POST",
|
|
80
|
+
headers: { "Idempotency-Key": stepId },
|
|
81
|
+
body: JSON.stringify({ customerId, chargeId }),
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Race condition caveats
|
|
87
|
+
|
|
88
|
+
Workflow does not currently provide distributed locking or true exactly-once delivery across concurrent runs. If two workflow runs could process the same entity concurrently:
|
|
89
|
+
|
|
90
|
+
- **Rely on the external API's idempotency** (like Stripe's `Idempotency-Key`) rather than checking a local flag.
|
|
91
|
+
- **Don't use check-then-act patterns** like "read a flag, then write if not set" -- another run could read the same flag between your read and write.
|
|
92
|
+
|
|
93
|
+
If your external API doesn't support idempotency keys natively, consider adding a deduplication layer (e.g., a database unique constraint on the operation ID).
|
|
94
|
+
|
|
95
|
+
## Tips
|
|
96
|
+
|
|
97
|
+
- **`stepId` is deterministic.** It's the same value across retries and replays of the same step, making it a reliable idempotency key.
|
|
98
|
+
- **Always provide idempotency keys for non-idempotent external calls.** Even if you think a step won't be retried, cold-start replay will re-execute it.
|
|
99
|
+
- **Handle 409/conflict as success.** If an external API returns "already processed," treat that as a successful result, not an error.
|
|
100
|
+
- **Make your own APIs idempotent** where possible. Accept an idempotency key and return the cached result on duplicate requests.
|
|
101
|
+
|
|
102
|
+
## Key APIs
|
|
103
|
+
|
|
104
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) -- declares the orchestrator function
|
|
105
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) -- declares step functions with full Node.js access
|
|
106
|
+
- [`getStepMetadata()`](/docs/api-reference/step/get-step-metadata) -- provides the deterministic `stepId` for idempotency keys
|
|
107
|
+
- [`start()`](/docs/api-reference/workflow-api/start) -- starts a new workflow run
|