workflow 5.4.0 → 5.6.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.
- package/dist/api-workflow.js +1 -1
- package/dist/api.js +1 -1
- package/dist/astro.js +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/builtins.js +1 -1
- package/dist/internal/class-serialization.js +1 -1
- package/dist/internal/errors.js +1 -1
- package/dist/nest-builder.js +1 -1
- package/dist/nest-vercel-builder.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.js +1 -1
- 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/chat-session-modeling.mdx +1 -1
- package/docs/ai/resumable-streams.mdx +1 -1
- package/docs/api-reference/workflow/create-hook.mdx +2 -2
- package/docs/api-reference/workflow/get-step-metadata.mdx +19 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +2 -1
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +4 -4
- package/docs/api-reference/workflow-api/get-run.mdx +0 -4
- package/docs/api-reference/workflow-api/resume-hook.mdx +1 -1
- package/docs/api-reference/workflow-api/start.mdx +1 -1
- package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +0 -3
- package/docs/api-reference/workflow-errors/index.mdx +1 -1
- package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +0 -2
- package/docs/api-reference/workflow-errors/workflow-not-registered-error.mdx +1 -1
- package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +1 -1
- package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +1 -1
- package/docs/api-reference/workflow-next/with-workflow.mdx +57 -0
- package/docs/api-reference/workflow-observability/create-state-resolver.mdx +56 -0
- package/docs/api-reference/workflow-observability/index.mdx +5 -0
- package/docs/api-reference/workflow-observability/meta.json +1 -0
- package/docs/api-reference/workflow-runtime/world/queue.mdx +70 -3
- package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -2
- package/docs/comparisons/index.mdx +4 -1
- package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +3 -1
- package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +4 -1
- package/docs/comparisons/workflow-sdk-vs-inngest.mdx +271 -28
- package/docs/comparisons/workflow-sdk-vs-temporal.mdx +6 -2
- package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +2 -0
- package/docs/configuration/build-and-diagnostics.mdx +2 -0
- package/docs/configuration/cli-and-web-ui.mdx +40 -1
- package/docs/configuration/framework-options.mdx +7 -0
- package/docs/configuration/runtime-tuning.mdx +31 -85
- package/docs/configuration/worlds.mdx +69 -40
- package/docs/cookbook/advanced/child-workflows.mdx +3 -3
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +1 -1
- package/docs/cookbook/common-patterns/batching.mdx +1 -1
- package/docs/cookbook/integrations/ai-sdk.mdx +2 -2
- package/docs/errors/corrupted-event-log.mdx +1 -1
- package/docs/errors/hook-force-claimed.mdx +1 -1
- package/docs/errors/index.mdx +1 -0
- package/docs/errors/max-events-exceeded.mdx +2 -2
- package/docs/errors/replay-timeout.mdx +2 -2
- package/docs/errors/runtime-decryption-failed.mdx +1 -1
- package/docs/errors/workflow-not-registered.mdx +1 -1
- package/docs/foundations/errors-and-retries.mdx +4 -5
- package/docs/foundations/serialization.mdx +80 -0
- package/docs/getting-started/next.mdx +2 -0
- package/docs/how-it-works/event-sourcing.mdx +4 -7
- package/docs/how-it-works/framework-integrations.mdx +2 -2
- package/docs/internal/index.mdx +1 -0
- package/docs/internal/nitro-native-build.mdx +1 -0
- package/docs/internal/nitro-web-ui.mdx +1 -0
- package/docs/internal/serializable-abort-controller.mdx +1 -0
- package/docs/observability/index.mdx +4 -0
- package/docs/whats-new.mdx +5 -5
- package/docs/worlds/building-a-world.mdx +63 -6
- package/docs/worlds/local.mdx +115 -26
- package/docs/worlds/postgres.mdx +110 -33
- package/docs/worlds/upgrading-to-v5.mdx +6 -6
- package/docs/worlds/vercel.mdx +194 -81
- package/package.json +17 -15
- package/dist/api-workflow.d.ts.map +0 -1
- package/dist/api.d.ts.map +0 -1
- package/dist/astro.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/internal/builtins.d.ts.map +0 -1
- package/dist/internal/class-serialization.d.ts.map +0 -1
- package/dist/internal/errors.d.ts.map +0 -1
- package/dist/nest-builder.d.ts.map +0 -1
- package/dist/nest-vercel-builder.d.ts.map +0 -1
- package/dist/nest.d.ts.map +0 -1
- package/dist/nitro.d.ts.map +0 -1
- package/dist/nuxt.d.ts.map +0 -1
- package/dist/observability.d.ts.map +0 -1
- package/dist/runtime.d.ts.map +0 -1
- package/dist/stdlib.d.ts.map +0 -1
- package/dist/sveltekit.d.ts.map +0 -1
- package/dist/vite.d.ts.map +0 -1
- package/dist/workflow.d.ts.map +0 -1
- package/docs/changelog/attributes-mvp.mdx +0 -380
- package/docs/changelog/batched-event-writes.mdx +0 -79
- package/docs/changelog/eager-processing.mdx +0 -273
- package/docs/changelog/index.mdx +0 -19
- package/docs/changelog/lazy-event-creation.md +0 -127
- package/docs/changelog/lazy-hook-resume.mdx +0 -78
- package/docs/changelog/meta.json +0 -16
- package/docs/changelog/resilient-resume.mdx +0 -32
- package/docs/changelog/resilient-start.mdx +0 -77
- package/docs/changelog/spec-9.mdx +0 -4019
- package/docs/changelog/step-message-ownership.mdx +0 -360
- package/docs/changelog/turbo-mode.md +0 -91
|
@@ -8,6 +8,7 @@ keywords:
|
|
|
8
8
|
- hydrateResourceIO
|
|
9
9
|
- observabilityRevivers
|
|
10
10
|
- hydrateData
|
|
11
|
+
- createStateResolver
|
|
11
12
|
- parseStepName
|
|
12
13
|
- parseWorkflowName
|
|
13
14
|
- parseClassName
|
|
@@ -23,6 +24,7 @@ import { // [!code highlight]
|
|
|
23
24
|
hydrateResourceIO, // [!code highlight]
|
|
24
25
|
observabilityRevivers, // [!code highlight]
|
|
25
26
|
hydrateData, // [!code highlight]
|
|
27
|
+
createStateResolver, // [!code highlight]
|
|
26
28
|
parseStepName, // [!code highlight]
|
|
27
29
|
parseWorkflowName, // [!code highlight]
|
|
28
30
|
parseClassName, // [!code highlight]
|
|
@@ -41,6 +43,9 @@ import { // [!code highlight]
|
|
|
41
43
|
<Card href="/docs/api-reference/workflow-observability/hydrate-data" title="hydrateData()">
|
|
42
44
|
Hydrate a single serialized value (lower-level than hydrateResourceIO).
|
|
43
45
|
</Card>
|
|
46
|
+
<Card href="/docs/api-reference/workflow-observability/create-state-resolver" title="createStateResolver()">
|
|
47
|
+
Rebuild frozen state a run stored by reference, so inspected values show in full.
|
|
48
|
+
</Card>
|
|
44
49
|
</Cards>
|
|
45
50
|
|
|
46
51
|
## Name parsing
|
|
@@ -13,6 +13,8 @@ keywords:
|
|
|
13
13
|
- getDeploymentId
|
|
14
14
|
- queue
|
|
15
15
|
- createQueueHandler
|
|
16
|
+
- experimental_hold
|
|
17
|
+
- send-and-hold
|
|
16
18
|
- ValidQueueName
|
|
17
19
|
- queue dispatch
|
|
18
20
|
---
|
|
@@ -58,9 +60,74 @@ const { messageId } = await world.queue(queueName, payload, opts); // [!code hig
|
|
|
58
60
|
|-----------|------|-------------|
|
|
59
61
|
| `queueName` | `ValidQueueName` | The queue name (branded string) |
|
|
60
62
|
| `message` | `QueuePayload` | Internal SDK payload |
|
|
61
|
-
| `opts` | `QueueOptions` | Optional: `deploymentId`, `idempotencyKey`, `delaySeconds`, `headers`, `region` (regional routing hint), `specVersion` |
|
|
63
|
+
| `opts` | `QueueOptions` | Optional: `deploymentId`, `idempotencyKey`, `delaySeconds`, `headers`, `region` (regional routing hint), `specVersion`, `experimental_hold` (see [Running a message in the request that sent it](#running-a-message-in-the-request-that-sent-it-experimental)) |
|
|
62
64
|
|
|
63
|
-
**Returns:** `{ messageId: MessageId | null }`
|
|
65
|
+
**Returns:** `QueueResult`: `{ messageId: MessageId | null, experimental_hold?: QueueHoldResult }`. `experimental_hold` is present only when you asked for a hold on a World that supports it (see below).
|
|
66
|
+
|
|
67
|
+
#### Running a message in the request that sent it (experimental)
|
|
68
|
+
|
|
69
|
+
By default, a message you queue is delivered to its consumer by a queue hop, a separate invocation. A **hold** lets the process that sends a message run it itself, in the same request, while the queue stays the crash backstop: the queue claims the message's first delivery for the sender before `queue()` returns, and delivers it as usual only if the sender stops renewing that claim. Use it when the sender is about to wait for the message's work, for example to stream an agent's first tokens back on the request that started the turn.
|
|
70
|
+
|
|
71
|
+
A World that supports holds declares `capabilities.experimental_queueHold` (`@workflow/world-vercel` does; the Local and Postgres Worlds don't). Check it before you send, and keep your existing path where it's unset:
|
|
72
|
+
|
|
73
|
+
{/* @skip-typecheck: shape illustration, not runnable code */}
|
|
74
|
+
```typescript lineNumbers
|
|
75
|
+
import { waitUntil } from "@vercel/functions";
|
|
76
|
+
|
|
77
|
+
if (world.capabilities?.experimental_queueHold) {
|
|
78
|
+
const { messageId, experimental_hold: hold } = await world.queue(queueName, payload, {
|
|
79
|
+
idempotencyKey, // always send one with a hold
|
|
80
|
+
experimental_hold: true, // [!code highlight]
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
if (hold?.status === "held") { // [!code highlight]
|
|
84
|
+
// Run it here as its first delivery, with the same handler the queue
|
|
85
|
+
// consumer for this prefix passes to createQueueHandler().
|
|
86
|
+
waitUntil(hold.consume(handler)); // [!code highlight]
|
|
87
|
+
}
|
|
88
|
+
// `not_held` (hold.reason says why) or no `experimental_hold` at all:
|
|
89
|
+
// the queue delivers the message as usual. Don't process it here.
|
|
90
|
+
} else {
|
|
91
|
+
await world.queue(queueName, payload, { idempotencyKey });
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`experimental_hold` is a discriminated union on `status`:
|
|
96
|
+
|
|
97
|
+
| `status` | Fields | What to do |
|
|
98
|
+
|----------|--------|------------|
|
|
99
|
+
| `held` | `messageId`, `leaseExpiresAt`, `consume(handler)`, `release(delaySeconds?)` | Call `consume(handler)` right away and keep the invocation alive until it settles (for example with `waitUntil`). Or call `release()` to hand the message back to the queue without running it. |
|
|
100
|
+
| `not_held` | `reason` | Nothing. The queue, or a delivery that's already running, takes care of the message. |
|
|
101
|
+
|
|
102
|
+
**Options**: pass `experimental_hold: true` for the defaults, or an object with any of:
|
|
103
|
+
|
|
104
|
+
| Option | Default | Description |
|
|
105
|
+
|--------|---------|-------------|
|
|
106
|
+
| `consumerGroup` | `default` | The consumer group that would otherwise receive the message, so a hold that lapses is delivered to the same route. The Workflow SDK's generated triggers subscribe as `default`. A Function whose trigger is configured in `vercel.json` or `vercel.ts` gets a group named after its path: pass `vercelTriggerConsumerGroup(functionPattern)` from `@workflow/world-vercel`, for example `vercelTriggerConsumerGroup("app/api/agent/route.ts")`. |
|
|
107
|
+
| `visibilityTimeoutSeconds` | `30` | The hold's lease. `consume()` renews it while the handler runs; if nothing renews it, the queue delivers the message about this long after the last renewal. On Vercel it's clamped to 30–3600 seconds and to the message's retention. |
|
|
108
|
+
|
|
109
|
+
**`consume(handler)`** runs `handler` as the message's first delivery (`deliveryCount: 1`), with the same result rules as `createQueueHandler()`: resolve to acknowledge, return `{ timeoutSeconds }` to have the same message delivered again later, or reject to retry with backoff. It renews the lease while the handler runs. Call it at most once, and not after `release()`. Two `meta` fields differ from a pushed delivery's:
|
|
110
|
+
|
|
111
|
+
- `invocationStartedAt` is when the enclosing queue delivery began if you call `consume` inside one, otherwise when you called `consume`.
|
|
112
|
+
- `requestId` is set only inside a queue delivery, so don't hold an `invoke: true` request.
|
|
113
|
+
|
|
114
|
+
**`not_held` reasons:**
|
|
115
|
+
|
|
116
|
+
| `reason` | Meaning |
|
|
117
|
+
|----------|---------|
|
|
118
|
+
| `unsupported` | The queue ignored the hold: send-and-hold isn't enabled on the queue service, it's local development, or the send was pinned to another deployment. The message is delivered as usual. |
|
|
119
|
+
| `deferred` | The queue accepted the message for deferred processing. It's delivered once it's ingested. |
|
|
120
|
+
| `lost` | Another claim won, or the run's orchestrator is busy. The queue delivers it. |
|
|
121
|
+
| `coalesced` | The run's orchestrator is running in another delivery, which covers this message. |
|
|
122
|
+
| `concurrency_limited` | No delivery slot was free. It's delivered once one is. |
|
|
123
|
+
| `duplicate` | The idempotency key belongs to an earlier message. |
|
|
124
|
+
| `error` | The hold couldn't be taken or read. The queue delivers the message once any lease taken for it lapses. |
|
|
125
|
+
|
|
126
|
+
**Limits:**
|
|
127
|
+
|
|
128
|
+
- A hold can't be combined with `delaySeconds` (`TypeError` before anything is sent).
|
|
129
|
+
- A send pinned to another deployment (`deploymentId`) is never held: its own deployment must run it, so it's sent as usual and reports `unsupported`.
|
|
130
|
+
- `queueBatch()` never holds a message, and its results carry no `experimental_hold`.
|
|
64
131
|
|
|
65
132
|
### createQueueHandler()
|
|
66
133
|
|
|
@@ -79,7 +146,7 @@ const handler = world.createQueueHandler(prefix, callback); // [!code highlight]
|
|
|
79
146
|
|
|
80
147
|
**Returns:** `(req: Request) => Promise<Response>`
|
|
81
148
|
|
|
82
|
-
`meta.messageId` should be stable across redeliveries of the same message (one ID per enqueued message, reused on every delivery attempt). The runtime records it on inline `step_started` events as a liveness lease so that only a redelivery of the owning message re-executes a crashed inline step before the lease expires
|
|
149
|
+
`meta.messageId` should be stable across redeliveries of the same message (one ID per enqueued message, reused on every delivery attempt). The runtime records it on inline `step_started` events as a liveness lease so that only a redelivery of the owning message re-executes a crashed inline step before the lease expires. A World whose queue mints a fresh ID per delivery degrades gracefully. Crashed inline steps recover via the delayed backstop instead of immediately on redelivery, but never wedge or duplicate.
|
|
83
150
|
|
|
84
151
|
## Related
|
|
85
152
|
|
|
@@ -182,8 +182,7 @@ a normal return, not an error, and a missing run throws
|
|
|
182
182
|
also return a non-terminal snapshot before `timeoutMs` is up. Callers pace
|
|
183
183
|
their own retries (`await run.returnValue` keeps consecutive non-terminal
|
|
184
184
|
observations at least one `WORKFLOW_RETURN_VALUE_POLL_INTERVAL_MS` apart), and
|
|
185
|
-
worlds that omit the method are polled on that interval instead.
|
|
186
|
-
`WORKFLOW_RETURN_VALUE_LONG_POLL=0` to force interval polling everywhere.
|
|
185
|
+
worlds that omit the method are polled on that interval instead.
|
|
187
186
|
</Callout>
|
|
188
187
|
|
|
189
188
|
### runs.list()
|
|
@@ -16,6 +16,7 @@ The Workflow SDK overlaps with several categories: durable execution engines, ba
|
|
|
16
16
|
- **It's an open-source SDK, not a hosted product.** Your workflows are plain TypeScript in your existing app. Run them on the managed [Vercel World](/worlds/vercel), or self-host on the [Postgres World](/worlds/postgres). The [World abstraction](/worlds/building-a-world) lets you own and swap the storage, queue, and streaming layers independently.
|
|
17
17
|
- **Versioning is safe by default.** Runs are pinned to the immutable deployment that started them, so shipping new code never disturbs in-flight runs. Upgrading a run is explicit and opt-in. See [Versioning](/docs/comparisons/workflow-sdk-vs-temporal#versioning).
|
|
18
18
|
- **Real-time durable streaming is built in.** Stream partial output, such as large language model (LLM) tokens and progress, to clients with [streams](/docs/foundations/streaming) that survive reconnects, cold starts, and replays. This durability supports chat and agent UIs.
|
|
19
|
+
- **Chaining steps is cheap.** A workflow invocation runs as many steps inline as it can before handing back to the queue and keeps the workflow VM alive between them, so step-to-step overhead stays flat as a run grows. See [Performance](/docs/performance).
|
|
19
20
|
- **First-class AI agents.** `WorkflowAgent` ships inside the [AI SDK](/docs/ai), turning an agent loop into a durable workflow with automatic step retries and human-in-the-loop pauses.
|
|
20
21
|
|
|
21
22
|
## Snapshot
|
|
@@ -50,7 +51,7 @@ These comparisons are compiled from each product's public documentation and are
|
|
|
50
51
|
An AI-agent hosting platform, not a durable-execution engine. Different axis.
|
|
51
52
|
</Card>
|
|
52
53
|
<Card href="/docs/comparisons/workflow-sdk-vs-inngest" title="vs Inngest">
|
|
53
|
-
Event-driven durable functions that run on your own infrastructure over HTTP.
|
|
54
|
+
Event-driven durable functions that run on your own infrastructure over HTTP. Includes a codemod for migrating.
|
|
54
55
|
</Card>
|
|
55
56
|
<Card href="/docs/comparisons/workflow-sdk-vs-trigger-dev" title="vs trigger.dev">
|
|
56
57
|
A TypeScript task platform that achieves durability by snapshotting the process (CRIU).
|
|
@@ -63,4 +64,6 @@ Each deep dive includes a concept-mapping section for moving an existing system.
|
|
|
63
64
|
```bash
|
|
64
65
|
npx skills add https://github.com/vercel/workflow --skill migrating-to-workflow-sdk
|
|
65
66
|
```
|
|
67
|
+
|
|
68
|
+
For Inngest, start with the codemod, which lifts every `step.run()` closure into a `"use step"` function and lists the variables each one captured: `npx workflow migrate inngest`. See [Run the codemod](/docs/comparisons/workflow-sdk-vs-inngest#run-the-codemod).
|
|
66
69
|
</Callout>
|
|
@@ -56,7 +56,9 @@ This guide assumes **Standard** workflows. Express workflows have different sema
|
|
|
56
56
|
| Map state | `for` loop / bounded `Promise.all` (e.g. `p-limit`) / [`start()`](/docs/foundations/starting-workflows) per item for large fan-out | Match the original concurrency mode. |
|
|
57
57
|
| Retry / Catch (`MaxAttempts`, `BackoffRate`, `IntervalSeconds`) | `maxRetries`, `RetryableError`, `FatalError`; `try/catch` for compensation | Retry logic moves to step boundaries; backoff curves use `retryAfter`. See [Errors & Retrying](/docs/foundations/errors-and-retries#advanced-example). |
|
|
58
58
|
| `.waitForTaskToken` | `createHook()` / `createWebhook()` | Hooks for typed signals; webhooks for HTTP. |
|
|
59
|
-
| Child state machine (`StartExecution`) | Call [`start()`](/docs/foundations/starting-workflows) directly from the workflow | Child runs are tagged with `$parentRunId` / `$rootRunId` automatically. |
|
|
59
|
+
| Child state machine (`StartExecution`) | Call [`start()`](/docs/foundations/starting-workflows) directly from the workflow | `.sync` becomes `await run.returnValue`, which suspends without polling. Child runs are tagged with `$parentRunId` / `$rootRunId` automatically. |
|
|
60
|
+
| Unique execution `name` (Standard workflows) | `start(workflow, args, { experimental_hook: { token, experimental_minRetention: '90 days' } })` | A duplicate start throws `HookConflictError` naming the owner. Step Functions refuses a reused name for 90 days after the execution **closes**; the retention counts from `start()`, so set it to the longest the run can take plus 90 days to refuse at least as long. Where Step Functions returned the running execution for a repeated identical request, catch `HookConflictError` and return `error.conflictingRunId`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency). |
|
|
61
|
+
| `StopExecution` | `run.cancel({ cancelReason })` | Bulk cancel with `workflow cancel --status=running`. See [Cancellation](/docs/foundations/cancellation). |
|
|
60
62
|
|
|
61
63
|
A single `Task` state and its Lambda collapse into two directive-tagged functions:
|
|
62
64
|
|
|
@@ -28,7 +28,7 @@ related:
|
|
|
28
28
|
| **Versioning** | Runs pinned to their immutable deployment, making them safe by default | **No version pinning**; running instances resume on the *latest* deployed code, and changing step names/order can desync the cached replay. No patching API |
|
|
29
29
|
| **Encryption** | Per-run AES-256-GCM **end-to-end** encryption | **At-rest only** (AES-256, Cloudflare-managed keys) + TLS; no E2E, no customer-managed keys |
|
|
30
30
|
| **AI & streaming** | `WorkflowAgent` in the AI SDK; native resumable streaming | Durable agents via Workflows + the Agents SDK; resumable streaming buffered in SQLite (mid-call eviction needs opt-in `chatRecovery`) |
|
|
31
|
-
| **Performance** | No-penalty resume; scale-to-zero; up to 100K concurrency (Vercel) | **~0 ms isolate cold starts**; 50K concurrent instances; global Anycast (330+ cities), providing the strongest cold-start and edge story |
|
|
31
|
+
| **Performance** | No-penalty resume; several steps execute inline per invocation; scale-to-zero; up to 100K concurrency (Vercel) | **~0 ms isolate cold starts**; 50K concurrent instances; global Anycast (330+ cities), providing the strongest cold-start and edge story |
|
|
32
32
|
| **Portability** | Apache-2.0; World abstraction; self-hostable | Engine proprietary; tied to Durable Objects; **highest lock-in** of these tools |
|
|
33
33
|
| **Pricing** | SDK free; pay your platform | Workers Standard: requests + CPU-time + storage + per-step ($0.80 / 100K steps); idle/sleep not billed |
|
|
34
34
|
| **Limits** | 50 MB payloads; 2 GB/run; 10K steps ([Vercel World limits](https://vercel.com/docs/workflows/pricing)) | **1 MiB** step result & event payload; 1 GB state/instance; 10K steps (up to 25K) |
|
|
@@ -64,6 +64,9 @@ There's no automated migration skill for Cloudflare specifically, but the mappin
|
|
|
64
64
|
| `step.waitForEvent` | `createHook()` / `createWebhook()` |
|
|
65
65
|
| Per-step `retries` config (`limit`, `delay`, `backoff`) | `maxRetries` caps attempts; any backoff curve via [`RetryableError`](/docs/api-reference/workflow/retryable-error)'s `retryAfter` derived from [`getStepMetadata().attempt`](/docs/api-reference/workflow/get-step-metadata); `FatalError` stops retries. See [Errors & Retrying](/docs/foundations/errors-and-retries#advanced-example) |
|
|
66
66
|
| `env.MY_WORKFLOW.create(...)` binding | `start(workflow, [args])` from your app |
|
|
67
|
+
| Custom instance `id` on `create({ id })` | `start(workflow, args, { experimental_hook: { token } })`; a duplicate start throws `HookConflictError` naming the owner. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) |
|
|
68
|
+
| `instance.sendEvent({ type, payload })` | `resumeHook(token, payload)` for a `createHook({ token })` in the workflow |
|
|
69
|
+
| `instance.terminate()` | `run.cancel({ cancelReason })` |
|
|
67
70
|
|
|
68
71
|
Side effects that lived in `step.do` callbacks move into named `"use step"` functions; the orchestration becomes plain `await` / `if` / `Promise.all` instead of the `WorkflowEntrypoint` class.
|
|
69
72
|
|
|
@@ -7,6 +7,7 @@ prerequisites:
|
|
|
7
7
|
- /docs/foundations/workflows-and-steps
|
|
8
8
|
related:
|
|
9
9
|
- /docs/foundations/hooks
|
|
10
|
+
- /docs/foundations/idempotency
|
|
10
11
|
- /docs/foundations/streaming
|
|
11
12
|
- /docs/ai
|
|
12
13
|
---
|
|
@@ -27,6 +28,8 @@ related:
|
|
|
27
28
|
| **Where execution runs** | Orchestration + execution co-located on your platform | **Your code runs on your infrastructure**; Inngest invokes it per step over HTTP (Serve) or a persistent worker connection (Connect, in public beta) |
|
|
28
29
|
| **Languages** | TypeScript / JavaScript (Python beta) | TypeScript; Python and Go (production, pre-1.0) |
|
|
29
30
|
| **Versioning** | Runs pinned to immutable deployment | Tracked by step-ID hashes: hot-edit functions, but editing a step's logic under the **same ID** reuses the old memoized result for in-flight runs; rename the ID or route a new function by timestamp for rewrites |
|
|
31
|
+
| **Duplicate starts** | `start(workflow, args, { experimental_hook: { token } })` admits one run per token, with an optional retention after the run ends | `idempotency` key (24-hour window) or `singleton` |
|
|
32
|
+
| **Searching runs** | String [attributes](/docs/observability/attributes) set with `setAttributes()` or at `start()`, filterable by `key=value` | Search by event payload in the Inngest dashboard |
|
|
30
33
|
| **AI & streaming** | `WorkflowAgent` in the AI SDK; native resumable streaming | Native AI SDK via `step.ai.wrap`; **AgentKit** multi-agent framework and durable **Realtime** (`step.realtime.publish`) + `useAgent` hook, both Developer Preview |
|
|
31
34
|
| **Security** | Zero-config per-run end-to-end (E2E) encryption by default; platform security is per World (the Vercel World inherits Vercel's security posture) | Runs on your infrastructure; signed requests; first-party E2E encryption middleware (TypeScript and Python); SOC 2 Type II, HIPAA add-on |
|
|
32
35
|
| **Portability** | Apache-2.0; World abstraction; **self-host supported** | Engine open source (Server Side Public License); self-host via single Go binary + Postgres, but **self-hosting is community/best-effort**: no support service-level agreement, and the `inngest start` binary is Beta (the hosted service is the default) |
|
|
@@ -39,7 +42,9 @@ related:
|
|
|
39
42
|
|
|
40
43
|
Inngest's engine lives outside your code and calls your functions step-by-step over HTTP (or a Connect worker). That keeps your code on your own infrastructure for portability and data locality, but adds a network round trip per step. This overhead matters for workflows with many small sequential steps. The Workflow SDK co-locates orchestration and execution on one platform, so steps don't require a per-step HTTP request.
|
|
41
44
|
|
|
42
|
-
|
|
45
|
+
Since v5, one invocation also runs as many steps as it can in a single pass, several of them in parallel, and only hands back to the queue for a wait, a hook, or when the function nears its time limit. A chain of small steps therefore costs a few invocations rather than one per step. See [Performance](/docs/performance) for the benchmarks.
|
|
46
|
+
|
|
47
|
+
Triggering also differs. Inngest is event-driven (publishers `send` events; functions subscribe), which supports loosely coupled fan-out. The Workflow SDK's `start()` imports the workflow function directly, providing tighter coupling and stronger type safety. For event-bus-style fan-out, wrap `start()` in a shared publisher. A run can also call `start()` itself to spawn a child run, without wrapping it in a step.
|
|
43
48
|
|
|
44
49
|
## Versioning
|
|
45
50
|
|
|
@@ -53,50 +58,288 @@ Inngest offers `step.ai.wrap()` (wrap Vercel AI SDK calls as durable steps), **A
|
|
|
53
58
|
|
|
54
59
|
## Migrating from Inngest
|
|
55
60
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
61
|
+
### Run the codemod
|
|
62
|
+
|
|
63
|
+
The `workflow` CLI includes a codemod that does the mechanical part of a migration. Run it from your project root, on a clean working tree so its changes are easy to review:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
npx workflow migrate inngest
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
It reads the project's `tsconfig.json` to find the files to migrate, and uses the project's own TypeScript. Pass paths to limit it (`npx workflow migrate inngest src/inngest`), `--dry-run` to see what would change without writing anything, and `--report <file>` to write a Markdown report. See [`workflow migrate`](/docs/configuration/cli-and-web-ui#migrate-from-inngest) for every flag.
|
|
70
|
+
|
|
71
|
+
The main job is lifting each `step.run()` closure into a named `"use step"` function. A closure can read anything in scope, but a step function only gets its arguments, because they are recorded in the event log. So the codemod finds every variable the closure reads from the handler (the event, earlier step results, loop variables), makes each one a parameter of the new step function, and passes it at the call site. It lists the captured variables of every step it lifts, so you can check that each one is [serializable](/docs/foundations/serialization). Variables declared at module scope, such as imports and constants, stay visible to a module-level step and are not passed.
|
|
72
|
+
|
|
73
|
+
{/* @skip-typecheck: Inngest code, the input of the codemod */}
|
|
74
|
+
```typescript title="inngest/functions.ts (before)"
|
|
75
|
+
import { inngest } from './client';
|
|
76
|
+
import { userActive, userSignup } from './events';
|
|
77
|
+
import { db, email } from './services';
|
|
78
|
+
|
|
79
|
+
export const onboardUser = inngest.createFunction(
|
|
80
|
+
{ id: 'onboard-user', retries: 5, triggers: [userSignup] },
|
|
81
|
+
async ({ event, step }) => {
|
|
82
|
+
const user = await step.run('create-user', () =>
|
|
83
|
+
db.users.create({ id: event.data.userId, email: event.data.email })
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
await step.sleep('wait-a-day', '1d');
|
|
87
|
+
|
|
88
|
+
const activity = await step.waitForEvent('wait-for-activity', {
|
|
89
|
+
event: userActive,
|
|
90
|
+
timeout: '7d',
|
|
91
|
+
match: 'data.userId',
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
await step.run('send-follow-up', () =>
|
|
95
|
+
email.send(user.email, activity ? 'tips' : 'nudge')
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
);
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
```typescript title="inngest/functions.ts (after, formatted)"
|
|
102
|
+
import { createHook, type Hook, sleep } from 'workflow';
|
|
103
|
+
declare const db: { users: { create(user: { id: string; email: string }): Promise<{ id: string; email: string }> } }; // @setup
|
|
104
|
+
declare const email: { send(to: string, template: string): Promise<void> }; // @setup
|
|
66
105
|
|
|
67
|
-
|
|
106
|
+
export async function onboardUser(event: {
|
|
107
|
+
data: { userId: string; email: string };
|
|
108
|
+
}) {
|
|
109
|
+
'use workflow';
|
|
110
|
+
const user = await createUser(event); // [!code highlight]
|
|
68
111
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
|
|
112
|
+
await sleep('1d');
|
|
113
|
+
|
|
114
|
+
// TODO(workflow-migrate): Only one run at a time can own this hook token. Inngest resumed every run waiting for a matching "app/user.active"; if two onboardUser runs can wait for the same key at once, add something unique to the token (for example the run ID) and resume each run where the event is sent. Otherwise, delete this comment.
|
|
115
|
+
const activity = await waitForHook(
|
|
116
|
+
createHook({ token: `app/user.active:onboardUser:${event.data.userId}` }), // [!code highlight]
|
|
117
|
+
sleep('7d')
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
await sendFollowUp(user, activity); // [!code highlight]
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function createUser(event: { data: { userId: string; email: string } }) {
|
|
124
|
+
'use step';
|
|
125
|
+
return db.users.create({ id: event.data.userId, email: event.data.email });
|
|
126
|
+
}
|
|
127
|
+
createUser.maxRetries = 5;
|
|
128
|
+
|
|
129
|
+
async function sendFollowUp(
|
|
130
|
+
user: { id: string; email: string },
|
|
131
|
+
activity: any
|
|
132
|
+
) {
|
|
133
|
+
'use step';
|
|
134
|
+
return email.send(user.email, activity ? 'tips' : 'nudge');
|
|
74
135
|
}
|
|
136
|
+
sendFollowUp.maxRetries = 5;
|
|
75
137
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
138
|
+
/** Resolves with the hook's payload, or with null once `timeout` resolves. */
|
|
139
|
+
async function waitForHook<T>(
|
|
140
|
+
hook: Hook<T>,
|
|
141
|
+
timeout?: Promise<void>
|
|
142
|
+
): Promise<T | null> {
|
|
143
|
+
try {
|
|
144
|
+
return await (timeout
|
|
145
|
+
? Promise.race([hook, timeout.then(() => null)])
|
|
146
|
+
: hook);
|
|
147
|
+
} finally {
|
|
148
|
+
hook.dispose();
|
|
149
|
+
}
|
|
80
150
|
}
|
|
81
151
|
```
|
|
82
152
|
|
|
153
|
+
The run above prints each step it lifted with the variables it captured:
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
inngest/functions.ts
|
|
157
|
+
onboardUser (was onboard-user)
|
|
158
|
+
step create-user -> createUser() captures event
|
|
159
|
+
step send-follow-up -> sendFollowUp() captures user, activity
|
|
160
|
+
hook app/user.active -> token `app/user.active:onboardUser:${event.data.userId}`
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Beyond `step.run()`, the codemod:
|
|
164
|
+
|
|
165
|
+
- Turns each `createFunction()` into an exported `"use workflow"` function that takes the triggering event as its argument, so `event.data` keeps working. With typed events, it types the parameter, and it types each captured parameter from its call site.
|
|
166
|
+
- Rewrites `step.sleep()`, `step.sleepUntil()`, `step.fetch()`, `step.invoke()` and `step.ai.wrap()`. A `step.ai.wrap()` step evaluates its inputs itself, so the model object is never passed as an argument, and returns only the fields you destructure from the result.
|
|
167
|
+
- Turns `step.waitForEvent()` and `step.waitForSignal()` into a hook raced against `sleep()`, through a small `waitForHook()` helper it adds to the file. The helper disposes the hook when the wait ends, so a later wait in the same run can use the same token, as Inngest allowed. A `waitForEvent()` token is built from the event name, the workflow name, and the value `match` compared (or an `if` expression that compares one field), so the code that sent the event can build the same token for `resumeHook()`.
|
|
168
|
+
- Turns `retries` into `maxRetries` on every step, `NonRetriableError` into `FatalError`, `RetryAfterError` into `RetryableError`, `runId` into `getWorkflowMetadata().workflowRunId`, `attempt` into `getStepMetadata().attempt - 1`, and `logger` into `console`. It follows `const` references, so `retries: MAX_RETRIES` and a config object declared elsewhere in the file are read too.
|
|
169
|
+
- Imports the Workflow APIs it uses under an alias when the file already has a binding with that name, and removes imports that nothing uses any more, such as the Inngest client and the error classes.
|
|
170
|
+
|
|
171
|
+
It never guesses. Code it cannot migrate without changing behavior is left in place under a `// TODO(workflow-migrate): ...` comment that says what to do. That covers a closure that assigns to a variable outside it (the write would be lost once the value is passed by value), a closure that calls a function declared in the handler, `step.sendEvent()`, flow-control options, cron triggers, function options it cannot read, and global `fetch()` calls outside a step. Every migrated `waitForEvent()` also gets one, because of [one owner per token](#one-owner-per-token).
|
|
172
|
+
|
|
173
|
+
The report lists every `inngest.send()` and `serve()` call in the project with its replacement, and has an **Event routing** table: for each event name, the workflows it starts and the hook tokens it resumes. That table is what you need to rewrite an app that forwards events generically, such as `inngest.send({ name: req.body.name, data: req.body.data })`.
|
|
174
|
+
|
|
175
|
+
### What the codemod converts
|
|
176
|
+
|
|
177
|
+
| Inngest | Converted automatically | Left as a TODO |
|
|
178
|
+
| --- | --- | --- |
|
|
179
|
+
| `createFunction()` | Module-level function, assigned to a `const` or `export default` | Created inside another function, or not assigned |
|
|
180
|
+
| Function options | `id`, `triggers`, `retries`, also through `const` references | `concurrency`, `throttle`, `rateLimit`, `debounce`, `batchEvents`, `priority`, `timeouts`, `cancelOn`, `idempotency`, `singleton`, `middleware`, cron triggers; options it cannot read; `onFailure` (kept as a named function) |
|
|
181
|
+
| `step.run()` | Closures and function references, with captured variables, inputs, and parameter defaults or computed keys | Closures that assign to a captured variable, call a function declared in the handler, use `this`, or call another step |
|
|
182
|
+
| `step.sleep()` / `step.sleepUntil()` / `step.fetch()` / `step.invoke()` | Yes | `step.invoke()` given a function by reference |
|
|
183
|
+
| `step.waitForEvent()` | `match`, or an `if` that compares one field | Any other `if`, a wait with neither, and the [one owner per token](#one-owner-per-token) check |
|
|
184
|
+
| `step.waitForSignal()` | Yes, keeping the `{ signal, data }` result, and a replaced wait timing out with `null` | None |
|
|
185
|
+
| `step.ai.wrap()` | Yes | Inputs that `await` |
|
|
186
|
+
| `step.sendEvent()`, `step.sendSignal()`, `step.ai.infer()`, `step.realtime.publish()` | None | All |
|
|
187
|
+
| Handler context | `event`, `runId`, `attempt`, `logger` | `events` (batches), middleware context |
|
|
188
|
+
|
|
83
189
|
<Callout type="info">
|
|
84
|
-
|
|
190
|
+
For what the codemod leaves to you, install the migration skill and ask your agent to finish the migration:
|
|
85
191
|
|
|
86
192
|
```bash
|
|
87
193
|
npx skills add https://github.com/vercel/workflow --skill migrating-to-workflow-sdk
|
|
88
194
|
```
|
|
89
195
|
</Callout>
|
|
90
196
|
|
|
91
|
-
###
|
|
197
|
+
### Concept mapping
|
|
198
|
+
|
|
199
|
+
| Inngest | Workflow SDK | Note |
|
|
200
|
+
| --- | --- | --- |
|
|
201
|
+
| `inngest.createFunction()` | `"use workflow"` function started with `start()` | No factory or event binding. |
|
|
202
|
+
| `step.run()` | `"use step"` function | Named async function with Node.js access. Variables the closure captured become arguments. |
|
|
203
|
+
| `step.sleep()` / `step.sleepUntil()` | `sleep('5m')` / `sleep(date)` | Import from `workflow`. |
|
|
204
|
+
| `step.waitForEvent()` | `createHook()` raced against `sleep()`, disposed when the wait ends | The token encodes what `match` compared; `resumeHook(token, event)` replaces sending the event, once for each workflow waiting for it. One run owns a token at a time: see [One owner per token](#one-owner-per-token). Use [`createWebhook()`](/docs/api-reference/workflow/create-webhook) when the sender needs a URL to call. |
|
|
205
|
+
| `step.waitForSignal()` / `inngest.sendSignal()` | `createHook({ token: signal })` / `resumeHook(signal, { signal, data })` | Resume with the `{ signal, data }` envelope, so code that reads `result.data` keeps working. `onConflict: 'replace'` maps to [`experimental_force: true`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds). The replaced run's `await hook` rejects with `HookForceClaimedError`; where Inngest left that wait pending until its timeout and then returned `null`, the codemod's helper catches the error and does the same. |
|
|
206
|
+
| `step.invoke()` | [`start()`](/docs/foundations/starting-workflows) called in the workflow, then `await run.returnValue` | Spawns a child run; the parent waits without polling. |
|
|
207
|
+
| `inngest.send()` / event triggers | `start()` from your app boundary | Start workflows directly. |
|
|
208
|
+
| `idempotency` | [`start(workflow, args, { experimental_hook: { token, experimental_minRetention: '24h' } })`](/docs/foundations/idempotency#start-a-run-once-per-key) | A duplicate start throws `HookConflictError` naming the run that owns the token, for 24 hours from the first start, as Inngest's idempotency window does. |
|
|
209
|
+
| `singleton: { mode: 'skip' }` | `start(workflow, args, { experimental_hook: { token } })` without a retention | Only overlapping runs are refused: the token is released when the run ends, so the next start is admitted. Catch `HookConflictError` to skip. |
|
|
210
|
+
| `singleton: { mode: 'cancel' }` | On `HookConflictError`, `await getRun(error.conflictingRunId).cancel()`, then start again | The newest run replaces the running one. Don't set a retention: a retained token stays refused after the cancel. |
|
|
211
|
+
| `cancelOn` / cancel from the dashboard | [`run.cancel()`](/docs/foundations/cancellation), or an `AbortController` whose signal is passed into steps | `run.cancel({ cancelReason })` records why. `workflow cancel --status running --workflowName <id>` cancels in bulk. |
|
|
212
|
+
| `retries` / `RetryAfterError` / `NonRetriableError` | `stepFn.maxRetries`, `RetryableError`, `FatalError` | Retries live at the step boundary. For custom backoff via `retryAfter`, see [Errors & Retrying](/docs/foundations/errors-and-retries#customize-retry-behavior). |
|
|
213
|
+
| `step.fetch()` | [`fetch`](/docs/api-reference/workflow/fetch) from `workflow` | A step that makes the request. |
|
|
214
|
+
| `step.ai.wrap()` | A `"use step"` function that calls the model | Or [`WorkflowAgent`](/docs/ai) for an agent loop. |
|
|
215
|
+
| `runId` / `attempt` | `getWorkflowMetadata().workflowRunId` / `getStepMetadata().attempt - 1` | `getStepMetadata().attempt` counts from 1, where Inngest counted from 0, and it is only available inside a step. |
|
|
216
|
+
| `step.realtime.publish()` / Realtime | `getWritable()` / named streams | Clients read from the stream. |
|
|
217
|
+
| Event payload search | [`setAttributes()`](/docs/api-reference/workflow/set-attributes) or `start({ attributes })` | Filter runs by `key=value` in the CLI, the web UI, and Vercel Observability. |
|
|
218
|
+
|
|
219
|
+
### What behaves differently
|
|
220
|
+
|
|
221
|
+
- **Step results keep their types.** Inngest serializes step results as JSON, so a `Date` came back as a string and a step that returned nothing came back as `null`. The Workflow SDK keeps `Date`, `Map`, `Set`, `URL`, typed arrays and the other [serializable types](/docs/foundations/serialization), and a step that returns nothing returns `undefined`. Code that parsed a string back into a `Date` keeps working; code that used the string directly needs a change.
|
|
222
|
+
- **Code outside steps runs in a sandbox.** An Inngest handler could call `fetch()` or a database outside `step.run()`, and the call ran again on every request. A workflow function runs deterministically, without Node.js APIs or I/O, so move that code into a step.
|
|
223
|
+
- **Step arguments are copies.** A step that changed a captured object in Inngest only changed it in the invocation that ran the step, and a memoized step does not run again. The same change is invisible to the workflow here, so return the new value instead.
|
|
224
|
+
- **The event shape is yours.** The workflow receives what you pass to `start()`. Fields Inngest filled in, such as `event.id` and `event.ts`, are only there if you pass them; use `getWorkflowMetadata()` for the run ID and start time.
|
|
225
|
+
|
|
226
|
+
### One owner per token
|
|
227
|
+
|
|
228
|
+
Inngest delivers an event to every run waiting for it. A hook token has one owner at a time: while a run holds it, another `createHook()` with the same token rejects with [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error). Three cases follow:
|
|
229
|
+
|
|
230
|
+
- **Two workflows waiting for the same event.** The codemod puts the workflow name in the token (`app/user.active:onboardUser:${userId}`), so each has its own. Where the event is sent, resume each of them; the report's Event routing table lists the tokens.
|
|
231
|
+
- **The same run waiting again.** The generated `waitForHook()` helper disposes the hook when the wait ends, so the next wait can create it again.
|
|
232
|
+
- **Two runs of the same workflow waiting for the same key at once.** This one needs a decision. Add something unique to the token, such as the run ID or the ID of the record the run handles, and resume each run from the sender. If only one run can wait per key, delete the TODO.
|
|
233
|
+
|
|
234
|
+
### Verify the migration
|
|
92
235
|
|
|
93
|
-
|
|
236
|
+
Before you switch traffic, run the same inputs through both versions and compare what each run returns:
|
|
94
237
|
|
|
95
|
-
|
|
238
|
+
1. Keep a copy of the Inngest app and run it against the Inngest dev server (`npx inngest-cli dev`).
|
|
239
|
+
2. Build the migrated app and run it locally against the [Local World](/worlds/local).
|
|
240
|
+
3. Give both apps the same entry points: one that sends an event, one that sends a signal, and one that reads a run's result. On the Inngest side, these call `inngest.send()`, `inngest.sendSignal()` and the dev server's API. On the Workflow side, they call `start()` and `resumeHook()` as the Event routing table says, and `getRun()`.
|
|
241
|
+
4. For every function, send the events that drive each path (success, the fatal error, retries, a wait that is resumed, a wait that times out) and compare the outputs and final statuses.
|
|
242
|
+
|
|
243
|
+
Also typecheck and build the migrated app: the codemod's annotations are checked against your project, but your own types only meet the new code once you build.
|
|
244
|
+
|
|
245
|
+
### Cut over
|
|
246
|
+
|
|
247
|
+
Runs started on Inngest keep running on Inngest. Move new work to the Workflow SDK, and keep the Inngest app deployed until its in-flight runs, sleeps and waits have drained:
|
|
248
|
+
|
|
249
|
+
1. Deploy the migrated app next to the Inngest one, with the Inngest `serve()` route still in place.
|
|
250
|
+
2. Point new events at `start()`. Senders that resume waits need both paths for a while: send the Inngest event for runs that started there, and call `resumeHook()` for runs that started on the Workflow SDK.
|
|
251
|
+
3. Keep business-level idempotency across both: a duplicate request should not start a Workflow run for work an Inngest run already does. `start({ experimental_hook: { token } })` with the same business key you used for Inngest `idempotency` covers the Workflow side.
|
|
252
|
+
4. Once no Inngest runs are left, delete the `serve()` route, the client and the `inngest` dependency. Keep protecting the endpoints that start or resume runs the way you protected the ones that sent events, and point dashboards and alerts at the Workflow SDK's [observability](/docs/observability).
|
|
253
|
+
|
|
254
|
+
### Flow control, schedules and failure handling
|
|
255
|
+
|
|
256
|
+
Inngest configures these on the function, and its event bus applies them before a run starts. The Workflow SDK has no event bus between the sender and the run, so you build each one where it belongs. A [start token](/docs/foundations/idempotency#run-idempotency) on `start()` keeps duplicate or excess work from ever becoming a run. A hook, a `sleep()` or a step inside the run handles the rest:
|
|
257
|
+
|
|
258
|
+
| Inngest | With the Workflow SDK |
|
|
96
259
|
| --- | --- |
|
|
97
|
-
|
|
|
98
|
-
|
|
|
99
|
-
|
|
|
260
|
+
| `rateLimit: { key, limit: 1, period }` | A start token per key, retained for the period. A second start before the period has passed throws `HookConflictError`; skip it. See [Rate limit](#rate-limit). |
|
|
261
|
+
| `debounce: { key, period }` | One run per key and window that waits out the window, then reads the current state in a step. See [Debounce](#debounce). |
|
|
262
|
+
| `batchEvents: { maxSize, timeout, key }` | The same shape as debounce: store each event where a step can read it, such as a table keyed by the batch key, start one run per window, and read the whole batch in a step once the window ends. |
|
|
263
|
+
| `concurrency: { key, limit: 1 }` where overlapping runs can be dropped | The `singleton: { mode: 'skip' }` row in [Concept mapping](#concept-mapping): a start token with no retention. |
|
|
264
|
+
| `concurrency` where runs wait their turn | Native per-key locks are in development (see the [concurrency controls discussion](https://github.com/vercel/workflow/discussions/301)). Until they ship, keep the lock you use today inside the steps that need it, and make those steps safe to repeat. |
|
|
265
|
+
| `throttle` | For a downstream API's limit, throw `RetryableError` with the provider's `retryAfter` from the step. See [Rate Limiting & Retries](/cookbook/common-patterns/rate-limiting). Native rate limiting inside runs is in development alongside locks. |
|
|
266
|
+
| `priority` | No equivalent. Runs start in the order `start()` is called. |
|
|
267
|
+
| Cron triggers | [Vercel Schedules](https://vercel.com/docs/schedules/workflows). A schedule publishes to a queue topic, and its consumer calls `start()` with the occurrence's `executionId` in the start token, retained for longer than redeliveries can arrive (for example `experimental_minRetention: '7 days'`), so a redelivered occurrence never starts a second run, even after the first has finished. Schedules take an IANA `timezone` and also run in Preview branches and custom environments. |
|
|
268
|
+
| Several functions triggered by one event | One `start()` per target workflow where the event is sent, each with its own start token, such as `` `${targetName}:${event.id}` ``, retained with `experimental_minRetention: '24h'`. A retried send within 24 hours then never starts a target twice, even one that has already finished, as with Inngest's 24-hour deduplication of events by `id`. Without the retention, the token is released when the target's run ends. |
|
|
269
|
+
| `onFailure` | [`registerLifecycleHooks({ onRunFailed })`](/docs/api-reference/workflow-api/register-lifecycle-hooks) reports failed runs from one place, for example to Slack or Sentry. It is best-effort. Where a workflow must compensate, also wrap its body in `try`/`catch`, call a cleanup step in `catch`, then rethrow. |
|
|
270
|
+
|
|
271
|
+
#### Rate limit
|
|
272
|
+
|
|
273
|
+
Inngest's `rateLimit` drops events once the limit for a key is reached in the period. A start token retained for the period does the same for `limit: 1`. The token stays taken until the period has passed since the accepted start, and for as long as that run is still running:
|
|
274
|
+
|
|
275
|
+
```typescript lineNumbers
|
|
276
|
+
import { start } from "workflow/api";
|
|
277
|
+
import { HookConflictError } from "workflow/errors";
|
|
278
|
+
declare function syncAccount(accountId: string): Promise<void>; // @setup
|
|
279
|
+
|
|
280
|
+
// Inngest: rateLimit: { key: "event.data.accountId", limit: 1, period: "1m" }
|
|
281
|
+
export async function requestSync(accountId: string) {
|
|
282
|
+
try {
|
|
283
|
+
await start(syncAccount, [accountId], {
|
|
284
|
+
experimental_hook: {
|
|
285
|
+
token: `sync-account:${accountId}`,
|
|
286
|
+
experimental_minRetention: "1m", // [!code highlight]
|
|
287
|
+
},
|
|
288
|
+
});
|
|
289
|
+
return { started: true };
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (HookConflictError.is(error)) return { started: false }; // rate-limited
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
To limit by fixed windows instead, put the window number in the token, as in `` `sync-account:${accountId}:${Math.floor(Date.now() / 60_000)}` ``. For `limit: n`, try `n` tokens per window (`:0` to `:n-1`) and skip when all of them are taken.
|
|
298
|
+
|
|
299
|
+
#### Debounce
|
|
300
|
+
|
|
301
|
+
Inngest's `debounce` runs once, with the last event, after events for a key stop arriving for the period. When the run can read the current state itself, one run per key and window gives the same result with the fewest runs and events. The first event in a window starts the run, and every later event in that window is refused at `start()`, so it never becomes a run:
|
|
302
|
+
|
|
303
|
+
```typescript title="lib/pack-changed.ts" lineNumbers
|
|
304
|
+
import { start } from "workflow/api";
|
|
305
|
+
import { HookConflictError } from "workflow/errors";
|
|
306
|
+
import { refreshPack } from "@/workflows/refresh-pack";
|
|
307
|
+
|
|
308
|
+
const WINDOW_MS = 3 * 60_000; // Inngest: debounce: { key: "event.data.packId", period: "3m" }
|
|
309
|
+
|
|
310
|
+
// Call after writing the change to the database.
|
|
311
|
+
export async function packChanged(packId: string) {
|
|
312
|
+
const windowEnd = (Math.floor(Date.now() / WINDOW_MS) + 1) * WINDOW_MS;
|
|
313
|
+
try {
|
|
314
|
+
await start(refreshPack, [packId, windowEnd], {
|
|
315
|
+
experimental_hook: { token: `refresh-pack:${packId}:${windowEnd}` }, // [!code highlight]
|
|
316
|
+
});
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (!HookConflictError.is(error)) throw error; // this window already has a run
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
```typescript title="workflows/refresh-pack.ts" lineNumbers
|
|
324
|
+
import { sleep } from "workflow";
|
|
325
|
+
declare function loadAndPublishPack(packId: string): Promise<void>; // @setup
|
|
326
|
+
|
|
327
|
+
export async function refreshPack(packId: string, windowEnd: number) {
|
|
328
|
+
"use workflow";
|
|
329
|
+
|
|
330
|
+
await sleep(new Date(windowEnd + 10_000)); // the window, plus a margin for late starts
|
|
331
|
+
await refreshFromDatabase(packId);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function refreshFromDatabase(packId: string) {
|
|
335
|
+
"use step";
|
|
336
|
+
await loadAndPublishPack(packId); // reads the pack's current state
|
|
337
|
+
}
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
An event that is refused wrote its change before it picked its window, so before that window ended. The run reads the database only after the window and the margin, so it sees every change in its window. If the run has already finished, the token is free again and the late event starts a new run, which reads the change too. The difference from Inngest is the timing: a key that keeps receiving events runs once per window instead of waiting for a quiet period, so set the window to the longest delay you can accept.
|
|
341
|
+
|
|
342
|
+
When the run needs the events themselves rather than the current state, store each event before calling `start()`, as for `batchEvents`, and read the window's events in the step.
|
|
100
343
|
|
|
101
344
|
---
|
|
102
345
|
*Compiled from public documentation. Inngest tier names and pricing vary across sources; verify against [inngest.com/pricing](https://www.inngest.com/pricing). Not based on head-to-head benchmarks.*
|
|
@@ -29,7 +29,7 @@ related:
|
|
|
29
29
|
| **Versioning** | Runs pinned to their immutable deployment, safe by default; opt-in `deploymentId: 'latest'` to upgrade | Editing workflow code can break in-flight runs (non-determinism errors); evolve safely via patch APIs or Worker Versioning (keep old worker fleets draining) |
|
|
30
30
|
| **AI SDK & agents** | `WorkflowAgent` ships in the AI SDK; durable agent loop; **native resumable streaming** (`getWritable`/`getReadable`, `WorkflowChatTransport`) | First-party `@temporalio/ai-sdk` and "Workflow Streams", both **Public Preview**; streaming rides on Signals/Updates (batched, history-bound) |
|
|
31
31
|
| **Security** | Zero-config per-run AES-256-GCM E2E encryption by default; platform security is per World (the Vercel World inherits Vercel's security posture) | Workers run your code on your infrastructure (never enters Temporal's plane); client-side E2E via a Codec Server you operate. Cloud: SOC 2 II, HIPAA, GDPR |
|
|
32
|
-
| **Performance** | No-penalty resume; serverless scale-to-zero (true suspension); up to 100,000 concurrency on Vercel | Self-managed workers are long-running; Cloud namespace default 500 actions/sec (auto-scales) |
|
|
32
|
+
| **Performance** | No-penalty resume; several steps execute inline per invocation, and the queue is used only for waits, hooks, or a function nearing its timeout; serverless scale-to-zero (true suspension); up to 100,000 concurrency on Vercel | Self-managed workers are long-running; Cloud namespace default 500 actions/sec (auto-scales) |
|
|
33
33
|
| **Portability** | Apache-2.0 SDK; World abstraction swaps storage/queue/streams independently | MIT server; pluggable persistence (Cassandra/Postgres/MySQL), but an opinionated monolithic backend you run or pay for |
|
|
34
34
|
| **Pricing** | SDK free; pay your platform (Vercel: events + data) or only your infrastructure if self-hosted | Self-host = free software; Temporal Cloud bills per Action (from $50 per million) + storage |
|
|
35
35
|
| **Limits** | No run/sleep cap; 10,000 steps, 50 MB payload, 2 GB/run ([Vercel World limits](https://vercel.com/docs/workflows/pricing)) | No run cap (Continue-As-New for long histories); event history capped at 51,200 events / 50 MB; 2 MB payloads |
|
|
@@ -66,9 +66,13 @@ The model maps closely. Keep your orchestration logic; drop the workers, task qu
|
|
|
66
66
|
| Worker + Task Queue | Managed execution | No worker fleet or polling loop to operate. |
|
|
67
67
|
| Signal | `createHook()` / `createWebhook()` | Hooks for typed resume signals; webhooks for HTTP callbacks. |
|
|
68
68
|
| Query | `getWritable({ namespace: 'status' })` stream | Stream status durably; clients read the stream instead of polling. |
|
|
69
|
-
| Child Workflow | Call [`start()`](/docs/foundations/starting-workflows) directly from the workflow | Child runs are tagged with `$parentRunId` / `$rootRunId` automatically. |
|
|
69
|
+
| Child Workflow | Call [`start()`](/docs/foundations/starting-workflows) directly from the workflow | `await run.returnValue` suspends without polling. Child runs are tagged with `$parentRunId` / `$rootRunId` automatically. |
|
|
70
|
+
| `continueAsNew()` | `start()` the same workflow from inside the workflow, then return | Pass `deploymentId: 'latest'` to move onto new code. See [Self upgrading workflows](/docs/foundations/versioning#self-upgrading-workflows). |
|
|
71
|
+
| Workflow ID + reuse / conflict policy | `start(workflow, args, { experimental_hook: { token } })` | A duplicate start throws `HookConflictError` naming the owner. `experimental_minRetention` keeps refusing after the run ends. See [Run idempotency](/docs/foundations/idempotency#run-idempotency). |
|
|
72
|
+
| Cancellation scopes / `handle.cancel()` | `AbortController` passed into steps; `run.cancel({ cancelReason })` | An abort reaches a step that is already running. See [Cancellation](/docs/foundations/cancellation). |
|
|
70
73
|
| Activity retry policy | `maxRetries`, `RetryableError`, `FatalError` | Retries live at the step boundary. See [Errors & Retrying](/docs/foundations/errors-and-retries). |
|
|
71
74
|
| Search attributes / visibility queries | [`setAttributes()`](/docs/api-reference/workflow/set-attributes) / `attributes` option on `start()` | Filter runs by `key=value`. See [Attributes](/docs/observability/attributes). |
|
|
75
|
+
| Memo | Workflow arguments, the return value, or a [stream](/docs/foundations/streaming) | Attributes are searchable plaintext strings (up to 256 bytes each, 64 per run), not a place for arbitrary data. Promote only the small labels you filter by. |
|
|
72
76
|
| Event History | Workflow event log / run timeline | Same durable replay; built-in observability UI. |
|
|
73
77
|
|
|
74
78
|
A minimal translation, where the orchestrator loses `proxyActivities` and becomes plain TypeScript:
|
|
@@ -58,6 +58,8 @@ trigger.dev offers AI SDK tool wrapping, a native `useChat` transport over its R
|
|
|
58
58
|
| `wait.forToken({ timeout })` | `createHook()` + `Promise.race` with `sleep()` | Hooks carry a typed token. |
|
|
59
59
|
| `triggerAndWait()` | [`start()`](/docs/foundations/starting-workflows) called directly from the workflow, then await the returned `Run` | Spawn + collect. |
|
|
60
60
|
| `batch.triggerAndWait()` | `Promise.all` over collected `Run` handles | Standard concurrency. |
|
|
61
|
+
| `idempotencyKey` / `idempotencyKeyTTL` | `start(workflow, args, { experimental_hook: { token, experimental_minRetention } })` | A duplicate start throws `HookConflictError` naming the owner. See [Run idempotency](/docs/foundations/idempotency#run-idempotency). |
|
|
62
|
+
| `runs.cancel()` / task `signal` | `run.cancel({ cancelReason })`; `AbortController` passed into steps | An abort reaches a step that is already running. See [Cancellation](/docs/foundations/cancellation). |
|
|
61
63
|
| `metadata.stream()` / Realtime | `getWritable()` / named streams | Clients read from the stream. |
|
|
62
64
|
| Run tags / `metadata.set()` | [`setAttributes()`](/docs/api-reference/workflow/set-attributes) / `attributes` option on `start()` | Filter runs by `key=value`. See [Attributes](/docs/observability/attributes). |
|
|
63
65
|
| `AbortTaskRunError` | `FatalError` | Stops retries immediately. |
|