Skip to content

Commit 4961fc4

Browse files
matt-aitkenTrigger.dev RepoOps
authored andcommitted
feat(sdk,core,webapp): key each concurrency limit separately with an object concurrencyKey
## Summary `concurrencyKey` now also takes an object, so one run can be limited by two limits keyed by different things, for example a cap per session and a cap per organization. A string key works exactly as before. ```ts export const orgLimit = concurrencyLimit({ name: "org-subagents", perKey: 20 }); export const subagent = task({ id: "subagent", // 3 per session, 200 in total, plus the org limit concurrency: [{ perKey: 3, total: 200 }, orgLimit], run: async () => {}, }); await subagent.trigger(payload, { concurrencyKey: { default: sessionId, [orgLimit.name]: orgId, }, }); ``` A limit uses its own entry if it has one, otherwise `default`. A string is shorthand for `{ default: string }`. ## Design `default` stays the run's own key, so the run is still queued and scheduled per default key and everything that reads a run's `concurrencyKey` still sees a string. Each other entry gives the named limit of that name its own key. The run queue already supports a key per limit, so there is no engine change. - `default` is required in the object form. Without it every run would wait in one unkeyed queue, where one key at its cap can hold up the keys behind it. - An entry for a limit the task does not declare adds that limit to the run, so triggers keep working while a deploy that adds the limit is still rolling out. A name that matches no declared limit caps nothing, and the limit that was meant falls back to `default`. - A server without this change rejects the object form instead of mis-keying the limits. - A run holds at most four limits, counting the task's inline limit and any added by an entry. Mono-RevId: 41d8c74aee7609f5f5c88ec33076504f7c4f3e28
1 parent 4302c02 commit 4961fc4

17 files changed

Lines changed: 506 additions & 38 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@trigger.dev/sdk": patch
3+
---
4+
5+
`concurrencyKey` now also takes an object, so one run can be limited by two limits keyed by different things, like a cap per session and a cap per organization. `default` is the run's own key and every other entry gives a named limit its own key: `concurrencyKey: { default: sessionId, [orgLimit.name]: orgId }`. A string key works as before.

‎apps/webapp/app/runEngine/concerns/queues.server.ts‎

