workflow 5.7.2 → 5.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/internal/errors.d.ts +1 -1
  2. package/dist/internal/errors.js +2 -2
  3. package/docs/advanced/quickjs-runtime.mdx +4 -4
  4. package/docs/ai/sleep-and-delays.mdx +1 -1
  5. package/docs/api-reference/workflow/fetch.mdx +1 -1
  6. package/docs/api-reference/workflow/index.mdx +3 -0
  7. package/docs/api-reference/workflow/rate-limit.mdx +114 -0
  8. package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +5 -1
  9. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +6 -4
  10. package/docs/api-reference/workflow-errors/throttle-error.mdx +1 -1
  11. package/docs/api-reference/workflow-runtime/world/queue.mdx +5 -1
  12. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +1 -1
  13. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +49 -5
  14. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +1 -0
  15. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +3 -1
  16. package/docs/configuration/runtime-tuning.mdx +478 -168
  17. package/docs/cookbook/common-patterns/batching.mdx +2 -2
  18. package/docs/cookbook/common-patterns/rate-limiting.mdx +27 -2
  19. package/docs/cookbook/index.mdx +1 -1
  20. package/docs/cookbook/integrations/chat-sdk.mdx +1 -1
  21. package/docs/errors/max-events-exceeded.mdx +1 -0
  22. package/docs/errors/rate-limit-max-wait.mdx +31 -0
  23. package/docs/foundations/errors-and-retries.mdx +2 -0
  24. package/docs/foundations/meta.json +1 -0
  25. package/docs/foundations/rate-limits.mdx +181 -0
  26. package/docs/performance.mdx +93 -59
  27. package/docs/worlds/building-a-world.mdx +6 -3
  28. package/docs/worlds/local.mdx +6 -2
  29. package/docs/worlds/postgres.mdx +9 -3
  30. package/docs/worlds/upgrading-to-v5.mdx +2 -2
  31. package/docs/worlds/vercel.mdx +2 -2
  32. 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
@@ -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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2ludGVybmFsL2Vycm9ycy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQ0wsK0JBQStCLEVBQy9CLG1CQUFtQixFQUNuQixpQkFBaUIsRUFDakIscUJBQXFCLEVBQ3JCLGlCQUFpQixFQUNqQixxQkFBcUIsRUFDckIsdUJBQXVCLEVBQ3ZCLGVBQWUsRUFDZixvQkFBb0IsRUFDcEIsc0JBQXNCLEVBQ3RCLFdBQVcsRUFDWCxhQUFhLEVBQ2IsYUFBYSxFQUNiLGFBQWEsRUFDYiwwQkFBMEIsRUFDMUIseUJBQXlCLEVBQ3pCLHNCQUFzQixFQUN0Qiw0QkFBNEIsRUFDNUIsd0JBQXdCLEVBQ3hCLG9CQUFvQixFQUNwQixrQkFBa0IsRUFDbEIsa0JBQWtCLEdBQ25CLE1BQU0sa0JBQWtCLENBQUMifQ==
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
- Snapshotting is on by default under QuickJS, so that is the only variable you need. See [Tuning](#tuning) to change how often a run snapshots.
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 | Plaintext | Runs have no encryption key, so snapshots are stored the same way as the event log and payloads. Protect snapshot storage like the rest of the World's storage. |
46
- | Other Worlds | Depends on the World | A World that implements snapshot storage snapshots by default, encrypted when it provides a run encryption key. Without snapshot storage, runs still execute on QuickJS and replay the full log on every resume. |
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
- When hitting API rate limits, use `RetryableError` with a delay:
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. On a third-party 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 of the experimental spec 9 runtime (`WORKFLOW_SPEC_VERSION=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.
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.
@@ -28,6 +28,10 @@ try {
28
28
  }
29
29
  ```
30
30
 
31
+ <Spec8Note>
32
+ the runtime does not fence its writes, and no World throws this error.
33
+ </Spec8Note>
34
+
31
35
  ## API signature
32
36
 
33
37
  ### Properties
@@ -14,11 +14,13 @@ No World in this repository throws it. A stale replay does not need to be refuse
14
14
 
15
15
  A World rejects only on evidence and accepts the creation whenever it cannot decide. This error always means the snapshot was stale, but not receiving it does not prove the snapshot was current.
16
16
 
17
- <Callout>
18
- The Workflow runtime handles this error by restarting the replay in the same invocation from a corrected event log. It re-invokes the run for a fresh replay only after spending its in-process restart budget. It never retries the rejected creation as-is because a replay working from a corrected log derives different events. You will only encounter it when interacting with World storage APIs directly.
19
- </Callout>
17
+ A run's orchestrator writes behind the in-band fence, which has no precondition guard: the fence refuses a write only from a superseded invocation, with [`InBandSupersededError`](/docs/api-reference/workflow-errors/in-band-superseded-error).
20
18
 
21
- A World may attach the events the client was missing to the rejection as `details`, which lets the runtime restart without re-reading the event log. This is optional, and the runtime falls back to a full reload when the details are absent or unusable.
19
+ <Spec8Note>
20
+ a World may refuse a write with this error. The Workflow runtime handles it by restarting the replay in the same invocation from a corrected event log, and re-invokes the run for a fresh replay only after spending its in-process restart budget. The runtime never retries the rejected creation as-is, because a replay working from a corrected log derives different events. You only encounter `PreconditionFailedError` when calling World storage APIs directly.
21
+
22
+ A World may attach the events the client was missing to the rejection as `details`, which lets the runtime restart without re-reading the event log. Attaching them is optional, and the runtime falls back to a full reload when the details are absent or unusable.
23
+ </Spec8Note>
22
24
 
23
25
  ```typescript lineNumbers
24
26
  import { PreconditionFailedError } from "workflow/errors"
@@ -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
 
@@ -146,7 +146,11 @@ const handler = world.createQueueHandler(prefix, callback); // [!code highlight]
146
146
 
147
147
  **Returns:** `(req: Request) => Promise<Response>`
148
148
 
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.
149
+ `meta.messageId` should be stable across redeliveries of the same message (one ID per enqueued message, reused on every delivery attempt).
150
+
151
+ <Spec8Note>
152
+ the runtime records `meta.messageId` 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.
153
+ </Spec8Note>
150
154
 
151
155
  ## Related
152
156
 
@@ -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 inside the run handles the rest:
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: 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
+ | `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` | 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
+ | `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. 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:
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 | Enforce limits inside steps or debounce at the publisher |
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