Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cdp): fast-first-retry + exponential backoff on janitor stalled-job resets (#71361)

Daniel Marchuk8e3ee35052a8
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index e92f51dbd4e5..03472c61dc30 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -162,6 +162,14 @@ export type CdpConfig = ClickhouseConfig & {
// record (a give-up is lost, exactly as before this change). Flip to false to
// roll back the recovery machinery instantly without a redeploy. Default true.
CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED: boolean
+ // Backoff on a stalled job's next scheduled time per janitor reset, keyed on
+ // janitor_touch_count. The first stall retries within seconds (so a transient
+ // stall / worker restart recovers fast); repeat stalls back off exponentially —
+ // at the defaults roughly ~30-60s, then ~1.5-3min, before give-up. Jittered
+ // throughout to de-sync a fleet-wide herd. Base 0 disables it (immediate retry);
+ // max caps the per-strike wait.
+ CYCLOTRON_NODE_JANITOR_STALL_BACKOFF_BASE_MS: number
+ CYCLOTRON_NODE_JANITOR_STALL_BACKOFF_MAX_MS: number
// Timing-edit reschedule sweep (CyclotronV2Manager.rescheduleParkedJobs)
// Scoped JWT keys authenticating Django's calls to the reschedule_parked route — comma-separated,
// newest first (first signs, all verify). Deliberately NOT the fleet-wide INTERNAL_API_SECRET
@@ -316,6 +324,8 @@ export function getDefaultCdpConfig(): CdpConfig {
CYCLOTRON_NODE_JANITOR_MAX_TOUCH_COUNT: 3,
CYCLOTRON_NODE_JANITOR_CLEANUP_GRACE_MS: 10000,
CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED: true,
+ CYCLOTRON_NODE_JANITOR_STALL_BACKOFF_BASE_MS: 60000,
+ CYCLOTRON_NODE_JANITOR_STALL_BACKOFF_MAX_MS: 600000,
// Floor > the hog flow cache's worst-case staleness (~6 min), so swept jobs
// always wake against post-edit config. Rate sized well under hogflow worker
// steady-state throughput: the past incident class here is an instantaneous
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
index 2dcb8e3a8baa..5d7f4f670d63 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -69,6 +69,9 @@ function createJanitor(overrides?: Record<string, unknown>, results?: HogInvocat
cleanupGraceMs: 0,
stallTimeoutMs: 0,
maxTouchCount: 2,
+ // Off by default so existing reset tests keep immediate-retry semantics;
+ // the backoff tests opt in explicitly.
+ stallBackoffBaseMs: 0,
...overrides,
},
results
@@ -1852,6 +1855,101 @@ describe('Cyclotron V2', () => {
expect(row.janitor_touch_count).toBe(1)
})
+ // Backoff on the reset job's next scheduled time, keyed on
+ // janitor_touch_count. The FIRST stall retries within the small jittered
+ // spread (~5s), not the full base — the exponential term is shifted
+ // (2^touch - 1 = 0 on the first strike) so a transient stall recovers fast.
+ // Repeat stalls then pay a growing, capped backoff. Bounds are loose to
+ // absorb jitter + db clock skew. maxTouchCount is high so these aren't given
+ // up as poison before reset.
+ it('resetStalledJobs retries the first stall fast (spread only, not the full base)', async () => {
+ const jobId = uuidv7()
+ await insertRawJob({
+ id: jobId,
+ status: 'running',
+ lock_id: uuidv7(),
+ last_heartbeat: new Date(Date.now() - 60_000),
+ scheduled: new Date(Date.now() - 60_000),
+ janitor_touch_count: 0,
+ })
+
+ const before = Date.now()
+ const janitor = createJanitor({
+ stallTimeoutMs: 1_000,
+ stallBackoffBaseMs: 10_000,
+ stallBackoffMaxMs: 600_000,
+ })
+ const result = await janitor.runOnce()
+ await janitor.stop()
+
+ expect(result.stalled).toBe(1)
+ const row = await queryJob(jobId)
+ expect(row.status).toBe('available')
+ const deferMs = new Date(row.scheduled).getTime() - before
+ // Rescheduled to ~now (not left 60s in the past → backoff ran) but only
+ // by the ~5s spread — well under the 10s base, so a first stall is fast.
+ expect(deferMs).toBeGreaterThanOrEqual(-500)
+ expect(deferMs).toBeLessThanOrEqual(6_000)
+ })
+
+ it.each([
+ { touchCount: 1, baseMs: 10_000, maxMs: 600_000, minDeferMs: 4_000, maxDeferMs: 18_000 },
+ { touchCount: 2, baseMs: 10_000, maxMs: 600_000, minDeferMs: 13_000, maxDeferMs: 38_000 },
+ { touchCount: 2, baseMs: 10_000, maxMs: 5_000, minDeferMs: 2_000, maxDeferMs: 12_000 },
+ ])(
+ 'resetStalledJobs backs off repeat stalls exponentially, capped (touch=$touchCount, cap=$maxMs)',
+ async ({ touchCount, baseMs, maxMs, minDeferMs, maxDeferMs }) => {
+ const jobId = uuidv7()
+ await insertRawJob({
+ id: jobId,
+ status: 'running',
+ lock_id: uuidv7(),
+ last_heartbeat: new Date(Date.now() - 60_000),
+ janitor_touch_count: touchCount,
+ })
+
+ const before = Date.now()
+ const janitor = createJanitor({
+ stallTimeoutMs: 1_000,
+ maxTouchCount: 100,
+ stallBackoffBaseMs: baseMs,
+ stallBackoffMaxMs: maxMs,
+ })
+ const result = await janitor.runOnce()
+ await janitor.stop()
+
+ expect(result.stalled).toBe(1)
+ const row = await queryJob(jobId)
+ expect(row.status).toBe('available')
+ const deferMs = new Date(row.scheduled).getTime() - before
+ expect(deferMs).toBeGreaterThan(minDeferMs)
+ expect(deferMs).toBeLessThanOrEqual(maxDeferMs)
+ }
+ )
+
+ it('resetStalledJobs leaves scheduled immediate when backoff is disabled (base 0)', async () => {
+ const jobId = uuidv7()
+ const pastScheduled = new Date(Date.now() - 5_000)
+ await insertRawJob({
+ id: jobId,
+ status: 'running',
+ lock_id: uuidv7(),
+ last_heartbeat: new Date(Date.now() - 60_000),
+ scheduled: pastScheduled,
+ janitor_touch_count: 0,
+ })
+
+ const before = Date.now()
+ const janitor = createJanitor({ stallTimeoutMs: 1_000, stallBackoffBaseMs: 0 })
+ await janitor.runOnce()
+ await janitor.stop()
+
+ const row = await queryJob(jobId)
+ expect(row.status).toBe('available')
+ // scheduled untouched → still in the past → immediately re-dequeuable.
+ expect(new Date(row.scheduled).getTime()).toBeLessThanOrEqual(before)
+ })
+
it('records a poison pill as a failed result and deletes it once recorded', async () => {
const staleHeartbeat = new Date(Date.now() - 60_000)
const jobId = uuidv7()
diff --git a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
index e1937218923d..cadf6d8348a3 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/janitor.ts
@@ -14,6 +14,13 @@ import { CyclotronV2CleanupResult, CyclotronV2DequeuedJob, CyclotronV2JanitorCon
// exactly these give-ups from the rerun tooling (rerun filter `error_kind`).
export const JANITOR_POISON_PILL_ERROR_KIND = 'janitor_poison_pill'
+// The first stall gets only this small jittered delay (not the full exponential
+// base), so a transient stall — a worker restart/deploy, where a healthy worker
+// should pick the job right back up — recovers in seconds rather than waiting a
+// full backoff step. The jitter still de-syncs a fleet-wide herd on that first
+// retry. Repeat stalls (a persistent signal) then pay the growing exponential.
+const STALL_BACKOFF_FIRST_RETRY_SPREAD_MS = 5000
+
const janitorDeletedCounter = new Counter({
name: 'cdp_cyclotron_v2_janitor_deleted',
help: 'Number of terminal jobs cleaned up by the janitor',
@@ -75,6 +82,8 @@ export class CyclotronV2Janitor {
private readonly maxTouchCount: number
private readonly cleanupGraceMs: number
private readonly poisonRecoveryEnabled: boolean
+ private readonly stallBackoffBaseMs: number
+ private readonly stallBackoffMaxMs: number
constructor(
config: CyclotronV2JanitorConfig,
@@ -95,6 +104,13 @@ export class CyclotronV2Janitor {
this.maxTouchCount = config.maxTouchCount ?? 3
this.cleanupGraceMs = config.cleanupGraceMs ?? 10000
this.poisonRecoveryEnabled = config.poisonRecoveryEnabled ?? true
+ // Clamp against a misconfigured value: a non-positive base disables backoff
+ // (same as 0), and a non-positive cap falls back to the default — otherwise
+ // a negative cap would win the LEAST() and schedule the retry in the past.
+ const backoffBaseMs = config.stallBackoffBaseMs ?? 60000
+ const backoffMaxMs = config.stallBackoffMaxMs ?? 600000
+ this.stallBackoffBaseMs = backoffBaseMs > 0 ? backoffBaseMs : 0
+ this.stallBackoffMaxMs = backoffMaxMs > 0 ? backoffMaxMs : 600000
if (!this.poisonRecoveryEnabled) {
logger.warn(
@@ -339,6 +355,28 @@ export class CyclotronV2Janitor {
private async resetStalledJobs(): Promise<number> {
const heartbeatCutoff = new Date(Date.now() - this.stallTimeoutMs)
+ // Defer the reset job's next scheduled time so repeated stalls back off
+ // and a fleet-wide stall doesn't immediately re-flood the workers that
+ // just recovered. Two parts, both jittered to break a synchronized herd:
+ // 1. a small first-retry spread (0..FIRST_RETRY_SPREAD_MS) applied every
+ // reset — on the FIRST stall it's the whole delay, so a transient
+ // stall retries within seconds instead of a full backoff step;
+ // 2. an exponential term shifted by one (`2^touch_count - 1`), so it's 0
+ // on the first stall and grows ~base, ~3x base, ... on repeats,
+ // capped at max — half-jitter ([0.5, 1] x) on this part.
+ // Disabled when stallBackoffBaseMs <= 0 — scheduled is left untouched
+ // (immediate retry, the pre-backoff behavior).
+ const backoffEnabled = this.stallBackoffBaseMs > 0
+ const backoffClause = backoffEnabled
+ ? `, scheduled = NOW() + (
+ $4::float8 * random()
+ + LEAST($2::float8 * (POWER(2, janitor_touch_count) - 1), $3::float8) * (0.5 + 0.5 * random())
+ ) * INTERVAL '1 millisecond'`
+ : ''
+ const params: (Date | number)[] = backoffEnabled
+ ? [heartbeatCutoff, this.stallBackoffBaseMs, this.stallBackoffMaxMs, STALL_BACKOFF_FIRST_RETRY_SPREAD_MS]
+ : [heartbeatCutoff]
+
const result = await this.pool.query(
`WITH stalled AS (
SELECT id
@@ -349,10 +387,10 @@ export class CyclotronV2Janitor {
)
UPDATE cyclotron_jobs
SET status = 'available', lock_id = NULL, last_heartbeat = NULL,
- janitor_touch_count = janitor_touch_count + 1
+ janitor_touch_count = janitor_touch_count + 1${backoffClause}
FROM stalled
WHERE cyclotron_jobs.id = stalled.id`,
- [heartbeatCutoff]
+ params
)
const count = result.rowCount ?? 0
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index e36fc654a523..d3ca08517eed 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -164,6 +164,12 @@ export type CyclotronV2JanitorConfig = {
// Kill-switch. When false the janitor reverts to master's legacy path — mark
// poison pills failed with no replay record (a give-up is lost). Defaults to true.
poisonRecoveryEnabled?: boolean
+ // Exponential backoff (with jitter) applied to a stalled job's next scheduled
+ // time on each janitor reset, keyed on janitor_touch_count. Staggers
+ // re-dequeue during a fleet-wide stall instead of re-flooding the workers that
+ // just recovered. `stallBackoffBaseMs = 0` disables it (immediate retry).
+ stallBackoffBaseMs?: number
+ stallBackoffMaxMs?: number
}
export type CyclotronV2CleanupResult = {
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index ee25ca478fc0..6072465ea18a 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -280,6 +280,8 @@ export class PluginServer implements NodeServer {
maxTouchCount: this.config.CYCLOTRON_NODE_JANITOR_MAX_TOUCH_COUNT,
cleanupGraceMs: this.config.CYCLOTRON_NODE_JANITOR_CLEANUP_GRACE_MS,
poisonRecoveryEnabled: this.config.CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED,
+ stallBackoffBaseMs: this.config.CYCLOTRON_NODE_JANITOR_STALL_BACKOFF_BASE_MS,
+ stallBackoffMaxMs: this.config.CYCLOTRON_NODE_JANITOR_STALL_BACKOFF_MAX_MS,
},
invocationResults
)