Skip to content

Commit 2b6d6d7

Browse files
committed
chore(docs): Improvements to the idempotency key docs for the user expored itempotency key changes
1 parent c859be9 commit 2b6d6d7

File tree

2 files changed

+224
-3
lines changed

2 files changed

+224
-3
lines changed

docs/idempotency.mdx

Lines changed: 224 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,44 @@
11
---
22
title: "Idempotency"
3-
description: "An API call or operation is idempotent if it has the same result when called more than once."
3+
description: "An API call or operation is idempotent if it has the same result when called more than once."
44
---
55

6-
We currently support idempotency at the task level, meaning that if you trigger a task with the same `idempotencyKey` twice, the second request will not create a new task run.
6+
We currently support idempotency at the task level, meaning that if you trigger a task with the same `idempotencyKey` twice, the second request will not create a new task run. Instead, the original run's handle is returned, allowing you to track the existing run's progress.
77

8+
## Why use idempotency keys?
9+
10+
The most common use case is **preventing duplicate child tasks when a parent task retries**. Without idempotency keys, each retry of the parent would trigger a new child task run:
11+
12+
```mermaid
13+
sequenceDiagram
14+
participant Parent as Parent Task
15+
participant SDK as Trigger.dev
16+
participant Child as Child Task
17+
18+
Note over Parent: Attempt 1
19+
Parent->>SDK: trigger(childTask, {idempotencyKey})
20+
SDK->>Child: Creates child run
21+
Child-->>SDK: Running...
22+
Parent->>Parent: Fails, will retry
23+
24+
Note over Parent: Attempt 2 (retry)
25+
Parent->>SDK: trigger(childTask, {idempotencyKey})
26+
Note over SDK: Same key, returns existing run
27+
SDK-->>Parent: Returns original child run
28+
29+
Note over Child: Child task only runs once
30+
```
31+
32+
Other common use cases include:
33+
34+
- **Preventing duplicate emails** - Ensure a confirmation email is only sent once, even if the parent task retries
35+
- **Avoiding double-charging customers** - Prevent duplicate payment processing during retries
36+
- **One-time setup tasks** - Ensure initialization or migration tasks only run once
37+
- **Deduplicating webhook processing** - Handle the same webhook event only once, even if it's delivered multiple times
838

939
## `idempotencyKey` option
1040

11-
You can provide an `idempotencyKey` to ensure that a task is only triggered once with the same key. This is useful if you are triggering a task within another task that might be retried:
41+
You can provide an `idempotencyKey` when triggering a task:
1242

1343
```ts
1444
import { idempotencyKeys, task } from "@trigger.dev/sdk";
@@ -72,6 +102,10 @@ import { myTask } from "./trigger/myTasks";
72102
await myTask.trigger({ some: "data" }, { idempotencyKey: myUser.id });
73103
```
74104

