OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
perf(ingest): session write-back no longer type-checks keys or flushes inline
Carl-Gerhard Lindesvärd61c3870cc522
diff --git a/packages/core/src/buffers/base-buffer.ts b/packages/core/src/buffers/base-buffer.tsindex 6d5614723..a9945f340 100644--- a/packages/core/src/buffers/base-buffer.ts+++ b/packages/core/src/buffers/base-buffer.ts@@ -6,6 +6,7 @@ import { type ChQueryInput, type ChScope, chQuery } from '../ch-query';import type { CoreConfig } from '../config';import type { Logger } from '../logger';import type { ServiceDeps } from '../services';+import { defineRedisScript } from './redis-script';/** What a buffer needs from the boot scope; a test constructs its own. */export interface BufferDeps {@@ -41,6 +42,14 @@ export interface BufferDeps {*/const DEFAULT_CH_INSERT_CONCURRENCY = 5;+const releaseLockScript = defineRedisScript(`+if redis.call("get", KEYS[1]) == ARGV[1] then+ return redis.call("del", KEYS[1])+else+ return 0+end+`);+export type FlushPhaseTimings = {lrangeMs?: number;/** Time spent in CH SELECT(s) during flush (e.g. profile-buffer's@@ -349,14 +358,7 @@ export class BaseBuffer {}private async releaseLock(lockId: string): Promise<void> {- const script = `- if redis.call("get", KEYS[1]) == ARGV[1] then- return redis.call("del", KEYS[1])- else- return 0- end- `;- await getRedisCache().eval(script, 1, this.lockKey, lockId);+ await releaseLockScript(getRedisCache(), [this.lockKey], [lockId]);}/**diff --git a/packages/core/src/buffers/redis-script.ts b/packages/core/src/buffers/redis-script.tsnew file mode 100644index 000000000..aca7c3294--- /dev/null+++ b/packages/core/src/buffers/redis-script.ts@@ -0,0 +1,27 @@+import { createHash } from 'node:crypto';+import type { Redis } from '@openpanel/redis';++/**+ * A Lua script sent as EVALSHA, so the body crosses the wire only when Redis+ * has not cached it yet (NOSCRIPT → EVAL, which caches it).+ */+export function defineRedisScript(lua: string) {+ const sha = createHash('sha1').update(lua).digest('hex');++ return async (+ redis: Redis,+ keys: string[],+ args: string[]+ ): Promise<unknown> => {+ try {+ return await redis.evalsha(sha, keys.length, ...keys, ...args);+ } catch (error) {+ const isNotCached =+ error instanceof Error && error.message.startsWith('NOSCRIPT');+ if (!isNotCached) {+ throw error;+ }+ return await redis.eval(lua, keys.length, ...keys, ...args);+ }+ };+}diff --git a/packages/core/src/buffers/session-buffer.test.ts b/packages/core/src/buffers/session-buffer.test.tsindex 5555d1fc0..f65b28a44 100644--- a/packages/core/src/buffers/session-buffer.test.ts+++ b/packages/core/src/buffers/session-buffer.test.ts@@ -1,6 +1,7 @@-import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';+import { beforeEach, describe, expect, it, mock } from 'bun:test';import { getRedisCache } from '@openpanel/redis';import { bufferDepsWithCh } from '../../test/buffer-fixtures';+import { testCoreConfig } from '../../test/config-fixture';import type { IServiceCreateEventPayload } from '../modules/event/event.service';import type { IClickhouseSession } from '../modules/session/session.service';@@ -363,52 +364,69 @@ describe('SessionBuffer', () => {expect(await sessionBuffer.getBufferSize()).toBe(1);});- // persist() is one Lua script, so a failure part-way through must leave the- // four session keys and the buffer list exactly as they were. A wrong-type- // key is the cheapest way to force that failure from outside.- describe('persist atomicity', () => {- // These tests poison shared keys on the local Redis on purpose. Clear them- // here too — beforeEach only protects this file, not a concurrently- // running stack.- afterEach(async () => {- await redis.del('session-buffer', `session:wallclock:${projectId}`);+ // The write-back runs once per client event, so every extra command on it is+ // multiplied by the whole ingest rate.+ it('ingest sends no TYPE, EVAL or EVALSHA to Redis', async () => {+ const monitor = await redis.duplicate().monitor();+ const commands: string[] = [];+ let sentinelSeen = false;+ // A dev stack may share this Redis, so only commands on this test's+ // project count.+ monitor.on('monitor', (_time: string, args: string[]) => {+ if (args.includes(MONITOR_SENTINEL)) {+ sentinelSeen = true;+ } else if (args.some((arg) => arg.includes(projectId))) {+ commands.push(String(args[0]).toLowerCase());+ }});- async function expectNothingWritten() {- expect(await redis.get(`session:${projectId}:${deviceId}`)).toBeNull();- expect(- await redis.get(`session:profile:${projectId}:profile-1`)- ).toBeNull();- expect(await redis.sismember('session:projects', projectId)).toBe(0);+ const t0 = Date.now();+ await sessionBuffer.ingest(makePayload({ createdAt: new Date(t0) }));+ await sessionBuffer.ingest(makePayload({ createdAt: new Date(t0 + 1000) }));+ await redis.ping(MONITOR_SENTINEL);+ while (!sentinelSeen) {+ await Bun.sleep(MONITOR_POLL_MS);}+ monitor.disconnect();- it('writes no key when the wallclock set holds the wrong type', async () => {- await redis.set(`session:wallclock:${projectId}`, 'not-a-zset');+ expect(commands).toContain('rpush');+ expect(commands).not.toContain('type');+ expect(commands).not.toContain('eval');+ expect(commands).not.toContain('evalsha');+ });- const result = await sessionBuffer.ingest(makePayload());+ it('ingest never flushes, even past the batch size', async () => {+ const buffer = bufferWithBatchSize(2);+ const t0 = Date.now();+ for (let i = 0; i < 5; i++) {+ await buffer.ingest(makePayload({ createdAt: new Date(t0 + i * 1000) }));+ }- expect(result).toBeNull();- await expectNothingWritten();- expect(await redis.llen('session-buffer')).toBe(0);- expect(await redis.get(`session:wallclock:${projectId}`)).toBe(- 'not-a-zset'- );- });+ expect(chInsert).not.toHaveBeenCalled();+ expect(await buffer.getBufferSize()).toBe(9);+ });- it('writes no key when the buffer list holds the wrong type', async () => {- // The buffer list is written last, so without an up-front type check- // the blob, wallclock entry and project registration would already be- // committed by the time this fails — Redis does not roll them back.- await redis.set('session-buffer', 'not-a-list');+ it('a flush drains a backlog larger than one batch', async () => {+ const buffer = bufferWithBatchSize(3);+ const t0 = Date.now();+ for (let i = 0; i < 10; i++) {+ await buffer.ingest(+ makePayload({ deviceId: `device-${i}`, createdAt: new Date(t0) })+ );+ }- const result = await sessionBuffer.ingest(makePayload());+ await buffer.tryFlush({ trigger: 'cron' });- expect(result).toBeNull();- await expectNothingWritten();- expect(- await redis.zscore(`session:wallclock:${projectId}`, deviceId)- ).toBeNull();- expect(await redis.get('session-buffer')).toBe('not-a-list');- });+ expect(chInsert).toHaveBeenCalledTimes(4);+ expect(await buffer.getBufferSize()).toBe(0);});});++const MONITOR_SENTINEL = 'session-buffer-test-done';+const MONITOR_POLL_MS = 5;++function bufferWithBatchSize(batchSize: number) {+ const config = testCoreConfig();+ config.buffers.session.batchSize = batchSize;+ return new SessionBuffer(bufferDepsWithCh({ insert: chInsert }, config));+}diff --git a/packages/core/src/buffers/session-buffer.ts b/packages/core/src/buffers/session-buffer.tsindex d69e77201..02ff81e85 100644--- a/packages/core/src/buffers/session-buffer.ts+++ b/packages/core/src/buffers/session-buffer.ts@@ -5,6 +5,7 @@ import type { IServiceCreateEventPayload } from '../modules/event/event.service'import type { IClickhouseSession } from '../modules/session/session.service';import { TABLE_NAMES } from '../shared/ch-tables';import { BaseBuffer, type BufferDeps } from './base-buffer';+import { defineRedisScript } from './redis-script';// 30min of idle in event-time → session ends.const DEFAULT_SESSION_TIMEOUT_MS = 1000 * 60 * 30;@@ -30,7 +31,7 @@ const PROJECTS_SET_KEY = 'session:projects';// profile pointer if the live blob's session id matches the one we're// closing. Prevents races where a boundary has already overwritten the slot// with a new session.-const CLEANUP_LUA = `+const cleanupScript = defineRedisScript(`local cur = redis.call('GET', KEYS[1])if cur thenlocal ok, parsed = pcall(cjson.decode, cur)@@ -44,53 +45,7 @@ if KEYS[3] ~= '' thenredis.call('DEL', KEYS[3])endreturn 1-`;--const PERSIST_KEY_COUNT = 5;--// Atomic session write-back: blob + wallclock entry + project registration +-// optional profile pointer + the ClickHouse rows, in one round trip. Returns-// the buffer list length so the caller can decide on a flush without a second-// call.-//-// Redis does not undo a script's completed writes when a later command fails,-// so every key is type-checked before the first write — a wrong-type key then-// aborts the script with nothing written, rather than half of it.-const PERSIST_LUA = `-local blobKey, wallclockKey, projectsKey, profileKey, bufferKey =- KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5]-local session, wallclockScore, deviceId, projectId =- ARGV[1], ARGV[2], ARGV[3], ARGV[4]--local function assertType(key, expected)- if key == '' then- return- end- local actual = redis.call('TYPE', key)['ok']- if actual ~= 'none' and actual ~= expected then- error({ err = 'WRONGTYPE ' .. key .. ' holds ' .. actual .. ', expected ' .. expected })- end-end--assertType(blobKey, 'string')-assertType(wallclockKey, 'zset')-assertType(projectsKey, 'set')-assertType(profileKey, 'string')-assertType(bufferKey, 'list')--redis.call('SET', blobKey, session)-redis.call('ZADD', wallclockKey, wallclockScore, deviceId)-redis.call('SADD', projectsKey, projectId)-if profileKey ~= '' then- redis.call('SET', profileKey, deviceId)-end--local bufferLength = redis.call('LLEN', bufferKey)-for i = 5, #ARGV do- bufferLength = redis.call('RPUSH', bufferKey, ARGV[i])-end-return bufferLength-`;+`);export type SessionIngestResult =| { kind: 'new'; current: IClickhouseSession }@@ -126,6 +81,8 @@ function pickUtm(const DEFAULT_BATCH_SIZE = 1000;const DEFAULT_CHUNK_SIZE = 1000;+/** One cron run drains as many batches as fit before the next run is due. */+const DRAIN_TIME_BUDGET_MS = 8000;export class SessionBuffer extends BaseBuffer {private readonly batchSize =@@ -137,7 +94,7 @@ export class SessionBuffer extends BaseBuffer {private readonly idleTimeoutMs = resolveSessionTimeoutMs(this.deps.config);private readonly redisKey = 'session-buffer';- private redis: Redis;+ private readonly redis: Redis;constructor(deps: BufferDeps) {super(deps, {name: 'session',@@ -247,14 +204,10 @@ export class SessionBuffer extends BaseBuffer {? profileIndexKey(projectId, profileId): '';- await this.redis.eval(- CLEANUP_LUA,- 3,- sessionKey(projectId, deviceId),- wallclockSetKey(projectId),- pointerKey,- sessionId,- deviceId+ await cleanupScript(+ this.redis,+ [sessionKey(projectId, deviceId), wallclockSetKey(projectId), pointerKey],+ [sessionId, deviceId]);}@@ -396,8 +349,9 @@ export class SessionBuffer extends BaseBuffer {}/**- * Atomic write-back: session blob + wallclock ZSET + projects SET +- * profile index + ClickHouse buffer rows, in a single Lua script.+ * Write-back in one MULTI: session blob + wallclock ZSET + projects SET ++ * profile index + ClickHouse buffer rows. Append only; the cron drains the+ * buffer, so ingest never waits on a ClickHouse insert.** No TTLs on the blob or profile index — they are removed exclusively by* `cleanup()` after `session_end` emission. This guarantees the reaper@@ -410,28 +364,27 @@ export class SessionBuffer extends BaseBuffer {) {const projectId = current.project_id;const deviceId = current.device_id;- const pointerKey =- current.profile_id && current.profile_id !== current.device_id- ? profileIndexKey(projectId, current.profile_id)- : '';+ const hasProfilePointer =+ current.profile_id && current.profile_id !== current.device_id;++ const multi = this.redis+ .multi()+ .set(sessionKey(projectId, deviceId), JSON.stringify(current))+ .zadd(wallclockSetKey(projectId), Date.now(), deviceId)+ .sadd(PROJECTS_SET_KEY, projectId);+ if (hasProfilePointer) {+ multi.set(profileIndexKey(projectId, current.profile_id), deviceId);+ }+ multi.rpush(this.redisKey, ...chRows.map((row) => JSON.stringify(row)));- const bufferLength = (await this.redis.eval(- PERSIST_LUA,- PERSIST_KEY_COUNT,- sessionKey(projectId, deviceId),- wallclockSetKey(projectId),- PROJECTS_SET_KEY,- pointerKey,- this.redisKey,- JSON.stringify(current),- Date.now().toString(),- deviceId,- projectId,- ...chRows.map((row) => JSON.stringify(row))- )) as number;-- if (bufferLength >= this.batchSize) {- await this.tryFlush();+ // Ioredis resolves a MULTI whose commands failed, with the error per entry.+ const results = await multi.exec();+ if (results === null) {+ throw new Error('session write-back transaction was aborted');+ }+ const rejected = results.find(([commandError]) => commandError !== null);+ if (rejected?.[0]) {+ throw rejected[0];}}@@ -532,13 +485,29 @@ export class SessionBuffer extends BaseBuffer {}async processBuffer() {+ const deadline = performance.now() + DRAIN_TIME_BUDGET_MS;+ let rowsProcessed = 0;++ while (performance.now() < deadline) {+ const processed = await this.processBatch();+ rowsProcessed += processed;+ if (processed < this.batchSize) {+ break;+ }+ }++ this.reportFlushStats({ rowsProcessed });+ }++ /** Inserts and trims one batch from the head of the list; returns its size. */+ private async processBatch(): Promise<number> {const events = await this.redis.lrange(this.redisKey,0,this.batchSize - 1);if (events.length === 0) {- return;+ return 0;}const parsed: IClickhouseSession[] = [];@@ -577,6 +546,7 @@ export class SessionBuffer extends BaseBuffer {await this.redis.ltrim(this.redisKey, events.length, -1);this.logger.debug({ count: events.length }, 'Processed sessions');+ return events.length;}protected getRedisListKey(): string {