: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
chore(ingestion): back off Cymbal retries with a per-step factor (#104332)
Paweł Ledwoń4f641ba8a651
diff --git a/nodejs/src/common/utils/retries.test.ts b/nodejs/src/common/utils/retries.test.tsindex 388e4ab7d52c..abe412ba9fa8 100644--- a/nodejs/src/common/utils/retries.test.ts+++ b/nodejs/src/common/utils/retries.test.ts@@ -1,16 +1,28 @@import { DEFAULT_JITTER_FACTOR, retryIfRetriable } from '~/common/utils/retries'-describe('retryIfRetriable jitter', () => {+describe('retryIfRetriable backoff', () => {+ /** Fake clock the sleeps drive, so elapsed time is deterministic. */+ let now = 0+function captureSleeps(): number[] {const sleeps: number[] = []+ jest.spyOn(Date, 'now').mockImplementation(() => now)jest.spyOn(global, 'setTimeout').mockImplementation(((fn: () => void, ms?: number) => {sleeps.push(ms ?? 0)+ now += ms ?? 0fn()return 0 as unknown as NodeJS.Timeout}) as typeof setTimeout)return sleeps}+ function alwaysFails(durationMs = 0): () => Promise<never> {+ return () => {+ now += durationMs+ return Promise.reject(Object.assign(new Error('x'), { isRetriable: true }))+ }+ }+function failThenSucceed(failures: number): () => Promise<string> {let attempts = 0return () => {@@ -22,26 +34,75 @@ describe('retryIfRetriable jitter', () => {}}+ beforeEach(() => (now = 0))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)+ await retryIfRetriable(failThenSucceed(2), { tries: 5, sleepMs: 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)+ await retryIfRetriable(failThenSucceed(2), { tries: 5, sleepMs: 100, jitter: 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+ await retryIfRetriable(failThenSucceed(1), { tries: 5, sleepMs: 100, jitter: 1 }) // full jitter -> floor is 0expect(sleeps[0]).toBe(0)})++ it('grows each backoff by a custom factor', async () => {+ const sleeps = captureSleeps()+ await retryIfRetriable(failThenSucceed(3), { tries: 5, sleepMs: 100, jitter: 0, backoffFactor: 4 })+ expect(sleeps).toEqual([100, 400, 1600])+ })++ it('caps each backoff at maxSleepMs', async () => {+ const sleeps = captureSleeps()+ await retryIfRetriable(failThenSucceed(3), {+ tries: 5,+ sleepMs: 100,+ jitter: 0,+ backoffFactor: 4,+ maxSleepMs: 500,+ })+ expect(sleeps).toEqual([100, 400, 500])+ })++ it('gives up early once a slow failure spends the soft deadline', async () => {+ const sleeps = captureSleeps()+ const fn = jest.fn(alwaysFails(4000))+ await expect(retryIfRetriable(fn, { tries: 5, sleepMs: 100, jitter: 0, softDeadlineMs: 5000 })).rejects.toThrow(+ 'x'+ )+ expect(fn).toHaveBeenCalledTimes(2)+ expect(sleeps).toEqual([100])+ })++ it('lets fast failures use every try within the soft deadline', async () => {+ const sleeps = captureSleeps()+ const fn = jest.fn(alwaysFails())+ await expect(+ retryIfRetriable(fn, { tries: 5, sleepMs: 100, jitter: 0, backoffFactor: 4, softDeadlineMs: 10000 })+ ).rejects.toThrow('x')+ expect(fn).toHaveBeenCalledTimes(5)+ expect(sleeps).toEqual([100, 400, 1600, 6400])+ })++ it('does not start an attempt after a sleep crosses the soft deadline', async () => {+ const sleeps = captureSleeps()+ const fn = jest.fn(alwaysFails(3000))+ await expect(+ retryIfRetriable(fn, { tries: 5, sleepMs: 100, jitter: 0, backoffFactor: 4, softDeadlineMs: 10000 })+ ).rejects.toThrow('x')+ expect(fn).toHaveBeenCalledTimes(3)+ expect(sleeps).toEqual([100, 400, 1600])+ })})diff --git a/nodejs/src/common/utils/retries.ts b/nodejs/src/common/utils/retries.tsindex a2bbe7b9a24d..6ca29175015c 100644--- a/nodejs/src/common/utils/retries.ts+++ b/nodejs/src/common/utils/retries.ts@@ -50,19 +50,32 @@ export function getNextRetryMs(baseMs: number, multiplier: number, attempt: numb/** Fraction of each backoff to jitter by default, de-correlating retries across workers. */export const DEFAULT_JITTER_FACTOR = 0.05+export interface RetrySchedule {+ /** Total attempts including the first. */+ tries?: number+ /** Sleep before the first retry, in ms. */+ sleepMs?: number+ backoffFactor?: number+ maxSleepMs?: number+ /** Fraction of each sleep to jitter down by. Pass 0 to opt out. */+ jitter?: number+ /** No attempt starts after this much time since the first, in ms. An attempt already running is never cut short. */+ softDeadlineMs?: number+}+/**- * 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.+ * Retry `fn` while `error.isRetriable` is not false. Sleeps are jittered so+ * callers don't retry in lockstep.*/-export async function retryIfRetriable<T>(- fn: () => Promise<T>,- tries = 3,- sleepMs = 100,- jitterFactor = DEFAULT_JITTER_FACTOR-): Promise<T> {- let currentSleepMs = sleepMs+export async function retryIfRetriable<T>(fn: () => Promise<T>, options: RetrySchedule = {}): Promise<T> {+ const tries = options.tries ?? defaultRetryConfig.MAX_RETRIES_DEFAULT+ const backoffFactor = options.backoffFactor ?? defaultRetryConfig.BACKOFF_FACTOR+ const maxSleepMs = options.maxSleepMs ?? defaultRetryConfig.MAX_INTERVAL+ const jitter = options.jitter ?? DEFAULT_JITTER_FACTOR+ const softDeadlineMs = options.softDeadlineMs++ const startedAt = Date.now()+ let currentSleepMs = options.sleepMs ?? defaultRetryConfig.RETRY_INTERVAL_DEFAULTfor (let i = 0; i < tries; i++) {try {return await fn()@@ -72,14 +85,19 @@ export async function retryIfRetriable<T>(throw error}+ const pastSoftDeadline = (): boolean =>+ softDeadlineMs !== undefined && Date.now() - startedAt >= softDeadlineMs+ if (pastSoftDeadline()) {+ throw error+ }+// Fall through, `fn` will retry after sleep.- const jitteredSleepMs =- jitterFactor > 0 ? currentSleepMs * (1 - jitterFactor + Math.random() * jitterFactor) : currentSleepMs+ const jitteredSleepMs = jitter > 0 ? currentSleepMs * (1 - jitter + Math.random() * jitter) : currentSleepMsawait sleep(jitteredSleepMs)- currentSleepMs = Math.min(- currentSleepMs * defaultRetryConfig.BACKOFF_FACTOR,- defaultRetryConfig.MAX_INTERVAL- )+ currentSleepMs = Math.min(currentSleepMs * backoffFactor, maxSleepMs)+ if (pastSoftDeadline()) {+ throw error+ }}}diff --git a/nodejs/src/ingestion/framework/retry.test.ts b/nodejs/src/ingestion/framework/retry.test.tsindex 73571ce2c53e..7bf9ff9abf97 100644--- a/nodejs/src/ingestion/framework/retry.test.ts+++ b/nodejs/src/ingestion/framework/retry.test.ts@@ -1,4 +1,5 @@import { captureException } from '~/common/utils/posthog'+import { sleep } from '~/common/utils/utils'import { ChunkProcessingStep } from './base-chunk-pipeline'import { newChunkPipelineBuilder, newPipelineBuilder } from './builders'@@ -19,7 +20,14 @@ jest.mock('~/common/utils/posthog', () => ({captureException: jest.fn(),}))+// Skip the retry backoff sleeps, and record what they would have been.+jest.mock('~/common/utils/utils', () => ({+ ...jest.requireActual('~/common/utils/utils'),+ sleep: jest.fn(() => Promise.resolve()),+}))+const mockCaptureException = captureException as jest.MockedFunction<typeof captureException>+const mockSleep = sleep as jest.MockedFunction<typeof sleep>class RetriableError extends Error {isRetriable = true@@ -150,6 +158,28 @@ describe('retry', () => {expect(await getRetryAttempts('retry_site', 'exhausted')).toEqual({ count: 1, sum: 3 })})+ it('forwards the whole retry schedule to retryIfRetriable', async () => {+ let attempts = 0+ const script = (): void => {+ attempts+++ if (attempts < 5) {+ throw new RetriableError('Temporary failure')+ }+ }++ const results = await variant.run(script, {+ name: 'retry_site',+ tries: 5,+ sleepMs: 100,+ jitter: 0,+ backoffFactor: 4,+ maxSleepMs: 1000,+ })++ expect(results.every(isOkResult)).toBe(true)+ expect(mockSleep.mock.calls.map(([ms]) => ms)).toEqual([100, 400, 1000, 1000])+ })+it('defaults the metric name to the step name', async () => {const results = await variant.run(() => {}, { sleepMs: 1 }, { stepName: 'geoipStep' })diff --git a/nodejs/src/ingestion/framework/retry.ts b/nodejs/src/ingestion/framework/retry.tsindex 8a2daa7993a6..3e8ecb559782 100644--- a/nodejs/src/ingestion/framework/retry.ts+++ b/nodejs/src/ingestion/framework/retry.ts@@ -1,19 +1,15 @@import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'-import { retryIfRetriable } from '~/common/utils/retries'+import { RetrySchedule, retryIfRetriable } from '~/common/utils/retries'import { ChunkProcessingStep } from './base-chunk-pipeline'import { pipelineRetryAttemptsHistogram } from './metrics'import { dlq } from './results'import { ProcessingStep } from './steps'-export interface RetryOptions {+export interface RetryOptions extends RetrySchedule {/** Identifies the retry site in the `ingestion_pipeline_retry_attempts` metric. Defaults to the step name. */name?: string- tries?: number- sleepMs?: number- /** Fraction of each backoff to jitter by. Defaults to `DEFAULT_JITTER_FACTOR`; pass `0` to opt out. */- jitter?: number}/**@@ -33,19 +29,15 @@ export function withStepRetry<T, U, R extends string = never>(step: ProcessingStep<T, U, R>,options: RetryOptions = {}): ProcessingStep<T, U, R> {- const name = options.name ?? step.name ?? 'unknown'+ const { name: optionName, ...schedule } = options+ const name = optionName ?? step.name ?? 'unknown'const wrappedStep: ProcessingStep<T, U, R> = async (value: T) => {let attempts = 0try {- const result = await retryIfRetriable(- () => {- attempts++- return step(value)- },- options.tries ?? 3,- options.sleepMs ?? 100,- options.jitter- )+ const result = await retryIfRetriable(() => {+ attempts+++ return step(value)+ }, schedule)pipelineRetryAttemptsHistogram.labels({ name, outcome: 'completed' }).observe(attempts)return result} catch (error) {@@ -89,19 +81,15 @@ export function withChunkRetry<T, U, R extends string = never>(step: ChunkProcessingStep<T, U, R>,options: RetryOptions = {}): ChunkProcessingStep<T, U, R> {- const name = options.name ?? step.name ?? 'unknown'+ const { name: optionName, ...schedule } = options+ const name = optionName ?? step.name ?? 'unknown'const wrappedStep: ChunkProcessingStep<T, U, R> = async (values: T[]) => {let attempts = 0try {- const result = await retryIfRetriable(- () => {- attempts++- return step(values)- },- options.tries ?? 3,- options.sleepMs ?? 100,- options.jitter- )+ const result = await retryIfRetriable(() => {+ attempts+++ return step(values)+ }, schedule)pipelineRetryAttemptsHistogram.labels({ name, outcome: 'completed' }).observe(attempts)return result} catch (error) {diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.tsindex 542c7b9b6edb..19dabaa5c1fe 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts@@ -670,12 +670,11 @@ describe('ErrorTrackingPipeline', () => {const pipeline = createErrorTrackingPipeline(pipelineConfig)- // Cymbal errors are retried 10 times (pipeline default), then propagate- // so Kafka doesn't commit and retries the batch+ // Cymbal errors propagate once the retries are exhausted, so Kafka+ // doesn't commit and retries the batchawait expect(runErrorTrackingPipeline(pipeline, [message])).rejects.toThrow('Cymbal unavailable')- // Cymbal was called 3 times (initial + 2 retries) before giving up- expect(mockCymbalClient.processExceptions).toHaveBeenCalledTimes(3)+ expect(mockCymbalClient.processExceptions).toHaveBeenCalledTimes(5)expect(mockHogTransformer.transformEventAndProduceMessages).not.toHaveBeenCalled()})diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.tsindex d5335bc11b26..3f08f33bf5a0 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts@@ -192,12 +192,10 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)const afterCymbal = preCymbal// Process through Cymbal as a batch (before enrichment - Cymbal only// needs raw exception data, not person/geoip/group data).- // Retry on transient failures (5xx, timeout, network errors).- // 3 retries keeps the worst-case batch time (3 × 45s timeout =- // 135s) well within the 180s liveness interval, and reduces- // amplification pressure on Cymbal during degradation.+ // softDeadlineMs (10s) + ERROR_TRACKING_CYMBAL_TIMEOUT_MS (15s) stays below+ // CONSUMER_MAX_HEARTBEAT_INTERVAL_MS (30s)..pipeChunk(createCymbalProcessingStep(cymbalClient), {- retry: { tries: 3, sleepMs: 100, name: 'cymbal_processing' },+ retry: { tries: 5, sleepMs: 100, backoffFactor: 4, softDeadlineMs: 10000, name: 'cymbal_processing' },})return (