Lines changed: 45 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { sanitizeQueueName } from "@trigger.dev/core/v3/isomorphic";
1+
import { CONCURRENCY_LIMIT_NAME_PATTERN, sanitizeQueueName } from "@trigger.dev/core/v3/isomorphic";
22
import type { PrismaClientOrTransaction } from "@trigger.dev/database";
33
import type { AuthenticatedEnvironment } from "~/services/apiAuth.server";
44
import { logger } from "~/services/logger.server";
@@ -230,7 +230,7 @@ export class DefaultQueueManager implements QueueManager {
230230
const triggerLimits = request.body.options?.concurrency;
231231

232232
for (const name of triggerLimits ?? []) {
233-
if (!/^[a-zA-Z0-9_-]{1,122}$/.test(name)) {
233+
if (!CONCURRENCY_LIMIT_NAME_PATTERN.test(name)) {
234234
throw new ServiceValidationError(
235235
`Invalid concurrency limit name "${name}": names are 1-122 characters using only letters, numbers, underscores and hyphens.`
236236
);
@@ -267,29 +267,61 @@ export class DefaultQueueManager implements QueueManager {
267267
taskGates ??
268268
undefined;
269269

270+
/**
271+
* An object concurrencyKey gives named limits their own key: `default` stays the
272+
* run's key and every other entry keys the gate of the limit it names. An entry for
273+
* a limit the run does not hold adds that limit to the run, on top of the others, so
274+
* triggers keep working while the deploy that declares the limit is rolling out.
275+
*/
276+
const runKey = request.body.options?.concurrencyKey;
277+
const limitKeys = new Map<string, { name: string; key: string }>();
278+
if (typeof runKey === "object" && runKey !== null) {
279+
if (!runKey.default) {
280+
throw new ServiceValidationError(
281+
"concurrencyKey needs a `default` key: runs are queued and scheduled fairly per default key, and limits without their own entry use it."
282+
);
283+
}
284+
for (const [name, key] of Object.entries(runKey)) {
285+
if (name === "default") {
286+
continue;
287+
}
288+
if (!CONCURRENCY_LIMIT_NAME_PATTERN.test(name)) {
289+
throw new ServiceValidationError(
290+
`Invalid concurrencyKey entry "${name}": entries other than \`default\` are concurrency limit names, 1-122 characters using only letters, numbers, underscores and hyphens.`
291+
);
292+
}
293+
limitKeys.set(sanitizeQueueName(`limit/${name}`), { name, key });
294+
}
295+
}
296+
297+
const heldLimits = new Set(requestedGates?.map((gate) => sanitizeQueueName(gate.queue)));
298+
const impliedGates = [...limitKeys.keys()]
299+
.filter((gateQueue) => !heldLimits.has(gateQueue))
300+
.map((queue): { queue: string; concurrencyKey?: string } => ({ queue }));
301+
270302
const seenGates = new Set<string>();
271-
const gates = requestedGates?.flatMap((gate) => {
272-
const sanitized = sanitizeQueueName(gate.queue);
303+
const gates = [...(requestedGates ?? []), ...impliedGates].flatMap((requestedGate) => {
304+
const sanitized = sanitizeQueueName(requestedGate.queue);
273305
if (!sanitized) {
274306
return [];
275307
}
276-
const dedupeKey = `${sanitized}${gate.concurrencyKey ?? ""}`;
308+
const concurrencyKey = limitKeys.get(sanitized)?.key ?? requestedGate.concurrencyKey;
309+
const dedupeKey = `${sanitized} ${concurrencyKey ?? ""}`;
277310
if (seenGates.has(dedupeKey)) {
278311
return [];
279312
}
280313
seenGates.add(dedupeKey);
281-
return [{ queue: sanitized, concurrencyKey: gate.concurrencyKey }];
314+
return [{ queue: sanitized, concurrencyKey }];
282315
});
283316

284317
/**
285-
* Unreachable through the public schemas (three requested gates plus one inline
286-
* gate is the ceiling), kept as a backstop so an overflowing set can never be
287-
* silently truncated downstream. Replays of three-gate runs against a task that
288-
* later gained an inline limit resolve to four and stay valid.
318+
* A run holds at most four limits: the task's inline limit plus three others, whether
319+
* declared on the task, named at trigger time or added by a concurrencyKey entry. A
320+
* task with an inline limit and two named limits has room for one more.
289321
*/
290-
if (gates && gates.length > 4) {
322+
if (gates.length > 4) {
291323
throw new ServiceValidationError(
292-
`A run can hold at most four gates; this request resolves to ${gates.length}.`
324+
`A run can hold at most four concurrency limits, counting the task's inline limit and any added by a concurrencyKey entry; this request resolves to ${gates.length}.`
293325
);
294326
}
295327

@@ -298,7 +330,7 @@ export class DefaultQueueManager implements QueueManager {
298330
lockedQueueId,
299331
taskTtl,
300332
taskKind,
301-
gates: gates && gates.length > 0 ? gates : undefined,
333+
gates: gates.length > 0 ? gates : undefined,
302334
templateKey,
303335
};
304336
}

‎apps/webapp/app/runEngine/services/triggerTask.server.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -991,10 +991,7 @@ export class RunEngineTriggerTaskService {
991991
// `string` on the API path, but the BatchQueue worker rebuilds
992992
// body.options from Redis-stored items (Record<string, unknown>),
993993
// which can still carry the pre-fix shape from in-flight batches.
994-
concurrencyKey:
995-
typeof args.body.options?.concurrencyKey === "number"
996-
? String(args.body.options.concurrencyKey)
997-
: args.body.options?.concurrencyKey,
994+
concurrencyKey: runConcurrencyKey(args.body.options?.concurrencyKey),
998995
queue: args.queueName,
999996
lockedQueueId: args.lockedQueueId,
1000997
gates: args.gates,
@@ -1091,3 +1088,16 @@ export class RunEngineTriggerTaskService {
10911088
};
10921089
}
10931090
}
1091+
1092+
/**
1093+
* The run's own key: the `default` of an object concurrencyKey, else the value as a
1094+
* string (batch items rebuilt from stored options can still carry a number).
1095+
*/
1096+
function runConcurrencyKey(
1097+
concurrencyKey: string | number | Record<string, string> | undefined
1098+
): string | undefined {
1099+
if (typeof concurrencyKey === "object" && concurrencyKey !== null) {
1100+
return concurrencyKey.default;
1101+
}
1102+
return typeof concurrencyKey === "number" ? String(concurrencyKey) : concurrencyKey;
1103+
}
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import { describe, expect, onTestFinished, vi } from "vitest";
2+
import { RunEngine } from "@internal/run-engine";
3+
import type { TriggerTaskRequestBody } from "@trigger.dev/core/v3";
4+
import type { PrismaClient } from "@trigger.dev/database";
5+
import type { RedisOptions } from "@internal/redis";
6+
import { setupAuthenticatedEnvironment, setupBackgroundWorker } from "@internal/run-engine/tests";
7+
import { assertNonNullable, containerTest } from "@internal/testcontainers";
8+
import { trace } from "@opentelemetry/api";
9+
import { IdempotencyKeyConcern } from "~/runEngine/concerns/idempotencyKeys.server";
10+
import { DefaultQueueManager } from "~/runEngine/concerns/queues.server";
11+
import { RunEngineTriggerTaskService } from "../../app/runEngine/services/triggerTask.server";
12+
import {
13+
MockPayloadProcessor,
14+
MockTraceEventConcern,
15+
MockTriggerTaskValidator,
16+
} from "./triggerTaskTestHelpers";
17+
18+
vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
19+
20+
async function setup(prisma: PrismaClient, redisOptions: RedisOptions) {
21+
const engine = new RunEngine({
22+
prisma,
23+
worker: { redis: redisOptions, workers: 1, tasksPerWorker: 10, pollIntervalMs: 100 },
24+
queue: { redis: redisOptions },
25+
runLock: { redis: redisOptions },
26+
machines: {
27+
defaultMachine: "small-1x",
28+
machines: {
29+
"small-1x": { name: "small-1x" as const, cpu: 0.5, memory: 0.5, centsPerMs: 0.0001 },
30+
},
31+
baseCostInCents: 0.0005,
32+
},
33+
tracer: trace.getTracer("test", "0.0.0"),
34+
});
35+
onTestFinished(() => engine.quit());
36+
37+
const environment = await setupAuthenticatedEnvironment(prisma, "PRODUCTION");
38+
const taskIdentifier = "test-task";
39+
await setupBackgroundWorker(engine, environment, taskIdentifier);
40+
await prisma.backgroundWorkerTask.updateMany({
41+
where: { slug: taskIdentifier, runtimeEnvironmentId: environment.id },
42+
data: { gates: [{ queue: "limit/org" }, { queue: "limit/region" }] },
43+
});
44+
45+
const triggerTaskService = new RunEngineTriggerTaskService({
46+
engine,
47+
prisma,
48+
payloadProcessor: new MockPayloadProcessor(),
49+
queueConcern: new DefaultQueueManager(prisma, engine),
50+
idempotencyKeyConcern: new IdempotencyKeyConcern(prisma, engine, new MockTraceEventConcern()),
51+
validator: new MockTriggerTaskValidator(),
52+
traceEventConcern: new MockTraceEventConcern(),
53+
tracer: trace.getTracer("test", "0.0.0"),
54+
metadataMaximumSize: 1024 * 1024,
55+
});
56+
57+
const trigger = async (options: NonNullable<TriggerTaskRequestBody["options"]>) => {
58+
const result = await triggerTaskService.call({
59+
taskId: taskIdentifier,
60+
environment,
61+
body: { payload: {}, options },
62+
});
63+
const run = await prisma.taskRun.findFirst({ where: { id: result?.run.id } });
64+
assertNonNullable(run);
65+
return run;
66+
};
67+
68+
return { taskIdentifier, trigger };
69+
}
70+
71+
const keysOf = (run: { concurrencyKey: string | null; gates: unknown }) => ({
72+
concurrencyKey: run.concurrencyKey,
73+
gates: run.gates,
74+
});
75+
76+
describe("RunEngineTriggerTaskService concurrency keys per limit", () => {
77+
// Catches: a named limit keyed by the default key, or an entry for an undeclared limit rejected or replacing declared ones.
78+
containerTest(
79+
"keys each named limit by its own entry, adding the limit when the task does not declare it",
80+
async ({ prisma, redisOptions }) => {
81+
const { taskIdentifier, trigger } = await setup(prisma, redisOptions);
82+
83+
expect(
84+
keysOf(await trigger({ concurrencyKey: { default: "session-1", org: "org-1" } }))
85+
).toEqual({
86+
concurrencyKey: "session-1",
87+
gates: [{ queue: "limit/org", concurrencyKey: "org-1" }, { queue: "limit/region" }],
88+
});
89+
90+
expect(
91+
keysOf(
92+
await trigger({
93+
concurrencyKey: { default: "session-1", priority: "org-1" },
94+
concurrency: ["priority"],
95+
})
96+
)
97+
).toEqual({
98+
concurrencyKey: "session-1",
99+
gates: [{ queue: "limit/priority", concurrencyKey: "org-1" }],
100+
});
101+
102+
expect(keysOf(await trigger({ concurrencyKey: "session-1" }))).toEqual({
103+
concurrencyKey: "session-1",
104+
gates: [{ queue: "limit/org" }, { queue: "limit/region" }],
105+
});
106+
107+
expect(
108+
keysOf(await trigger({ concurrencyKey: { default: "session-1", tier: "org-1" } }))
109+
).toEqual({
110+
concurrencyKey: "session-1",
111+
gates: [
112+
{ queue: "limit/org" },
113+
{ queue: "limit/region" },
114+
{ queue: "limit/tier", concurrencyKey: "org-1" },
115+
],
116+
});
117+
118+
expect(
119+
keysOf(
120+
await trigger({
121+
concurrencyKey: { default: "session-1", tier: "org-1" },
122+
concurrency: ["priority"],
123+
})
124+
)
125+
).toEqual({
126+
concurrencyKey: "session-1",
127+
gates: [{ queue: "limit/priority" }, { queue: "limit/tier", concurrencyKey: "org-1" }],
128+
});
129+
130+
await expect(
131+
trigger({ concurrencyKey: { default: "session-1", [`task/${taskIdentifier}`]: "org-1" } })
132+
).rejects.toThrow("Invalid concurrencyKey entry");
133+
}
134+
);
135+
136+
// Catches: a replay-shaped trigger losing or re-keying the per-limit keys (the replay service itself is not run).
137+
containerTest(
138+
"a replay-shaped trigger keeps each named limit's key and only changes the run's own",
139+
async ({ prisma, redisOptions }) => {
140+
const { trigger } = await setup(prisma, redisOptions);
141+
const original = await trigger({ concurrencyKey: { default: "session-1", org: "org-1" } });
142+
const gates = [{ queue: "limit/org", concurrencyKey: "org-1" }, { queue: "limit/region" }];
143+
expect(original.gates).toEqual(gates);
144+
145+
const replay = async (concurrencyKeyOverride?: string) =>
146+
keysOf(
147+
await trigger({
148+
queue: { name: original.queue },
149+
concurrencyKey: concurrencyKeyOverride ?? original.concurrencyKey ?? undefined,
150+
gates: original.gates as Array<{ queue: string; concurrencyKey?: string }>,
151+
})
152+
);
153+
154+
expect(await replay()).toEqual({ concurrencyKey: "session-1", gates });
155+
expect(await replay("session-2")).toEqual({ concurrencyKey: "session-2", gates });
156+
}
157+
);
158+
});

‎docs/concurrency.mdx‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,46 @@ export const processWebhook = task({
201201
await processWebhook.trigger(payload, { concurrencyKey: tenantId });
202202
```
203203

204+
## A different key for each limit
205+
206+
A string `concurrencyKey` keys every `perKey` bound the run holds. When two limits need different keys, for example a cap per session and a cap per organization on the same run, pass an object. `default` is the run's own key, and every other entry is a named limit and the key to use for it:
207+
208+
```ts /trigger/subagent.ts
209+
import { concurrencyLimit, task } from "@trigger.dev/sdk";
210+
211+
// each organization runs at most 20 sub-agents at once
212+
export const orgLimit = concurrencyLimit({ name: "org-subagents", perKey: 20 });
213+
214+
export const subagent = task({
215+
id: "subagent",
216+
// 3 per session, 200 in total, plus the organization limit
217+
concurrency: [{ perKey: 3, total: 200 }, orgLimit],
218+
run: async (payload) => {
219+
//...
220+
},
221+
});
222+
```
223+
224+
```ts app/api/subagent/route.ts
225+
import { orgLimit, subagent } from "~/trigger/subagent";
226+
227+
await subagent.trigger(payload, {
228+
concurrencyKey: {
229+
default: sessionId,
230+
[orgLimit.name]: orgId,
231+
},
232+
});
233+
```
234+
235+
The run starts only when the session has fewer than 3 running, the organization has fewer than 20, and fewer than 200 are running in total.
236+
237+
- **A limit uses its own entry if it has one, otherwise `default`.** A string is shorthand for `{ default: "..." }`.
238+
- **`default` is required.** Runs are queued and scheduled fairly per default key, so pick the key you want fairness across.
239+
- **A limit's own key is 1-128 characters.**
240+
- **An entry for a limit the task doesn't declare adds that limit to the run.** If the limit is declared in the same environment, by another task or by a deploy that is still rolling out, the run counts towards it, so triggers keep working during the deploy.
241+
- **A name that matches no declared limit caps nothing**, and the limit you meant falls back to `default`. Use `[limit.name]` rather than a string literal.
242+
- **`default` always means the default key**, so a limit that is itself named `default` can't be given its own key.
243+
204244
## A global cap for a shared resource
205245

206246
To cap something global, like total traffic to an external API, across many tasks and all tenants: declare a limit with only a `total` and share it. It counts every run holding it, whether or not the run has a `concurrencyKey`:

‎internal-packages/run-engine/src/run-queue/tests/queueGates.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,48 @@ describe("RunQueue gates", () => {
180180
}
181181
);
182182

183+
// Catches: a gate with no declared limit blocking or leaking slots, or a later limit not capping runs that carry it.
184+
redisTest(
185+
"a gate with no declared limit admits, then caps once the limit is declared",
186+
async ({ redisContainer }) => {
187+
const queue = createQueue(redisContainer, true);
188+
try {
189+
await queue.updateQueueConcurrencyLimits(authenticatedEnvDev, "task/my-task", 5);
190+
const held = () => queue.currentConcurrencyOfQueue(authenticatedEnvDev, "later", "acme");
191+
const enqueue = (runId: string) =>
192+
queue.enqueueMessage({
193+
env: authenticatedEnvDev,
194+
message: makeMessage({
195+
runId,
196+
timestamp: Date.now() - 1000,
197+
gates: [{ queue: "later", concurrencyKey: "acme" }],
198+
}),
199+
workerQueue: "main",
200+
});
201+
202+
await enqueue("r0");
203+
await enqueue("r1");
204+
expect(await waitFor(async () => (await held()) === 2)).toBe(true);
205+
206+
await queue.updateQueueConcurrencyLimits(authenticatedEnvDev, "later", 1);
207+
await enqueue("r2");
208+
await setTimeout(2000);
209+
expect(await held()).toBe(2);
210+
expect(await queue.lengthOfQueue(authenticatedEnvDev, "task/my-task")).toBe(1);
211+
212+
await queue.acknowledgeMessage(authenticatedEnvDev.organization.id, "r0");
213+
await queue.acknowledgeMessage(authenticatedEnvDev.organization.id, "r1");
214+
expect(await waitFor(async () => (await held()) === 1)).toBe(true);
215+
expect(await queue.lengthOfQueue(authenticatedEnvDev, "task/my-task")).toBe(0);
216+
217+
await queue.acknowledgeMessage(authenticatedEnvDev.organization.id, "r2");
218+
expect(await held()).toBe(0);
219+
} finally {
220+
await queue.quit();
221+
}
222+
}
223+
);
224+
183225
redisTest(
184226
"a gate's total limit caps keyed and keyless holders together",
185227
async ({ redisContainer }) => {

0 commit comments

Comments
 (0)