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(replay): let a lane overlap poll batches across exclusive stages (#101782)

Robbie776653a3558b
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/batch-stages.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/batch-stages.test.ts
new file mode 100644
index 000000000000..538d2f359a0d
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/batch-stages.test.ts
@@ -0,0 +1,210 @@
+import { BatchStages } from './batch-stages'
+import { SessionRecordingIngesterMetrics } from './metrics'
+
+describe('BatchStages', () => {
+ function gate(): { promise: Promise<void>; release: () => void } {
+ let release!: () => void
+ const promise = new Promise<void>((resolve) => (release = resolve))
+ return { promise, release }
+ }
+
+ async function until(condition: () => boolean): Promise<void> {
+ for (let i = 0; i < 1000 && !condition(); i++) {
+ await new Promise(setImmediate)
+ }
+ if (!condition()) {
+ throw new Error('condition not reached')
+ }
+ }
+
+ /** Settles to the resolved value or the rejection reason, so an expected failure is never an unhandled rejection. */
+ function settled<T>(promise: Promise<T>): Promise<T | unknown> {
+ return promise.then(
+ (value) => value,
+ (error) => error
+ )
+ }
+
+ it('lets the next batch into an earlier stage while the current batch holds a later one, and never two batches into one stage', async () => {
+ const stages = new BatchStages(['load', 'process'])
+ const events: string[] = []
+ const holdLoadOfFirst = gate()
+ const holdProcessOfFirst = gate()
+ const run = (id: number, holdLoad?: Promise<void>, holdProcess?: Promise<void>): Promise<number> =>
+ stages
+ .admit()
+ .stage('load', async () => {
+ events.push(`load ${id}`)
+ await holdLoad
+ return id
+ })
+ .stage('process', async (loaded) => {
+ events.push(`process ${id} start`)
+ await holdProcess
+ events.push(`process ${id} end`)
+ return loaded
+ })
+ .done()
+
+ const first = run(1, holdLoadOfFirst.promise, holdProcessOfFirst.promise)
+ const second = run(2)
+ await until(() => events.includes('load 1'))
+ await new Promise(setImmediate)
+ expect(events).toEqual(['load 1'])
+
+ holdLoadOfFirst.release()
+ await until(() => events.includes('load 2') && events.includes('process 1 start'))
+ await new Promise(setImmediate)
+ expect(events).not.toContain('process 2 start')
+
+ holdProcessOfFirst.release()
+ await expect(Promise.all([first, second])).resolves.toEqual([1, 2])
+ expect(events.filter((event) => event.startsWith('process'))).toEqual([
+ 'process 1 start',
+ 'process 1 end',
+ 'process 2 start',
+ 'process 2 end',
+ ])
+ })
+
+ it('stops the batches in flight behind a failed one at their next stage, lets the batch ahead finish, and admits new batches after it', async () => {
+ const stages = new BatchStages(['load', 'process'])
+ const holdProcessOfFirst = gate()
+ let secondLoadFailed = false
+ const loaded = new Set<number>()
+ const admitAfter = (id: number): Promise<unknown> =>
+ settled(
+ stages
+ .admit()
+ .stage('load', () => {
+ loaded.add(id)
+ return Promise.resolve()
+ })
+ .stage('process', () => Promise.resolve())
+ .done()
+ )
+
+ const first = stages
+ .admit()
+ .stage('load', () => Promise.resolve())
+ .stage('process', () => holdProcessOfFirst.promise)
+ .done()
+ const second = settled(
+ stages
+ .admit()
+ .stage('load', () => {
+ secondLoadFailed = true
+ return Promise.reject(new Error('broken'))
+ })
+ .stage('process', () => Promise.resolve())
+ .done()
+ )
+ const third = admitAfter(3)
+
+ await until(() => secondLoadFailed)
+ await new Promise(setImmediate)
+ expect(loaded.size).toBe(0)
+
+ // The rejections surface through the process stage, which sits behind the first batch until it is released.
+ holdProcessOfFirst.release()
+ await expect(first).resolves.toBeUndefined()
+ await expect(second).resolves.toEqual(new Error('broken'))
+ await expect(third).resolves.toEqual(new Error('broken'))
+ expect(loaded.size).toBe(0)
+
+ // Whether to admit anything after a failure is the consumer's call, so a batch admitted afterwards runs.
+ await expect(admitAfter(4)).resolves.toBeUndefined()
+ expect(loaded).toEqual(new Set([4]))
+ })
+
+ it('stops a later batch at its next stage when an earlier batch fails in a later stage while the later batch is mid-stage', async () => {
+ const stages = new BatchStages(['load', 'process'])
+ const holdLoadOfSecond = gate()
+ let secondProcessed = false
+
+ const first = settled(
+ stages
+ .admit()
+ .stage('load', () => Promise.resolve())
+ .stage('process', () => {
+ throw new Error('broken in process')
+ })
+ .done()
+ )
+ const second = settled(
+ stages
+ .admit()
+ .stage('load', () => holdLoadOfSecond.promise)
+ .stage('process', () => {
+ secondProcessed = true
+ return Promise.resolve()
+ })
+ .done()
+ )
+
+ await expect(first).resolves.toEqual(new Error('broken in process'))
+ holdLoadOfSecond.release()
+ await expect(second).resolves.toEqual(new Error('broken in process'))
+ expect(secondProcessed).toBe(false)
+ })
+
+ it('records a wait and a duration for every stage of every batch', async () => {
+ const stages = new BatchStages(['load', 'process'])
+ const countOf = async (metric: string, stage: string): Promise<number> => {
+ const collected = await (SessionRecordingIngesterMetrics as any)[metric].get()
+ return collected.values.find(
+ (v: { metricName: string; labels: { stage: string } }) =>
+ v.metricName.endsWith('_count') && v.labels.stage === stage
+ )?.value as number
+ }
+ const before = await countOf('batchStageDuration', 'process')
+ const waitBefore = await countOf('batchStageWait', 'load')
+
+ await stages
+ .admit()
+ .stage('load', () => Promise.resolve())
+ .stage('process', () => Promise.resolve())
+ .done()
+
+ expect(await countOf('batchStageDuration', 'process')).toBe((before ?? 0) + 1)
+ expect(await countOf('batchStageWait', 'load')).toBe((waitBefore ?? 0) + 1)
+ })
+
+ it.each([
+ ['two stages with the same name', () => new BatchStages(['load', 'load']), 'unique stage names'],
+ ['no stages', () => new BatchStages([]), 'at least one stage'],
+ [
+ 'a stage entered out of the declared order',
+ () => new BatchStages(['load', 'process']).admit().stage('process', () => Promise.resolve()),
+ "stage 0 is 'load'",
+ ],
+ [
+ 'a stage entered past the last one',
+ () =>
+ new BatchStages(['load'])
+ .admit()
+ .stage('load', () => Promise.resolve())
+ .stage('load', () => Promise.resolve()),
+ "stage 1 is 'none'",
+ ],
+ ])('rejects %s', (_case, build, message) => {
+ expect(build).toThrow(message)
+ })
+
+ it('rejects a batch that finishes before its last stage', async () => {
+ const stages = new BatchStages(['load', 'process'])
+ await expect(
+ stages
+ .admit()
+ .stage('load', () => Promise.resolve())
+ .done()
+ ).rejects.toThrow("after 1 of 2 stages, before 'process'")
+ })
+
+ it('rejects a stage queued after the tick that admitted the batch, because a later batch could enter it first', async () => {
+ const stages = new BatchStages(['load'])
+ const batch = stages.admit()
+ await Promise.resolve()
+ expect(() => batch.stage('load', () => Promise.resolve())).toThrow('after the tick that admitted it')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/batch-stages.ts b/nodejs/src/ingestion/pipelines/sessionreplay/batch-stages.ts
new file mode 100644
index 000000000000..de320e56010c
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/batch-stages.ts
@@ -0,0 +1,125 @@
+import pLimit from 'p-limit'
+
+import { SessionRecordingIngesterMetrics } from './metrics'
+
+type Timed<T> = { value: T; finishedAt: number }
+
+/** Open during the tick that admits the batch. The batch must queue all of its stages before the tick ends. If it queues a stage later, a later batch can enter that stage first. */
+type Admission = { sequence: number; open: boolean }
+
+/**
+ * Admits poll batches to a fixed sequence of stages. Each stage holds one batch at a time. Batches pass
+ * through every stage in admission order. Two batches can be in two different stages at the same time,
+ * so a stage that waits on I/O runs while another stage uses the CPU. A later batch never delays an
+ * earlier batch in the same stage.
+ */
+export class BatchStages {
+ private readonly limiters: Map<string, ReturnType<typeof pLimit>>
+ // When a batch fails, the batches behind it must not run more stages. Their offsets would go past the messages of the failed batch, and the consumer stores the tracked offsets when it stops. The batches ahead of the failed batch complete, because their work is complete and in order. The consumer decides whether to admit a batch after the failure, as it does for a lane that does not overlap batches.
+ private failure: { sequence: number; lastAdmitted: number; error: unknown } | null = null
+ private nextSequence = 0
+
+ constructor(private readonly names: readonly string[]) {
+ if (!names.length) {
+ throw new Error('BatchStages needs at least one stage')
+ }
+ if (new Set(names).size !== names.length) {
+ throw new Error(`BatchStages needs unique stage names, got ${names.join(', ')}`)
+ }
+ this.limiters = new Map(names.map((name) => [name, pLimit(1)]))
+ }
+
+ /** The most batches that can be in flight at the same time: one for each stage. */
+ public get lookahead(): number {
+ return this.names.length
+ }
+
+ /** Admits one batch after all the batches admitted before it. Queue all of its stages in the same tick. */
+ public admit(): AdmittedBatch<void> {
+ const admission: Admission = { sequence: this.nextSequence++, open: true }
+ queueMicrotask(() => (admission.open = false))
+ return new AdmittedBatch(
+ this,
+ admission,
+ 0,
+ Promise.resolve({ value: undefined, finishedAt: performance.now() })
+ )
+ }
+
+ /** @internal Called through {@link AdmittedBatch.stage}. */
+ public enter<T, U>(
+ admission: Admission,
+ index: number,
+ name: string,
+ previous: Promise<Timed<T>>,
+ work: (input: T) => Promise<U>
+ ): Promise<Timed<U>> {
+ if (!admission.open) {
+ throw new Error(`Batch queued stage '${name}' after the tick that admitted it`)
+ }
+ if (this.names[index] !== name) {
+ throw new Error(`Batch entered stage '${name}' but stage ${index} is '${this.names[index] ?? 'none'}'`)
+ }
+ const limiter = this.limiters.get(name)!
+ // The batch takes the slot while it is still in its previous stage. No other batch can use the slot, because the next batch is still behind this batch in that previous stage.
+ return limiter(async () => {
+ const { value, finishedAt: readyAt } = await previous
+ if (
+ this.failure &&
+ admission.sequence > this.failure.sequence &&
+ admission.sequence <= this.failure.lastAdmitted
+ ) {
+ throw this.failure.error
+ }
+ const startedAt = performance.now()
+ try {
+ const result = await work(value)
+ const finishedAt = performance.now()
+ SessionRecordingIngesterMetrics.observeBatchStage(name, startedAt - readyAt, finishedAt - startedAt)
+ return { value: result, finishedAt }
+ } catch (error) {
+ if (!this.failure || admission.sequence < this.failure.sequence) {
+ this.failure = { sequence: admission.sequence, lastAdmitted: this.nextSequence - 1, error }
+ }
+ throw error
+ }
+ })
+ }
+
+ /** @internal Called through {@link AdmittedBatch.done}. */
+ public assertComplete(index: number): void {
+ if (index !== this.names.length) {
+ throw new Error(
+ `Batch finished after ${index} of ${this.names.length} stages, before '${this.names[index]}'`
+ )
+ }
+ }
+}
+
+/** One admitted batch that moves through the stages. The output of each stage is the input of the next stage. */
+export class AdmittedBatch<T> {
+ constructor(
+ private readonly stages: BatchStages,
+ private readonly admission: Admission,
+ private readonly index: number,
+ private readonly previous: Promise<Timed<T>>
+ ) {}
+
+ /** Queues the batch for its next stage. The work starts when the batch leaves the previous stage and the next stage is free. */
+ public stage<U>(name: string, work: (input: T) => Promise<U>): AdmittedBatch<U> {
+ const next = this.stages.enter(this.admission, this.index, name, this.previous, work)
+ // The rejection reaches the caller through the last stage. The promise of an earlier stage must not count as unhandled while the batch waits for a slot.
+ next.catch(() => undefined)
+ return new AdmittedBatch(this.stages, this.admission, this.index + 1, next)
+ }
+
+ /** Resolves when the batch leaves the last stage. Rejects with the error of this batch, with the error of an earlier batch that failed, or with an error if the batch did not queue all of its stages. */
+ public done(): Promise<T> {
+ try {
+ this.stages.assertComplete(this.index)
+ } catch (error) {
+ return Promise.reject(error)
+ }
+ return this.previous.then(({ value }) => value)
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts
index df1fa86bf904..6cd4dfeb860f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts
@@ -11,11 +11,22 @@ import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionrepla
import { RedisPool } from '~/types'
import { getDefaultSessionRecordingApiConfig, getDefaultSessionRecordingConfig } from './config'
-import { SessionRecordingIngester, SessionRecordingIngesterConfig } from './consumer'
+import {
+ SessionRecordingIngester,
+ SessionRecordingIngesterCollaborators,
+ SessionRecordingIngesterConfig,
+} from './consumer'
import { BlackholeSessionBatchFileStorage } from './sessions/blackhole-session-batch-writer'
+import { SessionBatchRecorder } from './sessions/session-batch-recorder'
+import { BatchCommitter, StagedBatchRunner } from './staged-batch'
+
+const mockKafkaConsumerConfigs: Record<string, unknown>[] = []
jest.mock('~/common/kafka/consumer/consumer-v2', () => {
class FakeKafkaConsumerV2 {
+ constructor(config: Record<string, unknown>) {
+ mockKafkaConsumerConfigs.push(config)
+ }
public connect = jest.fn().mockResolvedValue(undefined)
public stopConsuming = jest.fn().mockResolvedValue(undefined)
public disconnect = jest.fn().mockResolvedValue(undefined)
@@ -73,7 +84,10 @@ describe('SessionRecordingIngester', () => {
const consumeTopic = getDefaultSessionRecordingConfig().INGESTION_SESSION_REPLAY_CONSUMER_CONSUME_TOPIC
- const createIngester = (configOverrides: Partial<SessionRecordingIngesterConfig> = {}): void => {
+ const createIngester = (
+ configOverrides: Partial<SessionRecordingIngesterConfig> = {},
+ collaborators: Partial<SessionRecordingIngesterCollaborators> = {}
+ ): void => {
const config: SessionRecordingIngesterConfig = {
...getDefaultSessionRecordingConfig(),
...getDefaultSessionRecordingApiConfig(),
@@ -111,6 +125,7 @@ describe('SessionRecordingIngester', () => {
keyStore: fakeKeyStore,
encryptor: fakeEncryptor,
createPipeline: () => ({}) as unknown as SessionReplayPipeline,
+ ...collaborators,
}
)
@@ -273,4 +288,156 @@ describe('SessionRecordingIngester', () => {
await ingester.stop()
})
+
+ it('passes the consumer no background task options for a runner with one stage', () => {
+ expect(mockKafkaConsumerConfigs.at(-1)).not.toHaveProperty('maxBackgroundTasks')
+ expect(mockKafkaConsumerConfigs.at(-1)).not.toHaveProperty('backgroundTaskTimeoutMs')
+ })
+
+ describe('with a runner of one stage', () => {
+ let runner: StagedBatchRunner
+
+ beforeEach(() => {
+ runner = { stages: ['ingest'], start: jest.fn(), run: jest.fn() }
+ createIngester({}, { runner })
+ })
+
+ it('completes the batch inside handleEachBatch and returns no task', async () => {
+ const done = deferred()
+ runner.run = (_messages, batch) => batch.stage('ingest', () => done.promise).done()
+ await ingester.start()
+
+ let returned: unknown = 'pending'
+ const handled = ingester.handleEachBatch([kafkaMessage(0, 42)]).then((result) => (returned = result))
+ await flushMicrotasks()
+ expect(returned).toBe('pending')
+
+ done.resolve()
+ await handled
+ expect(returned).toBeUndefined()
+ await ingester.stop()
+ })
+ })
+
+ describe('with a runner of several stages', () => {
+ let runner: StagedBatchRunner
+
+ beforeEach(() => {
+ runner = { stages: ['prepare', 'ingest'], start: jest.fn(), run: jest.fn() }
+ createIngester({}, { runner })
+ })
+
+ it('keeps one batch per stage in flight at the consumer', () => {
+ expect(mockKafkaConsumerConfigs.at(-1)).toMatchObject({ maxBackgroundTasks: 2 })
+ })
+
+ it('returns each poll batch as a background task, and tells the write which partitions are held under the lock', async () => {
+ const writtenInto: SessionBatchRecorder[] = []
+ const ownership: boolean[][] = []
+ runner.run = (messages, batch, committer) =>
+ batch
+ .stage('prepare', () => Promise.resolve())
+ .stage('ingest', () =>
+ committer.commit((recorder, isAssigned) => {
+ writtenInto.push(recorder)
+ ownership.push([isAssigned(0), isAssigned(1)])
+ const held = messages.filter((m) => isAssigned(m.partition))
+ return Promise.resolve({
+ maxOffsets: new Map(held.map((m) => [m.partition, m.offset])),
+ okMessages: held,
+ })
+ })
+ )
+ .done()
+ jest.mocked(ingester.kafkaConsumer).assignments.mockReturnValue([{ topic: consumeTopic, partition: 0 }])
+ await ingester.start()
+ expect(runner.start).toHaveBeenCalledTimes(1)
+
+ const result = await ingester.handleEachBatch([kafkaMessage(0, 42), kafkaMessage(1, 7)])
+
+ expect(result).toEqual({ backgroundTask: expect.any(Promise) })
+ await result!.backgroundTask
+ expect(runPipelineMock).not.toHaveBeenCalled()
+ expect(ownership).toEqual([[true, false]])
+ expect(writtenInto).toHaveLength(1)
+
+ await ingester.stop()
+ expect(jest.mocked(ingester.kafkaConsumer).offsetsStore).toHaveBeenCalledWith([
+ { topic: consumeTopic, partition: 0, offset: 43 },
+ ])
+ })
+
+ it('answers a known retention from the batch current at the time of the call, not the one current when the batch was admitted', async () => {
+ createIngester({ SESSION_RECORDING_MAX_BATCH_AGE_MS: 0 }, { runner })
+ let committer!: BatchCommitter
+ runner.run = (_messages, batch, handedCommitter) => {
+ committer = handedCommitter
+ return batch
+ .stage('prepare', () => Promise.resolve())
+ .stage('ingest', () =>
+ committer.commit(() => Promise.resolve({ maxOffsets: new Map(), okMessages: [] }))
+ )
+ .done()
+ }
+ await ingester.start()
+ const admittedInto = ingester['currentBatch']
+ jest.spyOn(admittedInto, 'getRetention').mockReturnValue('90d')
+
+ // The age trigger flushes inside this commit, so the batch current afterwards is a new one.
+ await (await ingester.handleEachBatch([kafkaMessage(0, 42)]))!.backgroundTask
+ const flushedInto = ingester['currentBatch']
+ expect(flushedInto).not.toBe(admittedInto)
+ jest.spyOn(flushedInto, 'getRetention').mockReturnValue('30d')
+
+ expect(committer.knownRetention(1, 'session')).toBe('30d')
+ expect(admittedInto.getRetention).not.toHaveBeenCalled()
+ await ingester.stop()
+ })
+
+ it('tracks the offsets of a commit under the same lock as its write, so a revoke flush queued behind it stores them', async () => {
+ const writeEntered = deferred()
+ const writeGate = deferred()
+ runner.run = (messages, batch, committer) =>
+ batch
+ .stage('prepare', () => Promise.resolve())
+ .stage('ingest', () =>
+ committer.commit(async () => {
+ writeEntered.resolve()
+ await writeGate.promise
+ return { maxOffsets: new Map([[0, 42]]), okMessages: messages }
+ })
+ )
+ .done()
+ jest.mocked(ingester.kafkaConsumer).assignments.mockReturnValue([{ topic: consumeTopic, partition: 0 }])
+ await ingester.start()
+ const onPartitionsRevoked = jest.mocked(ingester.kafkaConsumer).connect.mock.calls[0][1]!
+ const manager = ingester['sessionBatchManager']
+ const trackProcessedOffsets = manager.trackProcessedOffsets.bind(manager)
+ jest.spyOn(manager, 'trackProcessedOffsets').mockImplementation((offsets) => {
+ events.push('offsets_tracked')
+ trackProcessedOffsets(offsets)
+ })
+ const batchBeingWritten = ingester['currentBatch']
+ const flush = batchBeingWritten.flush.bind(batchBeingWritten)
+ batchBeingWritten.flush = () => {
+ events.push('flush_started')
+ return flush()
+ }
+
+ const result = await ingester.handleEachBatch([kafkaMessage(0, 42)])
+ await writeEntered.promise
+ // Models a revoke whose drain timed out: its flush queues on the batch lock while the commit still holds it.
+ const revoked = onPartitionsRevoked([{ topic: consumeTopic, partition: 0 }])
+ await flushMicrotasks()
+ writeGate.resolve()
+ await result!.backgroundTask
+ await revoked
+ await ingester.stop()
+
+ expect(events).toEqual(['offsets_tracked', 'flush_started', 'offsets_stored', 'disconnected'])
+ expect(jest.mocked(ingester.kafkaConsumer).offsetsStore).toHaveBeenCalledWith([
+ { topic: consumeTopic, partition: 0, offset: 43 },
+ ])
+ })
+ })
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
index 43ceb5821ec8..514a00f4c29a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
@@ -2,7 +2,7 @@ import { Message, TopicPartition, TopicPartitionOffset, features, librdkafkaVers
import pLimit from 'p-limit'
import { buildIntegerMatcher } from '~/common/config/config'
-import { KafkaConsumerV2 } from '~/common/kafka/consumer/consumer-v2'
+import { EachBatchResult, KafkaConsumerV2 } from '~/common/kafka/consumer/consumer-v2'
import { DlqOutput, IngestionWarningsOutput, LogEntriesOutput, OverflowOutput, TophogOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { instrumentFn } from '~/common/tracing/tracing-utils'
@@ -17,12 +17,7 @@ import { logger } from '~/common/utils/logger'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { IngestionConsumerConfig } from '~/ingestion/config'
import { TopHog } from '~/ingestion/framework/tophog/tophog'
-import {
- SessionReplayPipeline,
- SessionReplayPipelineConfig,
- createSessionReplayPipeline,
- runSessionReplayPipeline,
-} from '~/ingestion/pipelines/sessionreplay'
+import { SessionReplayPipelineConfig, createSessionReplayPipeline } from '~/ingestion/pipelines/sessionreplay'
import { getBlockEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/crypto'
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
import { getKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore'
@@ -38,10 +33,12 @@ import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/te
import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { HealthCheckResult, PluginServerService, RedisPool, ValueMatcher } from '~/types'
+import { BatchStages } from './batch-stages'
import { SessionRecordingApiConfig, SessionRecordingConfig } from './config'
import { KafkaOffsetManager } from './kafka/offset-manager'
import { SessionRecordingIngesterMetrics } from './metrics'
import { SessionReplayLagReporter } from './session-replay-lag-reporter'
+import { SessionReplayPipelineFactory, SessionReplayPipelineRunner } from './session-replay-pipeline-runner'
import { BlackholeSessionBatchFileStorage } from './sessions/blackhole-session-batch-writer'
import { RetentionAwareStorage } from './sessions/retention-aware-batch-writer'
import { SessionBatchFileStorage } from './sessions/session-batch-file-storage'
@@ -50,6 +47,12 @@ import { SessionBatchRecorder } from './sessions/session-batch-recorder'
import { SessionConsoleLogStore } from './sessions/session-console-log-store'
import { SessionFilter } from './sessions/session-filter'
import { SessionTracker } from './sessions/session-tracker'
+import {
+ BatchCommitter,
+ STAGED_BATCH_REBALANCE_TIMEOUT_MS,
+ STAGED_BATCH_TIMEOUT_MS,
+ StagedBatchRunner,
+} from './staged-batch'
/**
* Configuration for SessionRecordingIngester.
@@ -64,9 +67,6 @@ export type SessionRecordingIngesterConfig = SessionRecordingConfig &
'INGESTION_OVERFLOW_MODE' | 'INGESTION_PIPELINE' | 'INGESTION_LANE'
>
-/** Builds the session replay pipeline for a deployment (default or ML mirror). */
-export type SessionReplayPipelineFactory = (config: SessionReplayPipelineConfig) => SessionReplayPipeline
-
/** Collaborators a deployment can inject to vary ingester behavior; anything omitted uses the primary default. */
export interface SessionRecordingIngesterCollaborators {
fileStorage?: SessionBatchFileStorage
@@ -76,6 +76,8 @@ export interface SessionRecordingIngesterCollaborators {
keyStore?: KeyStore
encryptor?: RecordingEncryptor
createPipeline?: SessionReplayPipelineFactory
+ /** Runs each poll batch through its stages. If omitted, the session replay pipeline runs in one stage. A lane that overlaps batches supplies a runner with more stages. The consumer then keeps one batch in flight for each stage. */
+ runner?: StagedBatchRunner
/**
* Namespaces this ingester's session tracker/filter Redis keys. Leave unset for the main lane; a
* secondary lane (the ML mirror) must set it so it doesn't share seen/block state with the main lane
@@ -113,7 +115,6 @@ export class SessionRecordingIngester {
private readonly eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponent
private eventIngestionRestrictionManager!: EventIngestionRestrictionManager
private stopEventIngestionRestrictionManager?: () => Promise<void>
- private sessionReplayPipeline!: SessionReplayPipeline
private readonly outputs: IngestionOutputs<
| IngestionWarningsOutput
| DlqOutput
@@ -128,7 +129,8 @@ export class SessionRecordingIngester {
private readonly sessionFilter: SessionFilter
private readonly keyStore: KeyStore
private readonly encryptor: RecordingEncryptor
- private readonly createPipeline: SessionReplayPipelineFactory
+ private readonly runner: StagedBatchRunner
+ private readonly batchStages: BatchStages
private readonly usageBatch: UsageRecordBatch
constructor(
@@ -157,6 +159,13 @@ export class SessionRecordingIngester {
isTeamEnabled: usageReportTeamMatcher(config),
})
+ this.runner =
+ collaborators.runner ??
+ new SessionReplayPipelineRunner(
+ collaborators.createPipeline ?? createSessionReplayPipeline,
+ this.promiseScheduler
+ )
+ this.batchStages = new BatchStages(this.runner.stages)
// The v2 consumer defers the unassign on revoke until in-flight work is drained and the
// revoke hook has run, so a revoke can flush the current batch (persisting sessions and
// storing offsets) before the revoked partitions are given up.
@@ -166,6 +175,13 @@ export class SessionRecordingIngester {
callEachBatchWhenEmpty: true,
autoCommit: true,
autoOffsetStore: false,
+ ...(this.batchStages.lookahead > 1
+ ? {
+ maxBackgroundTasks: this.batchStages.lookahead,
+ backgroundTaskTimeoutMs: STAGED_BATCH_TIMEOUT_MS,
+ rebalanceTimeoutMs: STAGED_BATCH_REBALANCE_TIMEOUT_MS,
+ }
+ : {}),
})
this.redisPool = redisPool
@@ -191,7 +207,6 @@ export class SessionRecordingIngester {
this.retentionService = new RetentionService(this.redisPool, this.teamService)
const offsetManager = new KafkaOffsetManager(this.commitOffsets.bind(this), this.topic)
- this.createPipeline = collaborators.createPipeline ?? createSessionReplayPipeline
const metadataStore = collaborators.metadataStore ?? new SessionMetadataStore(outputs)
const consoleLogStore =
collaborators.consoleLogStore ??
@@ -266,7 +281,7 @@ export class SessionRecordingIngester {
}
}
- public async handleEachBatch(messages: Message[]): Promise<void> {
+ public async handleEachBatch(messages: Message[]): Promise<EachBatchResult> {
if (messages.length > 0) {
logger.info('🔁', `blob_ingester_consumer_v2 - handling batch`, {
size: messages.length,
@@ -275,16 +290,6 @@ export class SessionRecordingIngester {
})
}
- await instrumentFn(
- {
- key: `recordingingesterv2.handleEachBatch`,
- sendException: false,
- },
- async () => this.processBatchMessages(messages)
- )
- }
-
- private async processBatchMessages(messages: Message[]): Promise<void> {
messages.forEach((message) => {
SessionRecordingIngesterMetrics.incrementMessageReceived(message.partition)
})
@@ -294,29 +299,35 @@ export class SessionRecordingIngester {
SessionRecordingIngesterMetrics.observeKafkaBatchSize(batchSize)
SessionRecordingIngesterMetrics.observeKafkaBatchSizeKb(batchSizeKb)
- // Run messages through the pipeline (handles restrictions, parsing, team filtering, and recording)
- // and track the highest offset reached per partition — the single place Kafka progress is tracked.
- // Recording holds the batch lock so a concurrent revoke can't flush the batch mid-record.
- const { maxOffsets, okMessages } = await instrumentFn(
- `recordingingesterv2.handleEachBatch.runPipeline`,
- async () =>
- this.batchLock(() =>
- runSessionReplayPipeline(
- this.sessionReplayPipeline,
- messages,
- this.currentBatch,
- this.promiseScheduler
- )
- )
- )
- this.sessionBatchManager.trackProcessedOffsets(maxOffsets)
- // Buffer capture timestamps of the recorded (OK) messages; lag is reported once the batch is
- // durably flushed and committed.
- this.lagReporter.record(okMessages)
-
- if (this.sessionBatchManager.shouldFlush(this.currentBatch, this.lastFlushTime)) {
- await this.flushCurrentBatch()
+ const batch = this.runner.run(messages, this.batchStages.admit(), this.committer)
+ // A runner with one stage cannot overlap batches. The batch completes inside this call, which is what the consumer expects from a lane that returns no task.
+ if (this.batchStages.lookahead === 1) {
+ await instrumentFn({ key: `recordingingesterv2.handleEachBatch`, sendException: false }, () => batch)
+ return
}
+ return { backgroundTask: batch }
+ }
+
+ // A batch that is still in flight after a revoke drain must not write or report offsets for the partitions that this pod released. The new owner replays those partitions. The committer tells the write which partitions the pod holds, and the write reports progress for those partitions only.
+ private readonly committer: BatchCommitter = {
+ knownRetention: (teamId, sessionId) => this.currentBatch.getRetention(teamId, sessionId),
+ commit: async (write) => {
+ // The write holds the batch lock, so a revoke cannot flush the batch during the write. The committer takes the ownership snapshot under the lock, immediately before the write, because a revoke whose drain timed out can release a partition while this commit waits for the lock. The committer tracks the offsets under the same lock, so a revoke flush that waits behind this commit stores them together with the data.
+ const { okMessages } = await instrumentFn(`recordingingesterv2.handleEachBatch.runPipeline`, () =>
+ this.batchLock(async () => {
+ const assigned = new Set(this.assignedPartitions)
+ const progress = await write(this.currentBatch, (partition) => assigned.has(partition))
+ this.sessionBatchManager.trackProcessedOffsets(progress.maxOffsets)
+ return progress
+ })
+ )
+ // Buffer the capture timestamps of the written (OK) messages. The lag report waits until the batch
+ // is flushed and its offsets are committed.
+ this.lagReporter.record(okMessages)
+ if (this.sessionBatchManager.shouldFlush(this.currentBatch, this.lastFlushTime)) {
+ await this.flushCurrentBatch()
+ }
+ },
}
/**
@@ -362,7 +373,7 @@ export class SessionRecordingIngester {
this.eventIngestionRestrictionManager = started.value
this.stopEventIngestionRestrictionManager = started.stop
- this.sessionReplayPipeline = this.createPipeline({
+ const pipelineConfig: SessionReplayPipelineConfig = {
outputs: this.outputs,
eventIngestionRestrictionManager: this.eventIngestionRestrictionManager,
overflowMode: this.config.INGESTION_OVERFLOW_MODE,
@@ -376,7 +387,8 @@ export class SessionRecordingIngester {
topHog: this.topHog,
isDebugLoggingEnabled: this.isDebugLoggingEnabled,
usageBatch: this.usageBatch,
- })
+ }
+ this.runner.start(pipelineConfig)
// Check that the storage backend is healthy before starting the consumer
// This is especially important in local dev with minio
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
index 0cccfd241edd..3222578c9931 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
@@ -30,6 +30,20 @@ export class SessionRecordingIngesterMetrics {
buckets: BUCKETS_KB_WRITTEN,
})
+ private static readonly batchStageDuration = new Histogram({
+ name: 'recording_blob_ingestion_v2_batch_stage_duration_ms',
+ help: 'Wall time one poll batch spent running one stage. Batches overlap across stages, so a stage that runs for close to 100% of wall time is the one the lane is bound by',
+ labelNames: ['stage'],
+ buckets: [10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, 60000, Infinity],
+ })
+
+ private static readonly batchStageWait = new Histogram({
+ name: 'recording_blob_ingestion_v2_batch_stage_wait_ms',
+ help: 'Time one poll batch waited for a stage to free up after the previous stage finished with it, which is the previous batch still in that stage',
+ labelNames: ['stage'],
+ buckets: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, Infinity],
+ })
+
private static readonly sessionInfo = new Summary({
name: 'recording_blob_ingestion_v2_session_info_bytes',
help: 'Size of aggregated session information being processed',
@@ -134,4 +148,9 @@ export class SessionRecordingIngesterMetrics {
public static observeKafkaBatchSizeKb(sizeKb: number): void {
this.kafkaBatchSizeKb.observe(sizeKb)
}
+
+ public static observeBatchStage(stage: string, waitMs: number, durationMs: number): void {
+ this.batchStageWait.labels(stage).observe(waitMs)
+ this.batchStageDuration.labels(stage).observe(durationMs)
+ }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts
index 76f707a1f50a..09ad5a1a66c2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-context.ts
@@ -8,3 +8,8 @@ import { SessionBatchRecorder } from './sessions/session-batch-recorder'
export interface SessionBatchContext {
sessionBatchRecorder: SessionBatchRecorder
}
+
+/** The part of the recorder that a step can hold outside the batch lock: a retention lookup, not a write. A lane that overlaps batches stamps this, because a flush can replace the recorder at any time. */
+export interface RetentionLookupContext {
+ sessionBatchRecorder: Pick<SessionBatchRecorder, 'getRetention'>
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts
index 03bb5af48135..fb4046290c9c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts
@@ -7,7 +7,7 @@ import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-m
import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
import { SessionReplayHeaders } from './pipeline-types'
-import { SessionBatchContext } from './session-batch-context'
+import { RetentionLookupContext } from './session-batch-context'
import { SessionBatchMetrics } from './sessions/metrics'
/**
@@ -26,7 +26,7 @@ import { SessionBatchMetrics } from './sessions/metrics'
* stage picks it up (see {@link runSessionReplayPipeline}).
*/
export function createResolveRetentionStep<
- T extends { team: TeamForReplay; headers: SessionReplayHeaders } & SessionBatchContext,
+ T extends { team: TeamForReplay; headers: SessionReplayHeaders } & RetentionLookupContext,
>(retentionService: RetentionService): ChunkProcessingStep<T, T & { retentionPeriod: RetentionPeriod }> {
return async function resolveRetentionStep(values) {
// Reuse retention already resolved for sessions still in the current (unflushed) recorder,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-runner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-runner.ts
new file mode 100644
index 000000000000..128516c44534
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-runner.ts
@@ -0,0 +1,39 @@
+import { Message } from 'node-rdkafka'
+
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import {
+ SessionReplayPipeline,
+ SessionReplayPipelineConfig,
+ runSessionReplayPipeline,
+} from '~/ingestion/pipelines/sessionreplay'
+
+import { AdmittedBatch } from './batch-stages'
+import { BatchCommitter, StagedBatchRunner } from './staged-batch'
+
+/** Builds the session replay pipeline for a deployment. */
+export type SessionReplayPipelineFactory = (config: SessionReplayPipelineConfig) => SessionReplayPipeline
+
+/** Runs each poll batch through the session replay pipeline in one stage, so batches never overlap. */
+export class SessionReplayPipelineRunner implements StagedBatchRunner {
+ public readonly stages = ['ingest'] as const
+ private pipeline!: SessionReplayPipeline
+
+ constructor(
+ private readonly createPipeline: SessionReplayPipelineFactory,
+ private readonly scheduler: PromiseScheduler
+ ) {}
+
+ public start(config: SessionReplayPipelineConfig): void {
+ this.pipeline = this.createPipeline(config)
+ }
+
+ public run(messages: Message[], batch: AdmittedBatch<void>, committer: BatchCommitter): Promise<void> {
+ return batch
+ .stage('ingest', () =>
+ committer.commit((recorder) =>
+ runSessionReplayPipeline(this.pipeline, messages, recorder, this.scheduler)
+ )
+ )
+ .done()
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages.ts
index ec32583c01db..14b0559e2a15 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline-stages.ts
@@ -1,27 +1,37 @@
+import { Message } from 'node-rdkafka'
+
import { OverflowOutput } from '~/common/outputs'
import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
import { ChunkPipelineBuilder, PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders'
import { TopHogRegistry, createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
import { ProcessingStep } from '~/ingestion/framework/steps'
+import { EventHeaders } from '~/types'
import { NewSessionFlag, Recordable, SessionReplayHeaders } from './pipeline-types'
import { RecordSessionEventStepInput } from './record-session-event-step'
+import { RetentionLookupContext } from './session-batch-context'
import { createMarkSeenStep } from './session-batch-mark-seen-step'
import { createResolveRetentionStep } from './session-batch-resolve-retention-step'
import { createTrackAndGateStep } from './session-batch-track-and-gate-step'
-import type { SessionReplayPipelineConfig, SessionReplayPipelineInput } from './session-replay-pipeline'
+import type { SessionReplayPipelineConfig } from './session-replay-pipeline'
import { createResolveKeyStep } from './session-resolve-key-step'
import { RetentionPeriod } from './shared/constants'
-import { createTeamFilterStep } from './team-filter-step'
+import { TeamFilterStepOutput, createTeamFilterStep } from './team-filter-step'
import { TeamForReplay } from './teams/types'
import { createValidateSessionReplayHeadersStep } from './validate-headers-step'
-type ValidatedReplayInput = SessionReplayPipelineInput & { headers: SessionReplayHeaders; team: TeamForReplay }
+/** What preprocessing needs from an element. The main lane stamps the full recorder. A lane that overlaps batches stamps only the retention lookup. */
+export type SessionReplayPreprocessingInput = { message: Message } & RetentionLookupContext
+/** A preprocessed element: the headers validated and the team resolved. */
+export type PreprocessedReplayInput<I> = Omit<I & { headers: EventHeaders }, 'headers'> & {
+ headers: SessionReplayHeaders
+} & TeamFilterStepOutput
+type ValidatedReplayInput = SessionReplayPreprocessingInput & { headers: SessionReplayHeaders; team: TeamForReplay }
-export function addSessionReplayPreprocessing<C>(
- builder: StartPipelineBuilder<SessionReplayPipelineInput, C>,
+export function addSessionReplayPreprocessing<I extends SessionReplayPreprocessingInput, C>(
+ builder: StartPipelineBuilder<I, C>,
config: Pick<SessionReplayPipelineConfig, 'eventIngestionRestrictionManager' | 'overflowMode' | 'teamService'>
-): PipelineBuilder<SessionReplayPipelineInput, ValidatedReplayInput, C, OverflowOutput> {
+): PipelineBuilder<I, PreprocessedReplayInput<I>, C, OverflowOutput> {
const { eventIngestionRestrictionManager, overflowMode, teamService } = config
return (
builder
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/staged-batch.ts b/nodejs/src/ingestion/pipelines/sessionreplay/staged-batch.ts
new file mode 100644
index 000000000000..fb6e86852d34
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/staged-batch.ts
@@ -0,0 +1,32 @@
+import { Message } from 'node-rdkafka'
+
+import { AdmittedBatch } from './batch-stages'
+import { SessionReplayBatchProgress, SessionReplayPipelineConfig } from './session-replay-pipeline'
+import { SessionBatchRecorder } from './sessions/session-batch-recorder'
+import { RetentionPeriod } from './shared/constants'
+
+/** Tells whether this pod still holds a partition. A batch that is still in flight after a revoke then writes nothing that the new owner will replay. */
+export type PartitionOwnership = (partition: number) => boolean
+
+/** How a runner reaches the recorder of the ingester. The write runs under the batch lock and reports the progress of the batch for the partitions that the pod holds. The ingester tracks those offsets and decides whether to flush. Only the write receives the recorder, because a flush can replace the recorder at any time. */
+export interface BatchCommitter {
+ /** The retention that is already resolved for a session in the current batch, or undefined. The current batch is the batch at the time of the call. */
+ knownRetention(teamId: number, sessionId: string): RetentionPeriod | undefined
+ commit(
+ write: (recorder: SessionBatchRecorder, isAssigned: PartitionOwnership) => Promise<SessionReplayBatchProgress>
+ ): Promise<void>
+}
+
+/** Does the work of each stage for one poll batch. The ingester sizes its consumer from the stages before the runner starts. It admits each batch to the stages in poll order and gives the runner a committer to write through. */
+export interface StagedBatchRunner {
+ readonly stages: readonly string[]
+ start(config: SessionReplayPipelineConfig): void
+ /** Resolves when the batch is written and its offsets are tracked. */
+ run(messages: Message[], batch: AdmittedBatch<void>, committer: BatchCommitter): Promise<void>
+}
+
+/** A staged batch is done when its last stage completes. That stage can wait behind every earlier batch in flight and behind a flush, so this timeout is longer than the consumer default for a short background task. It stays below the max.poll.interval.ms of librdkafka (5 minutes). At the lookahead the consumer waits on the oldest batch, and the broker removes a member that waits longer than that interval before this timeout can fire. */
+export const STAGED_BATCH_TIMEOUT_MS = 4 * 60 * 1000
+
+/** A revoke drains every batch in flight before the revoke hook flushes. The last stages of those batches run one after another. The drain needs the lookahead multiplied by the slowest stage, plus the flush of the hook, all below the 5-minute max.poll.interval.ms of librdkafka. */
+export const STAGED_BATCH_REBALANCE_TIMEOUT_MS = 3 * 60 * 1000