Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

refactor(cron): remove maxConcurrentHandlers and improve pattern validation

Victor Hugo dos Santosb5ae04971b57
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 380073da93..f76d47527a 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -664,7 +664,6 @@ Recurring work runs through the cron manager in `src/lib/cron/cron-job.ts` (`cro
- Long-running handlers should override `handlerTimeoutMs` / `leaseDurationMs` per-entry (must satisfy `handlerTimeoutMs <= leaseDurationMs`).
- **A fire is not picked up at its scheduled time; it is picked up at a deterministic offset past it.** Cron patterns cluster hard, so without a spread one pod claims a dozen handlers in a single tick. Two knobs bound that, both in `cronJobFactory`:
- **Jitter** spreads pickup, and is *derived, never configured*: a job's window is `JITTER_INTERVAL_FRACTION` (0.25) of its own cron interval, capped by the factory's `maxJitterMs` (5 min), so a `*/5` job gets 75s and anything at or past a 20-minute interval gets the full 5 min. Two things follow from the fraction being below 1: a run can never reach its own next fire, and the first retry always fits (worst case `0.25 x interval + 30s backoff + 1s`, under `interval` for anything above ~41s, and cron cannot fire faster than every 60s). The offset within the window is `sha256(name) % window`, never random: every pod computes a run's eligibility independently and the run id is keyed on the *unjittered* fire, so a per-pod offset would break the Redis enqueue dedup and the lease logic. Only the pending-zset score carries the offset; the run id and `scheduled_at` are unchanged. Development wiring passes `maxJitterMs: 0` so a job runs when its pattern says. `register` rejects anything but a 5-field pattern: the retry model assumes minute granularity, and a 6-field pattern firing every 30s would have its first retry land past its own next fire. Sub-minute recurring work belongs on a `setInterval` or a queue, as the event outbox relay does.
- - **`maxConcurrentHandlers`** bounds accumulation across *overlapping* ticks, the failure mode when a handler runs long. **It does not bound a burst**, because the `processTick` loop is serial (`await processCandidate` per id), so one tick works through its whole batch back to back on a single pod whatever the cap is. `PROCESS_BATCH_SIZE` still bounds the zset scan, not execution.
**When to use cron vs. queue**:
- Scheduled/recurring (every N minutes, daily at X, cron pattern) → `cronJob.register(...)`.
diff --git a/backend/src/lib/cron/cron-job.test.ts b/backend/src/lib/cron/cron-job.test.ts
index 941a9a0a14..f1cd9f3255 100644
--- a/backend/src/lib/cron/cron-job.test.ts
+++ b/backend/src/lib/cron/cron-job.test.ts
@@ -901,7 +901,7 @@ describe("derived jitter", () => {
test("factory rejects a negative maxJitterMs", () => {
expect(() =>
cronJobFactory({ redis: makeRedis() as never, redlock: makeRedlock() as never, maxJitterMs: -1 })
- ).toThrow(/maxJitterMs/);
+ ).toThrow("maxJitterMs");
});
// A run hash that expires before its jittered pickup is reaped as an orphan, so the job
@@ -910,7 +910,7 @@ describe("derived jitter", () => {
test("register rejects a runHashTtlS that the cap could outlive", () => {
const { register } = makeFactory();
expect(() => register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 60 })).toThrow(
- /runHashTtlS.*must exceed the maximum jitter window/
+ "must exceed the maximum jitter window"
);
});
@@ -938,7 +938,7 @@ describe("derived jitter", () => {
vi.setSystemTime(new Date(now));
const { register } = makeFactory();
expect(() => register({ name: "x", pattern: UNEVEN, handler: vi.fn(), runHashTtlS: 20 })).toThrow(
- /runHashTtlS.*must exceed the maximum jitter window/
+ "must exceed the maximum jitter window"
);
}
});
@@ -983,161 +983,3 @@ describe("derived jitter", () => {
await stop();
});
});
-
-// Jitter is probabilistic. The per-pod cap is the deterministic guarantee that
-// one pod never executes a burst of handlers on the event loop it shares with
-// the HTTP API.
-describe("handler concurrency cap", () => {
- const SCHEDULED_AT = Date.parse("2024-01-01T00:00:00Z");
-
- const setupPendingRuns = (redis: ReturnType<typeof makeRedis>, count: number) => {
- redis.set.mockResolvedValue("OK");
- redis.eval.mockResolvedValue(1);
- redis.zrangebyscore.mockResolvedValue(Array.from({ length: count }, (_, i) => `x:${SCHEDULED_AT - i * 60_000}`));
- redis.hgetall.mockResolvedValue({
- name: "x",
- status: "pending",
- attempts: "0",
- enqueued_at_ms: "0"
- });
- };
-
- // Handlers that hang until the test releases them, so in-flight count is
- // fully under the test's control.
- const makeBlockingHandler = () => {
- const resolvers: Array<() => void> = [];
- const handler = vi.fn().mockImplementation(
- () =>
- new Promise<void>((resolve) => {
- resolvers.push(resolve);
- })
- );
- return { handler, resolvers };
- };
-
- const makeCappedFactory = (
- redis: ReturnType<typeof makeRedis>,
- redlock: ReturnType<typeof makeRedlock>,
- maxConcurrentHandlers: number
- ) =>
- cronJobFactory({
- redis: redis as never,
- redlock: redlock as never,
- slotRefreshMs: 50,
- enqueueIntervalMs: 100,
- processIntervalMs: 100,
- slotTtlMs: 200,
- leaseDurationMs: 60_000,
- handlerTimeoutMs: 60_000,
- drainTimeoutMs: 50,
- maxConcurrentHandlers
- });
-
- test("stops claiming at the cap and leaves the surplus in the pending zset", async () => {
- vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));
- const redis = makeRedis();
- setupPendingRuns(redis, 4);
- const { handler, resolvers } = makeBlockingHandler();
- const redlock = makeRedlock();
-
- const f = makeCappedFactory(redis, redlock, 1);
- f.register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 3600 });
- f.start();
-
- // Several process ticks see four due runs, but only one may be in flight.
- await vi.advanceTimersByTimeAsync(600);
- expect(redlock.using).toHaveBeenCalledTimes(1);
-
- // Deferred, not dropped: nothing was removed from the pending zset, so
- // another pod or a later tick can still take these runs.
- expect(redis.zrem).not.toHaveBeenCalled();
-
- // Freeing the slot lets the work resume rather than being lost.
- resolvers.forEach((resolve) => resolve());
- await vi.advanceTimersByTimeAsync(300);
- expect(redlock.using.mock.calls.length).toBeGreaterThan(1);
-
- resolvers.forEach((resolve) => resolve());
- const stopPromise = f.stop();
- await vi.advanceTimersByTimeAsync(100);
- await stopPromise;
- });
-
- // Guards against the cap collapsing to "one handler at a time".
- test("runs up to maxConcurrentHandlers at once", async () => {
- vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));
- const redis = makeRedis();
- setupPendingRuns(redis, 4);
- const { handler, resolvers } = makeBlockingHandler();
- const redlock = makeRedlock();
-
- const f = makeCappedFactory(redis, redlock, 2);
- f.register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 3600 });
- f.start();
-
- await vi.advanceTimersByTimeAsync(600);
- expect(redlock.using).toHaveBeenCalledTimes(2);
- expect(redis.zrem).not.toHaveBeenCalled();
-
- resolvers.forEach((resolve) => resolve());
- const stopPromise = f.stop();
- await vi.advanceTimersByTimeAsync(100);
- await stopPromise;
- });
-
- // The retry model assumes minute granularity. A 6-field pattern firing every 30s would get a
- // 7.5s window whose first retry lands at 38.5s, past its own next fire, and be marked
- // failed-final instead of retried. Reject it at registration rather than degrade quietly.
- test("rejects a sub-minute (6-field) pattern", () => {
- const { register } = makeFactory();
- expect(() => register({ name: "x", pattern: "*/30 * * * * *", handler: vi.fn(), runHashTtlS: 3600 })).toThrow(
- /must have 5 fields/
- );
- });
-
- test("accepts the 5-field patterns the codebase registers", () => {
- const { register } = makeFactory();
- ["*/5 * * * *", "0 0 * * *", "0 0 19 2,5,8,11 *", "23 3 * * *"].forEach((pattern, i) => {
- expect(() => register({ name: `x${i}`, pattern, handler: vi.fn(), runHashTtlS: 3 * 24 * 60 * 60 })).not.toThrow();
- });
- });
-
- // The pod defers on every tick while saturated, so the line is throttled. Without it a long
- // backlog emits one info line per processIntervalMs, for every pod, for as long as it lasts.
- test("the at-capacity line is throttled, not emitted every tick", async () => {
- vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));
- const redis = makeRedis();
- setupPendingRuns(redis, 4);
- const { handler, resolvers } = makeBlockingHandler();
- const redlock = makeRedlock();
- vi.mocked(logger.info).mockClear();
-
- const f = makeCappedFactory(redis, redlock, 1);
- f.register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 60 * 60 });
- f.start();
-
- // ~30 process ticks (processIntervalMs=100 here) inside one throttle window.
- await vi.advanceTimersByTimeAsync(3_000);
-
- const capacityLines = vi
- .mocked(logger.info)
- .mock.calls.map(([m]) => m)
- .filter((m) => typeof m === "string" && m.includes("at handler capacity"));
- expect(capacityLines.length).toBe(1);
-
- resolvers.forEach((resolve) => resolve());
- const stopPromise = f.stop();
- await vi.advanceTimersByTimeAsync(100);
- await stopPromise;
- });
-
- test("factory rejects a cap below 1", () => {
- expect(() =>
- cronJobFactory({
- redis: makeRedis() as never,
- redlock: makeRedlock() as never,
- maxConcurrentHandlers: 0
- })
- ).toThrow(/maxConcurrentHandlers/);
- });
-});
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 9b602e0b96..08f83842c0 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
import { CronExpressionParser } from "cron-parser";
import { Cluster, Redis } from "ioredis";
+import RE2 from "re2";
import { logger } from "@app/lib/logger";
import { ExecutionError, Redlock, ResourceLockedError } from "@app/lib/red-lock";
@@ -53,6 +54,7 @@ export const CronJobName = {
const JITTER_INTERVAL_FRACTION = 0.25; // keep below ~0.48 so 30s retry fits before next 1-min fire
const CRON_FIELD_COUNT = 5;
+const CRON_FIELD_SEPARATOR = new RE2(/\s+/);
const PARTICIPANT_SLOTS = 5;
const PROCESS_BATCH_SIZE = 50;
const NEXT_FIRE_BUFFER_MS = 1_000; // shared margin for fitsBeforeNextFire and jitterWindowMs
@@ -69,8 +71,7 @@ const DEFAULTS = {
retryBackoffBaseMs: 30_000,
retryBackoffMaxMs: 5 * 60_000,
drainTimeoutMs: 25_000,
- maxJitterMs: 5 * 60_000,
- maxConcurrentHandlers: 4
+ maxJitterMs: 5 * 60_000
} as const;
const KEY_HASH_TAG = "{cron}";
@@ -114,7 +115,6 @@ const ENQUEUE_RUN_LUA = `
// Release slot only if we still own it (stale stop() after TTL expiry).
const RELEASE_SLOT_IF_MINE_LUA = `if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end`;
-
type Handler = () => Promise<void>;
type CronEntry = {
name: string;
@@ -157,7 +157,6 @@ export const cronJobFactory = ({
retryBackoffMaxMs = DEFAULTS.retryBackoffMaxMs,
drainTimeoutMs = DEFAULTS.drainTimeoutMs,
maxJitterMs = DEFAULTS.maxJitterMs,
- maxConcurrentHandlers = DEFAULTS.maxConcurrentHandlers,
keyPrefix = KEY_HASH_TAG,
schedulingEnabled = true
}: {
@@ -173,22 +172,23 @@ export const cronJobFactory = ({
retryBackoffBaseMs?: number;
retryBackoffMaxMs?: number;
drainTimeoutMs?: number;
- /** 0 disables jitter (dev wiring). */
+ /**
+ * 0 disables jitter (dev wiring).
+ */
maxJitterMs?: number;
- /** In-flight handler ceiling per pod; excess stays in the pending zset. */
- maxConcurrentHandlers?: number;
- /** Must include a Redis Cluster hash tag; tests override to avoid slot collisions. */
+ /**
+ * Must include a Redis Cluster hash tag; tests override to avoid slot collisions.
+ */
keyPrefix?: string;
- /** When false, register is a no-op (api-only pods). */
+ /**
+ * When false, register is a no-op (api-only pods).
+ */
schedulingEnabled?: boolean;
}) => {
assertHashTagged(keyPrefix);
if (!Number.isFinite(maxJitterMs) || maxJitterMs < 0) {
throw new Error(`cron: maxJitterMs (${maxJitterMs}) must be a non-negative number`);
}
- if (!Number.isInteger(maxConcurrentHandlers) || maxConcurrentHandlers < 1) {
- throw new Error(`cron: maxConcurrentHandlers (${maxConcurrentHandlers}) must be an integer >= 1`);
- }
const SLOT_KEY = (i: number) => `${keyPrefix}:slot:${i}`;
const RUN_KEY = (id: string) => `${keyPrefix}:run:${id}`;
@@ -200,8 +200,6 @@ export const cronJobFactory = ({
}
const workerId = randomUUID();
- const CAPACITY_LOG_INTERVAL_MS = 60_000; // throttle capacity logs during sustained backlog
- let lastCapacityLogAtMs = 0;
const entries = new Map<string, CronEntry>();
const lastEnqueuedAt = new Map<string, number>();
const inFlight = new Set<Promise<unknown>>();
@@ -230,8 +228,6 @@ export const cronJobFactory = ({
return scheduledAt + jitterOffsetMs(entry.name, windowMs);
};
- const atHandlerCapacity = () => inFlight.size >= maxConcurrentHandlers;
-
const shuffleInPlace = <T>(arr: T[]): void => {
for (let i = arr.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
@@ -253,6 +249,7 @@ export const cronJobFactory = ({
await Promise.race([taskPromise, timeout]);
} finally {
if (timer) clearTimeout(timer);
+ // Nothing waits on the handler after a timeout, so absorb its eventual rejection.
taskPromise.catch(() => {});
}
};
@@ -332,7 +329,7 @@ export const cronJobFactory = ({
}
if (entries.has(name)) throw new Error(`cron[${name}] already registered`);
CronExpressionParser.parse(pattern, { tz: "UTC" }); // validate at registration
- if (pattern.trim().split(/\s+/).length !== CRON_FIELD_COUNT) {
+ if (pattern.trim().split(CRON_FIELD_SEPARATOR).length !== CRON_FIELD_COUNT) {
throw new Error(
`cron[${name}] pattern "${pattern}" must have ${CRON_FIELD_COUNT} fields. The cron manager schedules at minute granularity; sub-minute work belongs on a setInterval or a queue`
);
@@ -478,7 +475,7 @@ export const cronJobFactory = ({
const data = await redis.hgetall(RUN_KEY(id));
if (!data?.name) {
logger.error(
- `cron: pending run expired before it was claimed and will not execute, raise its runHashTtlS above its jitter window and expected backlog [id=${id}]`
+ `cron: pending run expired before it was claimed and will not execute, raise its runHashTtlS [id=${id}]`
);
await redis.zrem(PENDING_ZSET, id);
return;
@@ -504,8 +501,6 @@ export const cronJobFactory = ({
return;
}
- if (atHandlerCapacity()) return;
-
if (isStalled) {
logger.info(`cron[${data.name}]: re-claiming stalled run [id=${id}] [previous_worker=${data.worker_id}]`);
}
@@ -530,24 +525,12 @@ export const cronJobFactory = ({
const ids = await redis.zrangebyscore(PENDING_ZSET, "-inf", Date.now(), "LIMIT", 0, PROCESS_BATCH_SIZE);
shuffleInPlace(ids);
- for (let i = 0; i < ids.length; i += 1) {
- if (atHandlerCapacity()) {
- const now = Date.now();
- if (now - lastCapacityLogAtMs >= CAPACITY_LOG_INTERVAL_MS) {
- lastCapacityLogAtMs = now;
- logger.info(
- `cron: at handler capacity (${maxConcurrentHandlers}), deferring ${
- ids.length - i
- } due run(s) [worker=${workerId}]`
- );
- }
- break;
- }
+ for (const id of ids) {
try {
// eslint-disable-next-line no-await-in-loop
- await processCandidate(ids[i]);
+ await processCandidate(id);
} catch (err) {
- logger.error({ err, id: ids[i] }, "cron: processCandidate failed");
+ logger.error({ err, id }, "cron: processCandidate failed");
}
}
};