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): emit ingestion lag metrics after batch flush (#71539)

Paweł Ledwońcf3e2eb3fdb2
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts
index f418bd7f2644..24ae7a35c4bb 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts
@@ -1,7 +1,12 @@
import { Message } from 'node-rdkafka'
+import { ingestionLagGauge, ingestionLagHistogram } from '~/common/metrics'
import { PostgresRouter } from '~/common/utils/db/postgres'
-import { SessionReplayPipeline, runSessionReplayPipeline } from '~/ingestion/pipelines/sessionreplay'
+import {
+ SessionReplayBatchProgress,
+ SessionReplayPipeline,
+ runSessionReplayPipeline,
+} from '~/ingestion/pipelines/sessionreplay'
import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { RedisPool } from '~/types'
@@ -37,7 +42,7 @@ function flushMicrotasks(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve))
}
-function kafkaMessage(partition: number, offset: number): Message {
+function kafkaMessage(partition: number, offset: number, capturedAtMs?: number): Message {
return {
value: Buffer.from('data'),
size: 4,
@@ -45,9 +50,21 @@ function kafkaMessage(partition: number, offset: number): Message {
partition,
offset,
timestamp: Date.now(),
+ headers: capturedAtMs === undefined ? undefined : [{ now: Buffer.from(new Date(capturedAtMs).toISOString()) }],
}
}
+function progress(maxOffsets: Map<number, number>, okMessages: Message[] = []): SessionReplayBatchProgress {
+ return { maxOffsets, okMessages }
+}
+
+async function lagHistogramCount(partition: string): Promise<number | undefined> {
+ const metric = await ingestionLagHistogram.get()
+ return metric.values.find(
+ (v) => v.metricName === 'ingestion_lag_ms_histogram_count' && v.labels.partition === partition
+ )?.value
+}
+
describe('SessionRecordingIngester', () => {
let ingester: SessionRecordingIngester
let events: string[]
@@ -125,7 +142,7 @@ describe('SessionRecordingIngester', () => {
})
)
)
- return new Map([[0, 42]])
+ return progress(new Map([[0, 42]]))
})
const batchPromise = ingester.handleEachBatch([kafkaMessage(0, 42)])
@@ -165,7 +182,7 @@ describe('SessionRecordingIngester', () => {
})
)
)
- return Promise.resolve(new Map([[0, 42]]))
+ return Promise.resolve(progress(new Map([[0, 42]])))
})
await ingester.handleEachBatch([kafkaMessage(0, 42)])
@@ -178,6 +195,60 @@ describe('SessionRecordingIngester', () => {
])
})
+ it('reports ingestion lag only once the batch is flushed', async () => {
+ ingestionLagGauge.reset()
+ ingestionLagHistogram.reset()
+
+ // The default ingester keeps age/size out of reach, so recording a batch does not flush it —
+ // and lag must not be observed until the data is durably ingested.
+ const bufferedMessage = kafkaMessage(0, 42, Date.now() - 5000)
+ runPipelineMock.mockResolvedValue(progress(new Map([[0, 42]]), [bufferedMessage]))
+ await ingester.handleEachBatch([bufferedMessage])
+ expect(await lagHistogramCount('0')).toBeUndefined()
+
+ // With the age trigger the batch flushes immediately, so its capture lag is observed post-flush.
+ createIngester({ SESSION_RECORDING_MAX_BATCH_AGE_MS: 0 })
+ const flushedMessage = kafkaMessage(0, 43, Date.now() - 5000)
+ runPipelineMock.mockResolvedValue(progress(new Map([[0, 43]]), [flushedMessage]))
+ await ingester.handleEachBatch([flushedMessage])
+ expect(await lagHistogramCount('0')).toBe(1)
+ })
+
+ it('samples the pipeline OK-result messages, not the raw consumed batch', async () => {
+ ingestionLagHistogram.reset()
+ createIngester({ SESSION_RECORDING_MAX_BATCH_AGE_MS: 0 })
+
+ // The consumed message carries a capture header, but the pipeline dropped it (no OK results), so
+ // no lag is sampled even though the batch flushes.
+ runPipelineMock.mockResolvedValue(progress(new Map([[0, 42]]), []))
+ await ingester.handleEachBatch([kafkaMessage(0, 42, Date.now() - 5000)])
+ expect(await lagHistogramCount('0')).toBeUndefined()
+ })
+
+ it('keeps pending lag samples across a failed flush so a later successful flush still reports them', async () => {
+ ingestionLagHistogram.reset()
+ createIngester({ SESSION_RECORDING_MAX_BATCH_AGE_MS: 0 })
+
+ // A flush that fails after the capture timestamp was buffered must not observe or drop the pending
+ // sample. Poll-batch flush failures crash the process; the retain-and-report path that matters is a
+ // swallowed revoke-hook flush, after which this still-running process flushes successfully and
+ // reports the samples it kept. The failure is simulated here at the offset-store step.
+ jest.mocked(ingester.kafkaConsumer).offsetsStore.mockImplementationOnce(() => {
+ throw new Error('offset store failed')
+ })
+ const firstMessage = kafkaMessage(0, 42, Date.now() - 5000)
+ runPipelineMock.mockResolvedValue(progress(new Map([[0, 42]]), [firstMessage]))
+ await expect(ingester.handleEachBatch([firstMessage])).rejects.toThrow('offset store failed')
+ // The flush threw, so nothing is observed and the sample stays pending.
+ expect(await lagHistogramCount('0')).toBeUndefined()
+
+ // A later successful flush reports the retained sample alongside the new one.
+ const secondMessage = kafkaMessage(0, 43, Date.now() - 5000)
+ runPipelineMock.mockResolvedValue(progress(new Map([[0, 43]]), [secondMessage]))
+ await ingester.handleEachBatch([secondMessage])
+ expect(await lagHistogramCount('0')).toBe(2)
+ })
+
it('start() wires the revoke hook, and the hook flushes the tracked offsets', async () => {
await ingester.start()
const connectMock = jest.mocked(ingester.kafkaConsumer).connect
@@ -185,7 +256,7 @@ describe('SessionRecordingIngester', () => {
const [eachBatch, onPartitionsRevoked] = connectMock.mock.calls[0]
expect(onPartitionsRevoked).toBeDefined()
- runPipelineMock.mockImplementation(() => Promise.resolve(new Map([[0, 7]])))
+ runPipelineMock.mockImplementation(() => Promise.resolve(progress(new Map([[0, 7]]))))
await eachBatch([kafkaMessage(0, 7)])
// Age/size are out of reach, so nothing has flushed yet.
expect(events).toEqual([])
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
index cd52e098447d..21d720fdc244 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
@@ -39,6 +39,7 @@ import { HealthCheckResult, PluginServerService, RedisPool, ValueMatcher } from
import { SessionRecordingApiConfig, SessionRecordingConfig } from './config'
import { KafkaOffsetManager } from './kafka/offset-manager'
import { SessionRecordingIngesterMetrics } from './metrics'
+import { SessionReplayLagReporter } from './session-replay-lag-reporter'
import { BlackholeSessionBatchFileStorage } from './sessions/blackhole-session-batch-writer'
import { RetentionAwareStorage } from './sessions/retention-aware-batch-writer'
import { SessionBatchFileStorage } from './sessions/session-batch-file-storage'
@@ -89,6 +90,8 @@ export class SessionRecordingIngester {
private isDebugLoggingEnabled: ValueMatcher<number>
private readonly promiseScheduler: PromiseScheduler
private readonly sessionBatchManager: SessionBatchManager
+ /** Buffers capture timestamps of processed messages and reports ingestion lag after each flush. */
+ private readonly lagReporter: SessionReplayLagReporter
/** The accumulator for the current flush cycle. Owned here, minted and flushed via the manager. */
private currentBatch: SessionBatchRecorder
/** When the current accumulation cycle started (last flush, or startup), for the age flush trigger. */
@@ -241,6 +244,8 @@ export class SessionRecordingIngester {
encryptor: this.encryptor,
})
+ this.lagReporter = new SessionReplayLagReporter(this.topic)
+
this.currentBatch = this.sessionBatchManager.createBatch()
this.lastFlushTime = Date.now()
}
@@ -284,12 +289,22 @@ export class SessionRecordingIngester {
// 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 offsets = await instrumentFn(`recordingingesterv2.handleEachBatch.runPipeline`, async () =>
- this.batchLock(() =>
- runSessionReplayPipeline(this.sessionReplayPipeline, messages, this.currentBatch, this.promiseScheduler)
- )
+ const { maxOffsets, okMessages } = await instrumentFn(
+ `recordingingesterv2.handleEachBatch.runPipeline`,
+ async () =>
+ this.batchLock(() =>
+ runSessionReplayPipeline(
+ this.sessionReplayPipeline,
+ messages,
+ this.currentBatch,
+ this.promiseScheduler
+ )
+ )
)
- this.sessionBatchManager.trackProcessedOffsets(offsets)
+ 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()
@@ -312,6 +327,9 @@ export class SessionRecordingIngester {
await this.batchLock(async () => {
logger.info('🔁', 'blob_ingester_consumer_v2 - flushing batch', { batchSize: this.currentBatch.size })
await instrumentFn(`recordingingesterv2.handleEachBatch.flush`, async () => this.currentBatch.flush())
+ // The flush committed the batch's offsets, so its data is now durably ingested — report lag.
+ // Skipped if the flush above threw, so a failed flush records no premature lag sample.
+ this.lagReporter.flush()
this.currentBatch = this.sessionBatchManager.createBatch()
this.lastFlushTime = Date.now()
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/index.ts
index 78eec22ff09f..f50b74afd59a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/index.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/index.ts
@@ -1,6 +1,7 @@
export {
createSessionReplayPipeline,
runSessionReplayPipeline,
+ type SessionReplayBatchProgress,
type SessionReplayPipeline,
type SessionReplayPipelineConfig,
type SessionReplayPipelineInput,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-lag-reporter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-lag-reporter.test.ts
new file mode 100644
index 000000000000..05b6306fc958
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-lag-reporter.test.ts
@@ -0,0 +1,111 @@
+import { MessageHeader } from 'node-rdkafka'
+
+import { ingestionLagGauge, ingestionLagHistogram } from '~/common/metrics'
+
+import { LagReportableMessage, SessionReplayLagReporter } from './session-replay-lag-reporter'
+
+const FAKE_NOW_MS = 1702654321987 // 2023-12-15T14:32:01.987Z
+const TEST_TOPIC = 'test-topic'
+
+async function getGaugeValue(partition: string): Promise<number | undefined> {
+ const metric = await ingestionLagGauge.get()
+ return metric.values.find((v) => v.labels.topic === TEST_TOPIC && v.labels.partition === partition)?.value
+}
+
+async function getHistogramCountAndSum(partition: string): Promise<{ count: number; sum: number } | null> {
+ const metric = await ingestionLagHistogram.get()
+ const find = (suffix: string): number | undefined =>
+ metric.values.find(
+ (v) => v.metricName === `ingestion_lag_ms_histogram${suffix}` && v.labels.partition === partition
+ )?.value
+ const count = find('_count')
+ const sum = find('_sum')
+ return count === undefined || sum === undefined ? null : { count, sum }
+}
+
+function message(partition: number, headers?: MessageHeader[]): LagReportableMessage {
+ return { partition, headers }
+}
+
+function nowHeader(capturedAtMs: number): MessageHeader[] {
+ return [{ now: Buffer.from(new Date(capturedAtMs).toISOString()) }]
+}
+
+describe('SessionReplayLagReporter', () => {
+ let reporter: SessionReplayLagReporter
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ jest.setSystemTime(FAKE_NOW_MS)
+ ingestionLagGauge.reset()
+ ingestionLagHistogram.reset()
+ reporter = new SessionReplayLagReporter(TEST_TOPIC)
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('observes lag from capture time to flush time and reports it per partition', async () => {
+ reporter.record([message(0, nowHeader(FAKE_NOW_MS - 5000)), message(0, nowHeader(FAKE_NOW_MS - 3000))])
+ reporter.record([message(1, nowHeader(FAKE_NOW_MS - 2000))])
+
+ // Nothing is observed until the batch is durably flushed.
+ expect(await getGaugeValue('0')).toBeUndefined()
+
+ // The flush happens two seconds after the last record — lag is measured against flush time.
+ jest.setSystemTime(FAKE_NOW_MS + 2000)
+ reporter.flush()
+
+ // Gauge keeps the last sample per partition; the histogram aggregates every sample.
+ expect(await getGaugeValue('0')).toBe(5000)
+ expect(await getHistogramCountAndSum('0')).toEqual({ count: 2, sum: 12000 })
+ expect(await getGaugeValue('1')).toBe(4000)
+ expect(await getHistogramCountAndSum('1')).toEqual({ count: 1, sum: 4000 })
+ })
+
+ it('clears pending timestamps after a flush so the next flush does not re-report them', async () => {
+ reporter.record([message(0, nowHeader(FAKE_NOW_MS - 5000))])
+ reporter.flush()
+ expect(await getHistogramCountAndSum('0')).toEqual({ count: 1, sum: 5000 })
+
+ reporter.flush()
+
+ // A second flush with nothing recorded since must not add another sample.
+ expect(await getHistogramCountAndSum('0')).toEqual({ count: 1, sum: 5000 })
+ })
+
+ it('is a no-op when flushing with nothing pending', async () => {
+ reporter.flush()
+
+ expect(await getGaugeValue('0')).toBeUndefined()
+ expect(await getHistogramCountAndSum('0')).toBeNull()
+ })
+
+ it('uses the last valid now header when a message carries duplicates, matching parseEventHeaders', async () => {
+ // Kafka permits duplicate header keys and parseEventHeaders lets the last valid `now` win, so the
+ // lag sample must come from the same timestamp the message was processed with.
+ reporter.record([
+ message(0, [
+ { now: Buffer.from(new Date(FAKE_NOW_MS - 9000).toISOString()) },
+ { now: Buffer.from(new Date(FAKE_NOW_MS - 4000).toISOString()) },
+ ]),
+ ])
+ reporter.flush()
+
+ expect(await getGaugeValue('0')).toBe(4000)
+ expect(await getHistogramCountAndSum('0')).toEqual({ count: 1, sum: 4000 })
+ })
+
+ it.each<{ name: string; headers?: MessageHeader[] }>([
+ { name: 'no headers at all', headers: undefined },
+ { name: 'no now header', headers: [{ token: Buffer.from('t') }] },
+ { name: 'an unparseable now value', headers: [{ now: Buffer.from('not-a-date') }] },
+ ])('skips a message with $name', async ({ headers }) => {
+ reporter.record([message(0, headers)])
+ reporter.flush()
+
+ expect(await getGaugeValue('0')).toBeUndefined()
+ expect(await getHistogramCountAndSum('0')).toBeNull()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-lag-reporter.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-lag-reporter.ts
new file mode 100644
index 000000000000..19bea46a64bd
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-lag-reporter.ts
@@ -0,0 +1,87 @@
+import { Message, MessageHeader } from 'node-rdkafka'
+
+import { ingestionLagGauge, ingestionLagHistogram } from '~/common/metrics'
+
+/** The message fields the reporter reads — a raw Kafka {@link Message} satisfies this structurally. */
+export type LagReportableMessage = Pick<Message, 'partition' | 'headers'>
+
+/**
+ * Reports session replay ingestion lag — wall-clock time minus capture time (the `now` header set by
+ * capture) — but only once a batch is durably flushed and its offsets committed, because that is when
+ * replay data is actually ingested.
+ *
+ * The consumer records the recorded (OK-result) messages of each poll batch as they are processed and
+ * flushes the reporter after the session batch flush succeeds. Only the capture timestamps (epoch ms)
+ * are retained per partition; the messages themselves are never held.
+ *
+ * Only OK results are sampled — dropped, DLQ'd, and redirected messages are excluded — matching the
+ * per-event `record-ingestion-lag` step's ingested-only semantics.
+ *
+ * A failed poll-batch flush crashes the process (eachBatch errors are uncaught), so its pending samples
+ * die unreported and are re-read from the uncommitted offsets on restart. The one path that retains and
+ * later reports is a failed or timed-out revoke-hook flush: it is swallowed and the partitions are given
+ * up without committed offsets, so this still-running process can report its retained samples while the
+ * new owner reprocesses the same messages — a bounded duplicate consistent with the at-least-once
+ * delivery both owners already provide for the data itself.
+ */
+export class SessionReplayLagReporter {
+ private pendingByPartition: Map<number, number[]> = new Map()
+
+ constructor(private readonly topic: string) {}
+
+ /** Extracts and stores the capture timestamp of each message that carries a valid `now` header. */
+ public record(messages: LagReportableMessage[]): void {
+ for (const message of messages) {
+ const capturedAtMs = captureTimestampMs(message.headers)
+ if (capturedAtMs === undefined) {
+ continue
+ }
+ let pending = this.pendingByPartition.get(message.partition)
+ if (pending === undefined) {
+ pending = []
+ this.pendingByPartition.set(message.partition, pending)
+ }
+ pending.push(capturedAtMs)
+ }
+ }
+
+ /** Observes lag for every pending capture timestamp against a single now, then clears the state. */
+ public flush(): void {
+ const nowMs = Date.now()
+ for (const [partition, timestamps] of this.pendingByPartition) {
+ const partitionLabel = String(partition)
+ for (const capturedAtMs of timestamps) {
+ const lag = nowMs - capturedAtMs
+ ingestionLagGauge.labels({ topic: this.topic, partition: partitionLabel }).set(lag)
+ ingestionLagHistogram.labels({ partition: partitionLabel }).observe(lag)
+ }
+ }
+ this.pendingByPartition.clear()
+ }
+}
+
+/**
+ * Parses just the `now` header to epoch ms, mirroring the capture-time parse in `parseEventHeaders`.
+ * The pipeline already ran the full header parse (and its header-status metrics) on these messages, so
+ * re-running it here would double-count those metrics; reading the one header we need avoids that.
+ *
+ * Kafka allows duplicate header keys, so this iterates every header and keeps the last valid `now` —
+ * matching `parseEventHeaders`, so lag is reported from the same timestamp the message was processed
+ * with. An invalid value does not clear a valid one seen earlier.
+ */
+function captureTimestampMs(headers: MessageHeader[] | undefined): number | undefined {
+ if (headers === undefined) {
+ return undefined
+ }
+ let capturedAtMs: number | undefined
+ for (const header of headers) {
+ const value = header['now']
+ if (value !== undefined) {
+ const parsedMs = new Date(value.toString()).getTime()
+ if (!isNaN(parsedMs)) {
+ capturedAtMs = parsedMs
+ }
+ }
+ }
+ return capturedAtMs
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
index 6ce71eb07b78..b6d82e97a5f2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
@@ -296,11 +296,16 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1'), createMessage(0, 2, 'session-2')]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])
// Highest offset reached on the partition is tracked.
- expect(offsets).toEqual(new Map([[0, 2]]))
+ expect(maxOffsets).toEqual(new Map([[0, 2]]))
})
it('filters out dropped messages from restrictions', async () => {
@@ -334,12 +339,17 @@ describe('session-replay-pipeline', () => {
createMessage(0, 3, 'session-3'),
]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])
// The dropped message (offset 2) is not recorded, but its offset is still accounted for —
// the partition's committed offset advances past it rather than replaying it forever.
- expect(offsets).toEqual(new Map([[0, 3]]))
+ expect(maxOffsets).toEqual(new Map([[0, 3]]))
})
it('tracks the offset of a dropped message even when it is the highest in the partition', async () => {
@@ -373,12 +383,17 @@ describe('session-replay-pipeline', () => {
createMessage(0, 3, 'session-3'),
]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])
// The highest offset on the partition belongs to the dropped message; it must still be
// tracked or that partition would never commit past offset 2.
- expect(offsets).toEqual(new Map([[0, 3]]))
+ expect(maxOffsets).toEqual(new Map([[0, 3]]))
})
it('tracks the offset of a rate-limited session even when it is the highest in the partition', async () => {
@@ -418,12 +433,17 @@ describe('session-replay-pipeline', () => {
createMessage(0, 3, 'session-3'),
]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(recordedSessionIds()).toEqual(['session-1', 'session-2'])
// The highest offset on the partition belongs to the blocked session; it must still be tracked
// or that partition would never commit past offset 2.
- expect(offsets).toEqual(new Map([[0, 3]]))
+ expect(maxOffsets).toEqual(new Map([[0, 3]]))
})
// Offsets are tracked per partition. Each case drops the highest-offset message on partition 0 via
@@ -492,10 +512,15 @@ describe('session-replay-pipeline', () => {
createMessage(1, 5, 'session-4'), // recorded on partition 1 at a higher offset
]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(recordedSessionIds().sort()).toEqual(['session-1', 'session-2', 'session-4'])
- expect(offsets).toEqual(
+ expect(maxOffsets).toEqual(
new Map([
[0, 3],
[1, 5],
@@ -533,11 +558,16 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1'), invalidMessage, createMessage(0, 3, 'session-3')]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])
// The unparseable message (offset 2) is DLQ'd, but its offset is still accounted for.
- expect(offsets).toEqual(new Map([[0, 3]]))
+ expect(maxOffsets).toEqual(new Map([[0, 3]]))
})
it('sends messages that fail to parse to the DLQ topic', async () => {
@@ -615,20 +645,86 @@ describe('session-replay-pipeline', () => {
createMessage(0, 3, 'session-3'),
]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
// Wait for side effects to complete
await promiseScheduler.waitForAll()
expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])
// The redirected message (offset 2) is not recorded, but its offset is still accounted for.
- expect(offsets).toEqual(new Map([[0, 3]]))
+ expect(maxOffsets).toEqual(new Map([[0, 3]]))
// Verify the overflow message was produced
expect(outputs.produce).toHaveBeenCalledWith(OVERFLOW_OUTPUT, expect.anything())
})
- it('returns empty offsets for empty input', async () => {
+ it('collects only OK-result messages, excluding dropped, redirected, and DLQ dispositions', async () => {
+ // offset 2 dropped, offset 3 redirected to overflow; offset 4 fails to parse (DLQ); 1 and 5 are OK.
+ mockCreateApplyEventRestrictionsStep.mockReturnValue(
+ (input: { message: Message; headers: Record<string, string> }) => {
+ if (input.message.offset === 2) {
+ return Promise.resolve(drop('blocked'))
+ }
+ if (input.message.offset === 3) {
+ return Promise.resolve(redirect('overflow', OVERFLOW_OUTPUT, true, false))
+ }
+ return Promise.resolve(ok(input))
+ }
+ )
+
+ const pipeline = createSessionReplayPipeline({
+ outputs,
+ eventIngestionRestrictionManager: mockRestrictionManager,
+ overflowMode: 'redirect',
+ promiseScheduler,
+ teamService: mockTeamService,
+ retentionService,
+ sessionTracker,
+ sessionFilter,
+ keyStore,
+ sessionKeyResolutionMaxConcurrency: 20,
+ topHog,
+ isDebugLoggingEnabled,
+ })
+
+ const invalidMessage: Message = {
+ partition: 0,
+ offset: 4,
+ topic: 'test-topic',
+ value: Buffer.from('invalid json'),
+ key: Buffer.from('test-key'),
+ timestamp: Date.now(),
+ headers: [],
+ size: 12,
+ }
+ const messages = [
+ createMessage(0, 1, 'session-1'),
+ createMessage(0, 2, 'session-2'),
+ createMessage(0, 3, 'session-3'),
+ invalidMessage,
+ createMessage(0, 5, 'session-5'),
+ ]
+
+ const { maxOffsets, okMessages } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
+ await promiseScheduler.waitForAll()
+
+ // Only the recorded (OK) messages are collected for lag sampling.
+ expect(okMessages.map((m) => m.offset).sort((a, b) => a - b)).toEqual([1, 5])
+ // Every disposition still advances the committed offset.
+ expect(maxOffsets).toEqual(new Map([[0, 5]]))
+ })
+
+ it('returns empty progress for empty input', async () => {
const pipeline = createSessionReplayPipeline({
outputs,
eventIngestionRestrictionManager: mockRestrictionManager,
@@ -644,9 +740,15 @@ describe('session-replay-pipeline', () => {
isDebugLoggingEnabled,
})
- const offsets = await runSessionReplayPipeline(pipeline, [], mockBatchRecorder, promiseScheduler)
+ const { maxOffsets, okMessages } = await runSessionReplayPipeline(
+ pipeline,
+ [],
+ mockBatchRecorder,
+ promiseScheduler
+ )
- expect(offsets.size).toBe(0)
+ expect(maxOffsets.size).toBe(0)
+ expect(okMessages).toEqual([])
})
it('processes large batch with mixed dropped and passed messages correctly', async () => {
@@ -681,7 +783,12 @@ describe('session-replay-pipeline', () => {
messages.push(createMessage(0, i))
}
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
// 100 messages dropped (10, 20, ..., 1000), 900 recorded
const recorded = recordedSessionIds()
@@ -694,7 +801,7 @@ describe('session-replay-pipeline', () => {
}
}
// Every message's offset is accounted for regardless of disposition.
- expect(offsets).toEqual(new Map([[0, 1000]]))
+ expect(maxOffsets).toEqual(new Map([[0, 1000]]))
})
it('correctly parses and passes headers to the restrictions step', async () => {
@@ -767,14 +874,19 @@ describe('session-replay-pipeline', () => {
messages.push(createMessage(0, i))
}
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
const recorded = recordedSessionIds()
expect(recorded).toHaveLength(500)
for (let i = 0; i < 500; i++) {
expect(recorded[i]).toBe(`session-${i + 1}`)
}
- expect(offsets).toEqual(new Map([[0, 500]]))
+ expect(maxOffsets).toEqual(new Map([[0, 500]]))
})
it('filters out messages with invalid team', async () => {
@@ -809,11 +921,16 @@ describe('session-replay-pipeline', () => {
createMessage(0, 3, 'session-3', { token: 'valid-token' }),
]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(recordedSessionIds()).toEqual(['session-1', 'session-3'])
// The invalid-team message (offset 2) isn't recorded, but its offset is still tracked.
- expect(offsets).toEqual(new Map([[0, 3]]))
+ expect(maxOffsets).toEqual(new Map([[0, 3]]))
})
it('sends messages with no token header to DLQ', async () => {
@@ -835,11 +952,16 @@ describe('session-replay-pipeline', () => {
// Explicitly pass empty headers (no token)
const messages = [createMessage(0, 1, 'session-1', {})]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
// Message is dropped by team filter due to missing token — not recorded, offset still tracked.
expect(recordedSessionIds()).toEqual([])
- expect(offsets).toEqual(new Map([[0, 1]]))
+ expect(maxOffsets).toEqual(new Map([[0, 1]]))
})
it('sends ingestion warning for old lib version', async () => {
@@ -952,11 +1074,16 @@ describe('session-replay-pipeline', () => {
// Create a message with timestamps 10 days old (threshold is 7 days)
const messages = [createMessageWithOldTimestamps(0, 1, 'session-1', 10, { token: 'test-token' })]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
// Message is dropped (not recorded) but its offset is tracked and a warning is sent.
expect(recordedSessionIds()).toEqual([])
- expect(offsets).toEqual(new Map([[0, 1]]))
+ expect(maxOffsets).toEqual(new Map([[0, 1]]))
expect(outputs.queueMessages).toHaveBeenCalledTimes(1)
expect(outputs.queueMessages).toHaveBeenCalledWith(
@@ -1053,11 +1180,16 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1')]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(mockBatchRecorder.record).not.toHaveBeenCalled()
// Dropped, but its offset is still tracked so the partition commits past it.
- expect(offsets).toEqual(new Map([[0, 1]]))
+ expect(maxOffsets).toEqual(new Map([[0, 1]]))
})
it('does not record messages with invalid team to session batch', async () => {
@@ -1082,11 +1214,16 @@ describe('session-replay-pipeline', () => {
const messages = [createMessage(0, 1, 'session-1', { token: 'invalid-token' })]
- const offsets = await runSessionReplayPipeline(pipeline, messages, mockBatchRecorder, promiseScheduler)
+ const { maxOffsets } = await runSessionReplayPipeline(
+ pipeline,
+ messages,
+ mockBatchRecorder,
+ promiseScheduler
+ )
expect(mockBatchRecorder.record).not.toHaveBeenCalled()
// Dropped, but its offset is still tracked so the partition commits past it.
- expect(offsets).toEqual(new Map([[0, 1]]))
+ expect(maxOffsets).toEqual(new Map([[0, 1]]))
})
it('records parse time metric via TopHog', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
index dfa5ae635158..53335f116379 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts
@@ -11,7 +11,7 @@ import { newBatchingPipeline } from '~/ingestion/framework/builders'
import { TopHogRegistry, createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
import { createBatch } from '~/ingestion/framework/helpers'
import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
-import { ok } from '~/ingestion/framework/results'
+import { isOkResult, ok } from '~/ingestion/framework/results'
import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
import { SessionFilter } from '~/ingestion/pipelines/sessionreplay/sessions/session-filter'
@@ -245,15 +245,25 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)
)
}
+/** The Kafka progress and lag inputs a processed batch yields for the caller to act on after it drains. */
+export interface SessionReplayBatchProgress {
+ /** Highest Kafka offset reached per partition, across every terminal result — advances the commit. */
+ maxOffsets: Map<number, number>
+ /** Source messages of the OK (recorded) results only, for ingestion-lag sampling after the flush. */
+ okMessages: Message[]
+}
+
/**
- * Runs a batch of messages through the session replay pipeline and returns the highest Kafka offset
- * reached per partition.
+ * Runs a batch of messages through the session replay pipeline and returns the Kafka progress it made:
+ * the highest offset reached per partition, plus the source messages of the OK results.
*
* Every message ends the pipeline with a terminal result — OK (recorded), DROP, DLQ, or REDIRECT —
* and each result still carries its source message in the context. Draining them here and taking the
* max offset per partition is the single place Kafka progress is tracked: the recorder no longer
* tracks offsets while recording, and drop/dlq steps no longer have to remember to. The caller feeds
- * the returned offsets to the offset manager, which commits them on the next flush.
+ * the returned offsets to the offset manager, which commits them on the next flush. Every disposition
+ * advances the offset, but only OK results are collected for lag sampling — those are the messages
+ * actually recorded, matching the per-event `record-ingestion-lag` step's ingested-only semantics.
*
* Relies on the pipeline draining the whole fed batch before it returns null, so every fed message
* yields exactly one terminal result here.
@@ -268,10 +278,11 @@ export async function runSessionReplayPipeline(
messages: Message[],
sessionBatchRecorder: SessionBatchRecorder,
promiseScheduler: PromiseScheduler
-): Promise<Map<number, number>> {
- const maxOffsetByPartition = new Map<number, number>()
+): Promise<SessionReplayBatchProgress> {
+ const maxOffsets = new Map<number, number>()
+ const okMessages: Message[] = []
if (messages.length === 0) {
- return maxOffsetByPartition
+ return { maxOffsets, okMessages }
}
// Stamp the caller's current recorder onto every message, so the record step folds into the batch
@@ -289,15 +300,18 @@ export async function runSessionReplayPipeline(
for (const sideEffect of batchResult.sideEffects ?? []) {
void promiseScheduler.schedule(sideEffect)
}
- for (const { context } of batchResult.elements) {
+ for (const { result, context } of batchResult.elements) {
const { partition, offset } = context.message
- const current = maxOffsetByPartition.get(partition)
+ const current = maxOffsets.get(partition)
if (current === undefined || offset > current) {
- maxOffsetByPartition.set(partition, offset)
+ maxOffsets.set(partition, offset)
+ }
+ if (isOkResult(result)) {
+ okMessages.push(context.message)
}
}
batchResult = await pipeline.next()
}
- return maxOffsetByPartition
+ return { maxOffsets, okMessages }
}