105+
<Note>
106+
When you pass a raw string, it defaults to `"run"` scope (scoped to the parent run). See [Default behavior](#default-behavior) for details on how scopes work and how to use global scope instead.
107+
</Note>
108+
75109
<Note>Make sure you provide sufficiently unique keys to avoid collisions.</Note>
76110

77111
You can pass the `idempotencyKey` when calling `batchTrigger` as well:
@@ -87,6 +121,149 @@ await tasks.batchTrigger("my-task", [
87121
]);
88122
```
89123

124+
## Understanding scopes
125+
126+
The `scope` option determines how your idempotency key is processed. When you provide a key, it gets hashed together with additional context based on the scope. This means the same key string can produce different idempotency behaviors depending on the scope you choose.
127+
128+
### Available scopes
129+
130+
| Scope | What gets hashed | Description | Use case |
131+
| --- | --- | --- | --- |
132+
| `"run"` | `key + parentRunId` | Key is combined with the parent run ID | Prevent duplicates within a single parent run (default) |
133+
| `"attempt"` | `key + parentRunId + attemptNumber` | Key is combined with the parent run ID and attempt number | Allow child tasks to re-run on each retry of the parent |
134+
| `"global"` | `key` | Key is used as-is, no context added | Ensure a task only runs once ever, regardless of parent |
135+
136+
### `"run"` scope (default)
137+
138+
The `"run"` scope makes the idempotency key unique to the current parent task run. This is the default behavior for both raw strings and `idempotencyKeys.create()`.
139+
140+
```ts
141+
import { idempotencyKeys, task } from "@trigger.dev/sdk";
142+
143+
export const processOrder = task({
144+
id: "process-order",
145+
retry: { maxAttempts: 3 },
146+
run: async (payload: { orderId: string; email: string }) => {
147+
// This key is scoped to this specific run of processOrder
148+
// If processOrder retries, the same key still refers to the same child run
149+
const idempotencyKey = await idempotencyKeys.create(`send-confirmation-${payload.orderId}`);
150+
151+
// sendEmail will only be triggered once, even if processOrder retries multiple times
152+
await sendEmail.trigger(
153+
{ to: payload.email, subject: "Order confirmed" },
154+
{ idempotencyKey }
155+
);
156+
157+
// ... more processing that might fail and cause a retry
158+
},
159+
});
160+
```
161+
162+
With `"run"` scope, if you trigger `processOrder` twice with different run IDs, both will send emails because the idempotency keys are different (they include different parent run IDs).
163+
164+
### `"attempt"` scope
165+
166+
The `"attempt"` scope makes the idempotency key unique to each attempt of the parent task. Use this when you want child tasks to re-execute on each retry.
167+
168+
```ts
169+
import { idempotencyKeys, task } from "@trigger.dev/sdk";
170+
171+
export const syncData = task({
172+
id: "sync-data",
173+
retry: { maxAttempts: 3 },
174+
run: async (payload: { userId: string }) => {
175+
// This key changes on each retry attempt
176+
const idempotencyKey = await idempotencyKeys.create(`fetch-${payload.userId}`, {
177+
scope: "attempt",
178+
});
179+
180+
// fetchLatestData will run again on each retry, getting fresh data
181+
const result = await fetchLatestData.triggerAndWait(
182+
{ userId: payload.userId },
183+
{ idempotencyKey }
184+
);
185+
186+
// Process the fresh data...
187+
},
188+
});
189+
```
190+
191+
### `"global"` scope
192+
193+
The `"global"` scope makes the idempotency key truly global across all runs. Use this when you want to ensure a task only runs once ever (until the TTL expires), regardless of which parent task triggered it.
194+
195+
```ts
196+
import { idempotencyKeys, task } from "@trigger.dev/sdk";
197+
198+
export const onboardUser = task({
199+
id: "onboard-user",
200+
run: async (payload: { userId: string; email: string }) => {
201+
// This key is global - the welcome email will only be sent once per user,
202+
// even if onboardUser is triggered multiple times from different places
203+
const idempotencyKey = await idempotencyKeys.create(`welcome-email-${payload.userId}`, {
204+
scope: "global",
205+
});
206+
207+
await sendWelcomeEmail.trigger(
208+
{ to: payload.email },
209+
{ idempotencyKey, idempotencyKeyTTL: "7d" }
210+
);
211+
},
212+
});
213+
```
214+
215+
<Note>
216+
Even with `"global"` scope, idempotency keys are still isolated to the specific task and environment. Using the same key to trigger *different* tasks will not deduplicate - both tasks will run. See [Environment and task scoping](#environment-and-task-scoping) for more details.
217+
</Note>
218+
219+
## Default behavior
220+
221+
Understanding the default behavior is important to avoid unexpected results:
222+
223+
### Passing a raw string
224+
225+
When you pass a raw string directly to the `idempotencyKey` option, it is automatically processed with `"run"` scope:
226+
227+
```ts
228+
// These two are equivalent when called inside a task:
229+
await childTask.trigger(payload, { idempotencyKey: "my-key" });
230+
await childTask.trigger(payload, { idempotencyKey: await idempotencyKeys.create("my-key") });
231+
```
232+
233+
<Warning>
234+
**Breaking change in v4.3.1:** In v4.3.0 and earlier, raw strings defaulted to `"global"` scope. Starting in v4.3.1, raw strings now default to `"run"` scope. If you're upgrading and relied on the previous global behavior, you must now explicitly use `idempotencyKeys.create("key", { scope: "global" })`.
235+
</Warning>
236+
237+
This means raw strings are scoped to the parent run by default. If you want global behavior, you must explicitly create the key with `scope: "global"`:
238+
239+
```ts
240+
// For global idempotency, you must use idempotencyKeys.create with scope: "global"
241+
const idempotencyKey = await idempotencyKeys.create("my-key", { scope: "global" });
242+
await childTask.trigger(payload, { idempotencyKey });
243+
```
244+
245+
### Triggering from backend code
246+
247+
When triggering tasks from your backend code (outside of a task), there is no parent run context. In this case, `"run"` and `"attempt"` scopes behave the same as `"global"` since there's no run ID or attempt number to inject:
248+
249+
```ts
250+
// In your backend code (e.g., an API route)
251+
import { idempotencyKeys, tasks } from "@trigger.dev/sdk";
252+
253+
// All three of these behave the same when called outside a task:
254+
await tasks.trigger("my-task", payload, { idempotencyKey: "my-key" });
255+
await tasks.trigger("my-task", payload, {
256+
idempotencyKey: await idempotencyKeys.create("my-key", { scope: "run" }),
257+
});
258+
await tasks.trigger("my-task", payload, {
259+
idempotencyKey: await idempotencyKeys.create("my-key", { scope: "global" }),
260+
});
261+
```
262+
263+
<Note>
264+
When triggering from backend code, the scope doesn't matter since there's no task context. All scopes effectively behave as global.
265+
</Note>
266+
90267
## `idempotencyKeyTTL` option
91268

92269
The `idempotencyKeyTTL` option defines a time window during which a task with the same idempotency key will only run once. Here's how it works:
@@ -131,6 +308,32 @@ You can use the following units for the `idempotencyKeyTTL` option:
131308
- `h` for hours (e.g. `2h`)
132309
- `d` for days (e.g. `3d`)
133310

311+
## Failed runs and idempotency
312+
313+
When a run with an idempotency key **fails**, the key is automatically cleared. This means triggering the same task with the same idempotency key will create a new run. However, **successful** and **canceled** runs keep their idempotency key. If you need to re-trigger after a successful or canceled run, you can:
314+
315+
1. **Reset the idempotency key** using `idempotencyKeys.reset()`:
316+
317+
```ts
318+
import { idempotencyKeys } from "@trigger.dev/sdk";
319+
320+
// Clear the idempotency key to allow re-triggering
321+
await idempotencyKeys.reset("my-task", "my-idempotency-key");
322+
323+
// Now you can trigger the task again
324+
await myTask.trigger(payload, { idempotencyKey: "my-idempotency-key" });
325+
```
326+
327+
2. **Use a shorter TTL** so the key expires automatically:
328+
329+
```ts
330+
// Key expires after 5 minutes
331+
await myTask.trigger(payload, {
332+
idempotencyKey: "my-key",
333+
idempotencyKeyTTL: "5m"
334+
});
335+
```
336+
134337
## Payload-based idempotency
135338

136339
We don't currently support payload-based idempotency, but you can implement it yourself by hashing the payload and using the hash as the idempotency key.
@@ -178,6 +381,24 @@ Resetting an idempotency key only affects runs in the current environment. The r
178381

179382
## Important notes
180383

384+
### Environment and task scoping
385+
181386
Idempotency keys, even the ones scoped globally, are actually scoped to the task and the environment. This means that you cannot collide with keys from other environments (e.g. dev will never collide with prod), or to other projects and orgs.
182387

183388
If you use the same idempotency key for triggering different tasks, the tasks will not be idempotent, and both tasks will be triggered. There's currently no way to make multiple tasks idempotent with the same key.
389+
390+
### How scopes affect the key
391+
392+
The scope determines what gets hashed alongside your key:
393+
394+
- Same key + `"run"` scope in different parent runs = different hashes = both tasks run
395+
- Same key + `"global"` scope in different parent runs = same hash = only first task runs
396+
- Same key + different scopes = different hashes = both tasks run
397+
398+
This is why understanding scopes is crucial: the same string key can produce different idempotency behavior depending on the scope and context.
399+
400+
### Viewing scope in the dashboard
401+
402+
When you view a run in the Trigger.dev dashboard, you can see both the idempotency key and its scope in the run details panel. This helps you debug idempotency issues by understanding exactly how the key was configured.
403+
404+
![Idempotency section in the run details pane showing the key, scope, and expiration time](/images/idempotency-key-dashboard.png)
170 KB
Loading

0 commit comments

Comments
 (0)