Skip to content

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

fix(cron): adjust maxJitterMs to improve job scheduling reliability

Victor Hugo dos Santos7608273d311a
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index faf5034558..a05ec9a31a 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -663,7 +663,7 @@ Recurring work runs through the cron manager in `src/lib/cron/cron-job.ts` (`cro
- Failures (non-timeout) retry with exponential backoff (base 30 s, max 5 min) up to `maxAttempts`, but only if the retry would still fit before the next scheduled fire. Otherwise the next fire is treated as the natural retry.
- 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` (15 min), so a `*/5` job gets 75s and anything hourly or rarer gets the full 15 min. A fraction below 1 is what makes it safe by construction: 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. Hashing also spreads jobs permanently instead of letting them re-collide next fire. Only the pending-zset score carries the offset; the run id and `scheduled_at` are unchanged. `register` rejects a `runHashTtlS` that does not outlive the job's own window, since the hash would expire before pickup and the run would be reaped silently. Development wiring passes `maxJitterMs: 0` so a job runs when its pattern says.
+ - **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 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.
- **`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**:
diff --git a/backend/src/lib/cron/cron-job.test.ts b/backend/src/lib/cron/cron-job.test.ts
index 023f405adf..88b1b3548c 100644
--- a/backend/src/lib/cron/cron-job.test.ts
+++ b/backend/src/lib/cron/cron-job.test.ts
@@ -737,7 +737,7 @@ describe("derived jitter", () => {
const SCHEDULED_AT = Date.parse("2024-01-01T00:00:00Z");
// Mid-interval, so prevFire is SCHEDULED_AT for every pattern used below.
const NOW = new Date("2024-01-01T00:00:30Z");
- const MAX_JITTER_MS = 15 * 60_000; // factory default
+ const MAX_JITTER_MS = 5 * 60_000; // factory default
const FRACTION = 0.25;
const BACKOFF_MS = 30_000; // retryBackoffBaseMs default
const NEXT_FIRE_BUFFER_MS = 1_000;
@@ -904,25 +904,84 @@ describe("derived jitter", () => {
).toThrow(/maxJitterMs/);
});
- // A run hash that expires before its jittered pickup is reaped as an orphan,
- // so the job would silently never run. Catch that at registration.
- test("register rejects a runHashTtlS shorter than the derived window", () => {
+ // A run hash that expires before its jittered pickup is reaped as an orphan, so the job
+ // would never run. The comparison is against the cap rather than the job's own window,
+ // which is what keeps it independent of the pattern.
+ test("register rejects a runHashTtlS that the cap could outlive", () => {
const { register } = makeFactory();
- // Daily pattern, so the window is the 15-minute cap; a 60s hash cannot cover it.
expect(() => register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 60 })).toThrow(
- /runHashTtlS.*must exceed its jitter window/
+ /runHashTtlS.*must exceed the maximum jitter window/
);
});
- // The guard measures the job's own window, not the cap, so a short-interval job
- // with a modest TTL is not rejected for a window it will never be given.
- test("register accepts a short runHashTtlS when the job's own window is small", () => {
+ // The cap is deliberately set below every live registration's TTL, so the unconditional
+ // check costs nothing. This is the tightest one in the codebase.
+ test("register accepts the smallest runHashTtlS any live job uses", () => {
const { register } = makeFactory();
- // */15 gives a 225s window, comfortably under a 900s hash.
expect(() =>
register({ name: "x", pattern: "*/15 * * * *", handler: vi.fn(), runHashTtlS: 15 * 60 })
).not.toThrow();
});
+
+ // Each fire derives its window from the gap it sits in, so an uneven pattern gives different
+ // fires different windows. A guard that sampled one gap had a verdict that depended on which
+ // gap the process booted next to: registering at :00:10 rejected a 20s TTL while :01:10
+ // accepted it, and fires in the wider gap then outlived the hash and vanished with no trace.
+ // Comparing against the cap removes the sampling, so the verdict is the same from anywhere.
+ describe("uneven patterns", () => {
+ // Fires at :00,:01,:05,:06,... so gaps alternate 1 minute and 4 minutes.
+ const UNEVEN = "0,1,5,6,10,11,15,16,20,21,25,26,30,31,35,36,40,41,45,46,50,51,55,56 * * * *";
+ const BOOT_TIMES = ["2024-01-01T00:00:10Z", "2024-01-01T00:01:10Z", "2024-01-01T00:02:00Z"];
+
+ test("the guard's verdict does not depend on when the process booted", () => {
+ for (const now of BOOT_TIMES) {
+ 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/
+ );
+ }
+ });
+
+ test("a TTL above the cap is accepted from any gap", () => {
+ for (const now of BOOT_TIMES) {
+ vi.setSystemTime(new Date(now));
+ const { register } = makeFactory();
+ expect(() => register({ name: "x", pattern: UNEVEN, handler: vi.fn(), runHashTtlS: 30 * 60 })).not.toThrow();
+ }
+ });
+
+ // The property the cap buys: no fire of any pattern, uneven included, is held back
+ // longer than a TTL that already clears the cap.
+ test("no fire of an uneven pattern is held back past the cap", async () => {
+ const runs = await enqueueOnce([{ name: "x", pattern: UNEVEN, runHashTtlS: 30 * 60 }]);
+ expect(runs.length).toBeGreaterThan(0);
+ runs.forEach((run) => expect(run.eligibleAt - run.scheduledAt).toBeLessThan(MAX_JITTER_MS));
+ });
+ });
+
+ // A run whose hash expires before it is claimed is gone, and nothing else records it:
+ // it never completed, never failed, and its zset entry is reaped on sight. The log line
+ // is the only trace, so it is the thing an operator can alert on.
+ test("reaping a run whose hash expired before pickup is logged as an error", async () => {
+ vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));
+ const redis = makeRedis();
+ redis.set.mockResolvedValue("OK");
+ redis.zrangebyscore.mockResolvedValue(["x:1704067200000"]);
+ redis.hgetall.mockResolvedValue({}); // hash gone, zset entry lingers
+ vi.mocked(logger.error).mockClear();
+
+ const { register, start, stop } = makeFactory({ redis });
+ register({ name: "x", pattern: "*/10 * * * *", handler: vi.fn(), runHashTtlS: 3600 });
+ start();
+ await vi.advanceTimersByTimeAsync(300);
+
+ const messages = vi.mocked(logger.error).mock.calls.map(([a, b]) => (typeof a === "string" ? a : b));
+ expect(messages.some((m) => typeof m === "string" && m.includes("expired before it was claimed"))).toBe(true);
+ expect(redis.zrem).toHaveBeenCalledWith("{cron}:pending", "x:1704067200000");
+
+ await stop();
+ });
});
// Jitter is probabilistic. The per-pod cap is the deterministic guarantee that
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 84886e7483..64a386316d 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -84,7 +84,7 @@ const DEFAULTS = {
retryBackoffBaseMs: 30_000,
retryBackoffMaxMs: 5 * 60_000,
drainTimeoutMs: 25_000,
- maxJitterMs: 15 * 60_000,
+ maxJitterMs: 5 * 60_000,
maxConcurrentHandlers: 4
} as const;
@@ -207,10 +207,8 @@ export const cronJobFactory = ({
retryBackoffMaxMs?: number;
drainTimeoutMs?: number;
/**
- * Ceiling on the derived jitter window. Without it a daily job would be spread over six
- * hours; with it, every job past a ~1h interval shares the same widest window. Set it to 0
- * to disable jitter, which is what development wiring does so a job runs when its pattern
- * says it should.
+ * Ceiling on the derived jitter window. Set it to 0 to disable
+ * jitter, which is what development wiring does so a job runs when its pattern says.
*/
maxJitterMs?: number;
/**
@@ -275,15 +273,6 @@ export const cronJobFactory = ({
const jitterWindowMs = (intervalMs: number) =>
Math.min(intervalMs * JITTER_INTERVAL_FRACTION, maxJitterMs, Math.max(0, intervalMs - NEXT_FIRE_BUFFER_MS));
- // The window for a pattern, sampled at registration. A pattern with uneven intervals (say
- // quarterly) gets its window recomputed per fire at enqueue; this sample only has to be good
- // enough for the run-hash TTL check.
- const jitterWindowForPattern = (pattern: string) => {
- const it = CronExpressionParser.parse(pattern, { tz: "UTC" });
- const next = it.next().toDate().getTime();
- return jitterWindowMs(it.next().toDate().getTime() - next);
- };
-
// Per-job offset into the jitter window, derived from a stable hash of the job
// name. It MUST NOT be random: the run id is keyed on the scheduled fire time
// and every pod computes a run's eligibility time independently, so a per-pod offset
@@ -424,15 +413,11 @@ export const cronJobFactory = ({
if (entries.has(name)) throw new Error(`cron[${name}] already registered`);
CronExpressionParser.parse(pattern, { tz: "UTC" }); // validate at registration
- // The run hash has to outlive the offset, or it expires before its own pickup and
- // processCandidate reaps the orphaned zset entry with no log and no failed status: the
- // job would silently never run. Measured against this pattern's own window.
- const windowMs = jitterWindowForPattern(pattern);
- if (runHashTtlS * 1000 <= windowMs) {
+ if (runHashTtlS * 1000 <= maxJitterMs) {
throw new Error(
- `cron[${name}] runHashTtlS (${runHashTtlS}s) must exceed its jitter window (${Math.round(
- windowMs / 1000
- )}s), otherwise the run hash expires before the run is picked up`
+ `cron[${name}] runHashTtlS (${runHashTtlS}s) must exceed the maximum jitter window (${Math.round(
+ maxJitterMs / 1000
+ )}s), otherwise the run hash can expire before the run is picked up`
);
}
@@ -453,7 +438,7 @@ export const cronJobFactory = ({
handlerTimeoutMs: entryHandlerTimeoutMs,
leaseDurationMs: entryLeaseDurationMs
});
- logger.info(`cron[${name}]: registered (pattern="${pattern}") [jitter_window_ms=${windowMs}]`);
+ logger.info(`cron[${name}]: registered (pattern="${pattern}")`);
};
// ── slot election ───────────────────────────────────────────────────────────
@@ -614,7 +599,9 @@ export const cronJobFactory = ({
const processCandidate = async (id: string) => {
const data = await redis.hgetall(RUN_KEY(id));
if (!data?.name) {
- // Hash expired (TTL) but zset entry lingered; clean up.
+ 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}]`
+ );
await redis.zrem(PENDING_ZSET, id);
return;
}