workflow 5.7.1 → 5.8.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/internal/errors.d.ts +1 -1
- package/dist/internal/errors.js +2 -2
- package/docs/advanced/quickjs-runtime.mdx +4 -4
- package/docs/ai/sleep-and-delays.mdx +1 -1
- package/docs/api-reference/workflow/fetch.mdx +1 -1
- package/docs/api-reference/workflow/index.mdx +3 -0
- package/docs/api-reference/workflow/rate-limit.mdx +114 -0
- package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +1 -1
- package/docs/api-reference/workflow-errors/throttle-error.mdx +1 -1
- package/docs/api-reference/workflow-nitro/index.mdx +1 -0
- package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +1 -1
- package/docs/comparisons/workflow-sdk-vs-inngest.mdx +49 -5
- package/docs/comparisons/workflow-sdk-vs-temporal.mdx +1 -0
- package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +3 -1
- package/docs/configuration/cli-and-web-ui.mdx +15 -0
- package/docs/configuration/framework-options.mdx +6 -0
- package/docs/configuration/runtime-tuning.mdx +18 -8
- package/docs/cookbook/common-patterns/batching.mdx +2 -2
- package/docs/cookbook/common-patterns/rate-limiting.mdx +27 -2
- package/docs/cookbook/index.mdx +1 -1
- package/docs/errors/max-events-exceeded.mdx +2 -1
- package/docs/errors/rate-limit-max-wait.mdx +31 -0
- package/docs/foundations/errors-and-retries.mdx +2 -0
- package/docs/foundations/meta.json +1 -0
- package/docs/foundations/rate-limits.mdx +181 -0
- package/docs/observability/meta.json +1 -1
- package/docs/observability/retention.mdx +2 -1
- package/docs/observability/usage.mdx +83 -0
- package/docs/worlds/building-a-world.mdx +5 -3
- package/docs/worlds/local.mdx +2 -0
- package/docs/worlds/postgres.mdx +2 -0
- package/docs/worlds/upgrading-to-v5.mdx +2 -2
- package/package.json +11 -11
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { DynamicWorkflowsNotEnabledError, EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, InBandSupersededError, PreconditionFailedError, RunExpiredError, RunNotSupportedError, StepNotRegisteredError, StreamError, ThrottleError, TooEarlyError, WorkflowError, WorkflowNotRegisteredError, WorkflowRunCancelledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRunNotFoundError, WorkflowRuntimeError, WorkflowStartError, WorkflowWorldError, } from '@workflow/errors';
|
|
1
|
+
export { DynamicWorkflowsNotEnabledError, EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, InBandSupersededError, PreconditionFailedError, RateLimitMaxWaitError, RunExpiredError, RunNotSupportedError, StepNotRegisteredError, StreamError, ThrottleError, TooEarlyError, WorkflowError, WorkflowNotRegisteredError, WorkflowRunCancelledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRunNotFoundError, WorkflowRuntimeError, WorkflowStartError, WorkflowWorldError, } from '@workflow/errors';
|
|
2
2
|
//# sourceMappingURL=errors.d.ts.map
|
package/dist/internal/errors.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { DynamicWorkflowsNotEnabledError, EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, InBandSupersededError, PreconditionFailedError, RunExpiredError, RunNotSupportedError, StepNotRegisteredError, StreamError, ThrottleError, TooEarlyError, WorkflowError, WorkflowNotRegisteredError, WorkflowRunCancelledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRunNotFoundError, WorkflowRuntimeError, WorkflowStartError, WorkflowWorldError, } from '@workflow/errors';
|
|
2
|
-
//# sourceMappingURL=data:application/json;base64,
|
|
1
|
+
export { DynamicWorkflowsNotEnabledError, EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, InBandSupersededError, PreconditionFailedError, RateLimitMaxWaitError, RunExpiredError, RunNotSupportedError, StepNotRegisteredError, StreamError, ThrottleError, TooEarlyError, WorkflowError, WorkflowNotRegisteredError, WorkflowRunCancelledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRunNotFoundError, WorkflowRuntimeError, WorkflowStartError, WorkflowWorldError, } from '@workflow/errors';
|
|
2
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2ludGVybmFsL2Vycm9ycy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQ0wsK0JBQStCLEVBQy9CLG1CQUFtQixFQUNuQixpQkFBaUIsRUFDakIscUJBQXFCLEVBQ3JCLGlCQUFpQixFQUNqQixxQkFBcUIsRUFDckIsdUJBQXVCLEVBQ3ZCLHFCQUFxQixFQUNyQixlQUFlLEVBQ2Ysb0JBQW9CLEVBQ3BCLHNCQUFzQixFQUN0QixXQUFXLEVBQ1gsYUFBYSxFQUNiLGFBQWEsRUFDYixhQUFhLEVBQ2IsMEJBQTBCLEVBQzFCLHlCQUF5QixFQUN6QixzQkFBc0IsRUFDdEIsNEJBQTRCLEVBQzVCLHdCQUF3QixFQUN4QixvQkFBb0IsRUFDcEIsa0JBQWtCLEVBQ2xCLGtCQUFrQixHQUNuQixNQUFNLGtCQUFrQixDQUFDIn0=
|
|
@@ -25,7 +25,7 @@ Set `WORKFLOW_VM=quickjs` in the environment that starts runs, which is the proc
|
|
|
25
25
|
WORKFLOW_VM=quickjs
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
On the Vercel World, snapshotting is on by default under QuickJS, so that is the only variable you need. On the Local and Postgres Worlds, see [World support](#world-support). See [Tuning](#tuning) to change how often a run snapshots.
|
|
29
29
|
|
|
30
30
|
<Callout type="info">
|
|
31
31
|
The exemption from the per-run event limit needs `workflow` 5.2.3 or later. Earlier versions snapshot the same way, but only record the snapshot policy on the run when you also set `WORKFLOW_SNAPSHOT_THRESHOLD`.
|
|
@@ -42,8 +42,8 @@ Snapshots are stored by your World, next to the run's event log:
|
|
|
42
42
|
| World | Snapshots | Notes |
|
|
43
43
|
| --- | --- | --- |
|
|
44
44
|
| Vercel World | Encrypted | Each run has an encryption key, and its snapshots are encrypted and authenticated with it. |
|
|
45
|
-
| Local World, Postgres World |
|
|
46
|
-
| Other Worlds | Depends on the World | A World that implements snapshot storage snapshots by default, encrypted
|
|
45
|
+
| Local World, Postgres World | Off unless you opt in | Runs have no encryption key. Set [`WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED=1`](/docs/configuration/runtime-tuning#workflow_snapshot_allow_unencrypted) on the workflow handler to store plaintext snapshots. A snapshot holds the handler's environment variables, so protect snapshot storage like the deployment's secrets. Without the opt-in, runs replay the full log on every resume. |
|
|
46
|
+
| Other Worlds | Depends on the World | A World that implements snapshot storage and provides a run encryption key snapshots by default, encrypted with that key. Without a key, it snapshots only with the opt-in above. Without snapshot storage, runs still execute on QuickJS and replay the full log on every resume. |
|
|
47
47
|
|
|
48
48
|
The exemption from the per-run event limit applies on the Local World and the Vercel World.
|
|
49
49
|
|
|
@@ -61,7 +61,7 @@ QuickJS does not provide a few globals inside workflow functions. If your workfl
|
|
|
61
61
|
|
|
62
62
|
## Tuning
|
|
63
63
|
|
|
64
|
-
Snapshotting needs no configuration. To change how often a run snapshots, set `WORKFLOW_SNAPSHOT_THRESHOLD`. This is the same entry as on the [Runtime tuning](/docs/configuration/runtime-tuning#workflow_snapshot_threshold) page:
|
|
64
|
+
Snapshotting needs no configuration on Worlds that provide run encryption keys. To change how often a run snapshots, set `WORKFLOW_SNAPSHOT_THRESHOLD`. This is the same entry as on the [Runtime tuning](/docs/configuration/runtime-tuning#workflow_snapshot_threshold) page:
|
|
65
65
|
|
|
66
66
|
<include>../configuration/runtime-tuning.mdx#workflow_snapshot_threshold</include>
|
|
67
67
|
|
|
@@ -159,7 +159,7 @@ Aside from providing `sleep()` as a tool, there are other use cases for Agents t
|
|
|
159
159
|
|
|
160
160
|
### Rate limiting
|
|
161
161
|
|
|
162
|
-
|
|
162
|
+
To keep an agent's tool or model calls under a provider's rate limit across every run, call [`experimental_rateLimit()`](/docs/foundations/rate-limits) before the step that makes the call. When the provider still answers 429, use `RetryableError` with a delay:
|
|
163
163
|
|
|
164
164
|
```typescript lineNumbers
|
|
165
165
|
import { RetryableError } from "workflow";
|
|
@@ -148,5 +148,5 @@ export async function customFetch(
|
|
|
148
148
|
This example demonstrates:
|
|
149
149
|
|
|
150
150
|
- Throwing [`FatalError`](/docs/api-reference/workflow/fatal-error) for client errors (400-499) to prevent retries.
|
|
151
|
-
- Handling 429 rate limiting by reading the `Retry-After` header and using [`RetryableError`](/docs/api-reference/workflow/retryable-error).
|
|
151
|
+
- Handling 429 rate limiting by reading the `Retry-After` header and using [`RetryableError`](/docs/api-reference/workflow/retryable-error). To stay under the limit across every run, call [`experimental_rateLimit()`](/docs/foundations/rate-limits) before the request.
|
|
152
152
|
- Allowing automatic retries for server errors (5xx) by throwing a plain `Error`.
|
|
@@ -32,6 +32,9 @@ Workflow SDK contains the following functions you can use inside your workflow f
|
|
|
32
32
|
<Card href="/docs/api-reference/workflow/sleep" title="sleep()">
|
|
33
33
|
Sleeping workflows for a specified duration. Deterministic and replay-safe.
|
|
34
34
|
</Card>
|
|
35
|
+
<Card href="/docs/api-reference/workflow/rate-limit" title="experimental_rateLimit()">
|
|
36
|
+
Wait for a slot under a rate limit shared by every run of a project.
|
|
37
|
+
</Card>
|
|
35
38
|
<Card href="/docs/api-reference/workflow/fetch" title="fetch()">
|
|
36
39
|
Make HTTP requests from within a workflow with automatic retry semantics.
|
|
37
40
|
</Card>
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: experimental_rateLimit
|
|
3
|
+
description: Wait for a slot under a rate limit shared by every run of a project.
|
|
4
|
+
type: reference
|
|
5
|
+
summary: Use experimental_rateLimit to keep calls to a shared upstream under its rate limit across all workflow runs.
|
|
6
|
+
prerequisites:
|
|
7
|
+
- /docs/foundations/workflows-and-steps
|
|
8
|
+
related:
|
|
9
|
+
- /docs/foundations/rate-limits
|
|
10
|
+
- /docs/api-reference/workflow/sleep
|
|
11
|
+
- /docs/errors/rate-limit-max-wait
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
Waits for a slot under a rate limit that every run of the project shares. Calls with the same `key` get slots at most `limit` per `period`, each at least `period / limit` after the one before. A call whose slot is now resolves at once; otherwise the run sleeps until its slot, like [`sleep()`](/docs/api-reference/workflow/sleep), and resolves then. A call that wakes late can go ahead a little after its slot (see [Calls that wake late](#calls-that-wake-late)), so keep handling the upstream's own rate limit errors. For when and how to use rate limits, see [Rate Limits](/docs/foundations/rate-limits).
|
|
15
|
+
|
|
16
|
+
<Callout type="warn">
|
|
17
|
+
Experimental, and available in `workflow` 5.8.0 and later on the Vercel, Local and Postgres Worlds. It needs a spec 10 run, which those Worlds create by default. On a custom World that does not declare rate limits (`capabilities.rateLimits`), or with [`WORKFLOW_SPEC_VERSION`](/docs/configuration/runtime-tuning#workflow_spec_version) set below `10`, a run that calls it fails.
|
|
18
|
+
</Callout>
|
|
19
|
+
|
|
20
|
+
```typescript lineNumbers
|
|
21
|
+
import { experimental_rateLimit } from "workflow";
|
|
22
|
+
declare function callModel(doc: string): Promise<void>; // @setup
|
|
23
|
+
|
|
24
|
+
export async function summarize(docs: string[]) {
|
|
25
|
+
"use workflow";
|
|
26
|
+
for (const doc of docs) {
|
|
27
|
+
await experimental_rateLimit({ key: "openai", limit: 60, period: "1m" }); // [!code highlight]
|
|
28
|
+
await callModel(doc);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## API signature
|
|
34
|
+
|
|
35
|
+
### Parameters
|
|
36
|
+
|
|
37
|
+
<TSDoc
|
|
38
|
+
definition={`
|
|
39
|
+
import { experimental_rateLimit } from "workflow";
|
|
40
|
+
export default experimental_rateLimit;`}
|
|
41
|
+
showSections={['parameters']}
|
|
42
|
+
/>
|
|
43
|
+
|
|
44
|
+
#### RateLimitOptions
|
|
45
|
+
|
|
46
|
+
<TSDoc
|
|
47
|
+
definition={`
|
|
48
|
+
import type { RateLimitOptions } from "workflow";
|
|
49
|
+
export default RateLimitOptions;`}
|
|
50
|
+
/>
|
|
51
|
+
|
|
52
|
+
## Behavior
|
|
53
|
+
|
|
54
|
+
- Calls on one key share it across runs, so they are admitted in the order the World receives them. Use the same `limit`, `period` and `burst` everywhere you use a key (see [One key with different settings](#one-key-with-different-settings)).
|
|
55
|
+
- On Vercel, the rate is per project and environment: preview and production deployments have separate budgets for the same key. On the Local World it is per data directory, and on the Postgres World per [`jobPrefix`](/worlds/postgres).
|
|
56
|
+
- A `key` is 1 character to 512 bytes (UTF-8). Keys are stored as-is in the run's event log. Don't put personal data in them.
|
|
57
|
+
- Keys that start with `$` are reserved for Workflow SDK libraries, and a call with one throws. Don't use them in your own code: the `allowReservedKey` option that permits them exists only for those libraries, and a workflow that shares their keys can starve them or be starved by them.
|
|
58
|
+
- A `period` can be at most 24 hours.
|
|
59
|
+
- `burst` lets an idle key admit up to that many calls at once, and then refill one every `period / limit`, like a token bucket of that size. The default, 1, is no burst. It can be larger than `limit`, saving up to 24 hours of the rate: `limit: 1, period: "1s", burst: 60` lets a key that was idle for a minute send 60 calls at once. The long-run rate is still `limit` per `period`, but a rolling `period` can see up to `limit + burst - 1` calls. Set it to an upstream's published burst size, or keep `limit + burst - 1` under the most it allows in a window.
|
|
60
|
+
- A call that cannot get a slot within its `maxWait` rejects at once with [`RateLimitMaxWaitError`](/docs/errors/rate-limit-max-wait) and uses up none of the key's capacity. Without a `maxWait`, a call waits up to 30 days, which is also the longest a `maxWait` can be.
|
|
61
|
+
- A run that is cancelled or fails while a call waits keeps that call's slot: the next calls on the key still go after it.
|
|
62
|
+
|
|
63
|
+
## One key with different settings
|
|
64
|
+
|
|
65
|
+
A key keeps only its next free slot, and each call moves that slot on by its own `period / limit`. Nothing records a limit for the key, so the settings of each call apply to that call alone:
|
|
66
|
+
|
|
67
|
+
- **Changing a limit in a new deployment** applies only to runs on the new deployment, and takes effect after the slots that calls at the old limit already reserved. Runs still on the old deployment keep calling with the settings they were deployed with, so the key sees both until those runs finish. If you raise one per minute to one per second while calls are queued, the first call at the new limit waits behind them, and calls after it go one per second.
|
|
68
|
+
- **Using one key with different settings in different call sites** mixes them. A call at `limit: 1, period: "24h"` waits its turn like any other, but then takes a whole day of the key, so every call after it on that key waits a day or fails its `maxWait`. A call with a larger `burst` can go ahead of calls already waiting with a smaller one.
|
|
69
|
+
|
|
70
|
+
There is rarely a reason to do either. Give each upstream limit one key, set it in one place, and use a new key when the limit changes.
|
|
71
|
+
|
|
72
|
+
## Calls that wake late
|
|
73
|
+
|
|
74
|
+
A waiting call goes ahead when its run wakes, which is normally at its slot. When the run wakes late (a queue delay, a cold start), the call still goes ahead if it is within a grace of its slot: 10% of the `period`, at least 5 seconds and at most 60 seconds. So in any window of length `W`, up to `(W + grace) / (period / limit) + 1` calls can go ahead: for `limit: 10, period: "1s"`, a 5-second stall can let about 50 waiting calls through at once.
|
|
75
|
+
|
|
76
|
+
A call that wakes later than its grace is given a new slot behind the calls already queued, and each time that happens its grace doubles, up to 4 times the first. A call that has been given a new slot twice goes ahead if it is at most its largest grace plus one `period` late. If it is that late and also past its `maxWait`, it rejects with `RateLimitMaxWaitError`. Its slot was reserved, so that call does use up capacity.
|
|
77
|
+
|
|
78
|
+
## Examples
|
|
79
|
+
|
|
80
|
+
### Giving up when the wait is too long
|
|
81
|
+
|
|
82
|
+
```typescript lineNumbers
|
|
83
|
+
import { experimental_rateLimit } from "workflow";
|
|
84
|
+
import { RateLimitMaxWaitError } from "workflow/errors";
|
|
85
|
+
declare function sendSms(userId: string): Promise<void>; // @setup
|
|
86
|
+
|
|
87
|
+
export async function notify(userId: string) {
|
|
88
|
+
"use workflow";
|
|
89
|
+
try {
|
|
90
|
+
await experimental_rateLimit({ key: "sms", limit: 10, period: "1s", maxWait: "30s" }); // [!code highlight]
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (RateLimitMaxWaitError.is(error)) return "skipped";
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
await sendSms(userId);
|
|
96
|
+
return "sent";
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Letting a burst through at once
|
|
101
|
+
|
|
102
|
+
```typescript lineNumbers
|
|
103
|
+
import { experimental_rateLimit } from "workflow";
|
|
104
|
+
declare function fetchPage(url: string): Promise<void>; // @setup
|
|
105
|
+
|
|
106
|
+
export async function crawl(urls: string[]) {
|
|
107
|
+
"use workflow";
|
|
108
|
+
for (const url of urls) {
|
|
109
|
+
// The first 100 go at once; after that, one every 600 ms.
|
|
110
|
+
await experimental_rateLimit({ key: "crawler", limit: 100, period: "1m", burst: 100 }); // [!code highlight]
|
|
111
|
+
await fetchPage(url);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
```
|
|
@@ -7,7 +7,7 @@ related:
|
|
|
7
7
|
- /docs/api-reference/workflow-errors/workflow-world-error
|
|
8
8
|
---
|
|
9
9
|
|
|
10
|
-
A World throws `InBandSupersededError` (HTTP 412, code `in-band-superseded`) when it refuses a write made by a run's orchestrator because another invocation of the same run's orchestrator has written in-band since this one loaded the event log. It applies only to runs
|
|
10
|
+
A World throws `InBandSupersededError` (HTTP 412, code `in-band-superseded`) when it refuses a write made by a run's orchestrator because another invocation of the same run's orchestrator has written in-band since this one loaded the event log. It applies only to spec 9 and later runs, the default for new runs on Worlds with the in-band fence (`WORKFLOW_SPEC_VERSION=8` opts out).
|
|
11
11
|
|
|
12
12
|
<Callout>
|
|
13
13
|
The Workflow runtime handles this error. The refused invocation stops writing, sends the queue messages its own committed writes still owe, and asks for a redelivery of its queue message instead of acknowledging it. You will only encounter it when interacting with World storage APIs directly.
|
|
@@ -8,7 +8,7 @@ related:
|
|
|
8
8
|
- /docs/api-reference/workflow-errors/too-early-error
|
|
9
9
|
---
|
|
10
10
|
|
|
11
|
-
`ThrottleError` is thrown when a request to the workflow backend is rate-limited. It corresponds to HTTP 429 Too Many Requests semantics.
|
|
11
|
+
`ThrottleError` is thrown when a request to the workflow backend is rate-limited. It corresponds to HTTP 429 Too Many Requests semantics. It is about the backend limiting the SDK's own requests. To keep your workflows' calls to an upstream API under its limit, see [Rate Limits](/docs/foundations/rate-limits).
|
|
12
12
|
|
|
13
13
|
The `retryAfter` property contains the number of seconds to wait before retrying.
|
|
14
14
|
|
|
@@ -54,6 +54,7 @@ export default defineConfig({
|
|
|
54
54
|
| `typescriptPlugin` | `boolean` | `false` | Adds the `workflow` TypeScript plugin to the generated `tsconfig.json` for integrated development environment (IDE) IntelliSense. |
|
|
55
55
|
| `runtime` | `string` | — | Node.js runtime version for Vercel Functions (for example, `'nodejs22.x'` or `'nodejs24.x'`). Only applies when deploying to Vercel. |
|
|
56
56
|
| `sourcemap` | `boolean \| 'inline' \| 'linked' \| 'external' \| 'both'` | `'inline'` (dev) / `false` (prod) | Controls source maps on generated workflow bundles. Accepts the same values as esbuild's `sourcemap` option. Defaults to `'inline'` in development and `false` in production (smaller function bundles, which helps stay under the Vercel 250 MB function size limit). Set it explicitly, or use the `WORKFLOW_SOURCEMAP` environment variable, to override in either environment. |
|
|
57
|
+
| `dashboard` | `boolean \| { enabled?: boolean; path?: string; allowedHosts?: string[] \| true }` | `true` (dev) / `false` (prod) | Embeds the observability web UI at `/_workflow` (or `path`). Never mounted on Vercel. `allowedHosts` lists host names the dashboard accepts besides `localhost`, `*.localhost`, and IP addresses; defaults to `WORKFLOW_WEB_ALLOWED_HOSTS`. |
|
|
57
58
|
|
|
58
59
|
## Vite-based Nitro
|
|
59
60
|
|
|
@@ -105,7 +105,7 @@ Each row is a Step Functions capability the Workflow SDK does not replicate one-
|
|
|
105
105
|
| Step Functions feature | How to cover it with the Workflow SDK |
|
|
106
106
|
| --- | --- |
|
|
107
107
|
| Express workflows | At-least-once and 5-minute duration fit the durable-replay model poorly; keep them on Step Functions or move to a queue consumer |
|
|
108
|
-
| Distributed Map (up to 10,000 concurrent children, S3 item sources) | Fan out with `start()` per item directly from the workflow, then bound concurrency with `p-limit` |
|
|
108
|
+
| Distributed Map (up to 10,000 concurrent children, S3 item sources) | Fan out with `start()` per item directly from the workflow, then bound concurrency with `p-limit`. To keep the children under an upstream API's rate limit, call [`experimental_rateLimit()`](/docs/foundations/rate-limits) before the step: every child run shares the key |
|
|
109
109
|
| Optimized AWS service integrations | Become ordinary SDK calls inside steps; `.sync` waits become explicit polling or hooks |
|
|
110
110
|
| Per-state IAM roles | Steps share the deployment's credentials; scope secrets at deploy time |
|
|
111
111
|
|
|
@@ -29,6 +29,7 @@ related:
|
|
|
29
29
|
| **Languages** | TypeScript / JavaScript (Python beta) | TypeScript; Python and Go (production, pre-1.0) |
|
|
30
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
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
|
+
| **Rate limiting** | [`experimental_rateLimit()`](/docs/foundations/rate-limits) paces any call inside a run, on a key every run shares: a run waits for its slot, or gives up after `maxWait` | `throttle` (queues run starts) and `rateLimit` (drops run starts) on the function, applied before a run starts |
|
|
32
33
|
| **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 |
|
|
33
34
|
| **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 |
|
|
34
35
|
| **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 |
|
|
@@ -253,24 +254,67 @@ Runs started on Inngest keep running on Inngest. Move new work to the Workflow S
|
|
|
253
254
|
|
|
254
255
|
### Flow control, schedules and failure handling
|
|
255
256
|
|
|
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
|
|
257
|
+
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, and [`experimental_rateLimit()`](/docs/foundations/rate-limits) paces the work inside runs. A hook, a `sleep()` or a step handles the rest:
|
|
257
258
|
|
|
258
259
|
| Inngest | With the Workflow SDK |
|
|
259
260
|
| --- | --- |
|
|
260
|
-
| `rateLimit: { key, limit
|
|
261
|
+
| `rateLimit: { key, limit, period }` | [`experimental_rateLimit()`](/docs/foundations/rate-limits) with a short `maxWait` at the top of the workflow, returning when it rejects; or, to start no run at all, a start token per key retained for the period. See [Rate limit](#rate-limit). |
|
|
261
262
|
| `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
263
|
| `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
264
|
| `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
265
|
| `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
|
|
266
|
+
| `throttle: { key, limit, period, burst }` | [`experimental_rateLimit()`](/docs/foundations/rate-limits) at the top of the workflow, or in front of the step the limit protects. Each run waits for its slot, as a throttled run waits in Inngest's queue. See [Throttle](#throttle). |
|
|
266
267
|
| `priority` | No equivalent. Runs start in the order `start()` is called. |
|
|
267
268
|
| 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
269
|
| 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
270
|
| `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
|
|
|
272
|
+
#### Throttle
|
|
273
|
+
|
|
274
|
+
Inngest's `throttle` holds runs over the limit in a queue and starts them as capacity frees up. Call [`experimental_rateLimit()`](/docs/foundations/rate-limits) before the work the limit protects for the same effect. Every run starts, and each one waits for its slot on the key, suspended like a `sleep()`:
|
|
275
|
+
|
|
276
|
+
```typescript lineNumbers
|
|
277
|
+
import { experimental_rateLimit } from "workflow";
|
|
278
|
+
declare function pushToCrm(accountId: string): Promise<void>; // @setup
|
|
279
|
+
|
|
280
|
+
// Inngest: throttle: { key: "event.data.accountId", limit: 10, period: "1m" }
|
|
281
|
+
export async function syncAccount(accountId: string) {
|
|
282
|
+
"use workflow";
|
|
283
|
+
await experimental_rateLimit({ key: `crm:${accountId}`, limit: 10, period: "1m" }); // [!code highlight]
|
|
284
|
+
await pushToCrm(accountId);
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Unlike `throttle`, which limits run starts, `experimental_rateLimit()` can sit in front of any call in a run, so a workflow that calls an API in a loop stays under its limit on every call. Inngest's `burst: n` adds `n` starts on top of `limit`, while `experimental_rateLimit()`'s `burst` counts how many calls an idle key admits at once, so Inngest's `burst: n` is `burst: n + 1`. To give up on a call that would wait too long, as a start timeout does for a throttled run, set `maxWait`.
|
|
289
|
+
|
|
271
290
|
#### Rate limit
|
|
272
291
|
|
|
273
|
-
Inngest's `rateLimit` drops events once the limit for a key is reached in the period
|
|
292
|
+
Inngest's `rateLimit` drops events once the limit for a key is reached in the period, using GCRA. There are two ways to do the same, which differ in where the excess is dropped.
|
|
293
|
+
|
|
294
|
+
**Inside the run, with `experimental_rateLimit()`.** Call it first thing in the workflow with a short `maxWait`, and return when it rejects with `RateLimitMaxWaitError`. It takes any `limit`, `period` and `burst`, makes the same GCRA decision as Inngest, and can guard any call in the run, not only its start:
|
|
295
|
+
|
|
296
|
+
```typescript lineNumbers
|
|
297
|
+
import { experimental_rateLimit } from "workflow";
|
|
298
|
+
import { RateLimitMaxWaitError } from "workflow/errors";
|
|
299
|
+
declare function pushToCrm(accountId: string): Promise<void>; // @setup
|
|
300
|
+
|
|
301
|
+
// Inngest: rateLimit: { key: "event.data.accountId", limit: 10, period: "1m" }
|
|
302
|
+
export async function syncAccount(accountId: string) {
|
|
303
|
+
"use workflow";
|
|
304
|
+
try {
|
|
305
|
+
await experimental_rateLimit({ key: `sync:${accountId}`, limit: 10, period: "1m", maxWait: "1s" }); // [!code highlight]
|
|
306
|
+
} catch (error) {
|
|
307
|
+
if (RateLimitMaxWaitError.is(error)) return { skipped: true }; // rate-limited
|
|
308
|
+
throw error;
|
|
309
|
+
}
|
|
310
|
+
await pushToCrm(accountId);
|
|
311
|
+
return { skipped: false };
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
Every dropped event still starts a run, which records its creation, its start, the refused call and its completion before it ends. That is fine for occasional excess, but a sender that is rate-limited most of the time creates a run for every event it sends.
|
|
316
|
+
|
|
317
|
+
**Before the run, with a start token.** A start token retained for the period drops the excess at `start()`, so a dropped event never becomes a run. It covers `limit: 1` directly. The token stays taken until the period has passed since the accepted start, and for as long as that run is still running:
|
|
274
318
|
|
|
275
319
|
```typescript lineNumbers
|
|
276
320
|
import { start } from "workflow/api";
|
|
@@ -294,7 +338,7 @@ export async function requestSync(accountId: string) {
|
|
|
294
338
|
}
|
|
295
339
|
```
|
|
296
340
|
|
|
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.
|
|
341
|
+
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. To pace the excess runs instead of dropping them, see [Throttle](#throttle).
|
|
298
342
|
|
|
299
343
|
#### Debounce
|
|
300
344
|
|
|
@@ -70,6 +70,7 @@ The model maps closely. Keep your orchestration logic; drop the workers, task qu
|
|
|
70
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
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
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). |
|
|
73
|
+
| Task Queue rate limit (`maxTaskQueueActivitiesPerSecond`) | [`experimental_rateLimit()`](/docs/foundations/rate-limits) before the step | One key per upstream limit, shared by every run, instead of one rate per Task Queue. Waiting runs are suspended, not held by a worker. |
|
|
73
74
|
| Activity retry policy | `maxRetries`, `RetryableError`, `FatalError` | Retries live at the step boundary. See [Errors & Retrying](/docs/foundations/errors-and-retries). |
|
|
74
75
|
| 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
76
|
| 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. |
|
|
@@ -29,6 +29,7 @@ related:
|
|
|
29
29
|
| **Versioning** | Runs pinned to immutable deployment, safe by default | **Atomic versioning**: runs lock to their deploy version; new deploys never touch in-flight runs (same safety property) |
|
|
30
30
|
| **AI and streaming** | `WorkflowAgent` in the AI SDK; native resumable streaming | AI SDK tools, native `useChat` transport, resumable Realtime, durable multi-turn Sessions, human-in-the-loop (HITL) via `wait.forToken` |
|
|
31
31
|
| **Concurrency control** | Enforce in steps / at the publisher | First-class queues + concurrency keys |
|
|
32
|
+
| **Rate limiting** | [`experimental_rateLimit()`](/docs/foundations/rate-limits): calls per period on a key every run shares | Queue concurrency limits cap how many runs execute at once, which trigger.dev suggests for APIs that have rate limits |
|
|
32
33
|
| **Portability** | Apache-2.0; World abstraction; runs anywhere Node runs | Apache-2.0; self-host on Docker/Kubernetes, but CRIU needs a compatible host (heavier than plain Docker); TypeScript-only |
|
|
33
34
|
| **Pricing** | SDK free; pay your platform | Cloud: compute-seconds + per-run ($0.0000338/s Small + $0.000025/run); no charge while checkpointed |
|
|
34
35
|
| **Limits** | 50 MB payload; 2 GB/run; no duration cap ([Vercel World limits](https://vercel.com/docs/workflows/pricing)) | 3 MB payload / 10 MB output; 14-day maximum run lifetime; CPU-time-based maximum duration |
|
|
@@ -63,6 +64,7 @@ trigger.dev offers AI SDK tool wrapping, a native `useChat` transport over its R
|
|
|
63
64
|
| `metadata.stream()` / Realtime | `getWritable()` / named streams | Clients read from the stream. |
|
|
64
65
|
| 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). |
|
|
65
66
|
| `AbortTaskRunError` | `FatalError` | Stops retries immediately. |
|
|
67
|
+
| `concurrency` / `concurrencyKey` used to stay under an API's rate limit | [`experimental_rateLimit()`](/docs/foundations/rate-limits) before the step | Limits calls per period across every run, rather than runs at once. Build the key from the tenant, as you would a concurrency key. |
|
|
66
68
|
|
|
67
69
|
The `task()` factory collapses into a plain function, and because the workflow body is replayed, move side effects into steps:
|
|
68
70
|
|
|
@@ -98,7 +100,7 @@ Each row is a trigger.dev capability the Workflow SDK does not replicate one-to-
|
|
|
98
100
|
|
|
99
101
|
| trigger.dev feature | How to cover it with the Workflow SDK |
|
|
100
102
|
| --- | --- |
|
|
101
|
-
| Concurrency keys / queue concurrency limits |
|
|
103
|
+
| Concurrency keys / queue concurrency limits | To stay under an upstream API's rate limit, call [`experimental_rateLimit()`](/docs/foundations/rate-limits) before the step. To cap how many runs execute at once, enforce limits inside steps or debounce at the publisher |
|
|
102
104
|
| `schedules.task()` / cron | Trigger from Vercel Cron or a system cron calling `start()` |
|
|
103
105
|
| `machine` presets / custom images | Function resources are per-deployment (configured via your hosting platform) |
|
|
104
106
|
|
|
@@ -69,6 +69,12 @@ Whichever way they are resolved, the CLI ends up building a Vercel World from an
|
|
|
69
69
|
- Default: `3456`
|
|
70
70
|
- Port for the local web UI server.
|
|
71
71
|
|
|
72
|
+
### `--webAllowedHosts`
|
|
73
|
+
|
|
74
|
+
- Environment variable: `WORKFLOW_WEB_ALLOWED_HOSTS`
|
|
75
|
+
- Default: none
|
|
76
|
+
- Comma-separated host names the local web UI accepts in the `Host` header, in addition to `localhost`, `*.localhost`, and IP addresses, which are always accepted. An entry starting with a dot (`.example.com`) matches the domain and all of its subdomains; `*` accepts any host name. Requests under any other host name are rejected with `403`, which protects the UI from DNS rebinding by web pages you visit. Set this when you reach the UI under a domain name, for example behind a reverse proxy or through a hostname on your network.
|
|
77
|
+
|
|
72
78
|
### `--noBrowser`
|
|
73
79
|
|
|
74
80
|
- Environment variable: `WORKFLOW_DISABLE_BROWSER_OPEN`
|
|
@@ -184,6 +190,15 @@ per flag.
|
|
|
184
190
|
- Default: disabled
|
|
185
191
|
- Decrypts encrypted values. Triggers an audit-logged key retrieval.
|
|
186
192
|
|
|
193
|
+
### `--usage`
|
|
194
|
+
|
|
195
|
+
- Command: `workflow inspect run <run-id>`
|
|
196
|
+
- Default: disabled
|
|
197
|
+
- Prints the run's [usage](/docs/observability/usage) instead of the run: its events by type, and its storage. With `--json`, prints the same numbers as JSON.
|
|
198
|
+
- Only the Local World counts usage; on other backends the command fails rather than printing the run.
|
|
199
|
+
- Cannot be combined with `--url`/`--web`, `--withData`, or `--decrypt`.
|
|
200
|
+
- Prints in color only to a terminal; output is plain text when piped, with `NO_COLOR` set, or with `TERM=dumb`.
|
|
201
|
+
|
|
187
202
|
## Bulk cancel
|
|
188
203
|
|
|
189
204
|
`workflow cancel <run-id>` cancels one run. Given a filter instead, it bulk-cancels a batch; bulk mode requires `--status` or `--workflowName`.
|
|
@@ -81,6 +81,12 @@ Configure Workflow through the Nitro `workflow` module options.
|
|
|
81
81
|
- Default: `inline` in development, `false` in production
|
|
82
82
|
- Controls source maps for generated workflow bundles.
|
|
83
83
|
|
|
84
|
+
### `workflow.dashboard`
|
|
85
|
+
|
|
86
|
+
- Environment override: `WORKFLOW_WEB_ALLOWED_HOSTS` (for `allowedHosts`)
|
|
87
|
+
- Default: enabled in development, disabled in production builds, never mounted on Vercel
|
|
88
|
+
- Embeds the observability web UI in the Nitro server at `/_workflow`. Pass `true` or `false` to force it on or off, or an object `{ enabled, path, allowedHosts }`. `allowedHosts` lists host names the dashboard accepts in the `Host` header besides `localhost`, `*.localhost`, and IP addresses (`.example.com` matches the domain and its subdomains, `true` accepts any host); requests under any other name get a `403`. See [`--webAllowedHosts`](/docs/configuration/cli-and-web-ui#--weballowedhosts).
|
|
89
|
+
|
|
84
90
|
## NestJS
|
|
85
91
|
|
|
86
92
|
Configure Workflow through `WorkflowModule.forRoot()`.
|
|
@@ -193,7 +193,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
193
193
|
- Values: `node` or `quickjs`
|
|
194
194
|
- Selects the sandboxed VM engine that executes workflow functions (`"use workflow"`). Step functions are unaffected and always run with full Node.js access.
|
|
195
195
|
- `node` (default) runs workflow code in a [`node:vm`](https://nodejs.org/api/vm.html) context. Every resume replays the run's full event log, so resume cost grows with the log, and runs are subject to the World's default [per-run event limit](/docs/errors/max-events-exceeded).
|
|
196
|
-
- `quickjs` runs workflow code in a [QuickJS](https://github.com/quickjs-ng/quickjs) VM compiled to WebAssembly (via [`quickjs-wasi`](https://github.com/vercel-labs/quickjs-wasi)). **Use it for long-running workflows**: agents, chat sessions, and loops that wait on hooks or sleeps, or any run with many steps. With snapshotting (on by default, see [`WORKFLOW_SNAPSHOT_THRESHOLD`](#workflow_snapshot_threshold)), a run resumes from a VM-memory snapshot and replays only the events recorded since, so resume cost stays roughly flat as the log grows, and the run is exempt from the default per-run event limit on the Local and Vercel Worlds. It also runs on platforms that do not implement `node:vm`.
|
|
196
|
+
- `quickjs` runs workflow code in a [QuickJS](https://github.com/quickjs-ng/quickjs) VM compiled to WebAssembly (via [`quickjs-wasi`](https://github.com/vercel-labs/quickjs-wasi)). **Use it for long-running workflows**: agents, chat sessions, and loops that wait on hooks or sleeps, or any run with many steps. With snapshotting (on by default for encrypted runs, see [`WORKFLOW_SNAPSHOT_THRESHOLD`](#workflow_snapshot_threshold); on world-local and world-postgres also set [`WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED`](#workflow_snapshot_allow_unencrypted)), a run resumes from a VM-memory snapshot and replays only the events recorded since, so resume cost stays roughly flat as the log grows, and the run is exempt from the default per-run event limit on the Local and Vercel Worlds. It also runs on platforms that do not implement `node:vm`.
|
|
197
197
|
- Both engines implement the same event-replay execution model (seeded PRNG, deterministic clock, and correlation-ID sequences are identical), so workflow code that sticks to plain JavaScript and the Workflow APIs runs unchanged. To switch, set `WORKFLOW_VM=quickjs` in the environment that starts runs, and runs started after that use QuickJS. The few globals QuickJS does not provide in workflow functions are listed below.
|
|
198
198
|
- Global-surface differences under `quickjs` apply to workflow functions only. Step functions always have full Node.js, so the fix for each is to move that call into a step:
|
|
199
199
|
- `crypto.getRandomValues()` and `crypto.randomUUID()` are provided and deterministic (seeded like the node engine's). All `crypto.subtle.*` methods, including `digest`, throw with guidance to move to a step function. The node engine supports `digest`.
|
|
@@ -228,11 +228,16 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
228
228
|
What a snapshot contains, and how it is protected:
|
|
229
229
|
|
|
230
230
|
- A snapshot is the workflow VM's memory: the workflow's code and in-memory state, including step results and hook payloads it holds, and the copy of `process.env` the VM exposes. It is executable state, so write access to snapshot storage is equivalent to running code in the workflow VM.
|
|
231
|
-
-
|
|
232
|
-
-
|
|
231
|
+
- Snapshots are compressed and then encrypted with the run's encryption key. The encryption also authenticates the snapshot: on restore, the runtime rejects any snapshot that isn't encrypted with the run's key, or whose stored metadata doesn't match the metadata sealed inside it.
|
|
232
|
+
- By default, runs without an encryption key are never snapshotted. world-local and world-postgres provide no run encryption keys. Set `WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED=1` on the workflow handler to snapshot those runs anyway. Their snapshots are stored in plaintext (in `.workflow-data/snapshots/` or the `workflow_snapshots` table) and are not authenticated. Because a snapshot holds the VM's copy of `process.env`, anyone who can read snapshot storage can read the handler's environment variables, including credentials your workflows never use. Only enable this where snapshot storage is as trusted as the deployment's environment.
|
|
233
233
|
- A restored run sees `process.env` as of the current invocation, the same as a full replay.
|
|
234
234
|
- Snapshots are deleted after the run reaches a terminal state. world-local and world-postgres have no separate retention for them, so a snapshot of a run that ends without any invocation observing it (for example, one cancelled externally) stays until you remove it.
|
|
235
235
|
|
|
236
|
+
### `WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED`
|
|
237
|
+
|
|
238
|
+
- Default: disabled
|
|
239
|
+
- Set `1` or `true` on the workflow handler to let the QuickJS engine persist VM snapshots for runs without an encryption key. Those snapshots include the handler's environment variables in plaintext. See [`WORKFLOW_SNAPSHOT_THRESHOLD`](#workflow_snapshot_threshold) for what that stores.
|
|
240
|
+
|
|
236
241
|
## Dynamic workflows
|
|
237
242
|
|
|
238
243
|
### `WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS`
|
|
@@ -377,16 +382,21 @@ These variables are primarily for tests, debugging, or unusual deployments.
|
|
|
377
382
|
- The Local and Vercel Worlds both supply a limit; the Local World defaults to 25,000 and is configurable with [`WORKFLOW_MAX_EVENTS`](/docs/configuration/worlds#workflow_max_events). The Vercel World's ceiling is documented under [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits).
|
|
378
383
|
- QuickJS runs with snapshotting are exempt from the World's default limit, but this override still applies to them.
|
|
379
384
|
|
|
380
|
-
## Spec 9
|
|
385
|
+
## Spec 9
|
|
381
386
|
|
|
382
|
-
Everything above describes spec 8 runs
|
|
387
|
+
Everything above describes spec 8 runs. New runs are spec 10 by default on the Vercel, Local and Postgres Worlds, and `WORKFLOW_SPEC_VERSION=8` keeps them on spec 8. Spec 10 runs are spec 9 runs that may call [`experimental_rateLimit()`](/docs/api-reference/workflow/rate-limit), and everything in this section applies to both. Spec 9 runs read some of the settings above differently, and add the settings below.
|
|
383
388
|
|
|
384
389
|
### `WORKFLOW_SPEC_VERSION`
|
|
385
390
|
|
|
386
|
-
- Default: unset. New runs use spec version 8.
|
|
387
|
-
- `9` creates spec
|
|
391
|
+
- Default: unset. New runs use spec version 10 on a World that declares the in-band fence and reserves rate limit slots (the Vercel, Local and Postgres Worlds do), 9 on a World that declares only the fence, and 8 on one without the fence.
|
|
392
|
+
- `8` keeps new runs on spec 8. `6` to `10` select that version; `9` or `10` on a World without the fence creates spec 8 runs, and `10` on a World with the fence but no rate limits creates spec 9 runs. Any other value is ignored with a one-time warning and creates spec 8 runs, so a typo in an opt-out never creates spec 9 or 10 runs. A run keeps the version it was created with.
|
|
388
393
|
- `6` creates new runs on the scheme from before the [sealed log](/docs/how-it-works/event-sourcing), where each event position is allocated by the write that occupies it. Use it in an environment shared with a runtime that cannot read sealed logs yet, such as one that pins its own accepted spec range (the Python runtime). Runs below `8` cannot have their hook tokens taken over with [`experimental_force`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds): a forced hook in another run gets `HookConflictError` instead.
|
|
389
|
-
- Upgrade every deployment and process that shares the World
|
|
394
|
+
- Upgrade every deployment and process that shares the World together, setting `8` on the upgraded ones until all of them run this release, and do not roll back below this release once spec 9 or 10 runs exist.
|
|
395
|
+
|
|
396
|
+
### `WORKFLOW_ORCHESTRATOR_RATE_WAIT_MS`
|
|
397
|
+
|
|
398
|
+
- Default: `5000`
|
|
399
|
+
- How far ahead of an [`experimental_rateLimit()`](/docs/api-reference/workflow/rate-limit) call's slot the orchestrator waits for it in the same invocation. A call whose slot is further out is woken this far before it and waits the rest the same way, so it goes ahead at its slot instead of a second or more after. A queued wake for the slot itself is still scheduled, in case the invocation ends first. Each wait can keep an invocation idle for up to this long. `0` turns it off, and a waiting call is woken by the queue at its slot.
|
|
390
400
|
|
|
391
401
|
### `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS`
|
|
392
402
|
|
|
@@ -15,7 +15,7 @@ Use batching when you need to process a large list of items in parallel while co
|
|
|
15
15
|
|
|
16
16
|
- Bulk data imports (contacts, orders, or products from a comma-separated values (CSV) file)
|
|
17
17
|
- Processing hundreds or thousands of items against external APIs
|
|
18
|
-
- Calling rate-limited APIs where you need to control concurrency
|
|
18
|
+
- Calling rate-limited APIs where you need to control concurrency (for a calls-per-period limit, see [Rate Limits](/docs/foundations/rate-limits))
|
|
19
19
|
- Any fan-out where you want failure isolation between groups
|
|
20
20
|
- High-concurrency fan-out, where one flat `Promise.all` over the whole list would put more work in flight than your downstream services or the run's event log should carry at once
|
|
21
21
|
|
|
@@ -102,7 +102,7 @@ async function processRecord(record: Record): Promise<string> {
|
|
|
102
102
|
- **Batching bounds concurrency, not total event count**: Every record processed in its own step adds events to the same [event log](/docs/how-it-works/event-sourcing#how-fast-a-log-grows), regardless of batch size.
|
|
103
103
|
- **Use the QuickJS engine for long-running batches**: [Set `WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to run the workflow on QuickJS, which snapshots the workflow VM and replays only the events recorded since the last snapshot on resume. This reduces replay overhead as the log grows and exempts eligible runs from the default [per-run event limit](/worlds/vercel#per-run-limits) ([`MAX_EVENTS_EXCEEDED`](/docs/errors/max-events-exceeded)). It does not reduce event count or speed up the work inside each step.
|
|
104
104
|
- **Choose the retry and run boundaries you need**: Keep one step per record when independent retries and visibility matter. To write fewer events, process multiple records within each step and make the grouped work idempotent, since a retry can repeat the whole group. Use a [child workflow](/cookbook/advanced/child-workflows) per batch when you need separate run histories and failure boundaries.
|
|
105
|
-
- **
|
|
105
|
+
- **Pace calls with a rate limit**: To stay under an API's calls-per-period limit, call [`experimental_rateLimit()`](/docs/foundations/rate-limits) before each call. The limit is shared by every run, so concurrent imports stay under it together. A `sleep()` between batches also adds a durable delay, but only paces a single run.
|
|
106
106
|
- **Treat each `processRecord` call as an independent step**: If one call fails, it retries up to three times without affecting other items in the batch.
|
|
107
107
|
|
|
108
108
|
## Key APIs
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Rate Limiting & Retries
|
|
3
|
-
description:
|
|
3
|
+
description: Stay under an API's rate limit with experimental_rateLimit(), and handle 429 responses and transient failures with RetryableError and exponential backoff.
|
|
4
4
|
type: guide
|
|
5
5
|
summary: When an external API returns 429, throw RetryableError with the Retry-After value so the workflow runtime automatically reschedules the step after the specified delay.
|
|
6
6
|
---
|
|
@@ -9,14 +9,38 @@ summary: When an external API returns 429, throw RetryableError with the Retry-A
|
|
|
9
9
|
text="Add durable rate-limit handling to external API steps. Import `RetryableError`, `FatalError`, `getStepMetadata`, and `sleep` from `workflow` as needed. In each HTTP-calling "use step" helper, if the response status is 429, read the `Retry-After` header and throw `new RetryableError("Rate limited", { retryAfter })`. For transient 5xx/network failures, throw `RetryableError` with an exponential delay based on `getStepMetadata().attempt`. For permanent 4xx failures, throw `FatalError`. If the dependency is completely down, add a workflow-level circuit breaker that `await sleep("30s")` before probing again. Make requests idempotent with stable keys, and verify 429, 5xx, fatal 4xx, and circuit-breaker behavior."
|
|
10
10
|
/>
|
|
11
11
|
|
|
12
|
-
Use
|
|
12
|
+
Use these patterns when calling external APIs that enforce rate limits. Call [`experimental_rateLimit()`](/docs/foundations/rate-limits) before the call to keep every run under the API's limit, and throw `RetryableError` with a `retryAfter` value for the 429s that still get through, instead of writing manual retry loops.
|
|
13
13
|
|
|
14
14
|
## When to use this
|
|
15
15
|
|
|
16
|
+
- Calling an API with a published rate limit from many runs at once
|
|
16
17
|
- Calling APIs that return 429 (Too Many Requests) with `Retry-After` headers
|
|
17
18
|
- Any step that hits transient failures and needs backoff
|
|
18
19
|
- Syncing data with third-party services (Stripe, CRMs, scrapers)
|
|
19
20
|
|
|
21
|
+
## Pattern: stay under the limit with experimental_rateLimit()
|
|
22
|
+
|
|
23
|
+
Call `experimental_rateLimit()` in the workflow before the step that calls the API. Every run that uses the same key shares its limit, and a run whose slot is later waits for it like a `sleep()`:
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { experimental_rateLimit } from "workflow";
|
|
27
|
+
|
|
28
|
+
declare function fetchFromCrm(contactId: string): Promise<unknown>; // @setup
|
|
29
|
+
declare function upsertToWarehouse(contactId: string, contact: unknown): Promise<void>; // @setup
|
|
30
|
+
|
|
31
|
+
export async function syncContact(contactId: string) {
|
|
32
|
+
"use workflow";
|
|
33
|
+
|
|
34
|
+
await experimental_rateLimit({ key: "crm", limit: 100, period: "1m" }); // [!code highlight]
|
|
35
|
+
const contact = await fetchFromCrm(contactId);
|
|
36
|
+
await upsertToWarehouse(contactId, contact);
|
|
37
|
+
|
|
38
|
+
return { contactId, status: "synced" };
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
A step's retries don't wait for a new slot, so keep the 429 handling below in the step too. See [Rate Limits](/docs/foundations/rate-limits) for keys, `maxWait`, and `burst`.
|
|
43
|
+
|
|
20
44
|
## Pattern: RetryableError with Retry-After
|
|
21
45
|
|
|
22
46
|
A step function calls an external API. On 429, it reads the `Retry-After` header and throws `RetryableError`. The runtime reschedules the step automatically.
|
|
@@ -224,6 +248,7 @@ export async function downloadWithRetry(url: string) {
|
|
|
224
248
|
|
|
225
249
|
## Key APIs
|
|
226
250
|
|
|
251
|
+
- [`experimental_rateLimit()`](/docs/foundations/rate-limits) -- waits for a slot under a rate limit every run shares
|
|
227
252
|
- [`"use workflow"`](/docs/foundations/workflows-and-steps) -- marks the orchestrator function
|
|
228
253
|
- [`"use step"`](/docs/foundations/workflows-and-steps) -- marks functions that run with full Node.js access
|
|
229
254
|
- [`RetryableError`](/docs/api-reference/workflow/retryable-error) -- signals the runtime to retry after a delay
|
package/docs/cookbook/index.mdx
CHANGED
|
@@ -18,7 +18,7 @@ Use these workflow patterns and copy-paste code examples to implement common use
|
|
|
18
18
|
- [**Workflow Composition**](/cookbook/common-patterns/workflow-composition): Call workflows from other workflows by direct await or background spawn via `start()`
|
|
19
19
|
- [**Saga**](/cookbook/common-patterns/saga): Coordinate multi-step transactions with automatic rollback when a step fails
|
|
20
20
|
- [**Batching**](/cookbook/common-patterns/batching): Process large collections in parallel batches with failure isolation
|
|
21
|
-
- [**Rate Limiting**](/cookbook/common-patterns/rate-limiting):
|
|
21
|
+
- [**Rate Limiting**](/cookbook/common-patterns/rate-limiting): Stay under an API's rate limit with experimental_rateLimit(), and handle 429 responses with RetryableError and backoff
|
|
22
22
|
- [**Scheduling**](/cookbook/common-patterns/scheduling): Use durable sleep to schedule actions minutes, hours, or weeks ahead
|
|
23
23
|
- [**Timeouts**](/cookbook/common-patterns/timeouts): Add deadlines to slow steps, hooks, and webhooks by racing them against a durable sleep
|
|
24
24
|
- [**Idempotency**](/cookbook/common-patterns/idempotency): Ensure side effects and duplicate starts are safe to retry
|
|
@@ -56,6 +56,7 @@ A run qualifies when its `executionContext` records `workflowVm: "quickjs"` and
|
|
|
56
56
|
|
|
57
57
|
- Only runs started after the change are exempt. Runs keep the VM and snapshot policy they started with.
|
|
58
58
|
- Runs that have already failed with `MAX_EVENTS_EXCEEDED` are not revived. Start them again.
|
|
59
|
+
- On the Local World and Postgres World, snapshots are only stored when [`WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED=1`](/docs/configuration/runtime-tuning#workflow_snapshot_allow_unencrypted) is set. Without it, exempt runs still replay the full log on every invocation.
|
|
59
60
|
|
|
60
61
|
### Split the work into child workflows
|
|
61
62
|
|
|
@@ -63,7 +64,7 @@ If a run doesn't need to be a single long-lived run, start [child workflows](/co
|
|
|
63
64
|
|
|
64
65
|
### Fix unbounded loops
|
|
65
66
|
|
|
66
|
-
If the run wasn't expected to grow this large, check the workflow function for loops that create steps, hooks, or sleeps without terminating.
|
|
67
|
+
If the run wasn't expected to grow this large, check the workflow function for loops that create steps, hooks, or sleeps without terminating. A run's [usage](/docs/observability/usage) shows which steps and hooks write its events.
|
|
67
68
|
|
|
68
69
|
## This error cannot be caught
|
|
69
70
|
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: rate-limit-max-wait
|
|
3
|
+
description: An experimental_rateLimit() call could not get a slot within its maxWait.
|
|
4
|
+
type: troubleshooting
|
|
5
|
+
summary: Handle RateLimitMaxWaitError when a rate-limited call's next slot is later than its maxWait.
|
|
6
|
+
prerequisites:
|
|
7
|
+
- /docs/api-reference/workflow/rate-limit
|
|
8
|
+
related:
|
|
9
|
+
- /docs/foundations/rate-limits
|
|
10
|
+
- /docs/api-reference/workflow/rate-limit
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
This error is thrown by [`experimental_rateLimit()`](/docs/api-reference/workflow/rate-limit) when the key's next free slot is later than the call's `maxWait`. The call reserved nothing, so it used up none of the key's capacity.
|
|
14
|
+
|
|
15
|
+
It is also thrown, after waiting, by a call whose run woke [so late](/docs/api-reference/workflow/rate-limit#calls-that-wake-late) that it was given new slots and ended up past its `maxWait`. That call had reserved a slot.
|
|
16
|
+
|
|
17
|
+
## Error message
|
|
18
|
+
|
|
19
|
+
```text
|
|
20
|
+
Rate limit "<key>" has no slot within the call's maxWait (next slot at <time>)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Why this happens
|
|
24
|
+
|
|
25
|
+
Every call on a key takes the next slot, `period / limit` after the one before. When more calls arrive than the limit admits, slots move into the future, and a call whose slot would be past its `maxWait` fails at once instead of waiting.
|
|
26
|
+
|
|
27
|
+
## How to fix it
|
|
28
|
+
|
|
29
|
+
- Catch it with `RateLimitMaxWaitError.is(error)` from `workflow/errors` and skip, defer or report the work. `error.wouldAcquireAt` is when the call would have gone ahead (for a call that woke late, the slot it missed).
|
|
30
|
+
- Raise the `maxWait`, or leave it out to wait as long as it takes (up to 30 days).
|
|
31
|
+
- Spread the work across keys that the upstream limits separately.
|
|
@@ -97,6 +97,8 @@ async function callApi(endpoint: string) {
|
|
|
97
97
|
}
|
|
98
98
|
```
|
|
99
99
|
|
|
100
|
+
To keep calls under an upstream's rate limit across every run in the first place, call [`experimental_rateLimit()`](/docs/foundations/rate-limits) in the workflow before the step. A step's retries don't wait for a new slot, so keep handling 429 in the step too.
|
|
101
|
+
|
|
100
102
|
## Advanced example
|
|
101
103
|
|
|
102
104
|
This final example combines everything we've learned, along with [`getStepMetadata`](/docs/api-reference/workflow/get-step-metadata).
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Rate Limits
|
|
3
|
+
description: Use experimental_rateLimit() to keep calls to a shared upstream API under its rate limit across every workflow run.
|
|
4
|
+
type: conceptual
|
|
5
|
+
summary: Keep calls to an upstream API under its rate limit across all workflow runs.
|
|
6
|
+
prerequisites:
|
|
7
|
+
- /docs/foundations/workflows-and-steps
|
|
8
|
+
related:
|
|
9
|
+
- /docs/api-reference/workflow/rate-limit
|
|
10
|
+
- /docs/errors/rate-limit-max-wait
|
|
11
|
+
- /docs/foundations/errors-and-retries
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
Rate limits keep the calls your workflows make to an upstream API, such as a model provider or a payments API, under the limit that API enforces. Every run of your project shares the same limit, so a thousand runs started at once still call the upstream at the rate you set instead of all at once.
|
|
15
|
+
|
|
16
|
+
<Callout type="warn">
|
|
17
|
+
`experimental_rateLimit()` is experimental and is available in `workflow` 5.8.0 and later.
|
|
18
|
+
</Callout>
|
|
19
|
+
|
|
20
|
+
## Limit calls to an upstream API
|
|
21
|
+
|
|
22
|
+
Call [`experimental_rateLimit()`](/docs/api-reference/workflow/rate-limit) in a workflow before the step that calls the upstream. The call resolves when the key has a free slot for it:
|
|
23
|
+
|
|
24
|
+
```typescript lineNumbers
|
|
25
|
+
import { experimental_rateLimit } from "workflow";
|
|
26
|
+
|
|
27
|
+
async function summarizeDoc(doc: string) {
|
|
28
|
+
"use step";
|
|
29
|
+
const response = await fetch("https://api.example.com/summarize", {
|
|
30
|
+
method: "POST",
|
|
31
|
+
body: JSON.stringify({ doc }),
|
|
32
|
+
});
|
|
33
|
+
return response.json();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function summarizeAll(docs: string[]) {
|
|
37
|
+
"use workflow";
|
|
38
|
+
const summaries = [];
|
|
39
|
+
for (const doc of docs) {
|
|
40
|
+
await experimental_rateLimit({ key: "summarize-api", limit: 60, period: "1m" }); // [!code highlight]
|
|
41
|
+
summaries.push(await summarizeDoc(doc));
|
|
42
|
+
}
|
|
43
|
+
return summaries;
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
With `limit: 60` and `period: "1m"`, calls on the `summarize-api` key go ahead at most one per second, across every run that uses the key.
|
|
48
|
+
|
|
49
|
+
## How a rate limit decides when a call goes ahead
|
|
50
|
+
|
|
51
|
+
A rate limit uses the [generic cell rate algorithm (GCRA)](https://en.wikipedia.org/wiki/Generic_cell_rate_algorithm), which spaces calls `period / limit` apart. Each key keeps one number, its next free slot, and every call on the key takes that slot and moves it on by one interval:
|
|
52
|
+
|
|
53
|
+
- **A call whose slot is now** resolves at once, and the workflow continues.
|
|
54
|
+
- **A call whose slot is later** suspends the run until its slot, the same way [`sleep()`](/docs/api-reference/workflow/sleep) does, so a long wait uses no compute.
|
|
55
|
+
- **Calls from different runs** take slots in the order the World receives them, so no run can skip ahead of another.
|
|
56
|
+
|
|
57
|
+
Play the scenarios below, or change the options, to see runs ask a key for a slot, wait for it, and go ahead:
|
|
58
|
+
|
|
59
|
+
<RateLimitExplainer />
|
|
60
|
+
|
|
61
|
+
Calls in parallel each take their own slot. With `limit: 10, period: "1s"`, the first call in this `Promise.all()` resolves at once and the rest follow 100 ms apart:
|
|
62
|
+
|
|
63
|
+
```typescript lineNumbers
|
|
64
|
+
import { experimental_rateLimit } from "workflow";
|
|
65
|
+
declare function sendEmail(to: string): Promise<void>; // @setup
|
|
66
|
+
|
|
67
|
+
export async function notifyAll(recipients: string[]) {
|
|
68
|
+
"use workflow";
|
|
69
|
+
await Promise.all(
|
|
70
|
+
recipients.map(async (to) => {
|
|
71
|
+
await experimental_rateLimit({ key: "email", limit: 10, period: "1s" }); // [!code highlight]
|
|
72
|
+
await sendEmail(to);
|
|
73
|
+
})
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## How to choose a rate limit key
|
|
79
|
+
|
|
80
|
+
A key names one limit that an upstream enforces. Calls with the same key share it across every run and every workflow in the project. On Vercel each environment has its own: preview and production deployments never share a key's capacity.
|
|
81
|
+
|
|
82
|
+
- **One key per upstream limit**: Use `"openai"` for a limit that covers your whole account.
|
|
83
|
+
- **One key per tenant**: Build the key from an ID, such as `` `stripe:${accountId}` ``, when the upstream limits each account separately. Each tenant then gets its own rate.
|
|
84
|
+
- **Keep keys free of personal data**: Keys are stored as-is in the run's event log.
|
|
85
|
+
|
|
86
|
+
A key is 1 character to 512 bytes (UTF-8). Keys that start with `$` are reserved for Workflow SDK libraries, and `experimental_rateLimit()` throws for one.
|
|
87
|
+
|
|
88
|
+
## Give up when the wait is too long
|
|
89
|
+
|
|
90
|
+
Set `maxWait` when a call that waits too long isn't worth making. A call whose slot is further out than `maxWait` rejects at once with [`RateLimitMaxWaitError`](/docs/errors/rate-limit-max-wait) and uses up none of the key's capacity:
|
|
91
|
+
|
|
92
|
+
```typescript lineNumbers
|
|
93
|
+
import { experimental_rateLimit } from "workflow";
|
|
94
|
+
import { RateLimitMaxWaitError } from "workflow/errors";
|
|
95
|
+
declare function sendSms(userId: string): Promise<void>; // @setup
|
|
96
|
+
|
|
97
|
+
export async function notify(userId: string) {
|
|
98
|
+
"use workflow";
|
|
99
|
+
try {
|
|
100
|
+
await experimental_rateLimit({ key: "sms", limit: 10, period: "1s", maxWait: "30s" }); // [!code highlight]
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (RateLimitMaxWaitError.is(error)) return "skipped";
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
await sendSms(userId);
|
|
106
|
+
return "sent";
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Without `maxWait`, a call waits up to 30 days, which is also the longest `maxWait` can be.
|
|
111
|
+
|
|
112
|
+
## Let a burst through at once
|
|
113
|
+
|
|
114
|
+
Set `burst` when the upstream allows short bursts above its steady rate. An idle key then admits up to `burst` calls at once and refills one every `period / limit`, like a token bucket of that size:
|
|
115
|
+
|
|
116
|
+
```typescript lineNumbers
|
|
117
|
+
import { experimental_rateLimit } from "workflow";
|
|
118
|
+
declare function fetchPage(url: string): Promise<void>; // @setup
|
|
119
|
+
|
|
120
|
+
export async function crawl(urls: string[]) {
|
|
121
|
+
"use workflow";
|
|
122
|
+
for (const url of urls) {
|
|
123
|
+
// Up to 100 at once on an idle key, then one every 600 ms.
|
|
124
|
+
await experimental_rateLimit({ key: "crawler", limit: 100, period: "1m", burst: 100 }); // [!code highlight]
|
|
125
|
+
await fetchPage(url);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The default `burst` of 1 is no burst. A larger `burst` keeps the long-run rate at `limit` per `period`, but one rolling `period` can see up to `limit + burst - 1` calls. Set `burst` to the burst size the upstream publishes, or keep `limit + burst - 1` under the most it allows in any window. A `burst` can be larger than `limit` as long as it saves up at most 24 hours of the rate: `limit: 1, period: "1s", burst: 60` lets a key that was idle for a minute send 60 calls at once.
|
|
131
|
+
|
|
132
|
+
## Use one setting per key
|
|
133
|
+
|
|
134
|
+
Use the same `limit`, `period`, and `burst` everywhere you use a key. A key records only its next free slot, not a limit, so each call applies its own settings:
|
|
135
|
+
|
|
136
|
+
- **A limit changed in a new deployment** applies only to runs on the new deployment, and after the slots that calls at the old limit already reserved. Runs still on the old deployment keep calling with the old settings, which they were deployed with, so the key sees both until those runs finish.
|
|
137
|
+
- **A call with a longer interval** holds up every call after it. A `limit: 1, period: "24h"` call on a shared key makes every later call on that key wait a day.
|
|
138
|
+
- **A call with a larger `burst`** can go ahead of calls already waiting with a smaller one.
|
|
139
|
+
|
|
140
|
+
To change a limit, give the new limit a new key. See [One key with different settings](/docs/api-reference/workflow/rate-limit#one-key-with-different-settings) for the details.
|
|
141
|
+
|
|
142
|
+
## Handle the upstream's rate limit errors too
|
|
143
|
+
|
|
144
|
+
A rate limit controls when your workflow starts a call, but the upstream still decides whether to accept it. Keep handling its rate limit responses in the step, for two reasons:
|
|
145
|
+
|
|
146
|
+
- **Step retries skip the rate limit**: A step that fails is retried without running the workflow code before it again, so its retries don't wait for a new slot.
|
|
147
|
+
- **A run that wakes late can go ahead late**: A call goes ahead if its run wakes within a grace of its slot, which is 10% of the `period`, at least 5 seconds and at most 60 seconds. After a stall, calls queued in that window can go ahead together. See [Calls that wake late](/docs/api-reference/workflow/rate-limit#calls-that-wake-late).
|
|
148
|
+
|
|
149
|
+
Throw a [`RetryableError`](/docs/api-reference/workflow/retryable-error) with the wait the upstream asks for, so the retry doesn't run before the upstream accepts it:
|
|
150
|
+
|
|
151
|
+
```typescript lineNumbers
|
|
152
|
+
import { RetryableError } from "workflow";
|
|
153
|
+
|
|
154
|
+
async function callModel(prompt: string) {
|
|
155
|
+
"use step";
|
|
156
|
+
const response = await fetch("https://api.example.com/v1/complete", {
|
|
157
|
+
method: "POST",
|
|
158
|
+
body: JSON.stringify({ prompt }),
|
|
159
|
+
});
|
|
160
|
+
if (response.status === 429) {
|
|
161
|
+
const seconds = Number(response.headers.get("retry-after") ?? "1");
|
|
162
|
+
throw new RetryableError("Rate limited by the upstream", { // [!code highlight]
|
|
163
|
+
retryAfter: seconds * 1000, // [!code highlight]
|
|
164
|
+
}); // [!code highlight]
|
|
165
|
+
}
|
|
166
|
+
return response.json();
|
|
167
|
+
}
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## When to use a rate limit
|
|
171
|
+
|
|
172
|
+
- **Use a rate limit** when many runs call the same upstream and it limits how often you can call it, such as a model provider's requests per minute.
|
|
173
|
+
- **Use [`sleep()`](/docs/api-reference/workflow/sleep)** when one run needs to wait a fixed time, independent of other runs.
|
|
174
|
+
- **Use [`RetryableError`](/docs/foundations/errors-and-retries#customize-retry-behavior) alone** when calls are rare and an occasional 429 retry is cheaper than spacing every call.
|
|
175
|
+
|
|
176
|
+
## Related documentation
|
|
177
|
+
|
|
178
|
+
- [`experimental_rateLimit()` API reference](/docs/api-reference/workflow/rate-limit)
|
|
179
|
+
- [`RateLimitMaxWaitError`](/docs/errors/rate-limit-max-wait)
|
|
180
|
+
- [Errors & Retrying](/docs/foundations/errors-and-retries)
|
|
181
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep)
|
|
@@ -59,7 +59,8 @@ error; the payloads on the event log; and stream contents.
|
|
|
59
59
|
status, step names, and any [attributes](/docs/observability/attributes) you
|
|
60
60
|
set. They are kept for the World's default period so the run stays visible in
|
|
61
61
|
the CLI and web UI. A purged run is still listed and still traceable; its
|
|
62
|
-
payloads simply read back as expired.
|
|
62
|
+
payloads simply read back as expired. Its [usage](/docs/observability/usage)
|
|
63
|
+
still reports what it wrote.
|
|
63
64
|
|
|
64
65
|
Inspecting a purged run shows it as expired rather than failing. The Workflow
|
|
65
66
|
CLI renders the run's own input, output and error as `<data expired>`:
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Usage
|
|
3
|
+
description: See where a run's events come from and how much it stores.
|
|
4
|
+
type: reference
|
|
5
|
+
summary: See a run's events, by step and hook, and its storage, counted the way Vercel bills them.
|
|
6
|
+
prerequisites:
|
|
7
|
+
- /docs/foundations/workflows-and-steps
|
|
8
|
+
related:
|
|
9
|
+
- /docs/observability
|
|
10
|
+
- /docs/observability/retention
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
A run's usage shows where its events come from (which steps and hooks drive them) and how much it stores, counted the way Vercel bills them, so you can estimate a workflow's cost before you deploy it. Usage is available on the Local World.
|
|
14
|
+
|
|
15
|
+
## See a run's usage
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npx workflow inspect run <run_id> --usage
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
processOrder wrun_01M7V5GYES4PYRWR5STNZ6G5ME ● completed
|
|
23
|
+
|
|
24
|
+
Events 19
|
|
25
|
+
Storage (local) 3.52 KB
|
|
26
|
+
|
|
27
|
+
TYPE NAME EVENTS SHARE
|
|
28
|
+
Steps 3 calls ↻ 1 retry 11 58% ██████░░░░
|
|
29
|
+
├─ sendEmail 2 calls 6 32% ███░░░░░░░
|
|
30
|
+
└─ chargeCard 1 call ↻ 1 retry 5 26% ███░░░░░░░
|
|
31
|
+
Hooks 1 hook 3 16% ██░░░░░░░░
|
|
32
|
+
└─ approval:order-1042 3 16% ██░░░░░░░░
|
|
33
|
+
Sleeps 1 sleep 2 11% █░░░░░░░░░
|
|
34
|
+
Run 3 16% ██░░░░░░░░
|
|
35
|
+
TOTAL 19 100%
|
|
36
|
+
|
|
37
|
+
How usage is counted: https://workflow-sdk.dev/docs/observability/usage
|
|
38
|
+
|
|
39
|
+
STORAGE (LOCAL) SIZE
|
|
40
|
+
Run 500 B
|
|
41
|
+
Steps 2.82 KB
|
|
42
|
+
Hooks 200 B
|
|
43
|
+
TOTAL 3.52 KB
|
|
44
|
+
|
|
45
|
+
Local runs aren't billed. Counted from this run's log in your local data directory.
|
|
46
|
+
Machine-readable: --json
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
In the web UI, a run's header shows its **Events** and **Storage (local)**. Select either one, or the run's **Usage** tab, to open its Usage page (`/run/<run_id>/usage`), which shows the same table.
|
|
50
|
+
|
|
51
|
+
`--json` prints the same numbers as JSON. Its shape is experimental and may change.
|
|
52
|
+
|
|
53
|
+
The output includes hook tokens, and a token resumes its hook. Share it, `--json` included, only where you would share the run's data.
|
|
54
|
+
|
|
55
|
+
## What's counted
|
|
56
|
+
|
|
57
|
+
### Events
|
|
58
|
+
|
|
59
|
+
Every event in the run's log counts once. [Event sourcing](/docs/how-it-works/event-sourcing) describes which events a run, its steps, hooks and sleeps write.
|
|
60
|
+
|
|
61
|
+
### Storage
|
|
62
|
+
|
|
63
|
+
**Storage (local)** counts the bytes of the run's payloads as the SDK sent them (compressed when that saves space, and encrypted when encryption is on): run inputs and outputs, step inputs and results, errors, and hook metadata and payloads. It adds the bytes the run wrote to its streams. Event metadata, such as ids and timestamps, isn't counted. A run started with `experimental_retention: 0` reports what it wrote before its data was deleted.
|
|
64
|
+
|
|
65
|
+
When a run's data is deleted, its sizes stay in the local data directory, so usage can still report them.
|
|
66
|
+
|
|
67
|
+
Two kinds of data aren't counted locally:
|
|
68
|
+
|
|
69
|
+
- **QuickJS VM snapshots.**
|
|
70
|
+
- **A dynamic workflow's code.**
|
|
71
|
+
|
|
72
|
+
The numbers describe this run. The same workflow can record a different number of events on another run, for example with more or fewer retries.
|
|
73
|
+
|
|
74
|
+
## On Vercel
|
|
75
|
+
|
|
76
|
+
A run's events are its Workflow Events, and **Storage (local)** is counted the way Data Written is, except that Data Written also includes QuickJS VM snapshots and a dynamic workflow's code. Usage doesn't show Data Retained, function compute, or queues; see [Workflow pricing](https://vercel.com/docs/workflows/pricing), and open a run on the Workflows page in the [Vercel dashboard](https://vercel.com/dashboard) for what it was billed.
|
|
77
|
+
|
|
78
|
+
## Reduce a run's usage
|
|
79
|
+
|
|
80
|
+
- [Batching](/cookbook/common-patterns/batching)
|
|
81
|
+
- [Child workflows](/cookbook/advanced/child-workflows)
|
|
82
|
+
- [QuickJS runtime](/docs/advanced/quickjs-runtime)
|
|
83
|
+
- [Data retention](/docs/observability/retention)
|
|
@@ -274,7 +274,7 @@ The runtime handles a rejection wherever it arrives. It restarts the replay in-p
|
|
|
274
274
|
|
|
275
275
|
The in-band writer fence keeps a run to one orchestrator writer when two orchestrator invocations of the same run overlap, for example a delivery that outlives its queue lease while a redelivery of the run is already running. A write made by the run's orchestrator is **in-band** (`params.inBand: true`). Everything else is **out-of-band**: a background step's own events, `hook_received` from `resumeHook()` and webhooks, `run_cancelled` from `cancel()`, and `attr_set` from `setAttributes()` outside the workflow.
|
|
276
276
|
|
|
277
|
-
The fence is optional. The runtime sends `inBand` only on
|
|
277
|
+
The fence is optional. The runtime sends `inBand` only on spec 9 runs, so a World without the fence stays fully supported and keeps creating spec 8 runs. Declare `capabilities.inBandFence: true` when you implement all of the following:
|
|
278
278
|
|
|
279
279
|
- **Two counters per run.** Next to whatever allocates event positions, keep `seq`, the highest position allocated to any write, and `seqInBand`, the number of positions allocated to in-band writes. `run_created` counts as in-band and is never fenced itself, so a new run holds `seq = 1, seqInBand = 1` (`IN_BAND_SEQ_AT_RUN_CREATION` from `@workflow/world`).
|
|
280
280
|
- **List snapshot, or counters on a refusal.** On every `events.list()` page of a slot-numbered run, return `snapshot: { seq, seqInBand }`, read before the listing. A full load, followed to `hasMore: false`, covers every position up to the first page's `seq`. A fenced writer takes its count from that first page, never from counting events, because a count cannot tell which positions were in-band. If your store cannot read the counters on a list, you may list no snapshot, as long as every refusal carries both counters, read together (see below).
|
|
@@ -759,6 +759,8 @@ Your World will then appear on the [Worlds ecosystem](/worlds) page with its com
|
|
|
759
759
|
}
|
|
760
760
|
```
|
|
761
761
|
|
|
762
|
-
## Supporting spec 9 runs
|
|
762
|
+
## Supporting spec 9 runs
|
|
763
763
|
|
|
764
|
-
Everything above is the contract for spec 8 runs, which every World needs. A World may also
|
|
764
|
+
Everything above is the contract for spec 8 runs, which every World needs. A World may also support spec 9 runs, which it then uses for new runs by default (`WORKFLOW_SPEC_VERSION=8` opts its users out). To do so it implements the [in-band writer fence](#optional-the-in-band-writer-fence), serializes each spec 9 run's orchestrator deliveries, follows the spec 9 queue and deduplication rules, declares `capabilities.inBandFence: true`, and passes it on as `mintedSpecVersion(process.env, { inBandFence: true })`. `mintedSpecVersion()` called with no options never returns 9, so a World that does none of this keeps creating spec 8 runs.
|
|
765
|
+
|
|
766
|
+
A World that also reserves rate limit slots for [`experimental_rateLimit()`](/docs/api-reference/workflow/rate-limit) declares `capabilities.rateLimits: true` and passes `mintedSpecVersion(process.env, { inBandFence: true, rateLimits: true })`, which makes spec 10 its default instead. A spec 10 run is a spec 9 run that may hold rate events, so everything in this section applies to it. `WorldCapabilities.rateLimits` in `@workflow/world` documents the rate events such a World decides.
|
package/docs/worlds/local.mdx
CHANGED
|
@@ -30,6 +30,8 @@ npx workflow inspect runs
|
|
|
30
30
|
npx workflow web
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
+
`npx workflow inspect run <run_id> --usage` shows where a run's events come from and how much it stores; see [Usage](/docs/observability/usage).
|
|
34
|
+
|
|
33
35
|
Learn more in the [Observability](/docs/observability) documentation.
|
|
34
36
|
|
|
35
37
|
## Testing & compatibility
|
package/docs/worlds/postgres.mdx
CHANGED
|
@@ -343,6 +343,8 @@ Change it when: more than one application shares the database. Give each one its
|
|
|
343
343
|
|
|
344
344
|
A World claims jobs only under its own prefix and stamps that prefix on every run it creates. On `start()`, it re-enqueues only the active runs stamped with its prefix, so restarting one application does not hand another application's runs to its worker. `WORKFLOW_QUEUE_NAMESPACE` does not separate applications that share a database.
|
|
345
345
|
|
|
346
|
+
The prefix also scopes [`experimental_rateLimit()`](/docs/api-reference/workflow/rate-limit) keys: every deployment of an application shares a key's rate, and applications with different prefixes do not.
|
|
347
|
+
|
|
346
348
|
Set the prefix through `WORKFLOW_POSTGRES_JOB_PREFIX` rather than only in code. The CLI and the observability UI build their World from the environment, so a run they create, such as a re-run, is stamped with the prefix they see, and only a World with that prefix runs and recovers it.
|
|
347
349
|
|
|
348
350
|
### `WORKFLOW_POSTGRES_DEPLOYMENT_ID`
|
|
@@ -185,6 +185,6 @@ The cases worth covering explicitly:
|
|
|
185
185
|
|
|
186
186
|
The first-party implementations in `packages/world-local` and `packages/world-postgres` are the reference for everything else, and their test suites are the closest thing to full conformance while the compatibility tests are being rebuilt.
|
|
187
187
|
|
|
188
|
-
## Spec 9
|
|
188
|
+
## Spec 9
|
|
189
189
|
|
|
190
|
-
A World does not need to implement anything for
|
|
190
|
+
A World does not need to implement anything for spec 9 to migrate to v5: `mintedSpecVersion()` with no options keeps creating spec 8 runs. A World that opts in creates spec 9 runs by default (spec 10 if it also declares `capabilities.rateLimits`), so it must tell its users to upgrade every deployment and process that shares it together (with `WORKFLOW_SPEC_VERSION=8` on the upgraded ones until all of them run that release), and not to roll back below that release once spec 9 or 10 runs exist.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "workflow",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.8.0",
|
|
4
4
|
"description": "Workflow SDK - Build durable, resilient, and observable workflows",
|
|
5
5
|
"main": "dist/typescript-plugin.cjs",
|
|
6
6
|
"type": "module",
|
|
@@ -60,19 +60,19 @@
|
|
|
60
60
|
}
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@workflow/astro": "5.0.
|
|
64
|
-
"@workflow/cli": "5.3.
|
|
65
|
-
"@workflow/core": "5.
|
|
66
|
-
"@workflow/errors": "5.
|
|
63
|
+
"@workflow/astro": "5.0.15",
|
|
64
|
+
"@workflow/cli": "5.3.3",
|
|
65
|
+
"@workflow/core": "5.8.0",
|
|
66
|
+
"@workflow/errors": "5.2.0",
|
|
67
67
|
"@workflow/typescript-plugin": "5.0.1",
|
|
68
68
|
"@workflow/utils": "5.1.1",
|
|
69
69
|
"ms": "2.1.3",
|
|
70
|
-
"@workflow/next": "5.1.
|
|
71
|
-
"@workflow/nest": "5.1.
|
|
72
|
-
"@workflow/nitro": "5.0.
|
|
73
|
-
"@workflow/nuxt": "5.0.
|
|
74
|
-
"@workflow/sveltekit": "5.0.
|
|
75
|
-
"@workflow/rollup": "5.0.
|
|
70
|
+
"@workflow/next": "5.1.6",
|
|
71
|
+
"@workflow/nest": "5.1.13",
|
|
72
|
+
"@workflow/nitro": "5.0.15",
|
|
73
|
+
"@workflow/nuxt": "5.0.15",
|
|
74
|
+
"@workflow/sveltekit": "5.0.15",
|
|
75
|
+
"@workflow/rollup": "5.0.15"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
78
|
"@types/ms": "2.1.0",
|