: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion): jitter retry backoff by 5% by default (#82462)
Carlos Marchalaa2935e2cffd
diff --git a/nodejs/src/common/utils/retries.test.ts b/nodejs/src/common/utils/retries.test.tsnew file mode 100644index 000000000000..388e4ab7d52c--- /dev/null+++ b/nodejs/src/common/utils/retries.test.ts@@ -0,0 +1,47 @@+import { DEFAULT_JITTER_FACTOR, retryIfRetriable } from '~/common/utils/retries'++describe('retryIfRetriable jitter', () => {+ function captureSleeps(): number[] {+ const sleeps: number[] = []+ jest.spyOn(global, 'setTimeout').mockImplementation(((fn: () => void, ms?: number) => {+ sleeps.push(ms ?? 0)+ fn()+ return 0 as unknown as NodeJS.Timeout+ }) as typeof setTimeout)+ return sleeps+ }++ function failThenSucceed(failures: number): () => Promise<string> {+ let attempts = 0+ return () => {+ attempts+++ if (attempts <= failures) {+ return Promise.reject(Object.assign(new Error('x'), { isRetriable: true }))+ }+ return Promise.resolve('ok')+ }+ }++ afterEach(() => jest.restoreAllMocks())++ it('jitters each sleep down by up to the default factor', async () => {+ const sleeps = captureSleeps()+ jest.spyOn(Math, 'random').mockReturnValue(0) // worst case: the full downward jitter+ await retryIfRetriable(failThenSucceed(2), 5, 100)+ // 100 and 200 backoff, each scaled by (1 - DEFAULT_JITTER_FACTOR).+ expect(sleeps).toEqual([100 * (1 - DEFAULT_JITTER_FACTOR), 200 * (1 - DEFAULT_JITTER_FACTOR)])+ })++ it('is deterministic when jitter is explicitly disabled', async () => {+ const sleeps = captureSleeps()+ await retryIfRetriable(failThenSucceed(2), 5, 100, 0)+ expect(sleeps).toEqual([100, 200])+ })++ it('applies a stronger jitter factor when asked', async () => {+ const sleeps = captureSleeps()+ jest.spyOn(Math, 'random').mockReturnValue(0)+ await retryIfRetriable(failThenSucceed(1), 5, 100, 1) // full jitter -> floor is 0+ expect(sleeps[0]).toBe(0)+ })+})diff --git a/nodejs/src/common/utils/retries.ts b/nodejs/src/common/utils/retries.tsindex 0d5b0fb1701d..a2bbe7b9a24d 100644--- a/nodejs/src/common/utils/retries.ts+++ b/nodejs/src/common/utils/retries.ts@@ -47,10 +47,21 @@ export function getNextRetryMs(baseMs: number, multiplier: number, attempt: numbreturn baseMs * multiplier ** (attempt - 1)}+/** Fraction of each backoff to jitter by default, de-correlating retries across workers. */+export const DEFAULT_JITTER_FACTOR = 0.05+/*** Retry a function, respecting `error.isRetriable`.+ *+ * Each sleep is jittered down by up to `jitterFactor` of the backoff so+ * concurrent callers don't retry in lockstep. Pass `0` to opt out.*/-export async function retryIfRetriable<T>(fn: () => Promise<T>, tries = 3, sleepMs = 100): Promise<T> {+export async function retryIfRetriable<T>(+ fn: () => Promise<T>,+ tries = 3,+ sleepMs = 100,+ jitterFactor = DEFAULT_JITTER_FACTOR+): Promise<T> {let currentSleepMs = sleepMsfor (let i = 0; i < tries; i++) {try {@@ -62,7 +73,9 @@ export async function retryIfRetriable<T>(fn: () => Promise<T>, tries = 3, sleep}// Fall through, `fn` will retry after sleep.- await sleep(currentSleepMs)+ const jitteredSleepMs =+ jitterFactor > 0 ? currentSleepMs * (1 - jitterFactor + Math.random() * jitterFactor) : currentSleepMs+ await sleep(jitteredSleepMs)currentSleepMs = Math.min(currentSleepMs * defaultRetryConfig.BACKOFF_FACTOR,defaultRetryConfig.MAX_INTERVALdiff --git a/nodejs/src/ingestion/framework/retry.ts b/nodejs/src/ingestion/framework/retry.tsindex 583e51ec381e..8a2daa7993a6 100644--- a/nodejs/src/ingestion/framework/retry.ts+++ b/nodejs/src/ingestion/framework/retry.ts@@ -12,6 +12,8 @@ export interface RetryOptions {name?: stringtries?: numbersleepMs?: number+ /** Fraction of each backoff to jitter by. Defaults to `DEFAULT_JITTER_FACTOR`; pass `0` to opt out. */+ jitter?: number}/**@@ -41,7 +43,8 @@ export function withStepRetry<T, U, R extends string = never>(return step(value)},options.tries ?? 3,- options.sleepMs ?? 100+ options.sleepMs ?? 100,+ options.jitter)pipelineRetryAttemptsHistogram.labels({ name, outcome: 'completed' }).observe(attempts)return result@@ -96,7 +99,8 @@ export function withChunkRetry<T, U, R extends string = never>(return step(values)},options.tries ?? 3,- options.sleepMs ?? 100+ options.sleepMs ?? 100,+ options.jitter)pipelineRetryAttemptsHistogram.labels({ name, outcome: 'completed' }).observe(attempts)return result