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(ingestion): per-step retry and concurrentlyPerGroup builder API (#69267)

Paweł Ledwoń9f1388dee562
diff --git a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md
index ad2e001e9821..df0ed0d7a0d7 100644
--- a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md
+++ b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md
@@ -21,8 +21,7 @@ Kafka message
→ sequentially() for preprocessing
→ filterMap() to enrich context (e.g., team lookup)
→ teamAware()
- → groupBy(token:distinctId)
- → concurrently() for per-entity processing
+ → concurrentlyPerGroup(token:distinctId) for per-entity processing
→ gather()
→ pipeBatch() for batch operations
→ handleIngestionWarnings()
@@ -31,18 +30,18 @@ Kafka message
→ build()
```
-See `nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts` for the real implementation.
+See `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` for the real implementation.
## Key file locations
-| What | Where |
-| ----------------- | ------------------------------------------------------------- |
-| Step type | `nodejs/src/ingestion/pipelines/steps.ts` |
-| Result types | `nodejs/src/ingestion/pipelines/results.ts` |
-| Doc-test chapters | `nodejs/src/ingestion/pipelines/docs/*.test.ts` |
-| Joined pipeline | `nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts` |
-| Doctor agents | `.claude/agents/ingestion/` |
-| Test helpers | `nodejs/src/ingestion/pipelines/docs/helpers.ts` |
+| What | Where |
+| ----------------- | ----------------------------------------------------------------------- |
+| Step type | `nodejs/src/ingestion/framework/steps.ts` |
+| Result types | `nodejs/src/ingestion/framework/results.ts` |
+| Doc-test chapters | `nodejs/src/ingestion/framework/docs/*.test.ts` |
+| Joined pipeline | `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` |
+| Doctor agents | `.claude/agents/ingestion/` |
+| Test helpers | `nodejs/src/ingestion/framework/docs/helpers.ts` |
## Which agent to use
@@ -59,7 +58,7 @@ See `nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts` for the real i
**Results**: Use `ok()`, `dlq()`, `drop()`, `redirect()` constructors. Side effects as promises in `ok(value, [effects])`. Warnings as third parameter.
-**Composition**: `messageAware` wraps the pipeline. `handleResults` inside `messageAware`. `handleSideEffects` after. `groupBy` + `concurrently` for per-entity work. `gather` before batch steps.
+**Composition**: `messageAware` wraps the pipeline. `handleResults` inside `messageAware`. `handleSideEffects` after. `concurrentlyPerGroup` for per-entity work. `gather` before batch steps.
**Testing**: Step tests call factory directly. Use `consumeAll()`/`collectBatches()` helpers. Fake timers for async. Type guards for result assertions. No `any`.
diff --git a/.claude/agents/ingestion/pipeline-composition-doctor.md b/.claude/agents/ingestion/pipeline-composition-doctor.md
index cbe7aac366b4..6e02490ff134 100644
--- a/.claude/agents/ingestion/pipeline-composition-doctor.md
+++ b/.claude/agents/ingestion/pipeline-composition-doctor.md
@@ -41,16 +41,16 @@ You review, suggest, and implement pipeline composition code that follows the co
Before reviewing or writing any code, read these files:
-- `nodejs/src/ingestion/pipelines/docs/02-batch-pipelines.test.ts` — batch steps, cardinality invariant
-- `nodejs/src/ingestion/pipelines/docs/03-concurrent-processing.test.ts` — concurrently(), item-level processing
-- `nodejs/src/ingestion/pipelines/docs/04-sequential-processing.test.ts` — sequentially(), ordered processing
-- `nodejs/src/ingestion/pipelines/docs/05-grouping.test.ts` — groupBy(), within-group order
-- `nodejs/src/ingestion/pipelines/docs/06-gathering.test.ts` — gather(), re-batching after concurrent
-- `nodejs/src/ingestion/pipelines/docs/10-branching.test.ts` — branching(), branch convergence
-- `nodejs/src/ingestion/pipelines/docs/11-retries.test.ts` — retry(), isRetriable, exhaustion behavior
-- `nodejs/src/ingestion/pipelines/docs/12-filter-map.test.ts` — filterMap(), context enrichment
-- `nodejs/src/ingestion/pipelines/docs/13-conventions.test.ts` — pipeline factory functions, naming
-- `nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts` — real-world composition example
+- `nodejs/src/ingestion/framework/docs/02-batch-pipelines.test.ts` — batch steps, cardinality invariant
+- `nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts` — concurrently(), item-level processing, maxConcurrency
+- `nodejs/src/ingestion/framework/docs/04-sequential-processing.test.ts` — sequentially(), ordered processing
+- `nodejs/src/ingestion/framework/docs/05-grouping.test.ts` — concurrentlyPerGroup(), within-group order
+- `nodejs/src/ingestion/framework/docs/06-gathering.test.ts` — gather(), re-batching after concurrent
+- `nodejs/src/ingestion/framework/docs/10-branching.test.ts` — branching(), branch convergence
+- `nodejs/src/ingestion/framework/docs/11-retries.test.ts` — per-step retry option, isRetriable, exhaustion behavior
+- `nodejs/src/ingestion/framework/docs/12-filter-map.test.ts` — filterMap(), context enrichment
+- `nodejs/src/ingestion/framework/docs/13-conventions.test.ts` — pipeline factory functions, naming
+- `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` — real-world composition example
Also read any files the user points you to.
@@ -104,23 +104,26 @@ builder.concurrently((b) => b.pipe(createTeamLookup(db)))
builder.sequentially((b) => b.pipe(createOrderedWrite(db)))
```
-### 4. groupBy + concurrently pattern
+### 4. concurrentlyPerGroup pattern
-`groupBy()` must be followed by `concurrently()`.
-Within-group order is preserved. Groups complete independently.
+`concurrentlyPerGroup(keyFn, callback, options?)` processes groups concurrently.
+The callback receives a group builder whose only method is `sequentially`, which
+defines how items within a group are processed: one at a time, in input order.
+Spelling out `sequentially` keeps within-group ordering visible at the call site.
+Groups complete independently and results are returned as groups finish.
+Cap group parallelism with `{ maxConcurrency }`.
The ingestion pipeline groups by `token:distinctId`.
```typescript
-// GOOD
-builder.groupBy((event) => `${event.token}:${event.distinctId}`).concurrently((b) => b.pipe(createPersonProcessing()))
-
-// BAD - groupBy without concurrently
-builder.groupBy(keyFn).pipe(step) // won't compile
+builder.concurrentlyPerGroup(
+ (event) => `${event.token}:${event.distinctId}`,
+ (group) => group.sequentially((b) => b.pipe(createPersonProcessing()))
+)
```
### 5. gather() placement
-Use after `concurrently()` or `groupBy().concurrently()` when subsequent batch steps need all items at once.
+Use after `concurrently()` or `concurrentlyPerGroup()` when subsequent batch steps need all items at once.
Without gather, results stream one-by-one.
```typescript
@@ -147,14 +150,15 @@ builder.branching((event) => event.type, {
})
```
-### 7. retry() scope
+### 7. retry scope
-Retries re-execute the entire sub-pipeline, not just the failing step.
+Retry is a per-step option on `pipe()` / `pipeBatch()` — it retries only that step, never a sequence of steps.
Errors must have `isRetriable: boolean`. Non-retriable errors go to DLQ.
Exhausted retries cause a fatal throw (process should crash).
+Only steps doing transient-failure-prone I/O should retry; pure steps take no retry option.
```typescript
-builder.retry({ maxRetries: 3, backoff: { initial: 100, multiplier: 2 } }, (b) => b.pipe(createExternalApiStep(client)))
+builder.pipe(createExternalApiStep(client), { retry: { name: 'external_api', tries: 3, sleepMs: 100 } })
```
### 8. filterMap() for context enrichment
@@ -203,7 +207,7 @@ Produce a checklist grouped by rule:
### Concurrency
-- [x] groupBy followed by concurrently
+- [x] concurrentlyPerGroup used for keyed per-entity work
- [ ] **SUGGESTION**: Team lookup is I/O-bound, consider concurrently() instead of sequentially() (Rule 3)
### Gather
diff --git a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap
index 6c548678226d..6f73bae8c1ff 100644
--- a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap
+++ b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap
@@ -35,7 +35,7 @@ exports[`IngestionConsumer error handling should handle explicitly non retriable
"dlq_offset": "0",
"dlq_partition": "1",
"dlq_reason": "test",
- "dlq_step": "prefetchHogFunctionsStep",
+ "dlq_step": "processGroupsStepWrapper",
"dlq_timestamp": "2025-01-01T00:00:00.000Z",
"dlq_topic": "test",
"event": "$pageview",
diff --git a/nodejs/src/ingestion/common/subpipelines/helpers.ts b/nodejs/src/ingestion/common/subpipelines/helpers.ts
index 1b656c2b6107..77c65dfad84d 100644
--- a/nodejs/src/ingestion/common/subpipelines/helpers.ts
+++ b/nodejs/src/ingestion/common/subpipelines/helpers.ts
@@ -20,9 +20,9 @@ export function addTeamToContext<T extends { team: Team }, C>(
/**
* Group key for partitioning events within a batch by `(token, distinct_id)`.
- * Used by `groupBy` to ensure events for the same distinct id are processed
- * sequentially (preserves person/event ordering) while different distinct ids
- * run concurrently.
+ * Used by `concurrentlyPerGroup` to ensure events for the same distinct id are
+ * processed sequentially (preserves person/event ordering) while different
+ * distinct ids run concurrently.
*/
export function getTokenAndDistinctId(input: {
headers: EventHeaders
diff --git a/nodejs/src/ingestion/framework/TODO.md b/nodejs/src/ingestion/framework/TODO.md
index f8536c93dba8..dddff9a1651c 100644
--- a/nodejs/src/ingestion/framework/TODO.md
+++ b/nodejs/src/ingestion/framework/TODO.md
@@ -6,7 +6,7 @@
- ~~Feed refactor~~ — feed() only accepts OkResultWithContext
- ~~as-any casts in test feed() calls~~ — removed, use createMockPipeline instead
- ~~Doc comments for R parameter~~ — added to PipelineResult, Pipeline, ProcessingStep, BatchProcessingStep
-- ~~Living docs updated~~ — 01-introduction and 07-result-handling reflect named outputs
+- ~~Living docs updated~~ — chapters reflect current builder API (`concurrentlyPerGroup`, per-step `{ retry }`, `maxConcurrency`, redirect `awaitAck`/`preserveKey`) plus new chapters for batching, consuming pipelines, and TopHog metrics
- ~~Dead config cleanup~~ — removed overflowTopic from subpipeline configs, PERSON_MERGE_ASYNC_TOPIC from options
## Remaining (low priority)
diff --git a/nodejs/src/ingestion/framework/batch-retry.test.ts b/nodejs/src/ingestion/framework/batch-retry.test.ts
deleted file mode 100644
index 773ddab1af93..000000000000
--- a/nodejs/src/ingestion/framework/batch-retry.test.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-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
-jest.mock('~/common/utils/logger', () => ({
- logger: {
- debug: jest.fn(),
- info: jest.fn(),
- warn: jest.fn(),
- error: jest.fn(),
- },
-}))
-
-jest.mock('~/common/utils/posthog', () => ({
- captureException: jest.fn(),
-}))
-
-class RetriableError extends Error {
- isRetriable = true
-}
-
-class NonRetriableError extends Error {
- isRetriable = false
-}
-
-// Helper to create a batch of test inputs
-function createTestBatch<T>(values: T[]) {
- return values.map((value) => createOkContext(value, {}))
-}
-
-describe('withBatchRetry', () => {
- beforeEach(() => {
- jest.useFakeTimers()
- pipelineRetryAttemptsHistogram.reset()
- })
-
- afterEach(() => {
- jest.useRealTimers()
- })
-
- it('processes batch successfully without retries', async () => {
- const step: BatchProcessingStep<number, string> = (values) => {
- return Promise.resolve(values.map((v) => ok(String(v * 2))))
- }
-
- const pipeline = newBatchPipelineBuilder<number>().pipeBatchWithRetry(step).gather().build()
-
- const batch = createTestBatch([1, 2, 3])
- pipeline.feed(batch)
-
- const results = await pipeline.next()
-
- expect(results).toHaveLength(3)
- expect(results!.map((r) => (isOkResult(r.result) ? r.result.value : null))).toEqual(['2', '4', '6'])
- })
-
- it('retries on retriable errors', 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 })
- .gather()
- .build()
-
- const batch = createTestBatch([1])
- pipeline.feed(batch)
-
- const resultPromise = pipeline.next()
- await jest.advanceTimersByTimeAsync(300) // 100ms + 200ms for two retries
- const results = await resultPromise
-
- expect(attempts).toBe(3)
- expect(results).toHaveLength(1)
- expect(isOkResult(results![0].result)).toBe(true)
- })
-
- it('converts non-retriable errors to DLQ results', async () => {
- const step: BatchProcessingStep<number, string> = (_values) => {
- throw new NonRetriableError('Validation failed')
- }
-
- const pipeline = newBatchPipelineBuilder<number>()
- .pipeBatchWithRetry(step, { tries: 3, sleepMs: 100 })
- .gather()
- .build()
-
- const batch = createTestBatch([1, 2])
- pipeline.feed(batch)
-
- const results = await pipeline.next()
-
- // All inputs should be DLQ'd
- expect(results).toHaveLength(2)
- expect(isDlqResult(results![0].result)).toBe(true)
- expect(isDlqResult(results![1].result)).toBe(true)
- })
-
- it('rethrows after exhausting retries', async () => {
- // Use real timers for this test to avoid fake timer issues with promise rejections
- jest.useRealTimers()
-
- const step: BatchProcessingStep<number, string> = (_values) => {
- throw new RetriableError('Always fails')
- }
-
- const pipeline = newBatchPipelineBuilder<number>()
- .pipeBatchWithRetry(step, { tries: 2, sleepMs: 1 }) // Use tiny sleep for fast test
- .gather()
- .build()
-
- const batch = createTestBatch([1])
- pipeline.feed(batch)
-
- await expect(pipeline.next()).rejects.toThrow('Always fails')
- })
-
- it('preserves non-OK results from previous pipeline', async () => {
- // Create a pipeline where some inputs are already failed
- const failFirst: BatchProcessingStep<number, number> = (values) => {
- return Promise.resolve(values.map((v, i) => (i === 0 ? drop('test') : ok(v))))
- }
-
- const doubleStep: BatchProcessingStep<number, string> = (values) => {
- return Promise.resolve(values.map((v) => ok(String(v * 2))))
- }
-
- const pipeline = newBatchPipelineBuilder<number>()
- .pipeBatch(failFirst)
- .pipeBatchWithRetry(doubleStep)
- .gather()
- .build()
-
- const batch = createTestBatch([1, 2, 3])
- pipeline.feed(batch)
-
- const results = await pipeline.next()
-
- expect(results).toHaveLength(3)
- // First result should still be dropped
- expect(isDropResult(results![0].result)).toBe(true)
- // Other results should be processed
- expect(isOkResult(results![1].result) && results![1].result.value).toBe('4')
- expect(isOkResult(results![2].result) && results![2].result.value).toBe('6')
- })
-
- // Declare steps outside it.each to preserve inferred names from variable assignment
- const myNamedStep: BatchProcessingStep<number, string> = function myNamedStep(values) {
- return Promise.resolve(values.map((v) => ok(String(v))))
- }
- const myArrowStep: BatchProcessingStep<number, string> = (values) => {
- return Promise.resolve(values.map((v) => ok(String(v))))
- }
-
- it.each([
- { description: 'named function expression', step: myNamedStep, expectedName: 'myNamedStep' },
- { description: 'arrow function assigned to variable', step: myArrowStep, expectedName: 'myArrowStep' },
- ])('preserves step name for $description', ({ step, expectedName }) => {
- 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/framework/builders/batch-pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts
index 3b58dbcb6c9e..412d7a05ba56 100644
--- a/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts
+++ b/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts
@@ -5,7 +5,6 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { BaseBatchPipeline, BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'
import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'
-import { BatchRetryOptions, withBatchRetry } from '~/ingestion/framework/batch-retry'
import { BufferingBatchPipeline } from '~/ingestion/framework/buffering-batch-pipeline'
import { ConcurrentBatchProcessingPipeline } from '~/ingestion/framework/concurrent-batch-pipeline'
import {
@@ -17,6 +16,7 @@ import { GatheringBatchPipeline } from '~/ingestion/framework/gathering-batch-pi
import { IngestionWarningHandlingBatchPipeline } from '~/ingestion/framework/ingestion-warning-handling-batch-pipeline'
import { Pipeline } from '~/ingestion/framework/pipeline.interface'
import { PipelineConfig, ResultHandlingPipeline } from '~/ingestion/framework/result-handling-pipeline'
+import { RetryOptions, withBatchRetry } from '~/ingestion/framework/retry'
import { SequentialBatchPipeline } from '~/ingestion/framework/sequential-batch-pipeline'
import { SideEffectHandlingPipeline } from '~/ingestion/framework/side-effect-handling-pipeline'
@@ -31,62 +31,38 @@ export interface TeamIdContext {
}
/**
- * Builder for configuring how items within a group are processed.
+ * Configures how items within a group are processed. Groups produced by
+ * `concurrentlyPerGroup` run concurrently; this builder's `sequentially` method
+ * defines how the items within a single group are processed.
*/
export class GroupProcessingBuilder<
TInput,
TOutput,
CInput = Record<string, never>,
COutput = CInput,
- TKey = string,
R extends string = never,
> {
+ // Holds a completion function instead of the grouping function and previous
+ // pipeline directly: a groupingFn field would be contravariant in TOutput,
+ // making BatchPipelineBuilder invariant in TOutput and breaking covariant
+ // subpipeline callbacks (e.g. in newBatchingPipeline). In this closure's
+ // signature TOutput only appears in variance-neutral positions.
constructor(
- private previousPipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>,
- private groupingFn: GroupingFunction<TOutput, TKey>,
- private maxConcurrency?: number
+ private readonly buildGroupedPipeline: <U, R2 extends string>(
+ processor: Pipeline<TOutput, U, COutput, R2>
+ ) => BatchPipeline<TInput, U, CInput, COutput, R | R2>
) {}
/**
- * Process items within each group sequentially through the provided pipeline.
+ * Process the items within each group sequentially through the provided
+ * pipeline: one item at a time, in input order. Groups still run
+ * concurrently with respect to each other.
*/
sequentially<U, R2 extends string = never>(
callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>
): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()
- return new BatchPipelineBuilder(
- new ConcurrentlyGroupingBatchPipeline(
- this.groupingFn,
- processor,
- this.previousPipeline,
- this.maxConcurrency
- )
- )
- }
-}
-
-/**
- * Builder for grouped batch pipelines that allows configuring how groups are processed.
- */
-export class GroupingBatchPipelineBuilder<TInput, TOutput, CInput, COutput, TKey, R extends string = never> {
- constructor(
- private previousPipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>,
- private groupingFn: GroupingFunction<TOutput, TKey>
- ) {}
-
- /**
- * Process groups concurrently. Returns a builder to configure how items within each group are processed.
- * Results are returned unordered as each group completes.
- *
- * @param options.maxConcurrency - Cap on how many groups process at once. Omitted means unbounded.
- */
- concurrently<U, ROut extends string = never>(
- callback: (
- builder: GroupProcessingBuilder<TInput, TOutput, CInput, COutput, TKey, R>
- ) => BatchPipelineBuilder<TInput, U, CInput, COutput, ROut>,
- options?: { maxConcurrency?: number }
- ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | ROut> {
- return callback(new GroupProcessingBuilder(this.previousPipeline, this.groupingFn, options?.maxConcurrency))
+ return new BatchPipelineBuilder(this.buildGroupedPipeline(processor))
}
}
@@ -94,23 +70,11 @@ export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R e
constructor(protected pipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>) {}
pipeBatch<U, R2 extends string = never>(
- step: BatchProcessingStep<TOutput, U, R2>
- ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
- return new BatchPipelineBuilder(new BaseBatchPipeline(step, this.pipeline))
- }
-
- /**
- * Add a batch processing step with automatic retry logic.
- *
- * When the step throws a retriable error (error.isRetriable === true),
- * it will be retried with exponential backoff. Non-retriable errors
- * are converted to DLQ results for all inputs in the batch.
- */
- pipeBatchWithRetry<U, R2 extends string = never>(
step: BatchProcessingStep<TOutput, U, R2>,
- options?: BatchRetryOptions
+ options?: { retry?: RetryOptions }
): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
- return this.pipeBatch(withBatchRetry(step, options))
+ const wrappedStep = options?.retry ? withBatchRetry(step, options.retry) : step
+ return new BatchPipelineBuilder(new BaseBatchPipeline(wrappedStep, this.pipeline))
}
/**
@@ -128,15 +92,6 @@ export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R e
)
}
- pipeConcurrently<U, R2 extends string = never>(
- processor: Pipeline<TOutput, U, COutput, R2>,
- options?: { maxConcurrency?: number }
- ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
- return new BatchPipelineBuilder(
- new ConcurrentBatchProcessingPipeline(processor, this.pipeline, options?.maxConcurrency)
- )
- }
-
sequentially<U, R2 extends string = never>(
callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>
): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {
@@ -183,10 +138,29 @@ export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R e
)
}
- groupBy<TKey>(
- groupingFn: GroupingFunction<TOutput, TKey>
- ): GroupingBatchPipelineBuilder<TInput, TOutput, CInput, COutput, TKey, R> {
- return new GroupingBatchPipelineBuilder(this.pipeline, groupingFn)
+ /**
+ * Group items by key and process the groups concurrently, optionally capped
+ * by `maxConcurrency`. Results are returned unordered as each group completes.
+ *
+ * The callback receives a group builder whose only method, `sequentially`,
+ * configures how items WITHIN a group are processed. Making that step explicit
+ * keeps within-group ordering visible at the call site.
+ *
+ * @param options.maxConcurrency - Cap on how many groups process at once. Omitted means unbounded.
+ */
+ concurrentlyPerGroup<TKey, U, ROut extends string = never>(
+ groupingFn: GroupingFunction<TOutput, TKey>,
+ callback: (
+ group: GroupProcessingBuilder<TInput, TOutput, CInput, COutput, R>
+ ) => BatchPipelineBuilder<TInput, U, CInput, COutput, ROut>,
+ options?: { maxConcurrency?: number }
+ ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | ROut> {
+ return callback(
+ new GroupProcessingBuilder(
+ <U2, R2 extends string>(processor: Pipeline<TOutput, U2, COutput, R2>) =>
+ new ConcurrentlyGroupingBatchPipeline(groupingFn, processor, this.pipeline, options?.maxConcurrency)
+ )
+ )
}
handleSideEffects(
diff --git a/nodejs/src/ingestion/framework/builders/index.ts b/nodejs/src/ingestion/framework/builders/index.ts
index cfd02403849f..b20c4101c8f7 100644
--- a/nodejs/src/ingestion/framework/builders/index.ts
+++ b/nodejs/src/ingestion/framework/builders/index.ts
@@ -1,10 +1,9 @@
export {
BatchPipelineBuilder,
- GroupingBatchPipelineBuilder,
GroupProcessingBuilder,
MessageAwareBatchPipelineBuilder,
TeamAwareBatchPipelineBuilder,
} from './batch-pipeline-builders'
-export type { BatchRetryOptions } from '~/ingestion/framework/batch-retry'
+export type { RetryOptions } from '~/ingestion/framework/retry'
export { BranchingPipelineBuilder, PipelineBuilder, StartPipelineBuilder } from './pipeline-builders'
export { newBatchPipelineBuilder, newBatchingPipeline, newPipelineBuilder } from './helpers'
diff --git a/nodejs/src/ingestion/framework/builders/pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
index 129fd6b84371..c312094fa585 100644
--- a/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
+++ b/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
@@ -1,21 +1,17 @@
import { BranchDecisionFn, BranchingPipeline } from '~/ingestion/framework/branching-pipeline'
import { Pipeline } from '~/ingestion/framework/pipeline.interface'
-import { RetryingPipeline, RetryingPipelineOptions } from '~/ingestion/framework/retrying-pipeline'
+import { RetryOptions, withStepRetry } from '~/ingestion/framework/retry'
import { StartPipeline } from '~/ingestion/framework/start-pipeline'
import { StepPipeline } from '~/ingestion/framework/step-pipeline'
import { ProcessingStep } from '~/ingestion/framework/steps'
export class StartPipelineBuilder<T, C> {
- pipe<U, R extends string = never>(step: ProcessingStep<T, U, R>): PipelineBuilder<T, U, C, R> {
- return new PipelineBuilder(new StepPipeline(step, new StartPipeline<T, C>()))
- }
-
- retry<U, R extends string = never>(
- callback: (builder: StartPipelineBuilder<T, C>) => PipelineBuilder<T, U, C, R>,
- options?: RetryingPipelineOptions
+ pipe<U, R extends string = never>(
+ step: ProcessingStep<T, U, R>,
+ options?: { retry?: RetryOptions }
): PipelineBuilder<T, U, C, R> {
- const innerPipeline = callback(new StartPipelineBuilder<T, C>()).build()
- return new PipelineBuilder(new RetryingPipeline(innerPipeline, options))
+ const wrappedStep = options?.retry ? withStepRetry(step, options.retry) : step
+ return new PipelineBuilder(new StepPipeline(wrappedStep, new StartPipeline<T, C>()))
}
branching<TBranch extends string, U, RBranch extends string = never>(
@@ -36,8 +32,12 @@ export class StartPipelineBuilder<T, C> {
export class PipelineBuilder<TInput, TOutput, C, R extends string = never> {
constructor(protected pipeline: Pipeline<TInput, TOutput, C, R>) {}
- pipe<U, R2 extends string = never>(step: ProcessingStep<TOutput, U, R2>): PipelineBuilder<TInput, U, C, R | R2> {
- return new PipelineBuilder(new StepPipeline(step, this.pipeline))
+ pipe<U, R2 extends string = never>(
+ step: ProcessingStep<TOutput, U, R2>,
+ options?: { retry?: RetryOptions }
+ ): PipelineBuilder<TInput, U, C, R | R2> {
+ const wrappedStep = options?.retry ? withStepRetry(step, options.retry) : step
+ return new PipelineBuilder(new StepPipeline(wrappedStep, this.pipeline))
}
branching<TBranch extends string, U, RBranch extends string = never>(
diff --git a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts
index 24137e03a750..56c95c59654b 100644
--- a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts
@@ -512,14 +512,15 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {
})
})
- describe('groupBy builder DSL', () => {
- it('should work with the groupBy builder method', async () => {
+ describe('concurrentlyPerGroup builder DSL', () => {
+ it('should work with the concurrentlyPerGroup builder method', async () => {
const pipeline = createNewBatchPipeline<{ value: string; group: string }>()
- .groupBy((input) => input.group)
- .concurrently((group) =>
- group.sequentially((builder) =>
- builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
- )
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group.sequentially((builder) =>
+ builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
+ )
)
.build()
@@ -543,11 +544,12 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {
it('should chain with gather to collect all results', async () => {
const pipeline = createNewBatchPipeline<{ value: string; group: string }>()
- .groupBy((input) => input.group)
- .concurrently((group) =>
- group.sequentially((builder) =>
- builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
- )
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group.sequentially((builder) =>
+ builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
+ )
)
.gather()
.build()
@@ -753,16 +755,17 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {
it('should handle multiple items per group with sequential processing', async () => {
const processingOrder: string[] = []
const pipeline = createNewBatchPipeline<{ value: string; group: string }>()
- .groupBy((input) => input.group)
- .concurrently((group) =>
- group.sequentially((builder) =>
- builder.pipe(async (input) => {
- processingOrder.push(`start-${input.value}`)
- await new Promise((resolve) => setTimeout(resolve, 10))
- processingOrder.push(`end-${input.value}`)
- return ok({ ...input, processed: true })
- })
- )
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group.sequentially((builder) =>
+ builder.pipe(async (input) => {
+ processingOrder.push(`start-${input.value}`)
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ processingOrder.push(`end-${input.value}`)
+ return ok({ ...input, processed: true })
+ })
+ )
)
.gather()
.build()
@@ -801,11 +804,12 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {
it('should handle empty batches gracefully', async () => {
const pipeline = createNewBatchPipeline<{ value: string; group: string }>()
- .groupBy((input) => input.group)
- .concurrently((group) =>
- group.sequentially((builder) =>
- builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
- )
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group.sequentially((builder) =>
+ builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
+ )
)
.build()
@@ -817,11 +821,12 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {
it('should handle single item groups', async () => {
const pipeline = createNewBatchPipeline<{ value: string; group: string }>()
- .groupBy((input) => input.group)
- .concurrently((group) =>
- group.sequentially((builder) =>
- builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
- )
+ .concurrentlyPerGroup(
+ (input) => input.group,
+ (group) =>
+ group.sequentially((builder) =>
+ builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
+ )
)
.gather()
.build()
diff --git a/nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts b/nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts
index 9572d78b4e0a..cb6a1707767f 100644
--- a/nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts
+++ b/nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts
@@ -2,10 +2,11 @@
* # Chapter 3: Concurrent Processing
*
* The `concurrently()` method processes items in parallel, improving
- * throughput for I/O-bound operations. Concurrency is unbounded - all
- * items in a batch start processing at the same time. Although items
- * are processed concurrently, results are returned in the original
- * input order, one item at a time as they complete.
+ * throughput for I/O-bound operations. Concurrency is unbounded by default -
+ * every item in a batch starts processing at the same time. Pass
+ * `{ maxConcurrency }` to cap how many items run at once. Although items are
+ * processed concurrently, results are returned in the original input order,
+ * one item at a time as they complete.
*
* ## When to Use Concurrent Processing
*
@@ -17,7 +18,19 @@
*
* - **Throughput**: Higher with concurrency
* - **Order**: Results maintain input order (but returned one by one)
- * - **Resources**: More concurrent connections/requests (unbounded)
+ * - **Resources**: More concurrent connections/requests (unbounded by
+ * default; bound with `maxConcurrency`)
+ *
+ * ## Bounding Concurrency
+ *
+ * ```
+ * .concurrently(callback, { maxConcurrency: 2 })
+ * ```
+ *
+ * Unbounded concurrency is simplest but can overwhelm a downstream
+ * dependency (a database, an external API with a connection limit). A cap
+ * keeps at most N items in flight, starting the next item only as a slot
+ * frees up. Emission order stays FIFO regardless of the cap.
*/
import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'
import { createOkContext } from '~/ingestion/framework/helpers'
@@ -134,4 +147,47 @@ describe('Concurrent Processing', () => {
// But results maintain input order (1, 2, 3 -> 10, 20, 30)
expect(allValues).toEqual([10, 20, 30])
})
+
+ /**
+ * `{ maxConcurrency }` caps how many items process at once. With 5 items,
+ * a delay of 100ms each, and a cap of 2, work proceeds in waves of 2, 2, 1:
+ * the third item can only start once one of the first two frees its slot.
+ *
+ * ```
+ * Time ──────────────────────────────────────────►
+ * cap=2 [1]──►100ms [3]──►100ms [5]──►100ms
+ * [2]──►100ms [4]──►100ms
+ * ```
+ *
+ * The peak number of items running simultaneously never exceeds the cap.
+ */
+ it('maxConcurrency caps how many items run at once', async () => {
+ let running = 0
+ let peak = 0
+
+ function createTrackingStep(): ProcessingStep<number, number> {
+ return async function trackingStep(n) {
+ running++
+ peak = Math.max(peak, running)
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ running--
+ return ok(n * 2)
+ }
+ }
+
+ const pipeline = newBatchPipelineBuilder<number>()
+ .concurrently((builder) => builder.pipe(createTrackingStep()), { maxConcurrency: 2 })
+ .build()
+
+ const batch = [1, 2, 3, 4, 5].map((n) => createOkContext(n, {}))
+ pipeline.feed(batch)
+
+ // Three waves of 100ms (2 + 2 + 1 items)
+ const allValues = await consumeAll(pipeline, 300)
+
+ // Reached the cap (proving parallelism) but never exceeded it
+ expect(peak).toBe(2)
+ // Results still stream out in input order
+ expect(allValues).toEqual([2, 4, 6, 8, 10])
+ })
})
diff --git a/nodejs/src/ingestion/framework/docs/05-grouping.test.ts b/nodejs/src/ingestion/framework/docs/05-grouping.test.ts
index 51b2517e489d..f118da9a1932 100644
--- a/nodejs/src/ingestion/framework/docs/05-grouping.test.ts
+++ b/nodejs/src/ingestion/framework/docs/05-grouping.test.ts
@@ -1,8 +1,9 @@
/**
* # Chapter 5: Grouped Processing
*
- * The `groupBy()` method partitions items by a key. It must be followed by
- * `concurrently()`, which processes each group as a separate stream.
+ * The `concurrentlyPerGroup()` method partitions items by a key and processes
+ * each group as a separate stream. Groups run concurrently; items within a
+ * group run sequentially through the provided pipeline.
*
* ## Ordering Guarantees
*
@@ -12,19 +13,28 @@
*
* What grouping DOES guarantee:
* - Items within the same group maintain their relative input order
- * - Using `sequentially()` inside the group ensures items are processed one
- * at a time, preserving order within that group
+ * - Items within a group are processed one at a time, preserving order
+ * within that group
*
* ## How It Works
*
* ```
- * .groupBy(keyFn)
- * .concurrently((groupBuilder) => groupBuilder.sequentially(...))
+ * .concurrentlyPerGroup(keyFn, (group) => group.sequentially((b) => b.pipe(...)))
* ```
*
- * - `groupBy()` partitions items by key
- * - `concurrently()` processes groups in parallel (groups return as they complete)
- * - `sequentially()` inside ensures within-group order is preserved
+ * - `keyFn` partitions items by key
+ * - Groups are processed in parallel (each group returns as it completes)
+ * - The callback receives a group builder whose only method is `sequentially`.
+ * Spelling out `sequentially` makes within-group ordering visible at the call
+ * site: items within a group flow through that pipeline one at a time, in
+ * input order.
+ *
+ * Pass `{ maxConcurrency }` to cap how many groups process at once (the cap
+ * is on groups, not items):
+ *
+ * ```
+ * .concurrentlyPerGroup(keyFn, callback, { maxConcurrency: 4 })
+ * ```
*
* ## Real-World Use Cases
*
@@ -32,7 +42,7 @@
* - Team-scoped processing: Teams can be processed in parallel
* - User event ordering: Events for the same user maintain order
*/
-import { GroupProcessingBuilder, newBatchPipelineBuilder } from '~/ingestion/framework/builders'
+import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'
import { createOkContext } from '~/ingestion/framework/helpers'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
@@ -53,8 +63,8 @@ describe('Grouped Processing', () => {
jest.useRealTimers()
})
/**
- * The `groupBy()` method partitions items by a key function. Items with
- * the same key are grouped together for ordered processing.
+ * The `concurrentlyPerGroup()` method partitions items by a key function.
+ * Items with the same key are grouped together for ordered processing.
*
* Processing flow for the example below:
*
@@ -62,11 +72,11 @@ describe('Grouped Processing', () => {
* Input batch:
* [alice:1, bob:2, alice:3, bob:4]
*
- * After groupBy(userId):
+ * After grouping by userId:
* Group "alice": [1, 3]
* Group "bob": [2, 4]
*
- * concurrently() processes groups in parallel:
+ * Groups are processed in parallel:
* ┌─────────────────────────────────────┐
* │ Time ──────────────────────────► │
* │ │
@@ -80,7 +90,7 @@ describe('Grouped Processing', () => {
* Groups alice and bob process concurrently (in parallel).
* ```
*/
- it('groupBy() partitions items by a key function', async () => {
+ it('concurrentlyPerGroup() partitions items by a key function', async () => {
const groupsProcessed = new Map<string, number[]>()
function createProcessEventStep(): ProcessingStep<Event, Event> {
@@ -93,13 +103,11 @@ describe('Grouped Processing', () => {
}
}
- function createGroupPipeline(groupBuilder: GroupProcessingBuilder<Event, Event>) {
- return groupBuilder.sequentially((b) => b.pipe(createProcessEventStep()))
- }
-
const pipeline = newBatchPipelineBuilder<Event>()
- .groupBy((event) => event.userId)
- .concurrently(createGroupPipeline)
+ .concurrentlyPerGroup(
+ (event) => event.userId,
+ (group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createProcessEventStep()))
+ )
.build()
const events: Event[] = [
@@ -132,13 +140,11 @@ describe('Grouped Processing', () => {
}
}
- function createGroupPipeline(groupBuilder: GroupProcessingBuilder<Event, Event>) {
- return groupBuilder.sequentially((b) => b.pipe(createProcessEventStep()))
- }
-
const pipeline = newBatchPipelineBuilder<Event>()
- .groupBy((event) => event.userId)
- .concurrently(createGroupPipeline)
+ .concurrentlyPerGroup(
+ (event) => event.userId,
+ (group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createProcessEventStep()))
+ )
.build()
const events: Event[] = [
@@ -183,13 +189,11 @@ describe('Grouped Processing', () => {
}
}
- function createGroupPipeline(groupBuilder: GroupProcessingBuilder<Event, Event>) {
- return groupBuilder.sequentially((b) => b.pipe(createVariableDelayStep()))
- }
-
const pipeline = newBatchPipelineBuilder<Event>()
- .groupBy((event) => event.userId)
- .concurrently(createGroupPipeline)
+ .concurrentlyPerGroup(
+ (event) => event.userId,
+ (group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createVariableDelayStep()))
+ )
.build()
const events: Event[] = [
@@ -243,7 +247,7 @@ describe('Grouped Processing', () => {
* Input events:
* [token-A/user-1/login, token-B/user-1/signup, token-A/user-2/pageview, token-A/user-1/purchase]
*
- * After groupBy(token + distinct_id):
+ * After grouping by token + distinct_id:
* Group "token-A:user-1": [login, purchase] <- same user in same project
* Group "token-B:user-1": [signup] <- different project (different group)
* Group "token-A:user-2": [pageview] <- different user (different group)
@@ -273,13 +277,11 @@ describe('Grouped Processing', () => {
}
}
- function createGroupPipeline(groupBuilder: GroupProcessingBuilder<IngestionEvent, IngestionEvent>) {
- return groupBuilder.sequentially((b) => b.pipe(createProcessEventStep()))
- }
-
const pipeline = newBatchPipelineBuilder<IngestionEvent>()
- .groupBy((event) => `${event.token}:${event.distinctId}`)
- .concurrently(createGroupPipeline)
+ .concurrentlyPerGroup(
+ (event) => `${event.token}:${event.distinctId}`,
+ (group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createProcessEventStep()))
+ )
.build()
const events: IngestionEvent[] = [
diff --git a/nodejs/src/ingestion/framework/docs/06-gathering.test.ts b/nodejs/src/ingestion/framework/docs/06-gathering.test.ts
index bfd28ed52c01..2b6ecd6353a6 100644
--- a/nodejs/src/ingestion/framework/docs/06-gathering.test.ts
+++ b/nodejs/src/ingestion/framework/docs/06-gathering.test.ts
@@ -8,17 +8,17 @@
* ## When to Use gather()
*
* - After `concurrently()`: collect all concurrent results into one batch
- * - After `groupBy().concurrently()`: collect all group results into one batch
+ * - After `concurrentlyPerGroup()`: collect all group results into one batch
*
* ## How gather() Works
*
* Without gather(), pipelines stream results as they become available:
* - `concurrently()` returns items one at a time (in input order)
- * - `groupBy().concurrently()` returns groups one at a time as each completes
+ * - `concurrentlyPerGroup()` returns groups one at a time as each completes
*
* With gather(), all results are collected and returned in a single batch.
*/
-import { GroupProcessingBuilder, newBatchPipelineBuilder } from '~/ingestion/framework/builders'
+import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'
import { createOkContext } from '~/ingestion/framework/helpers'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
@@ -88,13 +88,13 @@ describe('Gathering Results', () => {
})
/**
- * Without gather(), groupBy().concurrently() returns groups one at a time
+ * Without gather(), concurrentlyPerGroup() returns groups one at a time
* as each group completes. With gather(), all groups are collected into
* a single batch.
*
* Within each group, events are always processed sequentially (order preserved).
*/
- it('gather() after groupBy().concurrently() collects groups into one batch', async () => {
+ it('gather() after concurrentlyPerGroup() collects groups into one batch', async () => {
const delays: Record<string, number> = {
alice: 30,
bob: 10,
@@ -107,10 +107,6 @@ describe('Gathering Results', () => {
}
}
- function createGroupPipeline(groupBuilder: GroupProcessingBuilder<Event, Event>) {
- return groupBuilder.sequentially((b) => b.pipe(createVariableDelayStep()))
- }
-
// Input order: alice:1, bob:2, alice:3, bob:4
const events: Event[] = [
{ userId: 'alice', eventId: 1 },
@@ -121,8 +117,10 @@ describe('Gathering Results', () => {
// Without gather: groups stream one at a time in completion order
const streamingPipeline = newBatchPipelineBuilder<Event>()
- .groupBy((event) => event.userId)
- .concurrently(createGroupPipeline)
+ .concurrentlyPerGroup(
+ (event) => event.userId,
+ (group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createVariableDelayStep()))
+ )
.build()
streamingPipeline.feed(events.map((e) => createOkContext(e, {})))
@@ -146,8 +144,10 @@ describe('Gathering Results', () => {
// With gather: all groups collected into one batch
const gatheringPipeline = newBatchPipelineBuilder<Event>()
- .groupBy((event) => event.userId)
- .concurrently(createGroupPipeline)
+ .concurrentlyPerGroup(
+ (event) => event.userId,
+ (group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createVariableDelayStep()))
+ )
.gather()
.build()
diff --git a/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts b/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts
index 271bd8fd3ac2..e051aa9e0ad1 100644
--- a/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts
+++ b/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts
@@ -12,6 +12,20 @@
* - **DROP**: Log and discard (no Kafka message)
* - **REDIRECT**: Send to a named output (e.g. overflow)
*
+ * ## Redirect Options
+ *
+ * `redirect(reason, output, preserveKey?, awaitAck?)` takes two optional flags,
+ * both defaulting to `true`:
+ *
+ * - **`preserveKey`** (default `true`): keep the original Kafka message key on
+ * the redirected message so partitioning/ordering is retained. Pass `false`
+ * to drop the key (the message is produced with a `null` key, letting the
+ * broker assign a partition).
+ * - **`awaitAck`** (default `true`): wait for the broker to acknowledge the
+ * redirected produce before the result is finalized. Pass `false` to schedule
+ * the produce as a fire-and-forget side effect instead - the pipeline does not
+ * block on the ack, trading delivery certainty for lower latency.
+ *
* ## Accessing handleResults()
*
* `handleResults()` is available through the `messageAware()` builder method.
@@ -196,7 +210,8 @@ describe('Result Handling', () => {
* REDIRECT results send items to a named output for alternative processing.
* Each redirect targets a specific output (e.g. overflow, high-priority)
* which is resolved to a Kafka topic and producer at runtime. The original
- * message key can optionally be preserved or discarded.
+ * message key is preserved by default (`preserveKey` defaults to `true`);
+ * pass `false` to discard it and let the broker assign a partition.
*/
it('REDIRECT sends items to a named output with optional key preservation', async () => {
const promiseScheduler = new PromiseScheduler()
@@ -286,4 +301,103 @@ describe('Result Handling', () => {
const discardedKeyMessage = mockOutputs.produce.mock.calls[1][1]
expect(discardedKeyMessage.headers!['redirect-timestamp']).toBeDefined()
})
+
+ /**
+ * `awaitAck` (default `true`) makes result handling wait for the broker to
+ * acknowledge the redirected produce before `next()` resolves. This is the
+ * safe default: the item is not considered handled until it is durably
+ * accepted downstream.
+ *
+ * Here the mocked produce never acknowledges, so `next()` stays pending
+ * until the ack resolves.
+ */
+ it('REDIRECT with awaitAck=true blocks on the produce ack (default)', async () => {
+ const promiseScheduler = new PromiseScheduler()
+ const OVERFLOW = 'overflow' as const
+
+ const mockOutputs = createMockIngestionOutputs<
+ typeof DLQ_OUTPUT | typeof OVERFLOW | typeof INGESTION_WARNINGS_OUTPUT
+ >()
+
+ // Produce that only acknowledges when we resolve it by hand
+ let ackResolve: () => void
+ const ack = new Promise<void>((resolve) => {
+ ackResolve = resolve
+ })
+ mockOutputs.produce.mockReturnValue(ack)
+
+ function createRoutingStep(): BatchProcessingStep<{ v: string }, { v: string }, 'overflow'> {
+ return function routingStep(items) {
+ // awaitAck defaults to true (fourth arg omitted)
+ return Promise.resolve(items.map(() => redirect('Overflow', OVERFLOW, true)))
+ }
+ }
+
+ // await: true so the redirect side effect (the produce) is awaited before next() resolves
+ const pipeline = newBatchPipelineBuilder<{ v: string }, { message: Message }>()
+ .pipeBatch(createRoutingStep())
+ .messageAware((builder) => builder)
+ .handleResults({ outputs: mockOutputs, promiseScheduler })
+ .handleSideEffects(promiseScheduler, { await: true })
+ .build()
+
+ pipeline.feed([createOkContext({ v: 'x' }, { message: createTestMessage() })])
+
+ let resolved = false
+ const nextPromise = pipeline.next().then((r) => {
+ resolved = true
+ return r
+ })
+
+ // Flush pending microtasks/macrotasks; next() is still blocked on the ack
+ await new Promise((resolve) => setImmediate(resolve))
+ expect(resolved).toBe(false)
+
+ // Once the broker acks, next() resolves
+ ackResolve!()
+ const results = await nextPromise
+ expect(resolved).toBe(true)
+ expect(isRedirectResult(results![0].result)).toBe(true)
+ })
+
+ /**
+ * `awaitAck=false` schedules the produce as a fire-and-forget side effect.
+ * Result handling does not wait for the broker ack, so `next()` resolves
+ * even though the produce is still in flight.
+ */
+ it('REDIRECT with awaitAck=false does not block on the produce ack', async () => {
+ const promiseScheduler = new PromiseScheduler()
+ const OVERFLOW = 'overflow' as const
+
+ const mockOutputs = createMockIngestionOutputs<
+ typeof DLQ_OUTPUT | typeof OVERFLOW | typeof INGESTION_WARNINGS_OUTPUT
+ >()
+
+ // Produce that never acknowledges within the test
+ mockOutputs.produce.mockReturnValue(new Promise<void>(() => {}))
+
+ function createRoutingStep(): BatchProcessingStep<{ v: string }, { v: string }, 'overflow'> {
+ return function routingStep(items) {
+ // preserveKey = true, awaitAck = false
+ return Promise.resolve(items.map(() => redirect('Overflow', OVERFLOW, true, false)))
+ }
+ }
+
+ // Even with await: true, the redirect side effect resolves immediately because
+ // awaitAck=false means it never waits on the produce ack.
+ const pipeline = newBatchPipelineBuilder<{ v: string }, { message: Message }>()
+ .pipeBatch(createRoutingStep())
+ .messageAware((builder) => builder)
+ .handleResults({ outputs: mockOutputs, promiseScheduler })
+ .handleSideEffects(promiseScheduler, { await: true })
+ .build()
+
+ pipeline.feed([createOkContext({ v: 'x' }, { message: createTestMessage() })])
+
+ // Resolves without the pending ack (would hang if awaitAck were honored as true)
+ const results = await pipeline.next()
+
+ expect(isRedirectResult(results![0].result)).toBe(true)
+ expect(mockOutputs.produce).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/nodejs/src/ingestion/framework/docs/11-retries.test.ts b/nodejs/src/ingestion/framework/docs/11-retries.test.ts
index 81927d93d2af..f26a57c4206c 100644
--- a/nodejs/src/ingestion/framework/docs/11-retries.test.ts
+++ b/nodejs/src/ingestion/framework/docs/11-retries.test.ts
@@ -1,25 +1,48 @@
/**
* # Chapter 11: Retry Logic
*
- * The `retry()` wrapper provides automatic retry logic for transient failures.
- * This is essential for handling temporary issues like network hiccups,
- * database connection timeouts, or rate limiting.
+ * Retry is a per-step option: pass `{ retry }` to `pipe()` or `pipeBatch()` to
+ * wrap that single step with automatic retry logic. This handles transient
+ * failures like network hiccups, database connection timeouts, or rate limiting.
+ *
+ * ```
+ * .pipe(step, { retry: { tries: 3, sleepMs: 100 } })
+ * .pipeBatch(step, { retry: { tries: 3, sleepMs: 100 } })
+ * ```
*
* ## Key Concepts
*
* - **Retriable errors**: Errors marked with `isRetriable: true` are retried
- * - **Non-retriable errors**: Sent directly to DLQ without retrying
- * - **Exponential backoff**: Delays increase between retries
- * - **Max retries**: After exhausting retries, the error is rethrown
+ * - **Non-retriable errors**: Errors marked with `isRetriable: false` go
+ * directly to DLQ without retrying
+ * - **Unknown errors**: Errors with no `isRetriable` property are retried, then
+ * rethrown once retries are exhausted (crashes the process - appropriate for
+ * unexpected failures)
+ * - **Exponential backoff**: The delay doubles between retries
+ * - **Defaults**: 3 tries, 100ms initial sleep
+ *
+ * `RetryOptions` is `{ name?, tries?, sleepMs? }`. The `name` labels the
+ * `ingestion_pipeline_retry_attempts` metric and defaults to the step name.
+ *
+ * ## Why Retries Wrap a Single Step
+ *
+ * Retry always wraps exactly one step, never a sequence. Retrying a sequence
+ * would re-run steps that already succeeded, which breaks idempotency: if
+ * step A writes to a database and step B (a later step) fails, retrying the
+ * whole block would run step A's write a second time. Keeping retry scoped to
+ * a single step means only the failing operation is repeated. Compose retries
+ * by attaching `{ retry }` to each step that needs it, not by wrapping a
+ * multi-step block.
*
* ## Error Classification
*
- * Errors must have an `isRetriable` property to indicate whether they should
- * be retried. This allows distinguishing between:
+ * Errors carry an `isRetriable` property to indicate whether they should be
+ * retried. This distinguishes:
* - Transient failures (network, timeout) - should retry
* - Permanent failures (validation, permission) - should not retry
*/
-import { newPipelineBuilder } from '~/ingestion/framework/builders'
+import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'
+import { newBatchPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'
import { createOkContext } from '~/ingestion/framework/helpers'
import { isDlqResult, isOkResult, ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
@@ -32,7 +55,7 @@ class NonRetriableError extends Error {
isRetriable = false
}
-describe('Retry Basics', () => {
+describe('Single-Step Retries', () => {
beforeEach(() => {
jest.useFakeTimers()
})
@@ -43,20 +66,17 @@ describe('Retry Basics', () => {
/**
* Retriable errors (those with `isRetriable: true`) are automatically
- * retried up to the configured number of times.
+ * retried up to the configured number of times. The step succeeds once
+ * the transient condition clears.
*/
- it('retriable errors are automatically retried', async () => {
+ it('retriable errors are retried until the step succeeds', async () => {
let attempts = 0
interface Input {
value: string
}
- interface Output {
- value: string
- }
-
- function createFlakyStep(): ProcessingStep<Input, Output> {
+ function createFlakyStep(): ProcessingStep<Input, { value: string }> {
return function flakyStep(input) {
attempts++
if (attempts < 3) {
@@ -67,7 +87,7 @@ describe('Retry Basics', () => {
}
const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createFlakyStep()), { tries: 5, sleepMs: 100 })
+ .pipe(createFlakyStep(), { retry: { tries: 5, sleepMs: 100 } })
.build()
const resultPromise = pipeline.process(createOkContext({ value: 'hello' }, {}))
@@ -81,48 +101,6 @@ describe('Retry Basics', () => {
}
})
- /**
- * When a retry occurs, the entire sub-pipeline is re-executed from the
- * beginning, not just the failing step.
- */
- it('retries run the entire sub-pipeline again', async () => {
- const stepCalls: string[] = []
- let step2Attempts = 0
-
- interface Input {
- value: string
- }
-
- function createStep1(): ProcessingStep<Input, Input> {
- return function step1(input) {
- stepCalls.push('step1')
- return Promise.resolve(ok(input))
- }
- }
-
- function createStep2(): ProcessingStep<Input, Input> {
- return function step2(input) {
- stepCalls.push('step2')
- step2Attempts++
- if (step2Attempts < 3) {
- throw new RetriableError('Step 2 failed')
- }
- return Promise.resolve(ok(input))
- }
- }
-
- const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createStep1()).pipe(createStep2()), { tries: 5, sleepMs: 100 })
- .build()
-
- const resultPromise = pipeline.process(createOkContext({ value: 'data' }, {}))
- await jest.advanceTimersByTimeAsync(300)
- await resultPromise
-
- // Each retry runs both steps: step1, step2 (fail), step1, step2 (fail), step1, step2 (success)
- expect(stepCalls).toEqual(['step1', 'step2', 'step1', 'step2', 'step1', 'step2'])
- })
-
/**
* Non-retriable errors (those with `isRetriable: false`) go directly
* to DLQ without any retry attempts.
@@ -134,11 +112,7 @@ describe('Retry Basics', () => {
data: string
}
- interface Output {
- data: string
- }
-
- function createValidationStep(): ProcessingStep<Input, Output> {
+ function createValidationStep(): ProcessingStep<Input, { data: string }> {
return function validationStep(_input) {
attempts++
throw new NonRetriableError('Validation failed - invalid format')
@@ -146,7 +120,7 @@ describe('Retry Basics', () => {
}
const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createValidationStep()), { tries: 5, sleepMs: 100 })
+ .pipe(createValidationStep(), { retry: { tries: 5, sleepMs: 100 } })
.build()
// No timer advancement needed - non-retriable errors don't wait
@@ -160,61 +134,11 @@ describe('Retry Basics', () => {
})
/**
- * When retries use exponential backoff, the delay between retries
- * increases to avoid overwhelming a struggling service.
- */
- it('retries use exponential backoff', async () => {
- let attempts = 0
-
- interface Input {
- value: string
- }
-
- interface Output {
- value: string
- }
-
- function createSlowlyRecoveringStep(): ProcessingStep<Input, Output> {
- return function slowlyRecoveringStep(input) {
- attempts++
- if (attempts < 4) {
- throw new RetriableError('Still recovering')
- }
- return Promise.resolve(ok({ value: input.value }))
- }
- }
-
- const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createSlowlyRecoveringStep()), { tries: 5, sleepMs: 100 })
- .build()
-
- const resultPromise = pipeline.process(createOkContext({ value: 'data' }, {}))
-
- // First attempt happens immediately
- await jest.advanceTimersByTimeAsync(0)
- expect(attempts).toBe(1)
-
- // After 100ms, second attempt
- await jest.advanceTimersByTimeAsync(100)
- expect(attempts).toBe(2)
-
- // After 200ms more (exponential), third attempt
- await jest.advanceTimersByTimeAsync(200)
- expect(attempts).toBe(3)
-
- // After 400ms more (exponential), fourth attempt succeeds
- await jest.advanceTimersByTimeAsync(400)
- expect(attempts).toBe(4)
-
- await resultPromise
- })
-
- /**
- * After exhausting the maximum number of retries, the error is rethrown.
- * This is a fatal error - the process should report it and crash rather
- * than continue in a broken state.
+ * After exhausting the maximum number of retries, a retriable error is
+ * rethrown. This is a fatal error - the process should report it and crash
+ * rather than continue in a broken state.
*/
- it('after max retries, the error is rethrown and the process should crash', async () => {
+ it('after max retries, the error is rethrown', async () => {
let attempts = 0
let caughtError: Error | null = null
@@ -222,11 +146,7 @@ describe('Retry Basics', () => {
value: string
}
- interface Output {
- value: string
- }
-
- function createAlwaysFailsStep(): ProcessingStep<Input, Output> {
+ function createAlwaysFailsStep(): ProcessingStep<Input, { value: string }> {
return function alwaysFailsStep(_input) {
attempts++
throw new RetriableError(`Attempt ${attempts} failed`)
@@ -234,7 +154,7 @@ describe('Retry Basics', () => {
}
const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createAlwaysFailsStep()), { tries: 3, sleepMs: 100 })
+ .pipe(createAlwaysFailsStep(), { retry: { tries: 3, sleepMs: 100 } })
.build()
const resultPromise = pipeline.process(createOkContext({ value: 'data' }, {})).catch((e) => {
@@ -249,37 +169,36 @@ describe('Retry Basics', () => {
})
/**
- * Errors without an `isRetriable` property are rethrown (not caught).
- * This preserves normal error handling for unexpected errors.
+ * Errors without an `isRetriable` property are retried (in case they are
+ * transient), then rethrown once retries are exhausted - never sent to DLQ.
+ * This preserves normal crash behavior for unexpected errors.
*/
- it('errors without isRetriable flag are rethrown', async () => {
+ it('errors without isRetriable are retried then rethrown', async () => {
+ let attempts = 0
let caughtError: Error | null = null
interface Input {
value: string
}
- interface Output {
- value: string
- }
-
- function createUnexpectedErrorStep(): ProcessingStep<Input, Output> {
+ function createUnexpectedErrorStep(): ProcessingStep<Input, { value: string }> {
return function unexpectedErrorStep(_input) {
+ attempts++
throw new Error('Unexpected internal error')
}
}
const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createUnexpectedErrorStep()), { tries: 3, sleepMs: 100 })
+ .pipe(createUnexpectedErrorStep(), { retry: { tries: 3, sleepMs: 100 } })
.build()
- // Errors without isRetriable are retried but then rethrown (not sent to DLQ)
const resultPromise = pipeline.process(createOkContext({ value: 'data' }, {})).catch((e) => {
caughtError = e
})
await jest.advanceTimersByTimeAsync(300) // 100ms + 200ms for retries
await resultPromise
+ expect(attempts).toBe(3) // Retried, not short-circuited like a non-retriable error
expect(caughtError).not.toBeNull()
expect(caughtError!.message).toBe('Unexpected internal error')
})
@@ -295,56 +214,17 @@ describe('Retry Configuration', () => {
})
/**
- * The `tries` option controls the maximum number of attempts before
- * giving up.
- */
- it('tries option controls maximum attempts', async () => {
- let attempts = 0
-
- interface Input {
- value: string
- }
-
- interface Output {
- value: string
- }
-
- function createAlwaysFailsStep(): ProcessingStep<Input, Output> {
- return function alwaysFailsStep(_input) {
- attempts++
- throw new RetriableError('fail')
- }
- }
-
- const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createAlwaysFailsStep()), { tries: 2, sleepMs: 100 })
- .build()
-
- const resultPromise = pipeline.process(createOkContext({ value: 'data' }, {})).catch(() => {
- // Expected to throw after max retries
- })
- await jest.advanceTimersByTimeAsync(100) // One retry (100ms between attempts)
- await resultPromise
-
- expect(attempts).toBe(2)
- })
-
- /**
- * The `sleepMs` option sets the initial delay between retries.
- * Subsequent retries use exponential backoff (delay doubles each time).
+ * `tries` caps the number of attempts and `sleepMs` sets the initial delay.
+ * Subsequent retries use exponential backoff (the delay doubles each time).
*/
- it('sleepMs option sets initial delay with exponential backoff', async () => {
+ it('tries and sleepMs control attempts and backoff', async () => {
let attempts = 0
interface Input {
value: string
}
- interface Output {
- value: string
- }
-
- function createSlowlyRecoveringStep(): ProcessingStep<Input, Output> {
+ function createSlowlyRecoveringStep(): ProcessingStep<Input, { value: string }> {
return function slowlyRecoveringStep(input) {
attempts++
if (attempts < 4) {
@@ -355,7 +235,7 @@ describe('Retry Configuration', () => {
}
const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createSlowlyRecoveringStep()), { tries: 5, sleepMs: 50 })
+ .pipe(createSlowlyRecoveringStep(), { retry: { tries: 5, sleepMs: 50 } })
.build()
const resultPromise = pipeline.process(createOkContext({ value: 'data' }, {}))
@@ -380,20 +260,16 @@ describe('Retry Configuration', () => {
})
/**
- * Default retry configuration is used when not specified.
+ * Omitting `tries`/`sleepMs` uses the defaults: 3 tries, 100ms initial sleep.
*/
- it('default retry configuration (3 tries, 100ms sleep)', async () => {
+ it('defaults to 3 tries and 100ms sleep', async () => {
let attempts = 0
interface Input {
value: string
}
- interface Output {
- value: string
- }
-
- function createFlakyStep(): ProcessingStep<Input, Output> {
+ function createFlakyStep(): ProcessingStep<Input, { value: string }> {
return function flakyStep(input) {
attempts++
if (attempts < 3) {
@@ -403,9 +279,7 @@ describe('Retry Configuration', () => {
}
}
- const pipeline = newPipelineBuilder<Input>()
- .retry((builder) => builder.pipe(createFlakyStep()))
- .build()
+ const pipeline = newPipelineBuilder<Input>().pipe(createFlakyStep(), { retry: {} }).build()
const resultPromise = pipeline.process(createOkContext({ value: 'data' }, {}))
await jest.advanceTimersByTimeAsync(300) // 100ms + 200ms for two retries (default sleepMs is 100)
@@ -415,3 +289,77 @@ describe('Retry Configuration', () => {
expect(attempts).toBe(3)
})
})
+
+describe('Batch Retries', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ /**
+ * `pipeBatch(step, { retry })` retries the whole batch step on retriable
+ * errors, the same way per-item retry works. The batch is reprocessed as a
+ * unit until it succeeds or retries are exhausted.
+ */
+ it('pipeBatch retries the batch step until it succeeds', async () => {
+ let attempts = 0
+
+ interface Event {
+ id: number
+ }
+
+ function createFlakyBatchStep(): BatchProcessingStep<Event, Event> {
+ return function flakyBatchStep(events) {
+ attempts++
+ if (attempts < 3) {
+ throw new RetriableError('Downstream unavailable')
+ }
+ return Promise.resolve(events.map((e) => ok(e)))
+ }
+ }
+
+ const pipeline = newBatchPipelineBuilder<Event>()
+ .pipeBatch(createFlakyBatchStep(), { retry: { tries: 5, sleepMs: 100 } })
+ .build()
+
+ pipeline.feed([{ id: 1 }, { id: 2 }].map((e) => createOkContext(e, {})))
+ const resultsPromise = pipeline.next()
+ await jest.advanceTimersByTimeAsync(300) // 100ms + 200ms for two retries
+ const results = await resultsPromise
+
+ expect(attempts).toBe(3)
+ expect(results).toHaveLength(2)
+ expect(results!.every((r) => isOkResult(r.result))).toBe(true)
+ })
+
+ /**
+ * When a batch step throws a non-retriable error, every input in the batch
+ * is converted to its own DLQ result. The failure is attributed per-input
+ * so each message is dead-lettered individually.
+ */
+ it('pipeBatch sends one DLQ per input on a non-retriable error', async () => {
+ interface Event {
+ id: number
+ }
+
+ function createFailingBatchStep(): BatchProcessingStep<Event, Event> {
+ return function failingBatchStep(_events) {
+ throw new NonRetriableError('Batch permanently invalid')
+ }
+ }
+
+ const pipeline = newBatchPipelineBuilder<Event>()
+ .pipeBatch(createFailingBatchStep(), { retry: { tries: 5, sleepMs: 100 } })
+ .build()
+
+ // Three inputs -> three DLQ results, no retries (non-retriable)
+ pipeline.feed([{ id: 1 }, { id: 2 }, { id: 3 }].map((e) => createOkContext(e, {})))
+ const results = await pipeline.next()
+
+ expect(results).toHaveLength(3)
+ expect(results!.every((r) => isDlqResult(r.result))).toBe(true)
+ })
+})
diff --git a/nodejs/src/ingestion/framework/docs/13-conventions.test.ts b/nodejs/src/ingestion/framework/docs/13-conventions.test.ts
index b085e2319d8f..2eb042a05f75 100644
--- a/nodejs/src/ingestion/framework/docs/13-conventions.test.ts
+++ b/nodejs/src/ingestion/framework/docs/13-conventions.test.ts
@@ -453,7 +453,7 @@ describe('Pipeline Phases', () => {
// Compose subpipelines like joined-ingestion-pipeline:
// messageAware → concurrently(preTeam) → filterMap(addTeam,
- // teamAware(concurrently(postTeam) → groupBy → concurrently(sequentially(processing)))
+ // teamAware(concurrently(postTeam) → concurrentlyPerGroup(processing))
// → handleIngestionWarnings)
// → handleResults → handleSideEffects
function createPipeline() {
@@ -474,10 +474,11 @@ describe('Pipeline Phases', () => {
b
// Post-team preprocessing: validate (concurrent)
.concurrently((b) => createPostTeamPreprocessingSubpipeline(b))
- // Processing: group by team and process sequentially within each group
- .groupBy((item) => item.teamId)
- .concurrently((group) =>
- group.sequentially((b) => createProcessingSubpipeline(b))
+ // Processing: group by team; groups run concurrently while the
+ // explicit `sequentially` step processes items within a group in order
+ .concurrentlyPerGroup(
+ (item) => item.teamId,
+ (group) => group.sequentially((b) => createProcessingSubpipeline(b))
)
)
.handleIngestionWarnings(createMockIngestionOutputs<IngestionWarningsOutput>())
diff --git a/nodejs/src/ingestion/framework/docs/14-batching.test.ts b/nodejs/src/ingestion/framework/docs/14-batching.test.ts
new file mode 100644
index 000000000000..26c7779ea3a9
--- /dev/null
+++ b/nodejs/src/ingestion/framework/docs/14-batching.test.ts
@@ -0,0 +1,167 @@
+/**
+ * # Chapter 14: Batching Pipelines
+ *
+ * `newBatchingPipeline(beforeBatch, callback, afterBatch, options?)` builds a
+ * `BatchingPipeline` that runs a hook before a batch enters the sub-pipeline
+ * and another after every item in that batch has come out. It is the tool for
+ * per-batch setup/teardown: prefetching data all the items in a batch will
+ * need, or flushing an accumulated write once the batch is done.
+ *
+ * ## Key concepts
+ *
+ * - **A batch is one `feed()` call.** The batching pipeline does not accumulate
+ * items itself - the caller decides batch boundaries (by size, by time, by
+ * however it chooses) and each `feed()` becomes exactly one batch.
+ * - **`beforeBatch`** runs once per batch before its items enter the
+ * sub-pipeline. It receives the batch's elements and a `batchContext`, and
+ * can enrich both (e.g. attach a shared store) for the whole batch.
+ * - **`callback`** builds the per-item sub-pipeline (the same builder DSL as
+ * the other chapters).
+ * - **`afterBatch`** runs once per batch after all its items exit, receiving
+ * the ordered results plus the `batchContext` and `batchId`.
+ * - **`batchId`** is a monotonic id assigned per batch; each element is also
+ * tagged with a monotonic `messageId` in its context.
+ *
+ * ## How it works
+ *
+ * ```
+ * feed(batch A) ─► beforeBatch(A) ─► [ sub-pipeline ] ─► afterBatch(A) ─► next()
+ * feed(batch B) ─► beforeBatch(B) ─► [ sub-pipeline ] ─► afterBatch(B) ─► next()
+ * ```
+ *
+ * Unlike a plain `BatchPipeline`, `feed()` is async and returns a `FeedResult`:
+ * `{ ok: true }` when accepted, or `{ ok: false, kind, reason }` when rejected.
+ * `next()` returns a `BatchResult` (`{ elements, sideEffects }`) per completed
+ * batch, or `null` when fully drained. Batches are returned in completion
+ * order; items within a batch keep their feed order.
+ *
+ * ## Backpressure
+ *
+ * `concurrentBatches` (default 1) caps how many batches can be in flight at
+ * once. When the pipeline is at capacity, `feed()` returns
+ * `{ ok: false, kind: 'at_capacity' }` instead of accepting the batch -
+ * the caller must drain a batch (via `next()`) to free a slot before retrying.
+ */
+import { newBatchingPipeline } from '~/ingestion/framework/builders'
+import { createOkContext } from '~/ingestion/framework/helpers'
+import { isOkResult, ok } from '~/ingestion/framework/results'
+
+interface Event {
+ id: number
+}
+
+type NoCtx = Record<string, never>
+
+describe('Batching Pipelines', () => {
+ /**
+ * Each feed() call is one batch: beforeBatch and afterBatch fire once per
+ * batch, batchIds increment, and every element is tagged with a monotonic
+ * messageId that continues across batches.
+ */
+ it('each feed() forms one batch with sequential batchId and messageId tagging', async () => {
+ const beforeBatchIds: number[] = []
+ const afterBatchIds: number[] = []
+
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(
+ (builder) =>
+ builder.pipe(function recordingBefore(input) {
+ beforeBatchIds.push(input.batchContext.batchId)
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ }),
+ (builder) => builder,
+ (builder) =>
+ builder.pipe(function recordingAfter(input) {
+ afterBatchIds.push(input.batchId)
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: Infinity }
+ )
+
+ await pipeline.feed([{ id: 10 }, { id: 20 }].map((e) => createOkContext(e, {})))
+ await pipeline.feed([{ id: 30 }].map((e) => createOkContext(e, {})))
+
+ const messageIds: number[] = []
+ let batch = await pipeline.next()
+ while (batch !== null) {
+ for (const element of batch.elements) {
+ messageIds.push(element.context.messageId)
+ }
+ batch = await pipeline.next()
+ }
+
+ // One beforeBatch/afterBatch per feed(), batchIds increment
+ expect(beforeBatchIds).toEqual([0, 1])
+ expect(afterBatchIds).toEqual([0, 1])
+ // messageIds are monotonic and continue across batches
+ expect(messageIds).toEqual([0, 1, 2])
+ })
+
+ /**
+ * beforeBatch can attach a shared store to the batchContext; that same
+ * context is handed to afterBatch. This is how a batch prefetches data once
+ * and cleans up once, rather than per item.
+ */
+ it('batch context flows from beforeBatch to afterBatch', async () => {
+ type BatchStore = { store: string }
+ let seenInAfter: string | undefined
+
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx, BatchStore>(
+ (builder) =>
+ builder.pipe(function attachStore(input) {
+ return Promise.resolve(
+ ok({
+ elements: input.elements,
+ batchContext: { ...input.batchContext, store: `store-${input.batchContext.batchId}` },
+ })
+ )
+ }),
+ (builder) => builder,
+ (builder) =>
+ builder.pipe(function readStore(input) {
+ seenInAfter = input.batchContext.store
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: Infinity }
+ )
+
+ await pipeline.feed([{ id: 1 }].map((e) => createOkContext(e, {})))
+ await pipeline.next()
+
+ expect(seenInAfter).toBe('store-0')
+ })
+
+ /**
+ * `concurrentBatches` caps how many batches are in flight. At the default
+ * of 1, a second feed() before the first drains is rejected with an
+ * `at_capacity` FeedResult. Draining a batch frees the slot.
+ */
+ it('feed() reports at_capacity backpressure when concurrentBatches is exceeded', async () => {
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(
+ (builder) =>
+ builder.pipe(function passThroughBefore(input) {
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ }),
+ (builder) => builder,
+ (builder) =>
+ builder.pipe(function passThroughAfter(input) {
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: 1 }
+ )
+
+ // First batch accepted
+ expect(await pipeline.feed([{ id: 1 }].map((e) => createOkContext(e, {})))).toEqual({ ok: true })
+
+ // Second batch rejected: already at capacity
+ const rejected = await pipeline.feed([{ id: 2 }].map((e) => createOkContext(e, {})))
+ expect(rejected).toMatchObject({ ok: false, kind: 'at_capacity' })
+
+ // Draining the in-flight batch frees the slot
+ const drained = await pipeline.next()
+ expect(drained).not.toBeNull()
+ expect(drained!.elements.every((e) => isOkResult(e.result))).toBe(true)
+
+ // Now a new batch is accepted again
+ expect(await pipeline.feed([{ id: 3 }].map((e) => createOkContext(e, {})))).toEqual({ ok: true })
+ })
+})
diff --git a/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts b/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts
new file mode 100644
index 000000000000..e667c899d8e2
--- /dev/null
+++ b/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts
@@ -0,0 +1,145 @@
+/**
+ * # Chapter 15: Consuming a Pipeline
+ *
+ * The earlier chapters build pipelines; this one shows how a built
+ * `BatchPipeline` is actually driven in production, and how
+ * `BatchPipelineUnwrapper` turns its results into plain values.
+ *
+ * ## The feed() / next() contract
+ *
+ * A `BatchPipeline` is a pull-based stream:
+ *
+ * - **`feed(elements)`** hands a batch of `OkResultWithContext` items to the
+ * pipeline. It buffers them; it does not process synchronously.
+ * - **`next()`** pulls the next available chunk of results (each a
+ * result-with-context), driving processing as needed. Depending on the
+ * stages involved, a `next()` may return one item, one group, or a whole
+ * batch.
+ * - **`next()` returns `null` when the pipeline is drained** - everything fed
+ * has been processed and emitted. A consumer loops `next()` until it sees
+ * `null`, then feeds the next batch.
+ *
+ * ```
+ * pipeline.feed(batch)
+ * let results = await pipeline.next()
+ * while (results !== null) {
+ * // handle results
+ * results = await pipeline.next()
+ * }
+ * ```
+ *
+ * ## BatchPipelineUnwrapper
+ *
+ * Most consumers do not want result-with-context objects; they want the plain
+ * output values. `BatchPipelineUnwrapper` wraps a pipeline and, on `next()`,
+ * returns a flat `TOutput[]` of just the OK values - non-OK results (DLQ, DROP,
+ * REDIRECT) are filtered out (they are assumed already handled by a
+ * `handleResults()` stage upstream). It returns `null` when the underlying
+ * pipeline drains.
+ *
+ * ### Warning on unhandled side effects
+ *
+ * The unwrapper is a terminal consumer, so any side effects still attached to
+ * the results it sees will never be awaited. When it finds results that still
+ * carry side effects, it logs a warning - a signal that a `handleSideEffects()`
+ * stage is missing from the pipeline.
+ */
+import { logger } from '~/common/utils/logger'
+import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'
+import { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'
+import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'
+import { createOkContext } from '~/ingestion/framework/helpers'
+import { drop, isOkResult, ok } from '~/ingestion/framework/results'
+
+interface Event {
+ id: number
+}
+
+type NoCtx = Record<string, never>
+
+describe('Consuming a Pipeline', () => {
+ /**
+ * A consumer feeds a batch, then loops next() until it returns null.
+ * next() drives processing; null marks the pipeline drained.
+ */
+ it('feed() then next() drives the pipeline until it returns null', async () => {
+ function createDoubleStep(): BatchProcessingStep<Event, Event> {
+ return function doubleStep(events) {
+ return Promise.resolve(events.map((event) => ok({ id: event.id * 2 })))
+ }
+ }
+
+ const pipeline = newBatchPipelineBuilder<Event, NoCtx>().pipeBatch(createDoubleStep()).build()
+
+ pipeline.feed([{ id: 1 }, { id: 2 }, { id: 3 }].map((e) => createOkContext(e, {})))
+
+ const values: number[] = []
+ let results = await pipeline.next()
+ while (results !== null) {
+ for (const r of results) {
+ if (isOkResult(r.result)) {
+ values.push(r.result.value.id)
+ }
+ }
+ results = await pipeline.next()
+ }
+
+ expect(values).toEqual([2, 4, 6])
+ // Once drained, next() keeps returning null
+ expect(await pipeline.next()).toBeNull()
+ })
+
+ /**
+ * BatchPipelineUnwrapper returns plain output values and filters out non-OK
+ * results (here, DROP). The consumer never sees result-with-context objects.
+ */
+ it('BatchPipelineUnwrapper returns plain values and drops non-OK results', async () => {
+ function createFilterStep(): BatchProcessingStep<Event, Event> {
+ return function filterStep(events) {
+ // Drop even ids, keep odd ones
+ return Promise.resolve(events.map((event) => (event.id % 2 === 0 ? drop('even filtered') : ok(event))))
+ }
+ }
+
+ const pipeline = newBatchPipelineBuilder<Event, NoCtx>().pipeBatch(createFilterStep()).build()
+ const unwrapper = new BatchPipelineUnwrapper(pipeline)
+
+ unwrapper.feed([{ id: 1 }, { id: 2 }, { id: 3 }].map((e) => createOkContext(e, {})))
+
+ const values: Event[] = []
+ let batch = await unwrapper.next()
+ while (batch !== null) {
+ values.push(...batch)
+ batch = await unwrapper.next()
+ }
+
+ // Only the OK (odd) values survive, as plain objects
+ expect(values).toEqual([{ id: 1 }, { id: 3 }])
+ })
+
+ /**
+ * When results still carry side effects (no handleSideEffects() stage ran),
+ * the unwrapper logs a warning: those side effects would otherwise be
+ * silently dropped.
+ */
+ it('BatchPipelineUnwrapper warns about unhandled side effects', async () => {
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined)
+
+ function createStepWithSideEffect(): BatchProcessingStep<Event, Event> {
+ return function stepWithSideEffect(events) {
+ // Attach a side effect that no downstream stage handles
+ return Promise.resolve(events.map((event) => ok(event, [Promise.resolve('unhandled')])))
+ }
+ }
+
+ const pipeline = newBatchPipelineBuilder<Event, NoCtx>().pipeBatch(createStepWithSideEffect()).build()
+ const unwrapper = new BatchPipelineUnwrapper(pipeline)
+
+ unwrapper.feed([{ id: 1 }].map((e) => createOkContext(e, {})))
+ await unwrapper.next()
+
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('remaining side effects'))
+
+ warnSpy.mockRestore()
+ })
+})
diff --git a/nodejs/src/ingestion/framework/docs/16-tophog-metrics.test.ts b/nodejs/src/ingestion/framework/docs/16-tophog-metrics.test.ts
new file mode 100644
index 000000000000..05ca24749f26
--- /dev/null
+++ b/nodejs/src/ingestion/framework/docs/16-tophog-metrics.test.ts
@@ -0,0 +1,193 @@
+/**
+ * # Chapter 16: TopHog Step Metrics
+ *
+ * TopHog is an in-process metric extension for pipeline steps. It tracks the
+ * top contributors to a named metric across arbitrary dimensions (e.g.
+ * `team_id`), keeping only the top N per metric and periodically flushing them
+ * to Kafka. It is a troubleshooting tool for multi-tenant systems - "which
+ * teams are producing the most events right now?" - not a product-analytics
+ * system.
+ *
+ * This chapter is an introduction; the full reference (metric types, keys,
+ * tuning, architecture) lives in `framework/tophog/README.md`.
+ *
+ * ## Key concepts
+ *
+ * - **`createTopHogWrapper(registry)`** returns a `topHog(step, factories)`
+ * wrapper. Wrapping a step with metric factories records metrics around each
+ * invocation without changing the step's result or context.
+ * - **Metric factories** come in families - `count`, `sum`, `max`, `average`,
+ * and `timer` - each with three timing variants:
+ * - plain (`count`, `sum`, ...): records from the step *input*, before it runs
+ * - `*Result` (`countResult`, ...): records after the step, on *every* result
+ * (ok, drop, dlq, redirect)
+ * - `*Ok` (`countOk`, ...): records after the step, only on OK results
+ * - **`MetricTracker` / `TopHog`** is the registry. It accumulates records
+ * keyed by dimension, evicts to stay within `maxKeys`, and on `flush()` emits
+ * the top N entries per metric.
+ *
+ * ## How it works
+ *
+ * ```
+ * const topHog = createTopHogWrapper(registry)
+ * builder.pipe(topHog(myStep, [count('events', (in) => ({ team_id: ... }))]))
+ * ```
+ */
+import { TOPHOG_OUTPUT, TophogOutput } from '~/common/outputs'
+import { parseJSON } from '~/common/utils/json-parse'
+import { newPipelineBuilder } from '~/ingestion/framework/builders'
+import {
+ TopHogRegistry,
+ count,
+ countOk,
+ countResult,
+ createTopHogWrapper,
+ timer,
+} from '~/ingestion/framework/extensions/tophog'
+import { createOkContext } from '~/ingestion/framework/helpers'
+import { dlq, ok } from '~/ingestion/framework/results'
+import { TopHog } from '~/ingestion/framework/tophog'
+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
+
+interface Event {
+ teamId: number
+}
+
+// A minimal registry that captures every recorded metric, so a test can assert
+// exactly what was recorded without a full TopHog flush.
+function createRecordingRegistry(): {
+ registry: TopHogRegistry
+ records: { metric: string; key: Record<string, string>; value: number }[]
+} {
+ const records: { metric: string; key: Record<string, string>; value: number }[] = []
+ const recorder = (metric: string) => ({
+ record: (key: Record<string, string>, value: number) => records.push({ metric, key, value }),
+ })
+ return {
+ records,
+ registry: {
+ registerSum: (name) => recorder(name),
+ registerMax: (name) => recorder(name),
+ registerAverage: (name) => recorder(name),
+ },
+ }
+}
+
+describe('TopHog Step Metrics', () => {
+ /**
+ * Wrapping a step with `count` records once per invocation, keyed by the
+ * dimension the factory extracts from the input. The step's own result is
+ * untouched.
+ */
+ it('count records once per invocation, keyed by a dimension', async () => {
+ const { registry, records } = createRecordingRegistry()
+ const topHog = createTopHogWrapper(registry)
+
+ function processEvent(event: Event) {
+ return Promise.resolve(ok({ ...event, processed: true }))
+ }
+
+ const pipeline = newPipelineBuilder<Event>()
+ .pipe(topHog(processEvent, [count('events', (event) => ({ team_id: String(event.teamId) }))]))
+ .build()
+
+ await pipeline.process(createOkContext({ teamId: 1 }, {}))
+ await pipeline.process(createOkContext({ teamId: 1 }, {}))
+ await pipeline.process(createOkContext({ teamId: 2 }, {}))
+
+ expect(records).toEqual([
+ { metric: 'events', key: { team_id: '1' }, value: 1 },
+ { metric: 'events', key: { team_id: '1' }, value: 1 },
+ { metric: 'events', key: { team_id: '2' }, value: 1 },
+ ])
+ })
+
+ /**
+ * The timing variant distinguishes what counts. `countResult` records for
+ * every result; `countOk` records only when the step returns OK. Here the
+ * step DLQs its input, so only `countResult` fires.
+ */
+ it('countResult records on all results, countOk only on OK results', async () => {
+ const { registry, records } = createRecordingRegistry()
+ const topHog = createTopHogWrapper(registry)
+
+ function rejectEvent(_event: Event) {
+ return Promise.resolve(dlq<Event>('invalid'))
+ }
+
+ const pipeline = newPipelineBuilder<Event>()
+ .pipe(
+ topHog(rejectEvent, [
+ countResult('seen', (_result, event) => ({ team_id: String(event.teamId) })),
+ countOk('accepted', (_output, event) => ({ team_id: String(event.teamId) })),
+ ])
+ )
+ .build()
+
+ await pipeline.process(createOkContext({ teamId: 7 }, {}))
+
+ // Only countResult recorded; countOk skipped the non-OK result
+ expect(records).toEqual([{ metric: 'seen', key: { team_id: '7' }, value: 1 }])
+ })
+
+ /**
+ * `timer` records the elapsed wall-clock time of the step in milliseconds,
+ * keyed from the input. It records regardless of the result type.
+ */
+ it('timer records elapsed step time', async () => {
+ const { registry, records } = createRecordingRegistry()
+ const topHog = createTopHogWrapper(registry)
+
+ async function slowStep(event: Event) {
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ return ok(event)
+ }
+
+ const pipeline = newPipelineBuilder<Event>()
+ .pipe(topHog(slowStep, [timer('step_time', (event) => ({ team_id: String(event.teamId) }))]))
+ .build()
+
+ await pipeline.process(createOkContext({ teamId: 3 }, {}))
+
+ expect(records).toHaveLength(1)
+ expect(records[0].metric).toBe('step_time')
+ expect(records[0].key).toEqual({ team_id: '3' })
+ expect(typeof records[0].value).toBe('number')
+ })
+
+ /**
+ * A real `TopHog` registry accumulates records via its `MetricTracker`s and,
+ * on `flush()`, emits the top contributors per metric to its Kafka output.
+ * Team 1 (3 events) outranks team 2 (1 event).
+ */
+ it('TopHog aggregates records and flushes top contributors', async () => {
+ const outputs = createMockIngestionOutputs<TophogOutput>()
+ const tophog = new TopHog({ outputs, pipeline: 'docs', lane: 'test' })
+ const topHog = createTopHogWrapper(tophog)
+
+ function processEvent(event: Event) {
+ return Promise.resolve(ok(event))
+ }
+
+ const pipeline = newPipelineBuilder<Event>()
+ .pipe(topHog(processEvent, [count('events_by_team', (event) => ({ team_id: String(event.teamId) }))]))
+ .build()
+
+ for (const teamId of [1, 1, 1, 2]) {
+ await pipeline.process(createOkContext({ teamId }, {}))
+ }
+
+ await tophog.flush()
+
+ // flush() queues one message per top-N entry to the TopHog output
+ expect(outputs.queueMessages).toHaveBeenCalledTimes(1)
+ const [output, messages] = outputs.queueMessages.mock.calls[0]
+ expect(output).toBe(TOPHOG_OUTPUT)
+
+ const entries = (messages as { value: Buffer }[]).map((m) => parseJSON(m.value.toString()))
+ const byTeam = new Map(entries.map((e) => [e.key.team_id, e]))
+
+ expect(byTeam.get('1')).toMatchObject({ metric: 'events_by_team', value: 3, count: 3 })
+ expect(byTeam.get('2')).toMatchObject({ metric: 'events_by_team', value: 1, count: 1 })
+ })
+})
diff --git a/nodejs/src/ingestion/framework/retry.test.ts b/nodejs/src/ingestion/framework/retry.test.ts
new file mode 100644
index 000000000000..bb50071852b4
--- /dev/null
+++ b/nodejs/src/ingestion/framework/retry.test.ts
@@ -0,0 +1,190 @@
+import { captureException } from '~/common/utils/posthog'
+
+import { BatchProcessingStep } from './base-batch-pipeline'
+import { newBatchPipelineBuilder, newPipelineBuilder } from './builders'
+import { createOkContext } from './helpers'
+import { pipelineRetryAttemptsHistogram } from './metrics'
+import { getRetryAttempts } from './metrics.test-utils'
+import { PipelineResult, isDlqResult, isOkResult, ok } from './results'
+import { withBatchRetry, withStepRetry } from './retry'
+import { ProcessingStep } from './steps'
+
+jest.setTimeout(1000)
+
+jest.mock('~/common/utils/logger', () => ({
+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
+}))
+
+jest.mock('~/common/utils/posthog', () => ({
+ captureException: jest.fn(),
+}))
+
+const mockCaptureException = captureException as jest.MockedFunction<typeof captureException>
+
+class RetriableError extends Error {
+ isRetriable = true
+}
+
+class NonRetriableError extends Error {
+ isRetriable = false
+}
+
+/**
+ * A `run` executes a step wrapped with retry through the public builder interface
+ * and returns the flat list of results, so `withStepRetry` (single item) and
+ * `withBatchRetry` (batch) can share the same behavioral assertions.
+ *
+ * `script` runs once per attempt and may throw to simulate failures.
+ */
+interface Variant {
+ label: string
+ run(
+ script: () => void,
+ retry: Parameters<typeof withStepRetry>[1],
+ opts?: { inputs?: number[]; stepName?: string }
+ ): Promise<PipelineResult<string>[]>
+}
+
+const stepVariant: Variant = {
+ label: 'withStepRetry (via pipe)',
+ async run(script, retry, opts) {
+ const inputs = opts?.inputs ?? [1]
+ // Inline function literal so the computed-property key names the step (for the metric-name test).
+ const step: ProcessingStep<number, string> = opts?.stepName
+ ? {
+ [opts.stepName]: (v: number): Promise<PipelineResult<string>> => {
+ script()
+ return Promise.resolve(ok(String(v)))
+ },
+ }[opts.stepName]
+ : (v: number): Promise<PipelineResult<string>> => {
+ script()
+ return Promise.resolve(ok(String(v)))
+ }
+ const pipeline = newPipelineBuilder<number>().pipe(step, { retry }).build()
+ const result = await pipeline.process(createOkContext(inputs[0], {}))
+ return [result.result]
+ },
+}
+
+const batchVariant: Variant = {
+ label: 'withBatchRetry (via pipeBatch)',
+ async run(script, retry, opts) {
+ const inputs = opts?.inputs ?? [1]
+ // Inline function literal so the computed-property key names the step (for the metric-name test).
+ const step: BatchProcessingStep<number, string> = opts?.stepName
+ ? {
+ [opts.stepName]: (values: number[]): Promise<PipelineResult<string>[]> => {
+ script()
+ return Promise.resolve(values.map((v) => ok(String(v))))
+ },
+ }[opts.stepName]
+ : (values: number[]): Promise<PipelineResult<string>[]> => {
+ script()
+ return Promise.resolve(values.map((v) => ok(String(v))))
+ }
+ const pipeline = newBatchPipelineBuilder<number>().pipeBatch(step, { retry }).gather().build()
+ pipeline.feed(inputs.map((v) => createOkContext(v, {})))
+ const results = await pipeline.next()
+ return (results ?? []).map((r) => r.result)
+ },
+}
+
+describe('retry', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ pipelineRetryAttemptsHistogram.reset()
+ })
+
+ describe.each([stepVariant, batchVariant])('$label', (variant) => {
+ it('retries retriable errors and eventually succeeds', async () => {
+ let attempts = 0
+ const script = (): void => {
+ attempts++
+ if (attempts < 3) {
+ throw new RetriableError('Temporary failure')
+ }
+ }
+
+ const results = await variant.run(script, { name: 'retry_site', tries: 5, sleepMs: 1 })
+
+ expect(attempts).toBe(3)
+ expect(results.every(isOkResult)).toBe(true)
+ expect(mockCaptureException).not.toHaveBeenCalled()
+ expect(await getRetryAttempts('retry_site', 'completed')).toEqual({ count: 1, sum: 3 })
+ })
+
+ it('converts non-retriable errors to DLQ without retrying', async () => {
+ const script = (): void => {
+ throw new NonRetriableError('Validation failed')
+ }
+
+ const results = await variant.run(script, { name: 'retry_site', tries: 3, sleepMs: 1 })
+
+ expect(results.length).toBeGreaterThanOrEqual(1)
+ expect(results.every(isDlqResult)).toBe(true)
+ expect(mockCaptureException).toHaveBeenCalledTimes(1)
+ expect(await getRetryAttempts('retry_site', 'non_retriable')).toEqual({ count: 1, sum: 1 })
+ })
+
+ it('rethrows retriable errors after exhausting retries', async () => {
+ const script = (): void => {
+ throw new RetriableError('Always fails')
+ }
+
+ await expect(variant.run(script, { name: 'retry_site', tries: 2, sleepMs: 1 })).rejects.toThrow(
+ 'Always fails'
+ )
+ expect(await getRetryAttempts('retry_site', 'exhausted')).toEqual({ count: 1, sum: 2 })
+ })
+
+ it('rethrows errors without isRetriable after exhausting the default of 3 tries', async () => {
+ const script = (): void => {
+ throw new Error('No isRetriable property')
+ }
+
+ await expect(variant.run(script, { name: 'retry_site', sleepMs: 1 })).rejects.toThrow(
+ 'No isRetriable property'
+ )
+ expect(mockCaptureException).not.toHaveBeenCalled()
+ expect(await getRetryAttempts('retry_site', 'exhausted')).toEqual({ count: 1, sum: 3 })
+ })
+
+ it('defaults the metric name to the step name', async () => {
+ const results = await variant.run(() => {}, { sleepMs: 1 }, { stepName: 'geoipStep' })
+
+ expect(results.every(isOkResult)).toBe(true)
+ expect(await getRetryAttempts('geoipStep', 'completed')).toEqual({ count: 1, sum: 1 })
+ })
+ })
+
+ it('maps a non-retriable batch error to one DLQ result per input value', async () => {
+ const results = await batchVariant.run(
+ () => {
+ throw new NonRetriableError('Validation failed')
+ },
+ { name: 'retry_site', tries: 3, sleepMs: 1 },
+ { inputs: [1, 2, 3] }
+ )
+
+ expect(results).toHaveLength(3)
+ expect(results.every(isDlqResult)).toBe(true)
+ })
+
+ describe('preserves the wrapped step name', () => {
+ const namedStep = function namedStep(): Promise<PipelineResult<string>> {
+ return Promise.resolve(ok('x'))
+ }
+ const namedBatchStep = function namedBatchStep(values: number[]): Promise<PipelineResult<string>[]> {
+ return Promise.resolve(values.map((v) => ok(String(v))))
+ }
+
+ it('for withStepRetry', () => {
+ expect(withStepRetry(namedStep).name).toBe('namedStep')
+ })
+
+ it('for withBatchRetry', () => {
+ expect(withBatchRetry(namedBatchStep).name).toBe('namedBatchStep')
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/framework/batch-retry.ts b/nodejs/src/ingestion/framework/retry.ts
similarity index 53%
rename from nodejs/src/ingestion/framework/batch-retry.ts
rename to nodejs/src/ingestion/framework/retry.ts
index 92f4270e218e..125df235652f 100644
--- a/nodejs/src/ingestion/framework/batch-retry.ts
+++ b/nodejs/src/ingestion/framework/retry.ts
@@ -5,14 +5,70 @@ import { retryIfRetriable } from '~/common/utils/retries'
import { BatchProcessingStep } from './base-batch-pipeline'
import { pipelineRetryAttemptsHistogram } from './metrics'
import { dlq } from './results'
+import { ProcessingStep } from './steps'
-export interface BatchRetryOptions {
+export interface RetryOptions {
/** Identifies the retry site in the `ingestion_pipeline_retry_attempts` metric. Defaults to the step name. */
name?: string
tries?: number
sleepMs?: number
}
+/**
+ * Wraps a processing step with retry logic.
+ *
+ * When the step throws a retriable error (error.isRetriable === true),
+ * it will be retried with exponential backoff up to the configured
+ * number of attempts.
+ *
+ * Non-retriable errors (error.isRetriable === false) are converted to
+ * a DLQ result.
+ *
+ * Errors without an isRetriable property are rethrown after exhausting
+ * retries, causing the process to crash (appropriate for unexpected errors).
+ */
+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 wrappedStep: ProcessingStep<T, U, R> = async (value: T) => {
+ let attempts = 0
+ try {
+ const result = await retryIfRetriable(
+ () => {
+ attempts++
+ return step(value)
+ },
+ options.tries ?? 3,
+ options.sleepMs ?? 100
+ )
+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'completed' }).observe(attempts)
+ return result
+ } catch (error) {
+ const isRetriable = (error as any)?.isRetriable
+
+ logger.error('🔥', `Step ${name} failed`, {
+ error: error instanceof Error ? error.message : String(error),
+ stack: (error as Error).stack,
+ isRetriable,
+ })
+
+ if (isRetriable === false) {
+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'non_retriable' }).observe(attempts)
+ captureException(error as Error)
+ return dlq('Processing error - non-retriable', error)
+ }
+
+ pipelineRetryAttemptsHistogram.labels({ name, outcome: 'exhausted' }).observe(attempts)
+ throw error
+ }
+ }
+
+ Object.defineProperty(wrappedStep, 'name', { value: step.name })
+ return wrappedStep
+}
+
/**
* Wraps a batch processing step with retry logic.
*
@@ -28,7 +84,7 @@ export interface BatchRetryOptions {
*/
export function withBatchRetry<T, U, R extends string = never>(
step: BatchProcessingStep<T, U, R>,
- options: BatchRetryOptions = {}
+ options: RetryOptions = {}
): BatchProcessingStep<T, U, R> {
const name = options.name ?? step.name ?? 'unknown'
const wrappedStep: BatchProcessingStep<T, U, R> = async (values: T[]) => {
@@ -47,7 +103,7 @@ export function withBatchRetry<T, U, R extends string = never>(
} catch (error) {
const isRetriable = (error as any)?.isRetriable
- logger.error('🔥', `Batch step ${step.name} failed`, {
+ logger.error('🔥', `Batch step ${name} failed`, {
error: error instanceof Error ? error.message : String(error),
stack: (error as Error).stack,
batchSize: values.length,
diff --git a/nodejs/src/ingestion/framework/retrying-pipeline.test.ts b/nodejs/src/ingestion/framework/retrying-pipeline.test.ts
deleted file mode 100644
index 983064eb8f6d..000000000000
--- a/nodejs/src/ingestion/framework/retrying-pipeline.test.ts
+++ /dev/null
@@ -1,632 +0,0 @@
-import { Message } from 'node-rdkafka'
-
-import { captureException } from '~/common/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'
-
-jest.setTimeout(1000)
-
-jest.mock('~/common/utils/posthog', () => ({
- captureException: jest.fn(),
-}))
-
-const mockCaptureException = captureException as jest.MockedFunction<typeof captureException>
-
-describe('RetryingPipeline', () => {
- beforeEach(() => {
- jest.clearAllMocks()
- pipelineRetryAttemptsHistogram.reset()
- })
-
- describe('basic functionality', () => {
- it('should process input through inner pipeline successfully', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {
- const value = input.message.value?.toString()
- return Promise.resolve(ok({ processed: value }))
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline)
- 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 })
-
- const result = await retryingPipeline.process(input)
-
- expect(mockProcessStep).toHaveBeenCalledTimes(1)
- expect(mockProcessStep).toHaveBeenCalledWith({ message })
- expect(result).toEqual(createContext(ok({ processed: 'test' }), { message, lastStep: 'mockConstructor' }))
- })
- })
-
- describe('retry behavior', () => {
- it('should retry on retriable errors and log errors after all retries', async () => {
- let callCount = 0
- const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {
- callCount++
- if (callCount < 3) {
- const error = new Error('Retriable error')
- ;(error as any).isRetriable = true
- return Promise.reject(error)
- }
- const value = input.message.value?.toString()
- return ok({ processed: value })
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline, { tries: 3, sleepMs: 150 })
- 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 })
-
- const processPromise = retryingPipeline.process(input)
-
- const result = await processPromise
-
- expect(callCount).toBe(3)
- expect(mockCaptureException).not.toHaveBeenCalled() // Should not capture retriable errors
- expect(result).toEqual(createContext(ok({ processed: 'test' }), { message, lastStep: 'mockConstructor' }))
- })
-
- it('should log errors when all retries are exhausted', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- const error = new Error('Retriable error that exhausts retries')
- ;(error as any).isRetriable = true
- return Promise.reject(error)
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline, { tries: 3, sleepMs: 200 })
- 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 })
-
- const processPromise = retryingPipeline.process(input)
-
- await expect(processPromise).rejects.toThrow('Retriable error that exhausts retries')
- expect(mockProcessStep).toHaveBeenCalledTimes(3) // Called 3 times (initial + 2 retries)
- expect(mockCaptureException).not.toHaveBeenCalled() // Should not capture retriable errors
- })
-
- it('should not retry on non-retriable errors and return DLQ result', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- const error = new Error('Non-retriable error')
- ;(error as any).isRetriable = false
- return Promise.reject(error)
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline, { tries: 5, sleepMs: 50 })
- 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 })
-
- const result = await retryingPipeline.process(input)
-
- expect(mockProcessStep).toHaveBeenCalledTimes(1)
- expect(mockCaptureException).toHaveBeenCalledTimes(1)
- expect(mockCaptureException).toHaveBeenCalledWith(expect.any(Error))
- expect(result.result.type).toBe(PipelineResultType.DLQ)
- if (result.result.type === PipelineResultType.DLQ) {
- expect(result.result.reason).toBe('Processing error - non-retriable')
- }
- expect(result.context).toEqual({ message, sideEffects: [], warnings: [] })
- })
-
- it('should treat errors without isRetriable property as retriable', async () => {
- let callCount = 0
- const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {
- callCount++
- if (callCount < 2) {
- const error = new Error('Error without isRetriable property')
- // No isRetriable property set
- throw error
- }
- const value = input.message.value?.toString()
- return Promise.resolve(ok({ processed: value }))
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline, { tries: 2, sleepMs: 75 })
- 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 })
-
- const processPromise = retryingPipeline.process(input)
-
- const result = await processPromise
-
- expect(callCount).toBe(2)
- expect(mockCaptureException).not.toHaveBeenCalled() // Should not capture retriable errors
- expect(result).toEqual(createContext(ok({ processed: 'test' }), { message, lastStep: 'mockConstructor' }))
- })
-
- it('should propagate DLQ results without retrying', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- return Promise.resolve(dlq('DLQ reason', new Error('test error')))
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline, { tries: 4, sleepMs: 300 })
- 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 })
-
- const result = await retryingPipeline.process(input)
-
- expect(result).toEqual(
- createContext(
- {
- type: PipelineResultType.DLQ,
- reason: 'DLQ reason',
- error: expect.any(Error),
- sideEffects: [],
- warnings: [],
- },
- { message, lastStep: 'mockConstructor' }
- )
- )
- })
- })
-
- describe('createRetryingPipeline helper', () => {
- it('should create a retrying pipeline', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {
- const value = input.message.value?.toString()
- return Promise.resolve(ok({ processed: value }))
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline, { tries: 1, sleepMs: 25 })
- expect(retryingPipeline).toBeInstanceOf(RetryingPipeline)
-
- 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 })
-
- const result = await retryingPipeline.process(input)
-
- expect(mockProcessStep).toHaveBeenCalledTimes(1)
- expect(result).toEqual(createContext(ok({ processed: 'test' }), { message, lastStep: 'mockConstructor' }))
- })
- })
-
- describe('retry configuration options', () => {
- it('should use custom retry count', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- const error = new Error('Retriable error')
- ;(error as any).isRetriable = true
- return Promise.reject(error)
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const options: RetryingPipelineOptions = { tries: 2, sleepMs: 80 }
- const retryingPipeline = new RetryingPipeline(innerPipeline, options)
- 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 })
-
- const processPromise = retryingPipeline.process(input)
-
- await expect(processPromise).rejects.toThrow('Retriable error')
- expect(mockProcessStep).toHaveBeenCalledTimes(2) // Called 2 times (initial + 1 retry)
- })
-
- it('should use custom sleep duration', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- const error = new Error('Retriable error')
- ;(error as any).isRetriable = true
- return Promise.reject(error)
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const options: RetryingPipelineOptions = { tries: 2, sleepMs: 50 }
- const retryingPipeline = new RetryingPipeline(innerPipeline, options)
- 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 })
-
- const processPromise = retryingPipeline.process(input)
-
- await expect(processPromise).rejects.toThrow('Retriable error')
- expect(mockProcessStep).toHaveBeenCalledTimes(2) // Called 2 times (initial + 1 retry)
- })
-
- it('should use default values when no options provided', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- const error = new Error('Retriable error')
- ;(error as any).isRetriable = true
- return Promise.reject(error)
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline) // No options - uses defaults
- 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 })
-
- const processPromise = retryingPipeline.process(input)
-
- await expect(processPromise).rejects.toThrow('Retriable error')
- expect(mockProcessStep).toHaveBeenCalledTimes(3) // Default retry count of 3
- })
-
- it('should use createRetryingPipeline helper with options', async () => {
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- const error = new Error('Retriable error')
- ;(error as any).isRetriable = true
- return Promise.reject(error)
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const options: RetryingPipelineOptions = { tries: 2, sleepMs: 120 }
- const retryingPipeline = new RetryingPipeline(innerPipeline, options)
- expect(retryingPipeline).toBeInstanceOf(RetryingPipeline)
-
- 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 })
-
- const processPromise = retryingPipeline.process(input)
-
- await expect(processPromise).rejects.toThrow('Retriable error')
- expect(mockProcessStep).toHaveBeenCalledTimes(2) // Called 2 times (initial + 1 retry)
- })
- })
-
- describe('warning handling', () => {
- it('should preserve warnings from successful results', async () => {
- const stepWarning = { type: 'merge_race_condition' as const, details: { message: 'from step' } }
- const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {
- const value = input.message.value?.toString()
- return Promise.resolve(ok({ processed: value }, [], [stepWarning]))
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline)
- 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 })
- const result = await retryingPipeline.process(input)
-
- expect(result.context.warnings).toEqual([stepWarning])
- })
-
- it('should preserve warnings after retries succeed', async () => {
- let callCount = 0
- const stepWarning = { type: 'merge_race_condition' as const, details: { message: 'from step' } }
- const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {
- callCount++
- if (callCount < 2) {
- const error = new Error('Retriable error')
- ;(error as any).isRetriable = true
- return Promise.reject(error)
- }
- const value = input.message.value?.toString()
- return ok({ processed: value }, [], [stepWarning])
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline, { tries: 3, sleepMs: 50 })
- 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 })
- const result = await retryingPipeline.process(input)
-
- expect(callCount).toBe(2)
- expect(result.context.warnings).toEqual([stepWarning])
- })
-
- it('should preserve context warnings with DLQ results', async () => {
- const contextWarning = { type: 'client_ingestion_warning' as const, details: { message: 'from context' } }
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- return Promise.resolve(dlq('DLQ reason', new Error('test error')))
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline)
- 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,
- warnings: [contextWarning],
- }
- )
- const result = await retryingPipeline.process(input)
-
- // Context warnings should be preserved when DLQ result is returned
- expect(result.context.warnings).toEqual([contextWarning])
- })
-
- it('should preserve context warnings with non-retriable errors', async () => {
- const contextWarning = { type: 'client_ingestion_warning' as const, details: { message: 'from context' } }
- const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {
- const error = new Error('Non-retriable error')
- ;(error as any).isRetriable = false
- return Promise.reject(error)
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline)
- 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,
- warnings: [contextWarning],
- }
- )
- const result = await retryingPipeline.process(input)
-
- expect(result.context.warnings).toEqual([contextWarning])
- expect(result.result.type).toBe(PipelineResultType.DLQ)
- })
-
- it('should merge context and step warnings', async () => {
- const contextWarning = { type: 'client_ingestion_warning' as const, details: { message: 'from context' } }
- const stepWarning = { type: 'schema_validation_failed' as const, details: { message: 'from step' } }
- const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {
- const value = input.message.value?.toString()
- return Promise.resolve(ok({ processed: value }, [], [stepWarning]))
- })
-
- const innerPipeline = createNewPipeline().pipe(mockProcessStep)
- const retryingPipeline = new RetryingPipeline(innerPipeline)
- 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,
- warnings: [contextWarning],
- }
- )
- const result = await retryingPipeline.process(input)
-
- // Should have both context and step warnings
- 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/framework/retrying-pipeline.ts b/nodejs/src/ingestion/framework/retrying-pipeline.ts
deleted file mode 100644
index 3e0effa8bba7..000000000000
--- a/nodejs/src/ingestion/framework/retrying-pipeline.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { logger } from '~/common/utils/logger'
-import { captureException } from '~/common/utils/posthog'
-import { retryIfRetriable } from '~/common/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?: string
- tries?: number
- sleepMs?: number
-}
-
-/**
- * A pipeline that wraps another pipeline with retry logic
- */
-export class RetryingPipeline<TInput, TOutput, C, R extends string = never> implements Pipeline<TInput, TOutput, C, R> {
- constructor(
- private readonly innerPipeline: Pipeline<TInput, TOutput, C, R>,
- private readonly options: RetryingPipelineOptions = {}
- ) {}
-
- async process(input: OkResultWithContext<TInput, C>): Promise<PipelineResultWithContext<TOutput, C, R>> {
- const name = this.options.name ?? 'unknown'
- let attempts = 0
- try {
- 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`, {
- stack: error.stack,
- error: error,
- })
-
- 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
- }
- }
- }
-}
diff --git a/nodejs/src/ingestion/ingestion-consumer.test.ts b/nodejs/src/ingestion/ingestion-consumer.test.ts
index 333f9f4a802e..8357f1cbdc70 100644
--- a/nodejs/src/ingestion/ingestion-consumer.test.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.test.ts
@@ -21,6 +21,7 @@ import {
} from '~/ingestion/common/cookieless/cookieless-manager'
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { createPrepareEventStep } from '~/ingestion/common/steps/event-processing/prepare-event-step'
+import { createProcessGroupsStep } from '~/ingestion/common/steps/event-processing/process-groups-step'
import { createAiEventSubpipeline } from '~/ingestion/pipelines/ai'
import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'
import { createTestIngestionOutputs, createTestMonitoringOutputs } from '~/tests/helpers/ingestion-outputs'
@@ -41,11 +42,16 @@ jest.mock('~/common/utils/posthog', () => {
}
})
-// Mock the prepare event step for error testing
+// Mock the prepare event step for error testing (a step without a retry option)
jest.mock('~/ingestion/common/steps/event-processing/prepare-event-step', () => ({
createPrepareEventStep: jest.fn(),
}))
+// Mock the process groups step for error testing (a step with a retry option)
+jest.mock('~/ingestion/common/steps/event-processing/process-groups-step', () => ({
+ createProcessGroupsStep: jest.fn(),
+}))
+
// Mock the IngestionWarningLimiter to always allow warnings (prevents rate limiting between tests)
jest.mock('~/common/utils/token-bucket', () => {
const mockConsume = jest.fn().mockReturnValue(true)
@@ -189,6 +195,11 @@ describe('IngestionConsumer', () => {
return original.createPrepareEventStep(...args)
})
+ jest.mocked(createProcessGroupsStep).mockImplementation((...args) => {
+ const original = jest.requireActual('~/ingestion/common/steps/event-processing/process-groups-step')
+ return original.createProcessGroupsStep(...args)
+ })
+
ingester = await createIngestionConsumer(infra)
})
@@ -977,15 +988,14 @@ describe('IngestionConsumer', () => {
})
it('should handle explicitly non retriable errors by sending to DLQ', async () => {
- // NOTE: I don't think this makes a lot of sense but currently is just mimicing existing behavior for the migration
- // We should figure this out better and have more explictly named errors
-
+ // Non-retriable errors are converted to DLQ results by the retry wrapper,
+ // so the throwing step must be one that carries a retry option.
const error: any = new Error('test')
error.isRetriable = false
- // Mock the prepare event step to throw the error
- jest.mocked(createPrepareEventStep).mockImplementation(() => {
- return async function prepareEventStepWrapper() {
+ // Mock the process groups step (retry-wrapped) to throw the error
+ jest.mocked(createProcessGroupsStep).mockImplementation(() => {
+ return async function processGroupsStepWrapper() {
return Promise.reject(error)
}
})
@@ -993,7 +1003,11 @@ describe('IngestionConsumer', () => {
const ingester = await createIngestionConsumer(infra)
await ingester.handleKafkaBatch(messages)
- expect(jest.mocked(logger.error)).toHaveBeenCalledWith('🔥', 'Error processing message', expect.any(Object))
+ expect(jest.mocked(logger.error)).toHaveBeenCalledWith(
+ '🔥',
+ 'Step process_groups failed',
+ expect.any(Object)
+ )
expect(forSnapshot(mockProducerObserver.getProducedKafkaMessages())).toMatchSnapshot()
})
@@ -1013,14 +1027,31 @@ describe('IngestionConsumer', () => {
await expect(ingester.handleKafkaBatch(messages)).rejects.toThrow()
})
+ it('should throw non retriable errors from steps without a retry option', async () => {
+ // Steps without a retry option have no error classification: an
+ // explicitly non-retriable error crashes the batch instead of DLQing.
+ const error: any = new Error('test')
+ error.isRetriable = false
+
+ // Mock the prepare event step (no retry option) to throw the error
+ jest.mocked(createPrepareEventStep).mockImplementation(() => {
+ return async function prepareEventStepWrapper() {
+ return Promise.reject(error)
+ }
+ })
+
+ const ingester = await createIngestionConsumer(infra)
+ await expect(ingester.handleKafkaBatch(messages)).rejects.toThrow()
+ })
+
it('should emit failures to dead letter queue for non-retriable errors', async () => {
const error = new Error('Non-retriable processing error')
const errorAny = error as any
errorAny.isRetriable = false
- // Mock the prepare event step to throw the error
- jest.mocked(createPrepareEventStep).mockImplementation(() => {
- return async function prepareEventStepWrapper() {
+ // Mock the process groups step (retry-wrapped) to throw the error
+ jest.mocked(createProcessGroupsStep).mockImplementation(() => {
+ return async function processGroupsStepWrapper() {
return Promise.reject(error)
}
})
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
index 27833ad3b4ae..3b308e12c3df 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
@@ -219,77 +219,77 @@ export function createAiIngestionPipeline<
.pipeBatch(
createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate)
)
+ // Per-event chain. Retry is applied per step: only the steps
+ // that do transient-failure-prone I/O (hog transform, group-type
+ // fetch, emit) retry, matching the analytics per-distinct-id path.
.sequentially((b) =>
- // Retry the per-event chain on transient failures (hog
- // transform, group-type fetch, emit), matching the
- // analytics per-distinct-id retry.
- b.retry(
- (e) =>
- e
- .pipe(createNormalizeProcessPersonFlagStep())
- .pipe(
- topHog(createHogTransformEventStep(hogTransformer), [
- sumOk(
- 'transformations_run',
- (output) => ({ team_id: String(output.team.id) }),
- (output) => output.transformationsRun
- ),
- sumOk(
- 'transformations_run_per_partition',
- (output, input) => ({
- team_id: String(output.team.id),
- partition: String(input.message.partition),
- }),
- (output) => output.transformationsRun
- ),
- sumResult(
- 'events_dropped_by_transformation',
- (_result, input) => ({
- team_id: String(input.team.id),
- }),
- (result) => (isDropResult(result) ? 1 : 0)
- ),
- sumResult(
- 'events_dropped_by_transformation_per_partition',
- (_result, input) => ({
- team_id: String(input.team.id),
- partition: String(input.message.partition),
- }),
- (result) => (isDropResult(result) ? 1 : 0)
- ),
- ])
- )
- .pipe(createNormalizeEventStep())
- .pipe(createProcessAiEventStep())
- // Read-only: drop person-update props so they don't
- // leak into person_properties (person is never written).
- .pipe(createStripPersonUpdatePropertiesStep())
- .pipe(createPrepareEventStep())
- // Read-only group-type resolution (no new group types created).
- .pipe(createReadOnlyProcessGroupsStep(groupTypeManager))
- .pipe(createCreateEventStep(EVENTS_OUTPUT))
- // Double-write to events + ai_events outputs.
- .pipe(createSplitAiEventsStep())
- .pipe(
- topHog(createEmitEventStep({ outputs }), [
- sum(
- 'emitted_events',
- (input) => ({ team_id: String(input.teamId) }),
- (input) => input.eventsToEmit.length
- ),
- sum(
- 'emitted_events_per_partition',
- (input) => ({
- team_id: String(input.teamId),
- partition: String(input.message.partition),
- }),
- (input) => input.eventsToEmit.length
- ),
- ])
- )
- .pipe(createRecordIngestionLagStep()),
- { tries: 5, sleepMs: 100, name: 'ai_event' }
- )
+ b
+ .pipe(createNormalizeProcessPersonFlagStep())
+ .pipe(
+ topHog(createHogTransformEventStep(hogTransformer), [
+ sumOk(
+ 'transformations_run',
+ (output) => ({ team_id: String(output.team.id) }),
+ (output) => output.transformationsRun
+ ),
+ sumOk(
+ 'transformations_run_per_partition',
+ (output, input) => ({
+ team_id: String(output.team.id),
+ partition: String(input.message.partition),
+ }),
+ (output) => output.transformationsRun
+ ),
+ sumResult(
+ 'events_dropped_by_transformation',
+ (_result, input) => ({
+ team_id: String(input.team.id),
+ }),
+ (result) => (isDropResult(result) ? 1 : 0)
+ ),
+ sumResult(
+ 'events_dropped_by_transformation_per_partition',
+ (_result, input) => ({
+ team_id: String(input.team.id),
+ partition: String(input.message.partition),
+ }),
+ (result) => (isDropResult(result) ? 1 : 0)
+ ),
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
+ )
+ .pipe(createNormalizeEventStep())
+ .pipe(createProcessAiEventStep())
+ // Read-only: drop person-update props so they don't
+ // leak into person_properties (person is never written).
+ .pipe(createStripPersonUpdatePropertiesStep())
+ .pipe(createPrepareEventStep())
+ // Read-only group-type resolution (no new group types created).
+ .pipe(createReadOnlyProcessGroupsStep(groupTypeManager), {
+ retry: { tries: 5, sleepMs: 100, name: 'readonly_process_groups' },
+ })
+ .pipe(createCreateEventStep(EVENTS_OUTPUT))
+ // Double-write to events + ai_events outputs.
+ .pipe(createSplitAiEventsStep())
+ .pipe(
+ topHog(createEmitEventStep({ outputs }), [
+ sum(
+ 'emitted_events',
+ (input) => ({ team_id: String(input.teamId) }),
+ (input) => input.eventsToEmit.length
+ ),
+ sum(
+ 'emitted_events_per_partition',
+ (input) => ({
+ team_id: String(input.teamId),
+ partition: String(input.message.partition),
+ }),
+ (input) => input.eventsToEmit.length
+ ),
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'emit_event' } }
+ )
+ .pipe(createRecordIngestionLagStep())
)
)
.handleIngestionWarnings(outputs)
diff --git a/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
index f81a0d86537c..7d71d3a87ffb 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.ts
@@ -61,21 +61,27 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,
}),
(result) => (isDropResult(result) ? 1 : 0)
),
- ])
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
)
.pipe(createNormalizeEventStep())
.pipe(createProcessAiEventStep())
- .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS))
+ .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS), {
+ retry: { tries: 5, sleepMs: 100, name: 'process_personless' },
+ })
.pipe(
topHog(createProcessPersonsStep(options, outputs), [
timer('process_persons_time', (input) => ({
team_id: String(input.team.id),
distinct_id: input.normalizedEvent.distinct_id,
})),
- ])
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'process_persons' } }
)
.pipe(createPrepareEventStep())
- .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options))
+ .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options), {
+ retry: { tries: 5, sleepMs: 100, name: 'process_groups' },
+ })
.pipe(createCreateEventStep(EVENTS_OUTPUT))
.pipe(createSplitAiEventsStep())
.pipe(
@@ -107,7 +113,8 @@ export function createAiEventSubpipeline<TInput extends AiEventSubpipelineInput,
(input) => input.eventsToEmit.length
),
]
- )
+ ),
+ { retry: { tries: 5, sleepMs: 100, name: 'emit_event' } }
)
.pipe(createRecordIngestionLagStep())
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
index 00e79a3c0480..19f605b92e46 100644
--- a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
@@ -100,10 +100,13 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput, TCo
}),
(result) => (isDropResult(result) ? 1 : 0)
),
- ])
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
)
.pipe(createNormalizeEventStep())
- .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS))
+ .pipe(createProcessPersonlessStep(options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS), {
+ retry: { tries: 5, sleepMs: 100, name: 'process_personless' },
+ })
.pipe(
topHog(createProcessPersonsStep(options, outputs), [
timer('process_persons_time', (input) => ({
@@ -129,10 +132,13 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput, TCo
}),
(input) => (input.normalizedEvent.event === '$groupidentify' ? 1 : 0)
),
- ])
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'process_persons' } }
)
.pipe(createPrepareEventStep())
- .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options))
+ .pipe(createProcessGroupsStep(teamManager, groupTypeManager, options), {
+ retry: { tries: 5, sleepMs: 100, name: 'process_groups' },
+ })
.pipe(createCreateEventStep(EVENTS_OUTPUT))
.pipe(
topHog(
@@ -163,7 +169,8 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput, TCo
(input) => input.eventsToEmit.length
),
]
- )
+ ),
+ { retry: { tries: 5, sleepMs: 100, name: 'emit_event' } }
)
.pipe(createRecordIngestionLagStep())
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index af440eac1ea3..031490e844de 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -263,11 +263,10 @@ export function createJoinedIngestionPipeline<
b
.teamAware((b) =>
createPostTeamPreprocessingSubpipeline(b, postTeamConfig)
- // Group by token:distinctId and process each group concurrently
- // Events within each group are processed sequentially
- .groupBy(getTokenAndDistinctId)
- .concurrently((eventsForDistinctId) =>
- eventsForDistinctId.sequentially((event) =>
+ // Group by token:distinctId and process each group concurrently.
+ // Events within each group are processed sequentially.
+ .concurrentlyPerGroup(getTokenAndDistinctId, (group) =>
+ group.sequentially((event) =>
createPerDistinctIdPipeline(event, perEventConfig)
)
)
diff --git a/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
index 8753b29dc2ba..c8cf183e06d9 100644
--- a/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
@@ -66,31 +66,29 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipeline
): PipelineBuilder<TInput, EmitEventStepOutput, TContext, AsyncOutput> {
const { options, outputs, aiSubpipelineFactory, teamManager, groupTypeManager, hogTransformer, topHog } = config
- return builder.retry(
- (e) =>
- e.branching(classifyEvent, (branches) =>
- branches
- .branch('ai', (b) =>
- aiSubpipelineFactory(b, {
- options,
- outputs,
- teamManager,
- groupTypeManager,
- hogTransformer,
- topHog,
- })
- )
- .branch('event', (b) =>
- createEventSubpipeline(b, {
- options,
- outputs,
- teamManager,
- groupTypeManager,
- hogTransformer,
- topHog,
- })
- )
- ),
- { tries: 5, sleepMs: 100, name: 'per_distinct_id' }
+ // Retry is applied per step inside each branch's subpipeline (on the I/O
+ // steps that can throw transient errors), rather than around the whole chain.
+ return builder.branching(classifyEvent, (branches) =>
+ branches
+ .branch('ai', (b) =>
+ aiSubpipelineFactory(b, {
+ options,
+ outputs,
+ teamManager,
+ groupTypeManager,
+ hogTransformer,
+ topHog,
+ })
+ )
+ .branch('event', (b) =>
+ createEventSubpipeline(b, {
+ options,
+ outputs,
+ teamManager,
+ groupTypeManager,
+ hogTransformer,
+ topHog,
+ })
+ )
)
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
index e3874c95ba92..16c81a29f99f 100644
--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
@@ -112,12 +112,14 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr
// Batch insert personless distinct IDs after prefetch (uses prefetch cache).
// 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(
+ .pipeBatch(
processPersonlessDistinctIdsBatchStep(personsPrefetchEnabled, flagCalledPersonlessDefaultTeams),
{
- tries: 5,
- sleepMs: 100,
- name: 'personless_distinct_ids',
+ retry: {
+ tries: 5,
+ sleepMs: 100,
+ name: 'personless_distinct_ids',
+ },
}
)
// Prefetch hog functions for all teams in the batch
diff --git a/nodejs/src/ingestion/pipelines/errortracking/cymbal/client.ts b/nodejs/src/ingestion/pipelines/errortracking/cymbal/client.ts
index 7888aeb947dd..d1855c9fcfd3 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/cymbal/client.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/cymbal/client.ts
@@ -128,8 +128,8 @@ function jumpConsistentHash(key: number, numBuckets: number): number {
* all events are sent to that address — no grouping overhead.
*
* Note: This client does not implement retry logic. Retries are handled at
- * the pipeline level using pipeBatchWithRetry(). The client throws CymbalError
- * with isRetriable flag to indicate whether errors should be retried.
+ * the pipeline level using pipeBatch()'s retry option. The client throws
+ * CymbalError with isRetriable flag to indicate whether errors should be retried.
*/
export class CymbalClient {
private hostname: string
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
index 8fd8f6a538f9..e9c54c66225c 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
@@ -263,10 +263,8 @@ export function createErrorTrackingPipeline(
// 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.
- .pipeBatchWithRetry(createCymbalProcessingStep(cymbalClient), {
- tries: 3,
- sleepMs: 100,
- name: 'cymbal_processing',
+ .pipeBatch(createCymbalProcessingStep(cymbalClient), {
+ retry: { tries: 3, sleepMs: 100, name: 'cymbal_processing' },
})
// Post-Cymbal team-global rate-limit chain. Drops events the team
// has explicitly capped. Empty / undefined → no-op.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
index 483d7552edf5..d41b9750c45b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
@@ -69,27 +69,23 @@ export function createMlMirrorReplayPipeline(
// Resolve retention up front (before parse), keyed on the (validated) session_id
// header; drop unresolvable sessions.
.gather()
- .pipeBatchWithRetry(createResolveRetentionStep(retentionService, sessionBatchManager), {
- tries: 3,
- sleepMs: 100,
+ .pipeBatch(createResolveRetentionStep(retentionService, sessionBatchManager), {
+ retry: { tries: 3, sleepMs: 100 },
})
// Track sessions and rate-limit new ones for the whole batch, tagging each with
// isNewSession and a gate verdict; blocked sessions are carried (not dropped) to the
// mark-seen step, all in this step's own retry scope.
- .pipeBatchWithRetry(createTrackAndGateStep(sessionTracker, sessionFilter), {
- tries: 3,
- sleepMs: 100,
+ .pipeBatch(createTrackAndGateStep(sessionTracker, sessionFilter), {
+ retry: { tries: 3, sleepMs: 100 },
})
// Resolve each session's encryption key once per session (grouped), concurrently across
// sessions with a bounded fan-out and per-session retry. Deleted sessions drop here.
- .groupBy((element) => `${element.team.teamId}:${element.headers.session_id}`)
- .concurrently(
+ .concurrentlyPerGroup(
+ (element) => `${element.team.teamId}:${element.headers.session_id}`,
(group) =>
group.sequentially((b) =>
- b.retry((rb) => rb.pipe(createResolveKeyStep(keyStore)), {
- name: 'resolve_session_key',
- tries: 3,
- sleepMs: 100,
+ b.pipe(createResolveKeyStep(keyStore), {
+ retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },
})
),
{ maxConcurrency: sessionKeyResolutionMaxConcurrency }
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
index 171c144ed6f8..d38d48bfbe4b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
@@ -129,30 +129,26 @@ export function createSessionReplayPipeline(
// recorded — keyed on the (validated) session_id header. Sessions with unresolvable
// retention are dropped before any parse or write.
.gather()
- .pipeBatchWithRetry(createResolveRetentionStep(retentionService, sessionBatchManager), {
- tries: 3,
- sleepMs: 100,
+ .pipeBatch(createResolveRetentionStep(retentionService, sessionBatchManager), {
+ retry: { tries: 3, sleepMs: 100 },
})
// Track sessions and rate-limit new ones for the whole batch, tagging the survivors with
// isNewSession and dropping the blocked ones right here (they carry no key, so nothing
// downstream acts on them). Its own retry scope means a later key-resolution failure never
// re-runs the rate limiter and double-charges the budget.
- .pipeBatchWithRetry(createTrackAndGateStep(sessionTracker, sessionFilter), {
- tries: 3,
- sleepMs: 100,
+ .pipeBatch(createTrackAndGateStep(sessionTracker, sessionFilter), {
+ retry: { tries: 3, sleepMs: 100 },
})
// Resolve each session's encryption key. Grouped by session so it runs once per session
// (the cached keystore fans the key to its other messages) and concurrently across
// sessions, capped to bound KMS/DynamoDB fan-out. Per-session retry isolates a transient
// keystore blip to that one session. Deleted sessions are dropped here.
- .groupBy((element) => `${element.team.teamId}:${element.headers.session_id}`)
- .concurrently(
+ .concurrentlyPerGroup(
+ (element) => `${element.team.teamId}:${element.headers.session_id}`,
(group) =>
group.sequentially((b) =>
- b.retry((rb) => rb.pipe(createResolveKeyStep(keyStore)), {
- name: 'resolve_session_key',
- tries: 3,
- sleepMs: 100,
+ b.pipe(createResolveKeyStep(keyStore), {
+ retry: { name: 'resolve_session_key', tries: 3, sleepMs: 100 },
})
),
{ maxConcurrency: sessionKeyResolutionMaxConcurrency }
diff --git a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
index b84041fdfd23..7681242e6a8b 100644
--- a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
+++ b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
@@ -356,11 +356,10 @@ class Harness {
.filterMap(addTeamToContext, (fb) =>
fb
.teamAware((tb) =>
- tb
- .groupBy((event) => event.key)
- .concurrently((group) =>
- group.sequentially((s) => s.pipe(processEventStep))
- )
+ tb.concurrentlyPerGroup(
+ (event) => event.key,
+ (group) => group.sequentially((s) => s.pipe(processEventStep))
+ )
)
.handleIngestionWarnings(this.outputs)
)
diff --git a/nodejs/tests/ingestion/framework/pipelines.integration.test.ts b/nodejs/tests/ingestion/framework/pipelines.integration.test.ts
index 34299160a395..9a6c5b5ad18c 100644
--- a/nodejs/tests/ingestion/framework/pipelines.integration.test.ts
+++ b/nodejs/tests/ingestion/framework/pipelines.integration.test.ts
@@ -11,7 +11,7 @@ import {
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'
import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'
-import { createBatch, createNewPipeline, createUnwrapper } from '~/ingestion/framework/helpers'
+import { createBatch, createUnwrapper } from '~/ingestion/framework/helpers'
import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
import { PipelineResult, dlq, drop, ok, redirect } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
@@ -271,11 +271,13 @@ describe('Pipeline Integration Tests', () => {
const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1).pipe(step2).pipe(step3)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep4)
+ builder
+ .concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3))
+ .gather()
+ .pipeBatch(batchStep4)
)
.handleResults(pipelineConfig)
.handleSideEffects(mockPromiseScheduler, { await: true })
@@ -351,11 +353,13 @@ describe('Pipeline Integration Tests', () => {
)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep2)
+ builder
+ .concurrently((b) => b.pipe(step1))
+ .gather()
+ .pipeBatch(batchStep2)
)
.handleResults(pipelineConfig)
.handleSideEffects(mockPromiseScheduler, { await: true })
@@ -418,11 +422,13 @@ describe('Pipeline Integration Tests', () => {
)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep2)
+ builder
+ .concurrently((b) => b.pipe(step1))
+ .gather()
+ .pipeBatch(batchStep2)
)
.handleResults(pipelineConfig)
.handleSideEffects(mockPromiseScheduler, { await: true })
@@ -494,11 +500,13 @@ describe('Pipeline Integration Tests', () => {
>(batchStep2Map)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep2)
+ builder
+ .concurrently((b) => b.pipe(step1))
+ .gather()
+ .pipeBatch(batchStep2)
)
.handleResults(pipelineConfig)
.handleSideEffects(mockPromiseScheduler, { await: true })
@@ -680,11 +688,13 @@ describe('Pipeline Integration Tests', () => {
const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1).pipe(step2).pipe(step3)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep4)
+ builder
+ .concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3))
+ .gather()
+ .pipeBatch(batchStep4)
)
.handleResults(pipelineConfig)
.handleSideEffects(mockPromiseScheduler, { await: true })
@@ -847,11 +857,13 @@ describe('Pipeline Integration Tests', () => {
const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1).pipe(step2).pipe(step3)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep4)
+ builder
+ .concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3))
+ .gather()
+ .pipeBatch(batchStep4)
)
.handleResults(pipelineConfig)
.handleSideEffects(mockPromiseScheduler, { await: true })
@@ -995,11 +1007,13 @@ describe('Pipeline Integration Tests', () => {
const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1).pipe(step2).pipe(step3)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep4)
+ builder
+ .concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3))
+ .gather()
+ .pipeBatch(batchStep4)
)
.handleResults({
outputs: mockOutputs,
@@ -1154,12 +1168,11 @@ describe('Pipeline Integration Tests', () => {
const batchStep3 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep3Map)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
builder
- .pipeConcurrently(preprocessingPipeline)
+ .concurrently((b) => b.pipe(step1))
.gather()
.pipeBatch(batchStep1)
.pipeBatch(batchStep2)
@@ -1259,10 +1272,9 @@ describe('Pipeline Integration Tests', () => {
)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1).pipe(step2)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
- .messageAware((builder) => builder.pipeConcurrently(preprocessingPipeline).gather())
+ .messageAware((builder) => builder.concurrently((b) => b.pipe(step1).pipe(step2)).gather())
.handleResults({
outputs: mockOutputs,
promiseScheduler: mockPromiseScheduler,
@@ -1288,7 +1300,7 @@ describe('Pipeline Integration Tests', () => {
})
describe('Concurrent Processing', () => {
- it('should preserve ordering with pipeConcurrently and gather using deterministic mocks', async () => {
+ it('should preserve ordering with concurrently and gather using deterministic mocks', async () => {
const messages: Message[] = [
{
topic: 'test-topic',
@@ -1373,10 +1385,9 @@ describe('Pipeline Integration Tests', () => {
const step1 = createMockStep<{ message: Message }, { message: Message; headers: TestHeaders }>(step1Map)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1).pipe(step2)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
- .messageAware((builder) => builder.pipeConcurrently(preprocessingPipeline).gather())
+ .messageAware((builder) => builder.concurrently((b) => b.pipe(step1).pipe(step2)).gather())
.handleResults({
outputs: mockOutputs,
promiseScheduler: mockPromiseScheduler,
@@ -1639,11 +1650,13 @@ describe('Pipeline Integration Tests', () => {
const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)
// Create pipeline
- const preprocessingPipeline = createNewPipeline().pipe(step1).pipe(step2).pipe(step3)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep4)
+ builder
+ .concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3))
+ .gather()
+ .pipeBatch(batchStep4)
)
.handleResults(pipelineConfig)
.handleSideEffects(mockPromiseScheduler, { await: true })
@@ -1904,11 +1917,13 @@ describe('Pipeline Integration Tests', () => {
const batchStep2 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep2Map)
// Create pipeline with single async step
- const preprocessingPipeline = createNewPipeline().pipe(step1)
const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()
.messageAware((builder) =>
- builder.pipeConcurrently(preprocessingPipeline).gather().pipeBatch(batchStep2)
+ builder
+ .concurrently((b) => b.pipe(step1))
+ .gather()
+ .pipeBatch(batchStep2)
)
.handleResults(pipelineConfig)
.handleSideEffects(mockPromiseScheduler, { await: true })