workflow 5.0.0-beta.2 → 5.0.0-beta.4

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 (42) hide show
  1. package/dist/api-workflow.d.ts +1 -1
  2. package/dist/api-workflow.d.ts.map +1 -1
  3. package/dist/api-workflow.js +2 -2
  4. package/docs/cookbook/{common-patterns → advanced}/child-workflows.mdx +1 -1
  5. package/docs/cookbook/advanced/distributed-abort-controller.mdx +318 -0
  6. package/docs/cookbook/advanced/meta.json +2 -3
  7. package/docs/cookbook/advanced/publishing-libraries.mdx +83 -26
  8. package/docs/cookbook/advanced/serializable-steps.mdx +15 -3
  9. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +205 -0
  10. package/docs/cookbook/agent-patterns/durable-agent.mdx +50 -91
  11. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +148 -171
  12. package/docs/cookbook/agent-patterns/meta.json +1 -7
  13. package/docs/cookbook/common-patterns/batching.mdx +44 -118
  14. package/docs/cookbook/common-patterns/meta.json +4 -4
  15. package/docs/cookbook/common-patterns/saga.mdx +126 -31
  16. package/docs/cookbook/common-patterns/scheduling.mdx +70 -194
  17. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
  18. package/docs/cookbook/common-patterns/timeouts.mdx +99 -0
  19. package/docs/cookbook/common-patterns/workflow-composition.mdx +118 -0
  20. package/docs/cookbook/index.mdx +13 -16
  21. package/docs/cookbook/integrations/ai-sdk.mdx +296 -140
  22. package/docs/cookbook/integrations/chat-sdk.mdx +251 -151
  23. package/docs/cookbook/integrations/sandbox.mdx +469 -81
  24. package/docs/cookbook/meta.json +1 -1
  25. package/docs/foundations/index.mdx +0 -3
  26. package/docs/foundations/meta.json +0 -1
  27. package/docs/foundations/serialization.mdx +1 -1
  28. package/docs/foundations/starting-workflows.mdx +1 -1
  29. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +60 -8
  30. package/docs/migration-guides/migrating-from-inngest.mdx +38 -6
  31. package/docs/migration-guides/migrating-from-temporal.mdx +38 -4
  32. package/docs/migration-guides/migrating-from-trigger-dev.mdx +52 -11
  33. package/package.json +11 -11
  34. package/docs/cookbook/advanced/custom-serialization.mdx +0 -168
  35. package/docs/cookbook/advanced/durable-objects.mdx +0 -148
  36. package/docs/cookbook/advanced/isomorphic-packages.mdx +0 -145
  37. package/docs/cookbook/agent-patterns/stop-workflow.mdx +0 -216
  38. package/docs/cookbook/agent-patterns/tool-orchestration.mdx +0 -255
  39. package/docs/cookbook/agent-patterns/tool-streaming.mdx +0 -181
  40. package/docs/cookbook/common-patterns/content-router.mdx +0 -207
  41. package/docs/cookbook/common-patterns/fan-out.mdx +0 -208
  42. package/docs/foundations/common-patterns.mdx +0 -265
@@ -7,165 +7,141 @@ summary: Use defineHook with the tool call ID to suspend an agent for human appr
7
7
 
8
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
9
 
10
- ## Pattern
11
-
12
- Create a typed hook using `defineHook()`. When the agent calls the approval tool, the tool creates a hook instance using the tool call ID as the token, then awaits it. The UI renders approval controls, and an API route resumes the hook with the decision.
13
-
14
- ### Simplified
10
+ ## When to use this
15
11
 
