:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(replay): support Brotli compression in session replay ingestion lanes (#103227)
Robbie45d84da19a9a
diff --git a/nodejs/src/common/utils/threadpool-concurrency.test.ts b/nodejs/src/common/utils/threadpool-concurrency.test.tsnew file mode 100644index 000000000000..71b8d06d289a--- /dev/null+++ b/nodejs/src/common/utils/threadpool-concurrency.test.ts@@ -0,0 +1,32 @@+import os from 'node:os'++import { threadpoolConcurrency } from './threadpool-concurrency'++describe('threadpoolConcurrency', () => {+ const uvThreadpoolSize = process.env.UV_THREADPOOL_SIZE++ afterEach(() => {+ jest.restoreAllMocks()+ if (uvThreadpoolSize === undefined) {+ delete process.env.UV_THREADPOOL_SIZE+ } else {+ process.env.UV_THREADPOOL_SIZE = uvThreadpoolSize+ }+ })++ it.each([+ ['resolves to available CPUs when below the pool', 3, '4', 3],+ ['is capped by the threadpool size', 16, '4', 4],+ ['never resolves below 1', 0, '0', 1],+ ['falls back to four when the pool size is unset', 16, undefined, 4],+ ])('%s', (_name, cpus, poolSize, expected) => {+ jest.spyOn(os, 'availableParallelism').mockReturnValue(cpus)+ if (poolSize === undefined) {+ delete process.env.UV_THREADPOOL_SIZE+ } else {+ process.env.UV_THREADPOOL_SIZE = poolSize+ }++ expect(threadpoolConcurrency()).toBe(expected)+ })+})diff --git a/nodejs/src/common/utils/threadpool-concurrency.ts b/nodejs/src/common/utils/threadpool-concurrency.tsnew file mode 100644index 000000000000..07dc15a48a3e--- /dev/null+++ b/nodejs/src/common/utils/threadpool-concurrency.ts@@ -0,0 +1,12 @@+import os from 'node:os'++const DEFAULT_UV_THREADPOOL_SIZE = 4++/**+ * How much work the libuv threadpool can carry at once. `os.availableParallelism()` respects cgroup CPU limits, so+ * in-container this sees the pod's cores rather than the node's.+ */+export function threadpoolConcurrency(): number {+ const uvThreadpoolSize = parseInt(process.env.UV_THREADPOOL_SIZE ?? '', 10) || DEFAULT_UV_THREADPOOL_SIZE+ return Math.max(1, Math.min(os.availableParallelism(), uvThreadpoolSize))+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.tsindex 514a00f4c29a..a80cc36d5d75 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts@@ -40,6 +40,7 @@ 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 { BlockCompression } from './sessions/block-compression'import { RetentionAwareStorage } from './sessions/retention-aware-batch-writer'import { SessionBatchFileStorage } from './sessions/session-batch-file-storage'import { SessionBatchManager } from './sessions/session-batch-manager'@@ -75,6 +76,7 @@ export interface SessionRecordingIngesterCollaborators {featureStore?: SessionFeatureStorekeyStore?: KeyStoreencryptor?: RecordingEncryptor+ compression?: BlockCompressioncreatePipeline?: 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@@ -129,6 +131,7 @@ export class SessionRecordingIngester {private readonly sessionFilter: SessionFilterprivate readonly keyStore: KeyStoreprivate readonly encryptor: RecordingEncryptor+ private readonly compression?: BlockCompressionprivate readonly runner: StagedBatchRunnerprivate readonly batchStages: BatchStagesprivate readonly usageBatch: UsageRecordBatch@@ -253,6 +256,7 @@ export class SessionRecordingIngester {}))this.encryptor = collaborators.encryptor ?? getBlockEncryptor(this.keyStore)+ this.compression = collaborators.compressionthis.sessionBatchManager = new SessionBatchManager({maxBatchSizeBytes: this.config.SESSION_RECORDING_MAX_BATCH_SIZE_KB * 1024,@@ -265,6 +269,7 @@ export class SessionRecordingIngester {consoleLogStore,featureStore,encryptor: this.encryptor,+ compression: this.compression,})this.lagReporter = new SessionReplayLagReporter(this.topic)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.tsindex ed4012990323..13c94b3ec606 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.test.ts@@ -1,4 +1,4 @@-import { getMlMirrorConfig, resolveMlAnonymizeMaxConcurrency, resolveMlMirrorRedisConnection } from './config'+import { getMlMirrorConfig, resolveMlMirrorRedisConnection } from './config'describe('ml-mirror config', () => {it.each(['S3_PREFIX', 'PSEUDONYM_SECRET', 'PSEUDONYM_KMS_REGION', 'PSEUDONYM_KEY_FINGERPRINT'] as const)(@@ -17,17 +17,6 @@ describe('ml-mirror config', () => {})- describe('resolveMlAnonymizeMaxConcurrency', () => {- it.each([- ['explicit value passes through verbatim, even above the pool', 8, 3, 4, 8],- ['sentinel resolves to available CPUs when below the pool', 0, 3, 4, 3],- ['sentinel is capped by the threadpool size', 0, 16, 4, 4],- ['sentinel never resolves below 1', -1, 0, 0, 1],- ])('%s', (_name, configured, cpus, poolSize, expected) => {- expect(resolveMlAnonymizeMaxConcurrency(configured, cpus, poolSize)).toBe(expected)- })- })-describe('resolveMlMirrorRedisConnection', () => {const config = (host: string) => ({SESSION_RECORDING_ML_REDIS_HOST: host,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 33ff9a0be404..f29faa209b8f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -1,5 +1,3 @@-import os from 'node:os'-import { overrideConfigWithEnv } from '~/common/config/config'import { KAFKA_SESSION_REPLAY_IMAGE_SCRUB_DLQ } from '~/common/config/kafka-topics'import { RedisConnectionConfig } from '~/common/utils/db/redis'@@ -209,13 +207,6 @@ export type MlMirrorConfig = {SESSION_RECORDING_ML_IMAGE_SCRUB_BATCH_SIZE: number// Per-write timeout (the S3 client has no built-in one). A flush does two writes, so it bounds at 2x this.SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: number- /**- * Cap on messages scrubbed concurrently per pod. Each in-flight scrub occupies one libuv- * threadpool thread (UV_THREADPOOL_SIZE, default 4, shared with the recorder's snappy- * compression). <= 0 (the default) resolves to min(available CPUs, threadpool size); an- * explicit positive value is used verbatim; 1 restores fully sequential scrubbing.- */- SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY: number}export function getDefaultMlMirrorConfig(): MlMirrorConfig {@@ -288,7 +279,6 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_IMAGE_SCRUB_DLQ_TOPIC: KAFKA_SESSION_REPLAY_IMAGE_SCRUB_DLQ,SESSION_RECORDING_ML_IMAGE_SCRUB_BATCH_SIZE: 50,SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: 30 * 1000,- SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY: 0,}}@@ -305,23 +295,6 @@ export function getMlMirrorConfig(env: Record<string, string | undefined> = proc})}-const DEFAULT_UV_THREADPOOL_SIZE = 4--/**- * `os.availableParallelism()` respects cgroup CPU limits, so in-container this sees the pod's- * cores, not the node's.- */-export function resolveMlAnonymizeMaxConcurrency(- configured: number,- availableParallelism: number = os.availableParallelism(),- uvThreadpoolSize: number = parseInt(process.env.UV_THREADPOOL_SIZE ?? '', 10) || DEFAULT_UV_THREADPOOL_SIZE-): number {- if (configured > 0) {- return configured- }- return Math.max(1, Math.min(availableParallelism, uvThreadpoolSize))-}-/*** A host of whitespace counts as unset: chart values render to an empty string when the underlying* secret key is missing, and connecting to `""` would fail every command rather than return `null`.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/block-compression.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/block-compression.tsnew file mode 100644index 000000000000..483eb0e8c693--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/block-compression.ts@@ -0,0 +1,33 @@+import { brotliCompress, constants } from 'node:zlib'+import snappy from 'snappy'++export type BlockCompression = { codec: 'brotli'; level: number } | { codec: 'snappy' }++export const DEFAULT_BLOCK_COMPRESSION: BlockCompression = { codec: 'snappy' }++/** Both codecs pack on the libuv threadpool, not on the event loop. */+export function compressBlock(data: Buffer, compression: BlockCompression): Promise<Buffer> {+ switch (compression.codec) {+ case 'snappy':+ return snappy.compress(data)+ case 'brotli':+ return new Promise((resolve, reject) => {+ // We tried setting LGWIN:24, but this performed worse than leaving it unset. Just leave this unset+ // and let Brotli choose a good enough value.+ brotliCompress(+ data,+ {+ params: {+ [constants.BROTLI_PARAM_QUALITY]: compression.level,+ [constants.BROTLI_PARAM_SIZE_HINT]: data.length,+ },+ },+ (error, result) => (error ? reject(error) : resolve(result))+ )+ })+ default: {+ const _exhaustive: never = compression+ throw new Error(`Unknown block codec: ${JSON.stringify(_exhaustive)}`)+ }+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.tsindex d9786eee4a6d..a9516e83e526 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts@@ -41,6 +41,27 @@ export class SessionBatchMetrics {this.messagesDroppedSessionKeyMismatch.inc(count)}+ private static readonly blockCompressionLatency = new Histogram({+ name: 'recording_blob_ingestion_v2_block_compression_seconds',+ help: 'Time taken to compress one session block, by codec. A flush waits on these, so this is flush latency',+ labelNames: ['codec'],+ buckets: [0.0005, 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],+ })++ private static readonly blockCompressionRatio = new Histogram({+ name: 'recording_blob_ingestion_v2_block_compression_ratio',+ help: 'Raw bytes divided by packed bytes for one session block, by codec. Higher stores less',+ labelNames: ['codec'],+ buckets: [1, 2, 4, 6, 8, 10, 15, 20, 30, 50],+ })++ public static observeBlockCompression(codec: string, rawBytes: number, packedBytes: number, seconds: number): void {+ this.blockCompressionLatency.observe({ codec }, seconds)+ if (packedBytes > 0) {+ this.blockCompressionRatio.observe({ codec }, rawBytes / packedBytes)+ }+ }+private static readonly sessionsFlushed = new Counter({name: 'recording_blob_ingestion_v2_sessions_flushed_total',help: 'Number of individual sessions that have been flushed',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.test.tsindex abe5130b1a9e..4a96562a547a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.test.ts@@ -32,6 +32,7 @@ describe('SessionBatchManager', () => {}) as unknown as jest.Mocked<SessionBatchRecorder>const config = (overrides: Partial<SessionBatchManagerConfig> = {}): SessionBatchManagerConfig => ({+ compression: { codec: 'snappy' as const },maxBatchSizeBytes: 100,maxBatchAgeMs: 1000,maxEventsPerSessionPerBatch: Number.MAX_SAFE_INTEGER,@@ -93,7 +94,8 @@ describe('SessionBatchManager', () => {mockFeatureStore,mockEncryptor,Number.MAX_SAFE_INTEGER,- 100+ 100,+ { codec: 'snappy' })})@@ -117,7 +119,8 @@ describe('SessionBatchManager', () => {mockFeatureStore,mockEncryptor,maxEventsPerSessionPerBatch,- 100+ 100,+ { codec: 'snappy' })})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.tsindex e9dd3f712610..ff616a394737 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts@@ -3,6 +3,7 @@ import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/import { SessionMetadataSink } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'import { RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'+import { BlockCompression } from './block-compression'import { SessionBatchFileStorage } from './session-batch-file-storage'import { SessionBatchRecorder } from './session-batch-recorder'import { SessionConsoleLogStore } from './session-console-log-store'@@ -20,6 +21,7 @@ export interface SessionBatchManagerConfig {consoleLogStore: SessionConsoleLogStorefeatureStore: SessionFeatureStoreencryptor: RecordingEncryptor+ compression?: BlockCompression // default Snappy}/**@@ -65,6 +67,7 @@ export class SessionBatchManager {private readonly consoleLogStore: SessionConsoleLogStoreprivate readonly featureStore: SessionFeatureStoreprivate readonly encryptor: RecordingEncryptor+ private readonly compression?: BlockCompressionconstructor(config: SessionBatchManagerConfig) {this.maxBatchSizeBytes = config.maxBatchSizeBytes@@ -77,6 +80,7 @@ export class SessionBatchManager {this.consoleLogStore = config.consoleLogStorethis.featureStore = config.featureStorethis.encryptor = config.encryptor+ this.compression = config.compression}public createBatch(): SessionBatchRecorder {@@ -88,7 +92,8 @@ export class SessionBatchManager {this.featureStore,this.encryptor,this.maxEventsPerSessionPerBatch,- this.featuresRolloutPercentage+ this.featuresRolloutPercentage,+ this.compression)}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.tsindex cf5138be1e2b..6da25906fd29 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts@@ -13,11 +13,11 @@ import { MessageWithTeam } from '~/ingestion/pipelines/sessionreplay/teams/typesimport { SessionBatchMetrics } from './metrics'import { SessionBatchFileStorage, SessionBatchFileWriter } from './session-batch-file-storage'-import { SessionBatchRecorder } from './session-batch-recorder'+import { BLOCK_BUILD_CONCURRENCY, SessionBatchRecorder } from './session-batch-recorder'+import { EndResult, SessionBlockRecorder } from './session-block-recorder'import { SessionConsoleLogRecorder } from './session-console-log-recorder'import { SessionConsoleLogStore } from './session-console-log-store'import { SessionFeatureRecorder } from './session-feature-recorder'-import { EndResult, SnappySessionRecorder } from './snappy-session-recorder'// RRWeb event type constantsconst enum EventType {@@ -43,7 +43,7 @@ interface MessageMetadata {rawSize?: number}-export class SnappySessionRecorderMock {+export class SessionBlockRecorderMock {private chunks: Buffer[] = []private size: number = 0private startDateTime: DateTime | null = null@@ -189,12 +189,12 @@ jest.mock('./metrics', () => ({}))jest.mock('./blackhole-session-batch-writer')-jest.mock('./snappy-session-recorder', () => ({- SnappySessionRecorder: jest+jest.mock('./session-block-recorder', () => ({+ SessionBlockRecorder: jest.fn().mockImplementation((sessionId: string, teamId: number, batchId: string) =>- new SnappySessionRecorderMock(sessionId, teamId, batchId)+ new SessionBlockRecorderMock(sessionId, teamId, batchId)),}))@@ -219,9 +219,9 @@ describe('SessionBatchRecorder', () => {beforeEach(() => {jest.clearAllMocks()- jest.mocked(SnappySessionRecorder).mockImplementation(+ jest.mocked(SessionBlockRecorder).mockImplementation((sessionId: string, teamId: number, batchId: string) =>- new SnappySessionRecorderMock(sessionId, teamId, batchId) as unknown as SnappySessionRecorder+ new SessionBlockRecorderMock(sessionId, teamId, batchId) as unknown as SessionBlockRecorder)mockWriter = {@@ -894,6 +894,42 @@ describe('SessionBatchRecorder', () => {})describe('flushing behavior', () => {+ it('builds every block before it writes any, so packing uses the whole threadpool', async () => {+ const release: (() => void)[] = []+ let building = 0+ jest.mocked(SessionBlockRecorder).mockImplementation(+ (sessionId: string, teamId: number, batchId: string) => {+ const mock = new SessionBlockRecorderMock(sessionId, teamId, batchId)+ const build = mock.end.bind(mock)+ mock.end = (() => {+ building += 1+ return new Promise<EndResult>((resolve) => release.push(() => resolve(build())))+ }) as unknown as typeof mock.end+ return mock as unknown as SessionBlockRecorder+ }+ )++ await record(createMessage('session1', []))+ await record(createMessage('session2', []))+ await record(createMessage('session3', []))+ const flushed = recorder.flush()+ await new Promise((resolve) => setImmediate(resolve))++ // The pool size bounds the builds, so a sequential loop only looks different above one.+ expect(building).toBe(Math.min(3, BLOCK_BUILD_CONCURRENCY))+ // At any limit, no write happens until every block exists.+ expect(mockWriter.writeSession).not.toHaveBeenCalled()++ while (release.length) {+ release.splice(0).forEach((resolve) => resolve())+ await new Promise((resolve) => setImmediate(resolve))+ }+ await flushed++ expect(building).toBe(3)+ expect(mockWriter.writeSession).toHaveBeenCalledTimes(3)+ })+it('should clear sessions after flush', async () => {const message1 = createMessage('session1', [{@@ -1323,8 +1359,8 @@ describe('SessionBatchRecorder', () => {describe('metadata handling', () => {it('should pass non-default metadata values to storeSessionBlocks', async () => {- // Create a custom mock implementation of SnappySessionRecorderMock that returns non-default values- const customRecorder = new SnappySessionRecorderMock('session_custom', 3, 'test_batch_id')+ // Create a custom mock implementation of SessionBlockRecorderMock that returns non-default values+ const customRecorder = new SessionBlockRecorderMock('session_custom', 3, 'test_batch_id')// Override the end method to return non-default valuescustomRecorder.end = jest.fn().mockReturnValue({@@ -1346,8 +1382,8 @@ describe('SessionBatchRecorder', () => {batchId: 'test_batch_id',})- jest.mocked(SnappySessionRecorder).mockImplementationOnce(- () => customRecorder as unknown as SnappySessionRecorder+ jest.mocked(SessionBlockRecorder).mockImplementationOnce(+ () => customRecorder as unknown as SessionBlockRecorder)jest.mocked(SessionConsoleLogRecorder).mockImplementationOnce(@@ -1535,12 +1571,12 @@ describe('SessionBatchRecorder', () => {},]- jest.mocked(SnappySessionRecorder).mockImplementation(+ jest.mocked(SessionBlockRecorder).mockImplementation(() =>({recordMessage: jest.fn().mockReturnValue(1),end: () => Promise.reject(new Error('Stream read error')),- }) as unknown as SnappySessionRecorder+ }) as unknown as SessionBlockRecorder)await record(createMessage('session', events))diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.tsindex 9a4f3a541b4f..33f55ab51b30 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts@@ -1,7 +1,9 @@+import pLimit from 'p-limit'import { v7 as uuidv7 } from 'uuid'import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'+import { threadpoolConcurrency } from '~/common/utils/threadpool-concurrency'import { KafkaOffsetManager } from '~/ingestion/pipelines/sessionreplay/kafka/offset-manager'import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'import {@@ -14,23 +16,29 @@ import { SessionMap } from '~/ingestion/pipelines/sessionreplay/shared/session-mimport { RecordingEncryptor, SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'import { MessageWithTeam } from '~/ingestion/pipelines/sessionreplay/teams/types'+import { BlockCompression } from './block-compression'import { SessionBatchMetrics } from './metrics'import { SessionBatchFileStorage } from './session-batch-file-storage'+import { SessionBlockRecorder } from './session-block-recorder'import { SessionConsoleLogRecorder } from './session-console-log-recorder'import { SessionConsoleLogStore } from './session-console-log-store'import { SessionFeatureRecorder } from './session-feature-recorder'import { SessionRateLimiter } from './session-rate-limiter'-import { SnappySessionRecorder } from './snappy-session-recorder'/** Per-session recording state held in the batch, keyed by `(teamId, sessionId)`. */interface SessionBatchEntry {- sessionBlockRecorder: SnappySessionRecorder+ sessionBlockRecorder: SessionBlockRecorderconsoleLogRecorder: SessionConsoleLogRecorderfeatureRecorder: SessionFeatureRecordersessionKey: SessionKeyretentionPeriod: RetentionPeriod}+// A flush holds the batch lock, so nothing else here wants the pool while it runs.+export const BLOCK_BUILD_CONCURRENCY = threadpoolConcurrency()++const buildBlock = pLimit(BLOCK_BUILD_CONCURRENCY)+/*** Manages the recording of a batch of session recordings:*@@ -91,7 +99,8 @@ export class SessionBatchRecorder {private readonly featureStore: SessionFeatureStore,private readonly encryptor: RecordingEncryptor,maxEventsPerSessionPerBatch: number = Number.MAX_SAFE_INTEGER,- private readonly featuresRolloutPercentage: number = 100+ private readonly featuresRolloutPercentage: number = 100,+ private readonly compression?: BlockCompression) {this.batchId = uuidv7()this.rateLimiter = new SessionRateLimiter(maxEventsPerSessionPerBatch)@@ -174,7 +183,7 @@ export class SessionBatchRecorder {}} else {this.sessions.set(teamId, sessionId, {- sessionBlockRecorder: new SnappySessionRecorder(sessionId, teamId, this.batchId),+ sessionBlockRecorder: new SessionBlockRecorder(sessionId, teamId, this.batchId, this.compression),consoleLogRecorder: new SessionConsoleLogRecorder(sessionId,teamId,@@ -265,13 +274,14 @@ export class SessionBatchRecorder {let totalBytes = 0try {- for (const {- sessionBlockRecorder,- consoleLogRecorder,- featureRecorder,- sessionKey,- retentionPeriod,- } of this.sessions.values()) {+ // Each block packs on its own, on the threadpool, so start them all at once. The writes stay in order, because they append to one file.+ const entries = [...this.sessions.values()]+ const built = await Promise.all(entries.map((entry) => buildBlock(() => entry.sessionBlockRecorder.end())))++ for (const [+ index,+ { sessionBlockRecorder, consoleLogRecorder, featureRecorder, sessionKey, retentionPeriod },+ ] of entries.entries()) {const {buffer,eventCount,@@ -291,7 +301,7 @@ export class SessionBatchRecorder {replayIndexEntries,replayIndexTruncated,batchId,- } = await sessionBlockRecorder.end()+ } = built[index]const features = featureRecorder.end()if (features) {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.test.tssimilarity index 91%rename from nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.tsrename to nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.test.tsindex 34f57e0a307f..1f760dce3841 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.test.ts@@ -1,17 +1,25 @@import { DateTime } from 'luxon'+import { brotliDecompressSync } from 'node:zlib'import snappy from 'snappy'import { parseJSON } from '~/common/utils/json-parse'import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'import { RRWebEventType } from '~/ingestion/pipelines/sessionreplay/rrweb-types'-import { SnappySessionRecorder } from './snappy-session-recorder'+import { compressBlock } from './block-compression'+import { SessionBatchMetrics } from './metrics'+import { SessionBlockRecorder } from './session-block-recorder'-describe('SnappySessionRecorder', () => {- let recorder: SnappySessionRecorder+jest.mock('./block-compression', () => {+ const actual = jest.requireActual('./block-compression')+ return { ...actual, compressBlock: jest.fn(actual.compressBlock) }+})++describe('SessionBlockRecorder', () => {+ let recorder: SessionBlockRecorderbeforeEach(() => {- recorder = new SnappySessionRecorder('test_session_id', 1, 'test_batch_id')+ recorder = new SessionBlockRecorder('test_session_id', 1, 'test_batch_id')})const createMessage = (windowId: string, events: any[]): ParsedMessageData => ({@@ -52,6 +60,90 @@ describe('SnappySessionRecorder', () => {.map((line) => parseJSON(line))}+ describe('compression', () => {+ it('packs with the declared codec at the declared level, and reports it', async () => {+ const recorder = new SessionBlockRecorder('test_session_id', 1, 'test_batch_id', {+ codec: 'brotli',+ level: 5,+ })+ recorder.recordMessage(createMessage('window1', [{ type: 3, timestamp: 1000, data: {} }]))++ const result = await recorder.end()++ expect(brotliDecompressSync(result.buffer).toString()).toContain('"timestamp":1000')+ })++ it('packs with snappy when a lane declares nothing', async () => {+ const recorder = new SessionBlockRecorder('test_session_id', 1, 'test_batch_id')+ recorder.recordMessage(createMessage('window1', [{ type: 3, timestamp: 1000, data: {} }]))++ const result = await recorder.end()++ expect(snappy.uncompressSync(result.buffer, { asBuffer: true }).toString()).toContain('"timestamp":1000')+ })++ it('stays callable after packing fails, so a retried flush can still write the block', async () => {+ jest.mocked(compressBlock).mockRejectedValueOnce(new Error('out of memory'))+ const recorder = new SessionBlockRecorder('test_session_id', 1, 'test_batch_id')+ recorder.recordMessage(createMessage('window1', [{ type: 3, timestamp: 1000, data: {} }]))++ await expect(recorder.end()).rejects.toThrow('out of memory')++ const result = await recorder.end()++ expect(jest.mocked(compressBlock)).toHaveBeenCalledTimes(2)+ expect(result.eventCount).toBe(1)+ expect((await recorder.end()).buffer).toEqual(result.buffer)+ })++ it('refuses a message once a block is being built, so no event is counted but left out', async () => {+ let release!: () => void+ jest.mocked(compressBlock).mockImplementationOnce(+ (data: Buffer) =>+ new Promise<Buffer>((resolve) => {+ release = () => resolve(data)+ })+ )+ const recorder = new SessionBlockRecorder('test_session_id', 1, 'test_batch_id')+ const message = createMessage('window1', [{ type: 3, timestamp: 1000, data: {} }])+ recorder.recordMessage(message)+ const building = recorder.end()++ expect(() => recorder.recordMessage(message)).toThrow('Cannot record message after end() has been called')++ release()+ expect((await building).eventCount).toBe(1)+ })++ it('packs once when two callers end the same block', async () => {+ const recorder = new SessionBlockRecorder('test_session_id', 1, 'test_batch_id')+ recorder.recordMessage(createMessage('window1', [{ type: 3, timestamp: 1000, data: {} }]))++ const [a, b] = await Promise.all([recorder.end(), recorder.end()])++ expect(jest.mocked(compressBlock)).toHaveBeenCalledTimes(1)+ expect(a.buffer).toEqual(b.buffer)+ })++ it('reports the codec and both byte counts, so the saving is measurable', async () => {+ const observe = jest.spyOn(SessionBatchMetrics, 'observeBlockCompression').mockImplementation()+ const recorder = new SessionBlockRecorder('test_session_id', 1, 'test_batch_id', {+ codec: 'brotli',+ level: 9,+ })+ recorder.recordMessage(createMessage('window1', [{ type: 3, timestamp: 1000, data: {} }]))++ const result = await recorder.end()++ expect(observe).toHaveBeenCalledTimes(1)+ const [codec, rawBytes, packedBytes] = observe.mock.calls[0]+ expect(codec).toBe('brotli')+ expect(packedBytes).toBe(result.buffer.length)+ expect(rawBytes).toBeGreaterThan(packedBytes)+ observe.mockRestore()+ })+ })+describe('recordMessage', () => {it('should record events in snappy-compressed JSONL format', async () => {const events = [@@ -178,14 +270,17 @@ describe('SnappySessionRecorder', () => {expect(() => recorder.recordMessage(message)).toThrow('Cannot record message after end() has been called')})- it('should throw error when calling end multiple times', async () => {+ it('returns the same block when end is called again, so a retried flush re-emits it', async () => {const message = createMessage('window1', [{ type: RRWebEventType.Custom, timestamp: new Date('2025-01-01T01:00:00Z').getTime(), data: {} },])recorder.recordMessage(message)- await recorder.end()+ const first = await recorder.end()++ const second = await recorder.end()- await expect(recorder.end()).rejects.toThrow('end() has already been called')+ expect(second.buffer).toEqual(first.buffer)+ expect(second.eventCount).toBe(first.eventCount)})})@@ -1073,7 +1168,7 @@ describe('SnappySessionRecorder', () => {describe('Batch ID', () => {it('should include batch ID in end result', async () => {const batchId = 'test-batch-123'- const recorder = new SnappySessionRecorder('test_session_id', 1, batchId)+ const recorder = new SessionBlockRecorder('test_session_id', 1, batchId)const message = createMessage('window1', [{type: RRWebEventType.Meta,@@ -1090,7 +1185,7 @@ describe('SnappySessionRecorder', () => {it('should maintain batch ID across multiple messages', async () => {const batchId = 'test-batch-456'- const recorder = new SnappySessionRecorder('test_session_id', 1, batchId)+ const recorder = new SessionBlockRecorder('test_session_id', 1, batchId)const message1 = createMessage('window1', [{ type: RRWebEventType.Meta, timestamp: DateTime.fromISO('2025-01-01T01:00:00Z').toMillis(), data: {} },@@ -1108,7 +1203,7 @@ describe('SnappySessionRecorder', () => {it('should include batch ID even with no messages', async () => {const batchId = 'test-batch-789'- const recorder = new SnappySessionRecorder('test_session_id', 1, batchId)+ const recorder = new SessionBlockRecorder('test_session_id', 1, batchId)const result = await recorder.end()expect(result.batchId).toBe(batchId)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.tssimilarity index 86%rename from nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.tsrename to nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.tsindex a1a9a5ac89f8..c63a899585b6 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.ts@@ -1,5 +1,4 @@import { DateTime } from 'luxon'-import snappy from 'snappy'import { logger } from '~/common/utils/logger'import {@@ -25,6 +24,9 @@ import {} from '~/ingestion/pipelines/sessionreplay/segmentation'import { ReplayIndexEntry } from '~/ingestion/pipelines/sessionreplay/shared/metadata/replay-index-entry'+import { BlockCompression, DEFAULT_BLOCK_COMPRESSION, compressBlock } from './block-compression'+import { SessionBatchMetrics } from './metrics'+const MAX_SNAPSHOT_FIELD_LENGTH = 1000const MAX_URL_LENGTH = 4 * 1024 // 4KBconst MAX_URLS_COUNT = 25@@ -68,14 +70,14 @@ export interface EndResult {}/**- * Records events for a single session recording using Snappy compression+ * Records events for a single session recording*- * Buffers events and provides them as a snappy-compressed session recording block that can be- * stored in a session batch file. The session recording block can be read as an independent unit.+ * Buffers events and provides them as a compressed session recording block that can be stored in a session batch+ * file. The session recording block can be read as an independent unit.** ```* Session Batch File- * ├── Snappy Session Recording Block 1 <── One SessionRecorder corresponds to one block+ * ├── Compressed Session Recording Block 1 <── One SessionBlockRecorder corresponds to one block* │ └── JSONL Session Recording Block* │ ├── [windowId, event1]* │ ├── [windowId, event2]@@ -90,11 +92,12 @@ export interface EndResult {* The session block format (after decompression) is a sequence of newline-delimited JSON records.* Each record is an array of [windowId, event].*/-export class SnappySessionRecorder {+export class SessionBlockRecorder {private readonly uncompressedChunks: Buffer[] = []private eventCount: number = 0private size: number = 0private ended = false+ private building?: Promise<EndResult>private startDateTime: DateTime | null = nullprivate endDateTime: DateTime | null = nullprivate _distinctId: string | null = null@@ -116,7 +119,8 @@ export class SnappySessionRecorder {constructor(public readonly sessionId: string,public readonly teamId: number,- public readonly batchId: string+ public readonly batchId: string,+ private readonly compression: BlockCompression = DEFAULT_BLOCK_COMPRESSION) {}/**@@ -302,18 +306,35 @@ export class SnappySessionRecorder {/*** Finalizes the session recording and returns the compressed buffer with metadata*+ * Idempotent. A flush writes every block before it finishes the batch file, so a throw in that loop abandons the+ * file and the retry must emit the blocks it already built. A failed build is discarded, so the retry rebuilds it.+ ** @returns The compressed session recording block with metadata- * @throws If called more than once*/- public async end(): Promise<EndResult> {- if (this.ended) {- throw new Error('end() has already been called')+ public end(): Promise<EndResult> {+ if (!this.building) {+ this.ended = true+ this.building = this.buildBlock().catch((error: unknown) => {+ this.building = undefined+ throw error+ })}- this.ended = true+ return this.building+ }+ private async buildBlock(): Promise<EndResult> {// Buffer.concat typings are missing the signature with Buffer[]const uncompressedBuffer = Buffer.concat(this.uncompressedChunks as any)- const buffer = await snappy.compress(uncompressedBuffer)+ const startedAt = performance.now()+ const buffer = await compressBlock(uncompressedBuffer, this.compression)+ // A built block answers every later end(), so the raw chunks are dead. A flush holds every block, so free them.+ this.uncompressedChunks.length = 0+ SessionBatchMetrics.observeBlockCompression(+ this.compression.codec,+ uncompressedBuffer.length,+ buffer.length,+ (performance.now() - startedAt) / 1000+ )// Calculate active time using segmentation eventsconst activeTime = activeMillisecondsFromSegmentationEvents(this.segmentationEvents)diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex 94a48761bcd5..097a30dcd98b 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -6,6 +6,7 @@ import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { PostgresRouter } from '~/common/utils/db/postgres'import { parseJSON } from '~/common/utils/json-parse'import { logger } from '~/common/utils/logger'+import { threadpoolConcurrency } from '~/common/utils/threadpool-concurrency'import { AllowListFetcher, loadAllowLists } from '~/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader'import { type SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'import {@@ -14,10 +15,7 @@ import {} from '~/ingestion/pipelines/sessionreplay/consumer'import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'import { DynamoDBCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history'-import {- resolveMlAnonymizeMaxConcurrency,- resolveMlMirrorRedisConnection,-} from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'+import { resolveMlMirrorRedisConnection } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'import { MlBlockMetadataSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink'import { resolvePseudonymKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key'@@ -131,9 +129,7 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServerrunner: new MlMirrorStagedBatchRunner({keyManager,- anonymizeMaxConcurrency: resolveMlAnonymizeMaxConcurrency(- this.config.SESSION_RECORDING_ML_ANONYMIZE_MAX_CONCURRENCY- ),+ anonymizeMaxConcurrency: threadpoolConcurrency(),},this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED? {