Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix(ingest): session replay buffer drains a large backlog instead of stalling

Carl-Gerhard Lindesvärdb2716cc41122
diff --git a/packages/core/src/buffers/replay-buffer.test.ts b/packages/core/src/buffers/replay-buffer.test.ts
new file mode 100644
index 000000000..b1f773b27
--- /dev/null
+++ b/packages/core/src/buffers/replay-buffer.test.ts
@@ -0,0 +1,102 @@
+import { beforeEach, describe, expect, it, mock } from 'bun:test';
+import type { Readable } from 'node:stream';
+import { getRedisCache } from '@openpanel/redis';
+import { bufferDepsWithCh } from '../../test/buffer-fixtures';
+import { testCoreConfig } from '../../test/config-fixture';
+import {
+ type IClickhouseSessionReplayChunk,
+ ReplayBuffer,
+} from './replay-buffer';
+
+const redis = getRedisCache();
+const REDIS_KEY = 'replay-buffer';
+const ONE_MB = 1024 * 1024;
+/** The production backlog's shape: more 1 MB chunks than one 8 MB batch holds. */
+const BACKLOG_CHUNKS = 30;
+/** One LRANGE slice past the byte budget is the most a batch may overshoot. */
+const MAX_ROWS_PER_BATCH_OF_1MB = 10;
+
+const insertedBatches: string[][] = [];
+const chInsert = mock(async (options: { values: Readable }) => {
+ const rows: string[] = [];
+ for await (const row of options.values) {
+ rows.push(row as string);
+ }
+ insertedBatches.push(rows);
+});
+
+function bufferWithBatchSize(batchSize: number) {
+ const config = testCoreConfig();
+ config.buffers.replay.batchSize = batchSize;
+ return new ReplayBuffer(bufferDepsWithCh({ insert: chInsert }, config));
+}
+
+function chunk(index: number, payloadBytes: number) {
+ return {
+ project_id: 'project-1',
+ session_id: 'session-1',
+ chunk_index: index,
+ started_at: '2026-10-08 09:00:00',
+ ended_at: '2026-10-08 09:00:10',
+ events_count: 1,
+ is_full_snapshot: false,
+ payload: 'x'.repeat(payloadBytes),
+ } satisfies IClickhouseSessionReplayChunk;
+}
+
+beforeEach(async () => {
+ await redis.del(REDIS_KEY, 'lock:replay');
+ insertedBatches.length = 0;
+ chInsert.mockClear();
+});
+
+describe('ReplayBuffer', () => {
+ it('only appends on add, even far past the batch size', async () => {
+ const buffer = bufferWithBatchSize(2);
+
+ for (let index = 0; index < 5; index++) {
+ await buffer.add(chunk(index, 10));
+ }
+
+ expect(await redis.llen(REDIS_KEY)).toBe(5);
+ expect(chInsert).not.toHaveBeenCalled();
+ });
+
+ it('drains a backlog of 1 MB chunks in byte-bounded batches in one flush', async () => {
+ const buffer = bufferWithBatchSize(1000);
+ for (let index = 0; index < BACKLOG_CHUNKS; index++) {
+ await buffer.add(chunk(index, ONE_MB));
+ }
+
+ await buffer.tryFlush({ trigger: 'cron' });
+
+ expect(await redis.llen(REDIS_KEY)).toBe(0);
+ expect(chInsert.mock.calls.length).toBeGreaterThan(1);
+ const insertedIndexes = insertedBatches
+ .flat()
+ .map((row) => (JSON.parse(row) as { chunk_index: number }).chunk_index);
+ expect(insertedIndexes).toEqual(
+ Array.from({ length: BACKLOG_CHUNKS }, (_, index) => index)
+ );
+ for (const batch of insertedBatches) {
+ expect(batch.length).toBeLessThanOrEqual(MAX_ROWS_PER_BATCH_OF_1MB);
+ }
+ });
+
+ it('keeps the batch when the insert fails and drains it on the next flush', async () => {
+ const buffer = bufferWithBatchSize(1000);
+ for (let index = 0; index < 3; index++) {
+ await buffer.add(chunk(index, 10));
+ }
+ chInsert.mockImplementationOnce(() =>
+ Promise.reject(new Error('clickhouse down'))
+ );
+
+ await buffer.tryFlush({ trigger: 'cron' });
+ expect(await redis.llen(REDIS_KEY)).toBe(3);
+
+ await buffer.tryFlush({ trigger: 'cron' });
+ expect(await redis.llen(REDIS_KEY)).toBe(0);
+ expect(insertedBatches.flat()).toHaveLength(3);
+ });
+});
diff --git a/packages/core/src/buffers/replay-buffer.ts b/packages/core/src/buffers/replay-buffer.ts
index dd73aef62..9f1fc9002 100644
--- a/packages/core/src/buffers/replay-buffer.ts
+++ b/packages/core/src/buffers/replay-buffer.ts
@@ -15,6 +15,15 @@ export interface IClickhouseSessionReplayChunk {
const DEFAULT_BATCH_SIZE = 500;
const DEFAULT_CHUNK_SIZE = 500;
+/**
+ * Chunks average ~270 KB and reach 1 MB, so a batch is bounded in bytes as well
+ * as count, and read a few items per LRANGE: one count-sized read once asked
+ * Redis for 260 MB, timed out on every retry and let the list grow unbounded.
+ */
+const READ_SLICE_SIZE = 10;
+const MAX_BATCH_BYTES = 8 * 1024 * 1024;
+/** One cron run drains as many batches as fit before the next run is due. */
+const DRAIN_TIME_BUDGET_MS = 8000;
export class ReplayBuffer extends BaseBuffer {
private readonly batchSize =
@@ -33,20 +42,14 @@ export class ReplayBuffer extends BaseBuffer {
});
}
+ /**
+ * Append only. Flushing is the cron's job: an add-triggered flush ran on
+ * every API request once a backlog existed, inside the request.
+ */
async add(chunk: IClickhouseSessionReplayChunk) {
return this.timeAdd(async () => {
try {
- const redis = getRedisCache();
- const result = await redis
- .multi()
- .rpush(this.redisKey, JSON.stringify(chunk))
- .llen(this.redisKey)
- .exec();
-
- const bufferLength = (result?.[1]?.[1] as number) ?? 0;
- if (bufferLength >= this.batchSize) {
- await this.tryFlush({ trigger: 'add' });
- }
+ await getRedisCache().rpush(this.redisKey, JSON.stringify(chunk));
} catch (error) {
this.logger.error(
{ err: error },
@@ -61,21 +64,66 @@ export class ReplayBuffer extends BaseBuffer {
}
async processBuffer() {
- const redis = getRedisCache();
+ const deadline = performance.now() + DRAIN_TIME_BUDGET_MS;
+ let rowsProcessed = 0;
+ const phases = { lrangeMs: 0, chInsertMs: 0, trimMs: 0 };
+
+ while (performance.now() < deadline) {
+ const lrangeStart = performance.now();
+ const { items, reachedEnd } = await this.readBatch();
+ phases.lrangeMs += performance.now() - lrangeStart;
+
+ if (items.length > 0) {
+ const chStart = performance.now();
+ await this.insert(items);
+ phases.chInsertMs += performance.now() - chStart;
+
+ const trimStart = performance.now();
+ await getRedisCache().ltrim(this.redisKey, items.length, -1);
+ phases.trimMs += performance.now() - trimStart;
+ rowsProcessed += items.length;
+ }
+
+ if (reachedEnd) {
+ break;
+ }
+ }
+
+ this.reportFlushStats({ rowsProcessed, phases });
+ }
- const lrangeStart = performance.now();
- const items = await redis.lrange(this.redisKey, 0, this.batchSize - 1);
- const lrangeMs = performance.now() - lrangeStart;
+ /** The head of the list, up to `batchSize` items or `MAX_BATCH_BYTES`. */
+ private async readBatch(): Promise<{ items: string[]; reachedEnd: boolean }> {
+ const redis = getRedisCache();
+ const items: string[] = [];
+ let bytes = 0;
- if (items.length === 0) {
- this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
- return;
+ while (items.length < this.batchSize && bytes < MAX_BATCH_BYTES) {
+ const requested = Math.min(
+ READ_SLICE_SIZE,
+ this.batchSize - items.length
+ );
+ const slice = await redis.lrange(
+ this.redisKey,
+ items.length,
+ items.length + requested - 1
+ );
+ for (const item of slice) {
+ items.push(item);
+ bytes += Buffer.byteLength(item);
+ }
+ if (slice.length < requested) {
+ return { items, reachedEnd: true };
+ }
}
- // Raw passthrough: each Redis entry is already a JSONEachRow line, and an
- // rrweb chunk's `payload` is 10–100KB, so skipping parse/stringify matters.
+ return { items, reachedEnd: false };
+ }
+
+ // Raw passthrough: each Redis entry is already a JSONEachRow line, and an
+ // rrweb chunk's `payload` is 10–100KB, so skipping parse/stringify matters.
+ private async insert(items: string[]) {
const ch = this.resolveCh();
- const chStart = performance.now();
await this.parallelLimit(this.chunks(items, this.chunkSize), (chunk) =>
ch.insert({
table: TABLE_NAMES.session_replay_chunks,
@@ -84,15 +132,5 @@ export class ReplayBuffer extends BaseBuffer {
clickhouse_settings: this.getClickhouseSettings(),
})
);
- const chInsertMs = performance.now() - chStart;
-
- const trimStart = performance.now();
- await redis.ltrim(this.redisKey, items.length, -1);
- const trimMs = performance.now() - trimStart;
-
- this.reportFlushStats({
- rowsProcessed: items.length,
- phases: { lrangeMs, chInsertMs, trimMs },
- });
}
}