16
- ```typescript lineNumbers
17
- import { DurableAgent } from "@workflow/ai/agent";
18
- import { defineHook, sleep, getWritable } from "workflow";
19
- import { z } from "zod";
20
- import type { ModelMessage, UIMessageChunk } from "ai";
21
-
22
- export const bookingApprovalHook = defineHook({
23
- schema: z.object({
24
- approved: z.boolean(),
25
- comment: z.string().optional(),
26
- }),
27
- });
28
-
29
- declare function confirmBooking(args: { flightId: string; passenger: string }): Promise<{ confirmationId: string }>; // @setup
30
-
31
- // This tool runs at the workflow level (no "use step") because hooks are workflow primitives
32
- async function requestBookingApproval(
33
- { flightId, passenger, price }: { flightId: string; passenger: string; price: number },
34
- { toolCallId }: { toolCallId: string }
35
- ) {
36
- const hook = bookingApprovalHook.create({ token: toolCallId }); // [!code highlight]
37
-
38
- const result = await Promise.race([ // [!code highlight]
39
- hook.then((payload) => ({ type: "decision" as const, ...payload })),
40
- sleep("24h").then(() => ({ type: "timeout" as const, approved: false })),
41
- ]);
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
42
16
 
43
- if (result.type === "timeout") return "Booking request expired after 24 hours.";
44
- if (!result.approved) return `Booking rejected: ${result.comment || "No reason given"}`;
45
-
46
- const booking = await confirmBooking({ flightId, passenger });
47
- return `Booked! Confirmation: ${booking.confirmationId}`;
48
- }
49
-
50
- export async function bookingAgent(messages: ModelMessage[]) {
51
- "use workflow";
52
-
53
- const agent = new DurableAgent({
54
- model: "anthropic/claude-haiku-4.5",
55
- instructions: "You help book flights. Always request approval before booking.",
56
- tools: {
57
- requestBookingApproval: {
58
- description: "Request human approval before booking a flight",
59
- inputSchema: z.object({
60
- flightId: z.string(),
61
- passenger: z.string(),
62
- price: z.number(),
63
- }),
64
- execute: requestBookingApproval,
65
- },
66
- },
67
- });
17
+ ## Pattern
68
18
 
69
- await agent.stream({ // [!code highlight]
70
- messages,
71
- writable: getWritable<UIMessageChunk>(),
72
- });
73
- }
74
- ```
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.
75
20
 
76
- ### Full Implementation
21
+ ### Workflow
77
22
 
78
- ```typescript lineNumbers
23
+ ```typescript
79
24
  import { DurableAgent } from "@workflow/ai/agent";
80
25
  import { defineHook, sleep, getWritable } from "workflow";
81
26
  import { z } from "zod";
82
27
  import type { ModelMessage, UIMessageChunk } from "ai";
83
28
 
