: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): instrument pipeline retries and widen persons-Postgres budget (#62095)
Paweł Ledwońe328524e322f
diff --git a/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts b/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.tsindex ed0e501f1df3..635246eccb16 100644--- a/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts+++ b/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts@@ -125,6 +125,6 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipeline}))),- { tries: 3, sleepMs: 100 }+ { tries: 5, sleepMs: 100, name: 'per_distinct_id' })}diff --git a/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.tsindex 16a76c73afe4..624e62d91276 100644--- a/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts+++ b/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts@@ -105,8 +105,9 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr// This step awaits its DB write, so retry transient persons-Postgres failures// (e.g. PgBouncer scale-down) instead of letting them crash the consumer loop..pipeBatchWithRetry(processPersonlessDistinctIdsBatchStep(personsStore, personsPrefetchEnabled), {- tries: 3,+ tries: 5,sleepMs: 100,+ name: 'personless_distinct_ids',})// Prefetch hog functions for all teams in the batch.pipeBatch(createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate))diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.tsindex c967d12e96c4..5407bb1685b0 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-pipeline.ts@@ -278,6 +278,7 @@ export function createErrorTrackingPipeline(.pipeBatchWithRetry(createCymbalProcessingStep(cymbalClient), {tries: 3,sleepMs: 100,+ name: 'cymbal_processing',})// Enrich, prepare, create, and emit events// Batch fetch person (read-only, no updates)diff --git a/nodejs/src/ingestion/pipelines/batch-retry.test.ts b/nodejs/src/ingestion/pipelines/batch-retry.test.tsindex d6fe0c05e321..2208429eb4ad 100644--- a/nodejs/src/ingestion/pipelines/batch-retry.test.ts+++ b/nodejs/src/ingestion/pipelines/batch-retry.test.ts@@ -2,6 +2,8 @@ import { BatchProcessingStep } from './base-batch-pipeline'import { withBatchRetry } from './batch-retry'import { newBatchPipelineBuilder } from './builders'import { createOkContext } from './helpers'+import { pipelineRetryAttemptsHistogram } from './metrics'+import { getRetryAttempts } from './metrics.test-utils'import { drop, isDlqResult, isDropResult, isOkResult, ok } from './results'// Suppress logger output during tests@@ -34,6 +36,7 @@ function createTestBatch<T>(values: T[]) {describe('withBatchRetry', () => {beforeEach(() => {jest.useFakeTimers()+ pipelineRetryAttemptsHistogram.reset()})afterEach(() => {@@ -167,4 +170,76 @@ describe('withBatchRetry', () => {const wrapped = withBatchRetry(step)expect(wrapped.name).toBe(expectedName)})++ describe('retry attempts metric', () => {+ it('records the attempt count and "completed" outcome when it succeeds after retries', async () => {+ let attempts = 0+ const step: BatchProcessingStep<number, string> = (values) => {+ attempts+++ if (attempts < 3) {+ throw new RetriableError('Temporary failure')+ }+ return Promise.resolve(values.map((v) => ok(String(v))))+ }++ const pipeline = newBatchPipelineBuilder<number>()+ .pipeBatchWithRetry(step, { tries: 5, sleepMs: 100, name: 'test_batch' })+ .gather()+ .build()++ pipeline.feed(createTestBatch([1]))+ const resultPromise = pipeline.next()+ await jest.advanceTimersByTimeAsync(300) // 100ms + 200ms for two retries+ await resultPromise++ expect(await getRetryAttempts('test_batch', 'completed')).toEqual({ count: 1, sum: 3 })+ })++ it('records "exhausted" outcome with the full attempt count when retries run out', async () => {+ jest.useRealTimers() // promise rejections + fake timers don't mix well here++ const step: BatchProcessingStep<number, string> = (_values) => {+ throw new RetriableError('Always fails')+ }++ const pipeline = newBatchPipelineBuilder<number>()+ .pipeBatchWithRetry(step, { tries: 2, sleepMs: 1, name: 'test_batch' })+ .gather()+ .build()++ pipeline.feed(createTestBatch([1]))+ await expect(pipeline.next()).rejects.toThrow('Always fails')++ expect(await getRetryAttempts('test_batch', 'exhausted')).toEqual({ count: 1, sum: 2 })+ })++ it('records "non_retriable" outcome with a single attempt', async () => {+ const step: BatchProcessingStep<number, string> = (_values) => {+ throw new NonRetriableError('Validation failed')+ }++ const pipeline = newBatchPipelineBuilder<number>()+ .pipeBatchWithRetry(step, { tries: 3, sleepMs: 100, name: 'test_batch' })+ .gather()+ .build()++ pipeline.feed(createTestBatch([1, 2]))+ await pipeline.next()++ expect(await getRetryAttempts('test_batch', 'non_retriable')).toEqual({ count: 1, sum: 1 })+ })++ it('defaults the metric name to the step name', async () => {+ const namedStep: BatchProcessingStep<number, string> = function geoipStep(values) {+ return Promise.resolve(values.map((v) => ok(String(v))))+ }++ const pipeline = newBatchPipelineBuilder<number>().pipeBatchWithRetry(namedStep).gather().build()++ pipeline.feed(createTestBatch([1]))+ await pipeline.next()++ expect(await getRetryAttempts('geoipStep', 'completed')).toEqual({ count: 1, sum: 1 })+ })+ })})diff --git a/nodejs/src/ingestion/pipelines/batch-retry.ts b/nodejs/src/ingestion/pipelines/batch-retry.tsindex 4df16d099dc9..96c511f807ff 100644--- a/nodejs/src/ingestion/pipelines/batch-retry.ts+++ b/nodejs/src/ingestion/pipelines/batch-retry.ts@@ -2,9 +2,12 @@ import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { retryIfRetriable } from '../../utils/retries'import { BatchProcessingStep } from './base-batch-pipeline'+import { pipelineRetryAttemptsHistogram } from './metrics'import { dlq } from './results'export interface BatchRetryOptions {+ /** Identifies the retry site in the `ingestion_pipeline_retry_attempts` metric. Defaults to the step name. */+ name?: stringtries?: numbersleepMs?: number}@@ -26,9 +29,20 @@ export function withBatchRetry<T, U, R extends string = never>(step: BatchProcessingStep<T, U, R>,options: BatchRetryOptions = {}): BatchProcessingStep<T, U, R> {+ const name = options.name ?? step.name ?? 'unknown'const wrappedStep: BatchProcessingStep<T, U, R> = async (values: T[]) => {+ let attempts = 0try {- return await retryIfRetriable(() => step(values), options.tries ?? 3, options.sleepMs ?? 100)+ const result = await retryIfRetriable(+ () => {+ attempts+++ return step(values)+ },+ options.tries ?? 3,+ options.sleepMs ?? 100+ )+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'completed' }).observe(attempts)+ return result} catch (error) {const isRetriable = (error as any)?.isRetriable@@ -40,10 +54,12 @@ export function withBatchRetry<T, U, R extends string = never>(})if (isRetriable === false) {+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'non_retriable' }).observe(attempts)captureException(error as Error)return values.map(() => dlq('Processing error - non-retriable', error))}+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'exhausted' }).observe(attempts)throw error}}diff --git a/nodejs/src/ingestion/pipelines/metrics.test-utils.ts b/nodejs/src/ingestion/pipelines/metrics.test-utils.tsnew file mode 100644index 000000000000..ba00f42a66c6--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics.test-utils.ts@@ -0,0 +1,19 @@+import { pipelineRetryAttemptsHistogram } from './metrics'++/**+ * Reads the {_count, _sum} of the retry-attempts histogram for a given name/outcome.+ * _sum holds the observed attempt count (a single observe per call), _count the number of calls.+ */+export async function getRetryAttempts(name: string, outcome: string): Promise<{ count: number; sum: number } | null> {+ const metric = await pipelineRetryAttemptsHistogram.get()+ const find = (suffix: string): number | undefined =>+ metric.values.find(+ (v) =>+ v.metricName === `ingestion_pipeline_retry_attempts${suffix}` &&+ v.labels.name === name &&+ v.labels.outcome === outcome+ )?.value+ const count = find('_count')+ const sum = find('_sum')+ return count === undefined || sum === undefined ? null : { count, sum }+}diff --git a/nodejs/src/ingestion/pipelines/metrics.ts b/nodejs/src/ingestion/pipelines/metrics.tsindex edde417b9e7d..3e52d72d579c 100644--- a/nodejs/src/ingestion/pipelines/metrics.ts+++ b/nodejs/src/ingestion/pipelines/metrics.ts@@ -12,3 +12,10 @@ export const pipelineStepDurationHistogram = new Histogram({labelNames: ['step_name', 'step_type', 'result'],buckets: exponentialBuckets(0.001, 2, 15), // 1ms -> ~16s})++export const pipelineRetryAttemptsHistogram = new Histogram({+ name: 'ingestion_pipeline_retry_attempts',+ help: 'Attempts a retrying pipeline wrapper made before completing, exhausting retries, or hitting a non-retriable error',+ labelNames: ['name', 'outcome'],+ buckets: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],+})diff --git a/nodejs/src/ingestion/pipelines/retrying-pipeline.test.ts b/nodejs/src/ingestion/pipelines/retrying-pipeline.test.tsindex 449059d07163..2ef5db83edf2 100644--- a/nodejs/src/ingestion/pipelines/retrying-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/retrying-pipeline.test.ts@@ -2,6 +2,8 @@ import { Message } from 'node-rdkafka'import { captureException } from '../../utils/posthog'import { createContext, createNewPipeline, createOkContext } from './helpers'+import { pipelineRetryAttemptsHistogram } from './metrics'+import { getRetryAttempts } from './metrics.test-utils'import { PipelineResultType, dlq, ok } from './results'import { RetryingPipeline, RetryingPipelineOptions } from './retrying-pipeline'@@ -16,6 +18,7 @@ const mockCaptureException = captureException as jest.MockedFunction<typeof captdescribe('RetryingPipeline', () => {beforeEach(() => {jest.clearAllMocks()+ pipelineRetryAttemptsHistogram.reset()})describe('basic functionality', () => {@@ -534,4 +537,95 @@ describe('RetryingPipeline', () => {expect(result.context.warnings).toEqual([contextWarning, stepWarning])})})++ describe('retry attempts metric', () => {+ const message: Message = {+ value: Buffer.from('test'),+ topic: 'test',+ partition: 0,+ offset: 1,+ key: Buffer.from('key'),+ size: 4,+ timestamp: Date.now(),+ headers: [],+ }+ const input = createOkContext<{ message: Message }, { message: Message }>({ message }, { message })++ it('records the attempt count and "completed" outcome when it succeeds after retries', async () => {+ let callCount = 0+ const step = jest.fn().mockImplementation(() => {+ callCount+++ if (callCount < 3) {+ const error = new Error('Retriable error')+ ;(error as any).isRetriable = true+ return Promise.reject(error)+ }+ return Promise.resolve(ok({ processed: true }))+ })++ const pipeline = new RetryingPipeline(createNewPipeline().pipe(step), {+ name: 'test_retry',+ tries: 3,+ sleepMs: 1,+ })+ await pipeline.process(input)++ // Succeeded on the 3rd attempt → one observation of value 3.+ expect(await getRetryAttempts('test_retry', 'completed')).toEqual({ count: 1, sum: 3 })+ expect(await getRetryAttempts('test_retry', 'exhausted')).toBeNull()+ })++ it('records "completed" with a single attempt when it succeeds first try', async () => {+ const step = jest.fn().mockResolvedValue(ok({ processed: true }))++ const pipeline = new RetryingPipeline(createNewPipeline().pipe(step), { name: 'test_retry' })+ await pipeline.process(input)++ expect(await getRetryAttempts('test_retry', 'completed')).toEqual({ count: 1, sum: 1 })+ })++ it('records "exhausted" with the full attempt count when retries run out', async () => {+ const step = jest.fn().mockImplementation(() => {+ const error = new Error('Always fails')+ ;(error as any).isRetriable = true+ return Promise.reject(error)+ })++ const pipeline = new RetryingPipeline(createNewPipeline().pipe(step), {+ name: 'test_retry',+ tries: 4,+ sleepMs: 1,+ })+ await expect(pipeline.process(input)).rejects.toThrow('Always fails')++ expect(await getRetryAttempts('test_retry', 'exhausted')).toEqual({ count: 1, sum: 4 })+ })++ it('records "non_retriable" with a single attempt and no retries', async () => {+ const step = jest.fn().mockImplementation(() => {+ const error = new Error('Non-retriable error')+ ;(error as any).isRetriable = false+ return Promise.reject(error)+ })++ const pipeline = new RetryingPipeline(createNewPipeline().pipe(step), {+ name: 'test_retry',+ tries: 5,+ sleepMs: 1,+ })+ await pipeline.process(input)++ expect(await getRetryAttempts('test_retry', 'non_retriable')).toEqual({ count: 1, sum: 1 })+ expect(step).toHaveBeenCalledTimes(1)+ })++ it('falls back to the "unknown" name label when none is provided', async () => {+ const step = jest.fn().mockResolvedValue(ok({ processed: true }))++ const pipeline = new RetryingPipeline(createNewPipeline().pipe(step))+ await pipeline.process(input)++ expect(await getRetryAttempts('unknown', 'completed')).toEqual({ count: 1, sum: 1 })+ })+ })})diff --git a/nodejs/src/ingestion/pipelines/retrying-pipeline.ts b/nodejs/src/ingestion/pipelines/retrying-pipeline.tsindex d5097abcc33d..b910b3373fc5 100644--- a/nodejs/src/ingestion/pipelines/retrying-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/retrying-pipeline.ts@@ -1,10 +1,13 @@import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { retryIfRetriable } from '../../utils/retries'+import { pipelineRetryAttemptsHistogram } from './metrics'import { OkResultWithContext, Pipeline, PipelineResultWithContext } from './pipeline.interface'import { dlq } from './results'export interface RetryingPipelineOptions {+ /** Identifies the retry site in the `ingestion_pipeline_retry_attempts` metric. */+ name?: stringtries?: numbersleepMs?: number}@@ -19,14 +22,18 @@ export class RetryingPipeline<TInput, TOutput, C, R extends string = never> impl) {}async process(input: OkResultWithContext<TInput, C>): Promise<PipelineResultWithContext<TOutput, C, R>> {+ const name = this.options.name ?? 'unknown'+ let attempts = 0try {const result = await retryIfRetriable(async () => {+ attempts++return await this.innerPipeline.process(input)},this.options.tries ?? 3,this.options.sleepMs ?? 100)+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'completed' }).observe(attempts)return result} catch (error) {logger.error('🔥', `Error processing message`, {@@ -35,12 +42,14 @@ export class RetryingPipeline<TInput, TOutput, C, R extends string = never> impl})if (error?.isRetriable === false) {+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'non_retriable' }).observe(attempts)captureException(error)return {result: dlq('Processing error - non-retriable', error),context: input.context,}} else {+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'exhausted' }).observe(attempts)throw error}}