84
- // Define the approval hook with schema validation
85
- export const bookingApprovalHook = defineHook({
29
+ // Exported so the approval API route can call .resume()
30
+ export const bookingApprovalHook = defineHook({ // [!code highlight]
86
31
  schema: z.object({
87
32
  approved: z.boolean(),
88
33
  comment: z.string().optional(),
89
34
  }),
90
35
  });
91
36
 
92
- // Step: Search for flights (full Node.js access, automatic retries)
93
- async function searchFlights({
94
- from,
95
- to,
96
- date,
97
- }: {
37
+ async function searchFlights({ from, to, date }: {
98
38
  from: string;
99
39
  to: string;
100
40
  date: string;
101
41
  }) {
102
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
+ }
103
48
 
104
- // Your real flight search API call here
105
- await new Promise((resolve) => setTimeout(resolve, 500));
106
- return {
107
- flights: [
108
- { id: "FL-100", airline: "Example Air", price: 299, from, to, date },
109
- { id: "FL-200", airline: "Demo Airlines", price: 349, from, to, date },
110
- ],
111
- };
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();
112
59
  }
113
60
 
114
- // Step: Confirm the booking after approval
115
- async function confirmBooking({
116
- flightId,
117
- passenger,
118
- }: {
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: {
119
66
  flightId: string;
120
67
  passenger: string;
68
+ price: number;
69
+ toolCallId: string;
121
70
  }) {
122
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
+ }
123
83
 
124
- await new Promise((resolve) => setTimeout(resolve, 500));
125
- return { confirmationId: `CONF-${flightId}-${Date.now().toString(36)}` };
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
+ }
126
100
  }
127
101
 
128
- // Workflow-level tool: hooks must be created in workflow context, not inside steps
102
+ // No "use step" hooks are workflow-level primitives
129
103
  async function requestBookingApproval(
130
- {
131
- flightId,
132
- passenger,
133
- price,
134
- }: { flightId: string; passenger: string; price: number },
104
+ { flightId, passenger, price }: {
105
+ flightId: string;
106
+ passenger: string;
107
+ price: number;
108
+ },
135
109
  { toolCallId }: { toolCallId: string }
136
110
  ) {
137
- // No "use step" hooks are workflow-level primitives
111
+ // Emit to the stream before suspending so the UI can show buttons
112
+ await emitApprovalRequest({ flightId, passenger, price, toolCallId }); // [!code highlight]
138
113
 
139
- const hook = bookingApprovalHook.create({ token: toolCallId }); // [!code highlight]
114
+ const hook = bookingApprovalHook.create({ token: toolCallId });
140
115
 
141
- // Race: human approval vs. 24-hour timeout
142
- const result = await Promise.race([ // [!code highlight]
116
+ // Race: human decision vs. timeout
117
+ const result = await Promise.race([
143
118
  hook.then((payload) => ({ type: "decision" as const, ...payload })),
144
- sleep("24h").then(() => ({ type: "timeout" as const, approved: false })),
119
+ sleep("24h").then(() => ({ type: "timeout" as const, approved: false as const })),
145
120
  ]);
146
121
 
147
122
  if (result.type === "timeout") {
148
- return "Booking request expired after 24 hours.";
123
+ const msg = "Booking request expired.";
124
+ await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
125
+ return msg;
149
126
  }
150
-
151
127
  if (!result.approved) {
152
- return `Booking rejected: ${result.comment || "No reason given"}`;
128
+ const msg = `Rejected: ${result.comment || "No reason given"}`;
129
+ await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
130
+ return msg;
153
131
  }
154
132
 
155
- // Approved — proceed with booking
156
133
  const booking = await confirmBooking({ flightId, passenger });
157
- return `Flight ${flightId} booked for ${passenger}. Confirmation: ${booking.confirmationId}`;
134
+ const msg = `Booked! Confirmation: ${booking.confirmationId}`;
135
+ await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
136
+ return msg;
158
137
  }
159
138
 
160
139
  export async function bookingAgent(messages: ModelMessage[]) {
161
140
  "use workflow";
162
141
 
163
- const writable = getWritable<UIMessageChunk>();
164
-
165
142
  const agent = new DurableAgent({
166
143
  model: "anthropic/claude-haiku-4.5",
167
- instructions:
168
- "You are a flight booking assistant. Search for flights, then request approval before booking.",
144
+ instructions: "You help book flights. Always request approval before booking.",
169
145
  tools: {
170
146
  searchFlights: {
171
147
  description: "Search for available flights",
@@ -188,86 +164,86 @@ export async function bookingAgent(messages: ModelMessage[]) {
188
164
  },
189
165
  });
190
166
 
191
- await agent.stream({ messages, writable }); // [!code highlight]
167
+ await agent.stream({
168
+ messages,
169
+ writable: getWritable<UIMessageChunk>(),
170
+ });
192
171
  }
193
172
  ```
194
173
 
195
- ### API Route for Approvals
174
+ ### Approval API route
175
+
176
+ The approval route imports the hook definition and calls `.resume()` with the tool call ID as the token:
196
177
 
197
- ```typescript lineNumbers
198
- import { bookingApprovalHook } from "@/workflows/booking-agent";
178
+ ```typescript
179
+ import { bookingApprovalHook } from "@/app/workflows/booking-agent";
199
180
 
200
- export async function POST(request: Request) {
201
- const { toolCallId, approved, comment } = await request.json();
181
+ export async function POST(req: Request) {
182
+ const { toolCallId, approved, comment } = await req.json();
202
183
 
203
- // Schema validation happens automatically via defineHook
204
184
  await bookingApprovalHook.resume(toolCallId, { approved, comment }); // [!code highlight]
205
185
 
206
186
  return Response.json({ success: true });
207
187
  }
208
188
  ```
209
189
 
210
- ### Approval Component
211
-
212
- ```tsx lineNumbers
213
- "use client";
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
+ ```
214
230
 
215
- import { useState } from "react";
231
+ ## How it works
216
232
 
217
- export function BookingApproval({
218
- toolCallId,
219
- input,
220
- output,
221
- }: {
222
- toolCallId: string;
223
- input?: { flightId: string; passenger: string; price: number };
224
- output?: string;
225
- }) {
226
- const [comment, setComment] = useState("");
227
- const [isSubmitting, setIsSubmitting] = useState(false);
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.
228
239
 
229
- if (output) {
230
- return <p className="text-sm text-muted-foreground">{output}</p>;
231
- }
240
+ ## Adapting to your use case
232
241
 
233
- const handleSubmit = async (approved: boolean) => {
234
- setIsSubmitting(true);
235
- await fetch("/api/hooks/approval", {
236
- method: "POST",
237
- headers: { "Content-Type": "application/json" },
238
- body: JSON.stringify({ toolCallId, approved, comment }),
239
- });
240
- setIsSubmitting(false);
241
- };
242
-
243
- return (
244
- <div className="border rounded-lg p-4 space-y-3">
245
- {input && (
246
- <div className="text-sm space-y-1">
247
- <div>Flight: {input.flightId}</div>
248
- <div>Passenger: {input.passenger}</div>
249
- <div>Price: ${input.price}</div>
250
- </div>
251
- )}
252
- <textarea
253
- value={comment}
254
- onChange={(e) => setComment(e.target.value)}
255
- placeholder="Add a comment (optional)..."
256
- className="w-full border rounded p-2 text-sm"
257
- rows={2}
258
- />
259
- <div className="flex gap-2">
260
- <button type="button" onClick={() => handleSubmit(true)} disabled={isSubmitting}>
261
- Approve
262
- </button>
263
- <button type="button" onClick={() => handleSubmit(false)} disabled={isSubmitting}>
264
- Reject
265
- </button>
266
- </div>
267
- </div>
268
- );
269
- }
270
- ```
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.
271
247
 
272
248
  ## Key APIs
273
249
 
@@ -275,4 +251,5 @@ export function BookingApproval({
275
251
  - [`"use step"`](/docs/api-reference/workflow/use-step) — declares step functions with retries
276
252
  - [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook with schema validation
277
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
278
255
  - [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — durable agent with tool definitions
@@ -1,10 +1,4 @@
1
1
  {
2
2
  "title": "Agent Patterns",
3
- "pages": [
4
- "durable-agent",
5
- "tool-streaming",
6
- "human-in-the-loop",
7
- "tool-orchestration",
8
- "stop-workflow"
9
- ]
3
+ "pages": ["durable-agent", "human-in-the-loop", "agent-cancellation"]
10
4
  }
@@ -9,167 +9,93 @@ Use batching when you need to process a large list of items in parallel while co
9
9
 
10
10
  ## When to use this
11
11
 
12
- - Processing hundreds or thousands of items (orders, images, records)
12
+ - Bulk data imports (contacts, orders, products from a CSV)
13
+ - Processing hundreds or thousands of items against external APIs
13
14
  - Calling rate-limited APIs where you need to control concurrency
14
15
  - Any fan-out where you want failure isolation between groups
15
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
+
16
24
  ## Pattern
17
25
 
18
- The workflow splits items into chunks and processes each chunk with `Promise.allSettled()`. A `sleep()` between chunks prevents overloading downstream services.
26
+ The workflow splits records into chunks, processes each chunk concurrently, tracks results per batch, and returns a final tally.
19
27
 
20
28
  ```typescript
21
29
  import { sleep } from "workflow";
22
30
 
23
- declare function processItem(item: string): Promise<{ item: string; ok: boolean }>; // @setup
31
+ type Record = { name: string; email: string; role: string };
32
+
33
+ declare function processRecord(record: Record): Promise<string>; // @setup
24
34
 
25
- export async function processBatch(items: string[], batchSize: number = 5) {
35
+ export async function batchImport(records: Record[], batchSize: number) {
26
36
  "use workflow";
27
37
 
28
- const results = [];
38
+ let totalSucceeded = 0;
39
+ let totalFailed = 0;
29
40
 
30
- for (let i = 0; i < items.length; i += batchSize) {
31
- const batch = items.slice(i, i + batchSize);
41
+ for (let i = 0; i < records.length; i += batchSize) {
42
+ const batch = records.slice(i, i + batchSize);
32
43
 
33
- // Run batch in parallel -- failures are isolated
44
+ // Run batch in parallel failures are isolated per record
34
45
  const outcomes = await Promise.allSettled( // [!code highlight]
35
- batch.map((item) => processItem(item))
46
+ batch.map((record) => processRecord(record))
36
47
  );
37
48
 
38
49
  for (let j = 0; j < outcomes.length; j++) {
39
- const outcome = outcomes[j];
40
- results.push(
41
- outcome.status === "fulfilled"
42
- ? outcome.value
43
- : { item: batch[j], ok: false, error: String(outcome.reason) }
44
- );
50
+ if (outcomes[j].status === "fulfilled") {
51
+ totalSucceeded++;
52
+ } else {
53
+ totalFailed++;
54
+ }
45
55
  }
46
56
 
47
- // Pace between batches to avoid overload
48
- if (i + batchSize < items.length) {
57
+ // Pace between batches to avoid overloading downstream
58
+ if (i + batchSize < records.length) {
49
59
  await sleep("1s"); // [!code highlight]
50
60
  }
51
61
  }
52
62
 
53
- const succeeded = results.filter((r) => r.ok).length;
54
- return { total: results.length, succeeded, failed: results.length - succeeded };
63
+ return { total: records.length, succeeded: totalSucceeded, failed: totalFailed };
55
64
  }
56
65
  ```
57
66
 
58
67
  ### Step function
59
68
 
60
- Each item is processed in its own step, giving it full Node.js access and automatic retries.
69
+ Each record is processed in its own step with full Node.js access and automatic retries.
61
70
 
62
71
  ```typescript
63
- async function processItem(item: string): Promise<{ item: string; ok: boolean }> {
72
+ type Record = { name: string; email: string; role: string };
73
+
74
+ async function processRecord(record: Record): Promise<string> {
64
75
  "use step";
65
- const res = await fetch(`https://api.example.com/process`, {
76
+ const res = await fetch(`https://api.example.com/contacts`, {
66
77
  method: "POST",
67
- body: JSON.stringify({ item }),
78
+ body: JSON.stringify(record),
68
79
  });
69
- if (!res.ok) throw new Error(`Failed to process ${item}`);
70
- return { item, ok: true };
80
+ if (!res.ok) throw new Error(`Failed to import ${record.email}`);
81
+ const { id } = await res.json();
82
+ return id;
71
83
  }
72
84
  ```
73
85
 
74
- ## Variations
75
-
76
- ### Scatter-gather
77
-
78
- When you need results from multiple independent sources before continuing, fan out in parallel and collect all results:
79
-
80
- ```typescript
81
- export async function scatterGather(query: string) {
82
- "use workflow";
83
-
84
- const [web, database, cache] = await Promise.allSettled([ // [!code highlight]
85
- searchWeb(query),
86
- searchDatabase(query),
87
- searchCache(query),
88
- ]);
89
-
90
- return {
91
- web: web.status === "fulfilled" ? web.value : null,
92
- database: database.status === "fulfilled" ? database.value : null,
93
- cache: cache.status === "fulfilled" ? cache.value : null,
94
- };
95
- }
96
-
97
- async function searchWeb(query: string): Promise<string[]> {
98
- "use step";
99
- // Full Node.js access -- call external APIs
100
- const res = await fetch(`https://search.example.com?q=${query}`);
101
- return res.json();
102
- }
103
-
104
- async function searchDatabase(query: string): Promise<string[]> {
105
- "use step";
106
- // Query your database
107
- return [`db-result-for-${query}`];
108
- }
109
-
110
- async function searchCache(query: string): Promise<string[]> {
111
- "use step";
112
- return [`cached-result-for-${query}`];
113
- }
114
- ```
115
-
116
- ## In-step concurrency control
117
-
118
- When you need to process many items against a rate-limited API but want the entire operation to be a single atomic step, batch the work inside the step itself. This keeps the event log clean (one step instead of hundreds) while still controlling concurrency.
119
-
120
- ```typescript
121
- async function processConcurrently<T>(
122
- items: string[],
123
- processor: (item: string) => Promise<T>,
124
- maxConcurrent: number = 5,
125
- ): Promise<T[]> {
126
- "use step";
127
- const results: T[] = [];
128
-
129
- for (let i = 0; i < items.length; i += maxConcurrent) {
130
- const batch = items.slice(i, i + maxConcurrent);
131
- const batchResults = await Promise.all(batch.map(processor)); // [!code highlight]
132
- results.push(...batchResults);
133
- }
134
-
135
- return results;
136
- }
137
- ```
138
-
139
- Usage in a workflow:
140
-
141
- ```typescript
142
- declare function processConcurrently<T>(items: string[], processor: (item: string) => Promise<T>, maxConcurrent?: number): Promise<T[]>; // @setup
143
-
144
- export async function moderateImages(imageUrls: string[]) {
145
- "use workflow";
146
-
147
- const results = await processConcurrently(
148
- imageUrls,
149
- async (url) => {
150
- const res = await fetch("https://api.example.com/moderate", {
151
- method: "POST",
152
- body: JSON.stringify({ url }),
153
- });
154
- return res.json();
155
- },
156
- 3, // max 3 concurrent API calls
157
- );
158
-
159
- return { total: results.length, results };
160
- }
161
- ```
86
+ ## Adapting to your use case
162
87
 
163
- **When to use in-step batching vs workflow-level batching:**
164
- - **Workflow-level** (the pattern above): Each item is its own step with independent retries and failure isolation. Use when items are independent and individual failures should be retried.
165
- - **In-step**: All items are processed in one step. Use when the items are tightly coupled (e.g., moderating all thumbnails for a single video) or when you want to minimize step overhead for large item counts.
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.
166
92
 
167
93
  ## Tips
168
94
 
169
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.
170
96
  - **Tune batch size to your downstream API limits.** If the API allows 10 concurrent requests, use `batchSize: 10`.
171
- - **Add pacing with `sleep()`** between batches to respect rate limits. The sleep is durable -- it survives cold starts.
172
- - **Each `processItem` call is an independent step.** If one fails, it retries up to 3 times without affecting other items in the batch.
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.
173
99
 
174
100
  ## Key APIs
175
101
 
@@ -2,14 +2,14 @@
2
2
  "title": "Common Patterns",
3
3
  "defaultOpen": true,
4
4
  "pages": [
5
+ "sequential-and-parallel",
6
+ "workflow-composition",
5
7
  "saga",
6
8
  "batching",
7
9
  "rate-limiting",
8
- "fan-out",
9
10
  "scheduling",
11
+ "timeouts",
10
12
  "idempotency",
11
- "webhooks",
12
- "content-router",
13
- "child-workflows"
13
+ "webhooks"
14
14
  ]
15
15
  }