Skip to content

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

fix: improve metrics for buffers

Carl-Gerhard Lindesvärd2841382fdc2c
diff --git a/apps/worker/src/jobs/cron.ts b/apps/worker/src/jobs/cron.ts
index 1cc45758f..d1e68be85 100644
--- a/apps/worker/src/jobs/cron.ts
+++ b/apps/worker/src/jobs/cron.ts
@@ -17,22 +17,22 @@ export async function cronJob(job: Job<CronQueuePayload>) {
return await salt();
}
case 'flushEvents': {
- return await eventBuffer.tryFlush();
+ return await eventBuffer.tryFlush({ trigger: 'cron' });
}
case 'flushProfiles': {
- return await profileBuffer.tryFlush();
+ return await profileBuffer.tryFlush({ trigger: 'cron' });
}
case 'flushSessions': {
- return await sessionBuffer.tryFlush();
+ return await sessionBuffer.tryFlush({ trigger: 'cron' });
}
case 'flushProfileBackfill': {
- return await profileBackfillBuffer.tryFlush();
+ return await profileBackfillBuffer.tryFlush({ trigger: 'cron' });
}
case 'flushReplay': {
- return await replayBuffer.tryFlush();
+ return await replayBuffer.tryFlush({ trigger: 'cron' });
}
case 'flushGroups': {
- return await groupBuffer.tryFlush();
+ return await groupBuffer.tryFlush({ trigger: 'cron' });
}
case 'ping': {
return await ping();
diff --git a/apps/worker/src/metrics.ts b/apps/worker/src/metrics.ts
index 0eabf89d6..6d8c3743a 100644
--- a/apps/worker/src/metrics.ts
+++ b/apps/worker/src/metrics.ts
@@ -1,6 +1,8 @@
import {
botBuffer,
eventBuffer,
+ groupBuffer,
+ profileBackfillBuffer,
profileBuffer,
replayBuffer,
sessionBuffer,
@@ -14,12 +16,11 @@ export const register = new Registry();
const queues = [sessionsQueue, cronQueue, ...eventsGroupQueues];
-// Histogram to track job processing time for eventsGroupQueues
export const eventsGroupJobDuration = new client.Histogram({
name: 'job_duration_ms',
help: 'Duration of job processing (in ms)',
labelNames: ['name', 'status'],
- buckets: [10, 25, 50, 100, 250, 500, 750, 1000, 2000, 5000, 10_000, 30_000], // 10ms to 30s
+ buckets: [10, 25, 50, 100, 250, 500, 750, 1000, 2000, 5000, 10_000, 30_000],
});
register.registerMetric(eventsGroupJobDuration);
@@ -85,57 +86,161 @@ queues.forEach((queue) => {
);
});
-register.registerMetric(
- new client.Gauge({
- name: `buffer_${eventBuffer.name}_count`,
- help: 'Number of unprocessed events',
- async collect() {
- const metric = await eventBuffer.getBufferSize();
- this.set(metric);
- },
- })
-);
+// -----------------------------------------------------------------------------
+// Buffer metrics
+// -----------------------------------------------------------------------------
-register.registerMetric(
- new client.Gauge({
- name: `buffer_${profileBuffer.name}_count`,
- help: 'Number of unprocessed profiles',
- async collect() {
- const metric = await profileBuffer.getBufferSize();
- this.set(metric);
- },
- })
-);
+const allBuffers = [
+ eventBuffer,
+ profileBuffer,
+ botBuffer,
+ sessionBuffer,
+ replayBuffer,
+ groupBuffer,
+ profileBackfillBuffer,
+];
-register.registerMetric(
- new client.Gauge({
- name: `buffer_${botBuffer.name}_count`,
- help: 'Number of unprocessed bot events',
- async collect() {
- const metric = await botBuffer.getBufferSize();
- this.set(metric);
- },
- })
-);
+// Ground-truth LLEN of each buffer's main list. O(1) — no shadow counter.
+for (const buf of allBuffers) {
+ register.registerMetric(
+ new client.Gauge({
+ name: `buffer_${buf.name.replace(/-/g, '_')}_count`,
+ help: 'Buffer size (LLEN of the Redis list)',
+ async collect() {
+ try {
+ this.set(await buf.getBufferSize());
+ } catch {
+ // ignore — scrape continues
+ }
+ },
+ }),
+ );
+}
+// Number of events sitting in event-buffer's in-process micro-batch (pre-Redis).
+// Other buffers don't have a local layer.
register.registerMetric(
new client.Gauge({
- name: `buffer_${sessionBuffer.name}_count`,
- help: 'Number of unprocessed sessions',
- async collect() {
- const metric = await sessionBuffer.getBufferSize();
- this.set(metric);
+ name: 'buffer_event_pending_local_count',
+ help: 'Events in event-buffer process-local micro-batch (not yet in Redis)',
+ collect() {
+ try {
+ this.set(eventBuffer.getPendingLocalCount());
+ } catch {
+ // ignore
+ }
},
- })
+ }),
);
-register.registerMetric(
- new client.Gauge({
- name: `buffer_${replayBuffer.name}_count`,
- help: 'Number of unprocessed replay chunks',
- async collect() {
- const metric = await replayBuffer.getBufferSize();
- this.set(metric);
- },
- })
-);
+// ---- Flush metrics (populated via flushObserver hooks) ----
+
+const flushDuration = new client.Histogram({
+ name: 'buffer_flush_duration_ms',
+ help: 'Wall time of a tryFlush call, including lock acquisition',
+ labelNames: ['buffer', 'result', 'trigger'],
+ buckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10_000, 30_000, 60_000],
+});
+register.registerMetric(flushDuration);
+
+const flushTotal = new client.Counter({
+ name: 'buffer_flush_total',
+ help: 'Count of tryFlush invocations by result (success/error/locked/paused) and trigger (add/cron)',
+ labelNames: ['buffer', 'result', 'trigger'],
+});
+register.registerMetric(flushTotal);
+
+const flushRowsTotal = new client.Counter({
+ name: 'buffer_flush_rows_total',
+ help: 'Rows drained from the buffer per flush (sum)',
+ labelNames: ['buffer'],
+});
+register.registerMetric(flushRowsTotal);
+
+// Per-phase Redis op timing on the flush hot path.
+const redisOpDurationMs = new client.Histogram({
+ name: 'buffer_redis_op_duration_ms',
+ help: 'Duration of a Redis op during flush',
+ labelNames: ['buffer', 'op'],
+ buckets: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 5000],
+});
+register.registerMetric(redisOpDurationMs);
+
+const chInsertDurationMs = new client.Histogram({
+ name: 'buffer_ch_insert_duration_ms',
+ help: 'Duration of the ClickHouse insert(s) inside a single flush',
+ labelNames: ['buffer'],
+ buckets: [10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10_000, 30_000, 60_000],
+});
+register.registerMetric(chInsertDurationMs);
+
+const flushLlenAtStart = new client.Histogram({
+ name: 'buffer_flush_llen_at_start',
+ help: 'LLEN observed at the start of a flush attempt',
+ labelNames: ['buffer'],
+ buckets: [0, 10, 100, 500, 1000, 5000, 10_000, 50_000, 100_000, 500_000, 1_000_000, 5_000_000],
+});
+register.registerMetric(flushLlenAtStart);
+
+// ---- Add-path metrics ----
+
+const addDurationMs = new client.Histogram({
+ name: 'buffer_add_duration_ms',
+ help: 'Duration of a single add() call (per-event ingest path)',
+ labelNames: ['buffer'],
+ buckets: [0.5, 1, 2.5, 5, 10, 25, 50, 100, 250, 500, 1000, 5000],
+});
+register.registerMetric(addDurationMs);
+
+const addTotal = new client.Counter({
+ name: 'buffer_add_total',
+ help: 'Total add() calls per buffer (ingest rate). Pair with buffer_flush_rows_total for fill-vs-drain.',
+ labelNames: ['buffer'],
+});
+register.registerMetric(addTotal);
+
+for (const buf of allBuffers) {
+ buf.flushObserver = (obs) => {
+ flushTotal.inc({
+ buffer: obs.buffer,
+ result: obs.result,
+ trigger: obs.trigger,
+ });
+ flushDuration.observe(
+ { buffer: obs.buffer, result: obs.result, trigger: obs.trigger },
+ obs.totalMs,
+ );
+
+ if (obs.llenAtStart != null) {
+ flushLlenAtStart.observe({ buffer: obs.buffer }, obs.llenAtStart);
+ }
+
+ if (obs.rowsProcessed != null && obs.rowsProcessed > 0) {
+ flushRowsTotal.inc({ buffer: obs.buffer }, obs.rowsProcessed);
+ }
+
+ if (obs.phases?.lrangeMs != null) {
+ redisOpDurationMs.observe(
+ { buffer: obs.buffer, op: 'lrange' },
+ obs.phases.lrangeMs,
+ );
+ }
+ if (obs.phases?.trimMs != null) {
+ redisOpDurationMs.observe(
+ { buffer: obs.buffer, op: 'trim' },
+ obs.phases.trimMs,
+ );
+ }
+ if (obs.phases?.chInsertMs != null) {
+ chInsertDurationMs.observe(
+ { buffer: obs.buffer },
+ obs.phases.chInsertMs,
+ );
+ }
+ };
+
+ buf.addObserver = (obs) => {
+ addTotal.inc({ buffer: obs.buffer });
+ addDurationMs.observe({ buffer: obs.buffer }, obs.durationMs);
+ };
+}
diff --git a/packages/db/src/buffers/base-buffer.ts b/packages/db/src/buffers/base-buffer.ts
index ba5cc360f..daf183eb7 100644
--- a/packages/db/src/buffers/base-buffer.ts
+++ b/packages/db/src/buffers/base-buffer.ts
@@ -1,17 +1,71 @@
import { generateSecureId } from '@openpanel/common/server';
import { type ILogger, createLogger } from '@openpanel/logger';
import { cronQueue } from '@openpanel/queue';
-import { getRedisCache, runEvery } from '@openpanel/redis';
+import { getRedisCache } from '@openpanel/redis';
+
+export type FlushPhaseTimings = {
+ lrangeMs?: number;
+ chInsertMs?: number;
+ trimMs?: number;
+ /** Total time spent inside onFlush (subclass-specific processing) */
+ onFlushMs?: number;
+};
+
+export type FlushTrigger = 'add' | 'cron';
+
+export type FlushObservation = {
+ buffer: string;
+ /**
+ * - `success`: flush ran and completed without error
+ * - `error`: flush ran and threw
+ * - `locked`: another worker held the lock (no-op)
+ * - `paused`: cron queue paused (no-op)
+ */
+ result: 'success' | 'error' | 'locked' | 'paused';
+ /** What invoked this flush: `add` = fast-path (buffer crossed batchSize), `cron` = periodic scheduler. */
+ trigger: FlushTrigger;
+ /** Total wall time of the tryFlush call, including lock acquisition. */
+ totalMs: number;
+ /** Number of rows actually processed by this flush (subclass-reported). */
+ rowsProcessed?: number;
+ /** LLEN of the buffer's main list captured at flush start. */
+ llenAtStart?: number;
+ phases?: FlushPhaseTimings;
+ err?: unknown;
+};
+
+export type FlushObserver = (obs: FlushObservation) => void;
+
+export type AddObservation = {
+ buffer: string;
+ durationMs: number;
+};
+
+export type AddObserver = (obs: AddObservation) => void;
export class BaseBuffer {
name: string;
logger: ILogger;
lockKey: string;
lockTimeout = 60;
- onFlush: () => void;
+ onFlush: () => Promise<void> | void;
enableParallelProcessing: boolean;
- protected bufferCounterKey: string;
+ /**
+ * Subclass-reported counts/timings for the in-flight flush. Populated by
+ * `reportFlushStats` from within `onFlush` so the base-class observer can
+ * include them in the FlushObservation.
+ */
+ private inflightStats: {
+ rowsProcessed?: number;
+ phases?: FlushPhaseTimings;
+ } = {};
+
+ /** Optional hook used by the worker to bridge flushes into Prometheus. */
+ public flushObserver: FlushObserver | null = null;
+
+ /** Optional hook for instrumenting add() latency. */
+ public addObserver: AddObserver | null = null;
constructor(options: {
name: string;
@@ -22,10 +76,20 @@ export class BaseBuffer {
this.name = options.name;
this.lockKey = `lock:${this.name}`;
this.onFlush = options.onFlush;
- this.bufferCounterKey = `${this.name}:buffer:count`;
this.enableParallelProcessing = options.enableParallelProcessing ?? false;
}
+ /**
+ * Returns the Redis key of the buffer's main list (the queue of pending
+ * rows). Used by base-class methods for ground-truth size and
+ * observability. Subclasses MUST override.
+ */
+ protected getRedisListKey(): string {
+ throw new Error(
+ `${this.name}: subclass must override getRedisListKey()`,
+ );
+ }
+
protected chunks<T>(items: T[], size: number) {
const chunks = [];
for (let i = 0; i < items.length; i += size) {
@@ -35,57 +99,56 @@ export class BaseBuffer {
}
/**
- * Utility method to safely get buffer size with counter fallback
+ * Subclasses call this from within onFlush to record what they actually
+ * did. The base class includes these in the FlushObservation it emits.
+ */
+ protected reportFlushStats(stats: {
+ rowsProcessed?: number;
+ phases?: FlushPhaseTimings;
+ }) {
+ if (stats.rowsProcessed !== undefined) {
+ this.inflightStats.rowsProcessed = stats.rowsProcessed;
+ }
+ if (stats.phases) {
+ this.inflightStats.phases = {
+ ...(this.inflightStats.phases ?? {}),
+ ...stats.phases,
+ };
+ }
+ }
+
+ /**
+ * Ground-truth size of the buffer (LLEN of the Redis list). O(1). The
+ * previous implementation kept a shadow counter to "avoid" LLEN — but
+ * LLEN and GET are both O(1) single-roundtrip ops in Redis, so the
+ * counter was free complexity that silently drifted (see incident
+ * 2026-05-20). Always use this.
*/
- protected async getBufferSizeWithCounter(
- fallbackFn: () => Promise<number>,
- ): Promise<number> {
- const key = this.bufferCounterKey;
+ async getBufferSize(): Promise<number> {
+ return await getRedisCache().llen(this.getRedisListKey());
+ }
+
+ /**
+ * Time the body of an `add()` call. Subclasses wrap their work with this
+ * so all add latency is reported uniformly via the `addObserver` hook.
+ */
+ protected async timeAdd<T>(fn: () => Promise<T>): Promise<T> {
+ const start = performance.now();
try {
- await runEvery({
- interval: 60 * 60,
- key: `${this.name}-buffer:resync`,
- fn: async () => {
- try {
- const actual = await fallbackFn();
- await getRedisCache().set(this.bufferCounterKey, actual.toString());
- } catch (error) {
- this.logger.warn(
- { err: error },
- 'Failed to resync buffer counter',
- );
- }
- },
- }).catch(() => {});
-
- const counterValue = await getRedisCache().get(key);
- if (counterValue !== null) {
- const parsed = Number.parseInt(counterValue, 10);
- if (!Number.isNaN(parsed)) {
- return Math.max(0, parsed);
- }
- // Corrupted value → treat as missing
- this.logger.warn(
- { key, counterValue },
- 'Invalid buffer counter value, reinitializing',
- );
+ return await fn();
+ } finally {
+ try {
+ this.addObserver?.({
+ buffer: this.name,
+ durationMs: performance.now() - start,
+ });
+ } catch {
+ // observer errors must not break add
}
-
- // Initialize counter with current size
- const count = await fallbackFn();
- await getRedisCache().set(key, count.toString());
- return count;
- } catch (error) {
- this.logger.warn(
- { err: error },
- 'Failed to get buffer size from counter, using fallback',
- );
- return fallbackFn();
}
}
private async releaseLock(lockId: string): Promise<void> {
- this.logger.debug('Releasing lock...');
const script = `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
@@ -96,35 +159,110 @@ export class BaseBuffer {
await getRedisCache().eval(script, 1, this.lockKey, lockId);
}
- async tryFlush() {
- const now = performance.now();
+ /**
+ * Emit a flush observation to the configured observer and to the structured
+ * logger. Catches observer errors so a bad metrics path can never break
+ * the worker.
+ */
+ private emitFlushObservation(obs: FlushObservation): void {
+ try {
+ this.flushObserver?.(obs);
+ } catch (error) {
+ this.logger.warn({ err: error }, 'flushObserver threw');
+ }
+
+ const logPayload = {
+ result: obs.result,
+ trigger: obs.trigger,
+ totalMs: Math.round(obs.totalMs),
+ rowsProcessed: obs.rowsProcessed,
+ llenAtStart: obs.llenAtStart,
+ lrangeMs:
+ obs.phases?.lrangeMs != null
+ ? Math.round(obs.phases.lrangeMs)
+ : undefined,
+ chInsertMs:
+ obs.phases?.chInsertMs != null
+ ? Math.round(obs.phases.chInsertMs)
+ : undefined,
+ trimMs:
+ obs.phases?.trimMs != null
+ ? Math.round(obs.phases.trimMs)
+ : undefined,
+ onFlushMs:
+ obs.phases?.onFlushMs != null
+ ? Math.round(obs.phases.onFlushMs)
+ : undefined,
+ };
+
+ if (obs.result === 'error') {
+ this.logger.error({ ...logPayload, err: obs.err }, 'Buffer flush');
+ } else if (obs.result === 'paused') {
+ // Demoted to debug — happens every 10s when intentionally paused
+ this.logger.debug(logPayload, 'Buffer flush skipped (cron paused)');
+ } else {
+ this.logger.info(logPayload, 'Buffer flush');
+ }
+ }
+
+ async tryFlush(options: { trigger?: FlushTrigger } = {}) {
+ const trigger: FlushTrigger = options.trigger ?? 'cron';
+ const startedAt = performance.now();
+ this.inflightStats = {};
+
+ let llenAtStart: number | undefined;
+ try {
+ llenAtStart = await this.getBufferSize();
+ } catch {
+ // best-effort
+ }
+
const isCronQueuePaused = await cronQueue.isPaused();
if (isCronQueuePaused) {
- this.logger.info('Cron queue is paused, skipping flush');
+ this.emitFlushObservation({
+ buffer: this.name,
+ result: 'paused',
+ trigger,
+ totalMs: performance.now() - startedAt,
+ llenAtStart,
+ });
return;
}
- // Parallel mode: No locking, multiple workers can process simultaneously
if (this.enableParallelProcessing) {
+ const onFlushStarted = performance.now();
try {
- this.logger.debug('Processing buffer (parallel mode)...');
await this.onFlush();
- this.logger.debug(
- { elapsed: performance.now() - now },
- 'Flush completed (parallel mode)',
- );
+ this.emitFlushObservation({
+ buffer: this.name,
+ result: 'success',
+ trigger,
+ totalMs: performance.now() - startedAt,
+ rowsProcessed: this.inflightStats.rowsProcessed,
+ llenAtStart,
+ phases: {
+ ...this.inflightStats.phases,
+ onFlushMs: performance.now() - onFlushStarted,
+ },
+ });
} catch (error) {
- this.logger.error(
- { err: error },
- 'Failed to process buffer (parallel mode)',
- );
- // In parallel mode, we can't safely reset counter as other workers might be active
- // Counter will be resynced automatically by the periodic job
+ this.emitFlushObservation({
+ buffer: this.name,
+ result: 'error',
+ trigger,
+ totalMs: performance.now() - startedAt,
+ rowsProcessed: this.inflightStats.rowsProcessed,
+ llenAtStart,
+ phases: {
+ ...this.inflightStats.phases,
+ onFlushMs: performance.now() - onFlushStarted,
+ },
+ err: error,
+ });
}
return;
}
- // Sequential mode: Use lock to ensure only one worker processes at a time
const lockId = generateSecureId('lock');
const acquired = await getRedisCache().set(
this.lockKey,
@@ -133,27 +271,49 @@ export class BaseBuffer {
this.lockTimeout,
'NX',
);
- if (acquired === 'OK') {
- try {
- this.logger.debug({ lockId }, 'Acquired lock. Processing buffer...');
- await this.onFlush();
- } catch (error) {
- this.logger.error(
- { err: error, lockId },
- 'Failed to process buffer',
- );
- // On error, we might want to reset counter to avoid drift
- if (this.bufferCounterKey) {
- this.logger.warn('Resetting buffer counter due to flush error');
- await getRedisCache().del(this.bufferCounterKey);
- }
- } finally {
- await this.releaseLock(lockId);
- this.logger.debug(
- { elapsed: performance.now() - now, lockId },
- 'Flush completed',
- );
- }
+
+ if (acquired !== 'OK') {
+ this.emitFlushObservation({
+ buffer: this.name,
+ result: 'locked',
+ trigger,
+ totalMs: performance.now() - startedAt,
+ llenAtStart,
+ });
+ return;
+ }
+
+ const onFlushStarted = performance.now();
+ try {
+ await this.onFlush();
+ this.emitFlushObservation({
+ buffer: this.name,
+ result: 'success',
+ trigger,
+ totalMs: performance.now() - startedAt,
+ rowsProcessed: this.inflightStats.rowsProcessed,
+ llenAtStart,
+ phases: {
+ ...this.inflightStats.phases,
+ onFlushMs: performance.now() - onFlushStarted,
+ },
+ });
+ } catch (error) {
+ this.emitFlushObservation({
+ buffer: this.name,
+ result: 'error',
+ trigger,
+ totalMs: performance.now() - startedAt,
+ rowsProcessed: this.inflightStats.rowsProcessed,
+ llenAtStart,
+ phases: {
+ ...this.inflightStats.phases,
+ onFlushMs: performance.now() - onFlushStarted,
+ },
+ err: error,
+ });
+ } finally {
+ await this.releaseLock(lockId);
}
}
}
diff --git a/packages/db/src/buffers/bot-buffer.ts b/packages/db/src/buffers/bot-buffer.ts
index a7d648b81..e65019aa8 100644
--- a/packages/db/src/buffers/bot-buffer.ts
+++ b/packages/db/src/buffers/bot-buffer.ts
@@ -22,62 +22,62 @@ export class BotBuffer extends BaseBuffer {
this.redis = getRedisCache();
}
- async add(event: IClickhouseBotEvent) {
- try {
- // Add event and increment counter atomically
- await this.redis
- .multi()
- .rpush(this.redisKey, JSON.stringify(event))
- .incr(this.bufferCounterKey)
- .exec();
+ protected getRedisListKey(): string {
+ return this.redisKey;
+ }
- // Check buffer length using counter (fallback to LLEN if missing)
- const bufferLength = await this.getBufferSize();
+ async add(event: IClickhouseBotEvent) {
+ return this.timeAdd(async () => {
+ try {
+ const result = await this.redis
+ .multi()
+ .rpush(this.redisKey, JSON.stringify(event))
+ .llen(this.redisKey)
+ .exec();
- if (bufferLength >= this.batchSize) {
- await this.tryFlush();
+ const bufferLength = (result?.[1]?.[1] as number) ?? 0;
+ if (bufferLength >= this.batchSize) {
+ await this.tryFlush({ trigger: 'add' });
+ }
+ } catch (error) {
+ this.logger.error({ err: error }, 'Failed to add bot event');
}
- } catch (error) {
- this.logger.error({ err: error }, 'Failed to add bot event');
- }
+ });
}
async processBuffer() {
- try {
- // Get events from the start without removing them
- const events = await this.redis.lrange(
- this.redisKey,
- 0,
- this.batchSize - 1,
- );
-
- if (events.length === 0) return;
+ const lrangeStart = performance.now();
+ const events = await this.redis.lrange(
+ this.redisKey,
+ 0,
+ this.batchSize - 1,
+ );
+ const lrangeMs = performance.now() - lrangeStart;
- const parsedEvents = events.map((e) =>
- getSafeJson<IClickhouseBotEvent>(e),
- );
+ if (events.length === 0) {
+ this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
+ return;
+ }
- // Insert to ClickHouse
- await ch.insert({
- table: TABLE_NAMES.events_bots,
- values: parsedEvents,
- format: 'JSONEachRow',
- });
+ const parsedEvents = events.map((e) =>
+ getSafeJson<IClickhouseBotEvent>(e),
+ );
- // Only remove events after successful insert and update counter
- await this.redis
- .multi()
- .ltrim(this.redisKey, events.length, -1)
- .decrby(this.bufferCounterKey, events.length)
- .exec();
+ const chStart = performance.now();
+ await ch.insert({
+ table: TABLE_NAMES.events_bots,
+ values: parsedEvents,
+ format: 'JSONEachRow',
+ });
+ const chInsertMs = performance.now() - chStart;
- this.logger.debug({ count: events.length }, 'Processed bot events');
- } catch (error) {
- this.logger.error({ err: error }, 'Failed to process buffer');
- }
- }
+ const trimStart = performance.now();
+ await this.redis.ltrim(this.redisKey, events.length, -1);
+ const trimMs = performance.now() - trimStart;
- async getBufferSize() {
- return this.getBufferSizeWithCounter(() => this.redis.llen(this.redisKey));
+ this.reportFlushStats({
+ rowsProcessed: events.length,
+ phases: { lrangeMs, chInsertMs, trimMs },
+ });
}
}
diff --git a/packages/db/src/buffers/event-buffer.test.ts b/packages/db/src/buffers/event-buffer.test.ts
index e269ef0b1..3e82aa6cb 100644
--- a/packages/db/src/buffers/event-buffer.test.ts
+++ b/packages/db/src/buffers/event-buffer.test.ts
@@ -286,9 +286,11 @@ describe('EventBuffer', () => {
.spyOn(ch, 'insert')
.mockRejectedValueOnce(new Error('ClickHouse unavailable'));
- await eventBuffer.processBuffer();
-
- // Events must still be in the queue — not lost
+ // Errors propagate to tryFlush (which resyncs the counter). The safety
+ // property — queue preserved on CH failure — still holds.
+ await expect(eventBuffer.processBuffer()).rejects.toThrow(
+ 'ClickHouse unavailable',
+ );
expect(await eventBuffer.getBufferSize()).toBe(1);
insertSpy.mockRestore();
diff --git a/packages/db/src/buffers/event-buffer.ts b/packages/db/src/buffers/event-buffer.ts
index 69134b9ce..d486a6d4a 100644
--- a/packages/db/src/buffers/event-buffer.ts
+++ b/packages/db/src/buffers/event-buffer.ts
@@ -26,7 +26,6 @@ export class EventBuffer extends BaseBuffer {
private flushRetryCount = 0;
private queueKey = 'event_buffer:queue';
- protected bufferCounterKey = 'event_buffer:total_count';
constructor() {
super({
@@ -44,19 +43,33 @@ export class EventBuffer extends BaseBuffer {
}
add(event: IClickhouseEvent) {
+ // Event-buffer's add() is synchronous (in-memory push). Measured anyway
+ // for consistency with the other buffers' add-latency tracking.
+ const start = performance.now();
this.pendingEvents.push(event);
if (this.pendingEvents.length >= this.microBatchMaxSize) {
this.flushLocalBuffer();
- return;
- }
-
- if (!this.flushTimer) {
+ } else if (!this.flushTimer) {
this.flushTimer = setTimeout(() => {
this.flushTimer = null;
this.flushLocalBuffer();
}, this.microBatchIntervalMs);
}
+
+ try {
+ this.addObserver?.({
+ buffer: this.name,
+ durationMs: performance.now() - start,
+ });
+ } catch {
+ // never break add on observer failure
+ }
+ }
+
+ /** Number of events buffered locally in process memory, before Redis. */
+ public getPendingLocalCount(): number {
+ return this.pendingEvents.length;
}
public async flush() {
@@ -84,7 +97,6 @@ export class EventBuffer extends BaseBuffer {
for (const event of eventsToFlush) {
multi.rpush(this.queueKey, JSON.stringify(event));
}
- multi.incrby(this.bufferCounterKey, eventsToFlush.length);
await multi.exec();
@@ -114,92 +126,76 @@ export class EventBuffer extends BaseBuffer {
}
}
+ protected getRedisListKey(): string {
+ return this.queueKey;
+ }
+
async processBuffer() {
const redis = getRedisCache();
- try {
- const queueEvents = await redis.lrange(
- this.queueKey,
- 0,
- this.batchSize - 1
- );
+ const lrangeStart = performance.now();
+ const queueEvents = await redis.lrange(
+ this.queueKey,
+ 0,
+ this.batchSize - 1,
+ );
+ const lrangeMs = performance.now() - lrangeStart;
- if (queueEvents.length === 0) {
- this.logger.debug('No events to process');
- return;
- }
+ if (queueEvents.length === 0) {
+ this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
+ return;
+ }
- const eventsToClickhouse: IClickhouseEvent[] = [];
- for (const eventStr of queueEvents) {
- const event = getSafeJson<IClickhouseEvent>(eventStr);
- if (event) {
- if (!Array.isArray(event.groups)) {
- event.groups = [];
- }
- eventsToClickhouse.push(event);
+ const eventsToClickhouse: IClickhouseEvent[] = [];
+ for (const eventStr of queueEvents) {
+ const event = getSafeJson<IClickhouseEvent>(eventStr);
+ if (event) {
+ if (!Array.isArray(event.groups)) {
+ event.groups = [];
}
+ eventsToClickhouse.push(event);
}
+ }
- if (eventsToClickhouse.length === 0) {
- this.logger.debug('No valid events to process');
- return;
- }
-
- eventsToClickhouse.sort(
- (a, b) =>
- new Date(a.created_at || 0).getTime() -
- new Date(b.created_at || 0).getTime()
- );
-
- this.logger.info(
- {
- totalEvents: eventsToClickhouse.length,
- chunks: Math.ceil(eventsToClickhouse.length / this.chunkSize),
- },
- 'Inserting events into ClickHouse',
- );
-
- for (const chunk of this.chunks(eventsToClickhouse, this.chunkSize)) {
- await ch.insert({
- table: 'events',
- values: chunk,
- format: 'JSONEachRow',
- });
- }
+ if (eventsToClickhouse.length === 0) {
+ this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
+ return;
+ }
- const countByProject = new Map<string, number>();
- for (const event of eventsToClickhouse) {
- countByProject.set(
- event.project_id,
- (countByProject.get(event.project_id) ?? 0) + 1
- );
- }
- for (const [projectId, count] of countByProject) {
- publishEvent('events', 'batch', { projectId, count });
- }
+ eventsToClickhouse.sort(
+ (a, b) =>
+ new Date(a.created_at || 0).getTime() -
+ new Date(b.created_at || 0).getTime(),
+ );
- await redis
- .multi()
- .ltrim(this.queueKey, queueEvents.length, -1)
- .decrby(this.bufferCounterKey, queueEvents.length)
- .exec();
+ const chStart = performance.now();
+ for (const chunk of this.chunks(eventsToClickhouse, this.chunkSize)) {
+ await ch.insert({
+ table: 'events',
+ values: chunk,
+ format: 'JSONEachRow',
+ });
+ }
+ const chInsertMs = performance.now() - chStart;
- this.logger.info(
- {
- batchSize: this.batchSize,
- eventsProcessed: eventsToClickhouse.length,
- },
- 'Processed events from Redis buffer',
+ const countByProject = new Map<string, number>();
+ for (const event of eventsToClickhouse) {
+ countByProject.set(
+ event.project_id,
+ (countByProject.get(event.project_id) ?? 0) + 1,
);
- } catch (error) {
- this.logger.error({ err: error }, 'Error processing Redis buffer');
}
- }
+ for (const [projectId, count] of countByProject) {
+ publishEvent('events', 'batch', { projectId, count });
+ }
- public getBufferSize() {
- return this.getBufferSizeWithCounter(async () => {
- const redis = getRedisCache();
- return await redis.llen(this.queueKey);
+ const trimStart = performance.now();
+ await redis.ltrim(this.queueKey, queueEvents.length, -1);
+ const trimMs = performance.now() - trimStart;
+
+ this.reportFlushStats({
+ rowsProcessed: queueEvents.length,
+ phases: { lrangeMs, chInsertMs, trimMs },
});
}
diff --git a/packages/db/src/buffers/group-buffer.ts b/packages/db/src/buffers/group-buffer.ts
index a98c70f42..6fcfb6d8c 100644
--- a/packages/db/src/buffers/group-buffer.ts
+++ b/packages/db/src/buffers/group-buffer.ts
@@ -88,109 +88,107 @@ export class GroupBuffer extends BaseBuffer {
}
async add(input: IGroupBufferInput): Promise<void> {
- try {
- const cacheKey = this.getCacheKey(input.projectId, input.id);
-
- const existing =
- (await this.fetchFromCache(input.projectId, input.id)) ??
- (await this.fetchFromClickhouse(input.projectId, input.id));
-
- const mergedProperties = toDots({
- ...(existing?.properties ?? {}),
- ...(input.properties ?? {}),
- }) as Record<string, string>;
-
- const entry: IGroupBufferEntry = {
- project_id: input.projectId,
- id: input.id,
- type: input.type,
- name: input.name,
- properties: mergedProperties,
- created_at: formatClickhouseDate(
- existing?.created_at ? new Date(existing.created_at) : new Date()
- ),
- version: String(Date.now()),
- deleted: 0,
- };
-
- if (
- existing &&
- existing.type === entry.type &&
- existing.name === entry.name &&
- shallowEqual(existing.properties, entry.properties)
- ) {
- this.logger.debug({ id: input.id }, 'Group not changed, skipping');
- return;
+ return this.timeAdd(async () => {
+ try {
+ const cacheKey = this.getCacheKey(input.projectId, input.id);
+
+ const existing =
+ (await this.fetchFromCache(input.projectId, input.id)) ??
+ (await this.fetchFromClickhouse(input.projectId, input.id));
+
+ const mergedProperties = toDots({
+ ...(existing?.properties ?? {}),
+ ...(input.properties ?? {}),
+ }) as Record<string, string>;
+
+ const entry: IGroupBufferEntry = {
+ project_id: input.projectId,
+ id: input.id,
+ type: input.type,
+ name: input.name,
+ properties: mergedProperties,
+ created_at: formatClickhouseDate(
+ existing?.created_at ? new Date(existing.created_at) : new Date(),
+ ),
+ version: String(Date.now()),
+ deleted: 0,
+ };
+
+ if (
+ existing &&
+ existing.type === entry.type &&
+ existing.name === entry.name &&
+ shallowEqual(existing.properties, entry.properties)
+ ) {
+ this.logger.debug({ id: input.id }, 'Group not changed, skipping');
+ return;
+ }
+
+ const cacheEntry: IGroupCacheEntry = {
+ id: entry.id,
+ project_id: entry.project_id,
+ type: entry.type,
+ name: entry.name,
+ properties: entry.properties,
+ created_at: entry.created_at,
+ };
+
+ const result = await this.redis
+ .multi()
+ .set(cacheKey, JSON.stringify(cacheEntry), 'EX', this.ttlInSeconds)
+ .rpush(this.redisKey, JSON.stringify(entry))
+ .llen(this.redisKey)
+ .exec();
+
+ if (!result) {
+ this.logger.error({ input }, 'Failed to add group to Redis');
+ return;
+ }
+
+ const bufferLength = (result?.[2]?.[1] as number) ?? 0;
+ if (bufferLength >= this.batchSize) {
+ await this.tryFlush({ trigger: 'add' });
+ }
+ } catch (error) {
+ this.logger.error({ err: error, input }, 'Failed to add group');
}
+ });
+ }
- const cacheEntry: IGroupCacheEntry = {
- id: entry.id,
- project_id: entry.project_id,
- type: entry.type,
- name: entry.name,
- properties: entry.properties,
- created_at: entry.created_at,
- };
-
- const result = await this.redis
- .multi()
- .set(cacheKey, JSON.stringify(cacheEntry), 'EX', this.ttlInSeconds)
- .rpush(this.redisKey, JSON.stringify(entry))
- .incr(this.bufferCounterKey)
- .llen(this.redisKey)
- .exec();
-
- if (!result) {
- this.logger.error({ input }, 'Failed to add group to Redis');
- return;
- }
- const bufferLength = (result?.[3]?.[1] as number) ?? 0;
- if (bufferLength >= this.batchSize) {
- await this.tryFlush();
- }
- } catch (error) {
- this.logger.error({ err: error, input }, 'Failed to add group');
- }
+ protected getRedisListKey(): string {
+ return this.redisKey;
}
async processBuffer(): Promise<void> {
- try {
- this.logger.debug('Starting group buffer processing');
- const items = await this.redis.lrange(this.redisKey, 0, this.batchSize - 1);
-
- if (items.length === 0) {
- this.logger.debug('No groups to process');
- return;
- }
+ const lrangeStart = performance.now();
+ const items = await this.redis.lrange(this.redisKey, 0, this.batchSize - 1);
+ const lrangeMs = performance.now() - lrangeStart;
- this.logger.debug(`Processing ${items.length} groups in buffer`);
- const parsed = items.map((i) => getSafeJson<IGroupBufferEntry>(i));
+ if (items.length === 0) {
+ this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
+ return;
+ }
- for (const chunk of this.chunks(parsed, this.chunkSize)) {
- await ch.insert({
- table: TABLE_NAMES.groups,
- values: chunk,
- format: 'JSONEachRow',
- });
- }
+ const parsed = items.map((i) => getSafeJson<IGroupBufferEntry>(i));
- await this.redis
- .multi()
- .ltrim(this.redisKey, items.length, -1)
- .decrby(this.bufferCounterKey, items.length)
- .exec();
-
- this.logger.debug(
- { totalGroups: items.length },
- 'Successfully completed group processing',
- );
- } catch (error) {
- this.logger.error({ err: error }, 'Failed to process buffer');
+ const chStart = performance.now();
+ for (const chunk of this.chunks(parsed, this.chunkSize)) {
+ await ch.insert({
+ table: TABLE_NAMES.groups,
+ values: chunk,
+ format: 'JSONEachRow',
+ });
}
- }
+ const chInsertMs = performance.now() - chStart;
+
+ const trimStart = performance.now();
+ await this.redis.ltrim(this.redisKey, items.length, -1);
+ const trimMs = performance.now() - trimStart;
- async getBufferSize(): Promise<number> {
- return this.getBufferSizeWithCounter(() => this.redis.llen(this.redisKey));
+ this.reportFlushStats({
+ rowsProcessed: items.length,
+ phases: { lrangeMs, chInsertMs, trimMs },
+ });
}
}
diff --git a/packages/db/src/buffers/profile-backfill-buffer.ts b/packages/db/src/buffers/profile-backfill-buffer.ts
index c50dec364..163137dfb 100644
--- a/packages/db/src/buffers/profile-backfill-buffer.ts
+++ b/packages/db/src/buffers/profile-backfill-buffer.ts
@@ -32,94 +32,88 @@ export class ProfileBackfillBuffer extends BaseBuffer {
}
async add(entry: ProfileBackfillEntry) {
- try {
- this.logger.info({ entry }, 'Adding profile backfill entry');
- await this.redis
- .multi()
- .rpush(this.redisKey, JSON.stringify(entry))
- .incr(this.bufferCounterKey)
- .exec();
- } catch (error) {
- this.logger.error(
- { err: error },
- 'Failed to add profile backfill entry',
- );
- }
+ return this.timeAdd(async () => {
+ try {
+ this.logger.info({ entry }, 'Adding profile backfill entry');
+ await this.redis.rpush(this.redisKey, JSON.stringify(entry));
+ } catch (error) {
+ this.logger.error(
+ { err: error },
+ 'Failed to add profile backfill entry',
+ );
+ }
+ });
+ }
+
+
+ protected getRedisListKey(): string {
+ return this.redisKey;
}
async processBuffer() {
- try {
- const raw = await this.redis.lrange(this.redisKey, 0, this.batchSize - 1);
-
- if (raw.length === 0) return;
-
- // Deduplicate by sessionId — last write wins (most recent profileId)
- const seen = new Map<string, ProfileBackfillEntry>();
- for (const r of raw) {
- const parsed = getSafeJson<ProfileBackfillEntry>(r);
- if (parsed) {
- seen.set(parsed.sessionId, parsed);
- }
- }
- const entries = Array.from(seen.values());
-
- const table = getReplicatedTableName(TABLE_NAMES.events);
-
- const chunks = this.chunks(entries, CHUNK_SIZE);
- let processedChunks = 0;
-
- for (const chunk of chunks) {
- const caseClause = chunk
- .map(({ sessionId, profileId }) => `WHEN ${sqlstring.escape(sessionId)} THEN ${sqlstring.escape(profileId)}`)
- .join('\n');
- const tupleList = chunk
- .map(({ projectId, sessionId }) => `(${sqlstring.escape(projectId)}, ${sqlstring.escape(sessionId)})`)
- .join(',');
-
- const query = `
- UPDATE ${table}
- SET profile_id = CASE session_id
- ${caseClause}
- END
- WHERE (project_id, session_id) IN (${tupleList})
- AND created_at > now() - INTERVAL 6 HOURS`;
-
- await ch.command({
- query,
- clickhouse_settings: {
- mutations_sync: '0',
- allow_experimental_lightweight_update: '1'
- },
- });
-
- processedChunks++;
- this.logger.info(
- { count: chunk.length },
- 'Profile backfill chunk applied',
- );
- }
+ const lrangeStart = performance.now();
+ const raw = await this.redis.lrange(this.redisKey, 0, this.batchSize - 1);
+ const lrangeMs = performance.now() - lrangeStart;
- if (processedChunks === chunks.length) {
- await this.redis
- .multi()
- .ltrim(this.redisKey, raw.length, -1)
- .decrby(this.bufferCounterKey, raw.length)
- .exec();
+ if (raw.length === 0) {
+ this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
+ return;
+ }
- this.logger.info(
- { total: entries.length },
- 'Profile backfill buffer processed',
- );
+ // Deduplicate by sessionId — last write wins (most recent profileId)
+ const seen = new Map<string, ProfileBackfillEntry>();
+ for (const r of raw) {
+ const parsed = getSafeJson<ProfileBackfillEntry>(r);
+ if (parsed) {
+ seen.set(parsed.sessionId, parsed);
}
- } catch (error) {
- this.logger.error(
- { err: error },
- 'Failed to process profile backfill buffer',
- );
}
- }
+ const entries = Array.from(seen.values());
+
+ const table = getReplicatedTableName(TABLE_NAMES.events);
+
+ const chunks = this.chunks(entries, CHUNK_SIZE);
+ let processedChunks = 0;
+
+ const chStart = performance.now();
+ for (const chunk of chunks) {
+ const caseClause = chunk
+ .map(({ sessionId, profileId }) => `WHEN ${sqlstring.escape(sessionId)} THEN ${sqlstring.escape(profileId)}`)
+ .join('\n');
+ const tupleList = chunk
+ .map(({ projectId, sessionId }) => `(${sqlstring.escape(projectId)}, ${sqlstring.escape(sessionId)})`)
+ .join(',');
+
+ const query = `
+ UPDATE ${table}
+ SET profile_id = CASE session_id
+ ${caseClause}
+ END
+ WHERE (project_id, session_id) IN (${tupleList})
+ AND created_at > now() - INTERVAL 6 HOURS`;
+
+ await ch.command({
+ query,
+ clickhouse_settings: {
+ mutations_sync: '0',
+ allow_experimental_lightweight_update: '1'
+ },
+ });
+
+ processedChunks++;
+ }
+ const chInsertMs = performance.now() - chStart;
+
+ let trimMs: number | undefined;
+ if (processedChunks === chunks.length) {
+ const trimStart = performance.now();
+ await this.redis.ltrim(this.redisKey, raw.length, -1);
+ trimMs = performance.now() - trimStart;
+ }
- async getBufferSize() {
- return this.getBufferSizeWithCounter(() => this.redis.llen(this.redisKey));
+ this.reportFlushStats({
+ rowsProcessed: raw.length,
+ phases: { lrangeMs, chInsertMs, trimMs },
+ });
}
}
diff --git a/packages/db/src/buffers/profile-buffer.test.ts b/packages/db/src/buffers/profile-buffer.test.ts
index 070b758ec..b0a9cb8d1 100644
--- a/packages/db/src/buffers/profile-buffer.test.ts
+++ b/packages/db/src/buffers/profile-buffer.test.ts
@@ -178,9 +178,11 @@ describe('ProfileBuffer', () => {
.spyOn(ch, 'insert')
.mockRejectedValueOnce(new Error('ClickHouse unavailable'));
- await profileBuffer.processBuffer();
-
- // Profiles must still be in the queue — not lost
+ // Errors propagate to tryFlush (which resyncs the counter). The safety
+ // property — queue preserved on CH failure — still holds.
+ await expect(profileBuffer.processBuffer()).rejects.toThrow(
+ 'ClickHouse unavailable',
+ );
expect(await profileBuffer.getBufferSize()).toBe(1);
insertSpy.mockRestore();
diff --git a/packages/db/src/buffers/profile-buffer.ts b/packages/db/src/buffers/profile-buffer.ts
index 53f14b256..63d2e2421 100644
--- a/packages/db/src/buffers/profile-buffer.ts
+++ b/packages/db/src/buffers/profile-buffer.ts
@@ -79,37 +79,38 @@ export class ProfileBuffer extends BaseBuffer {
}
async add(profile: IClickhouseProfile, isFromEvent = false) {
- try {
- if (isFromEvent) {
- const cacheKey = this.getProfileCacheKey({
- profileId: profile.id,
- projectId: profile.project_id,
- });
- const exists = await this.redis.exists(cacheKey);
- if (exists === 1) {
- return;
+ return this.timeAdd(async () => {
+ try {
+ if (isFromEvent) {
+ const cacheKey = this.getProfileCacheKey({
+ profileId: profile.id,
+ projectId: profile.project_id,
+ });
+ const exists = await this.redis.exists(cacheKey);
+ if (exists === 1) {
+ return;
+ }
}
- }
- const result = await this.redis
- .multi()
- .rpush(this.redisKey, JSON.stringify(profile))
- .incr(this.bufferCounterKey)
- .llen(this.redisKey)
- .exec();
+ const result = await this.redis
+ .multi()
+ .rpush(this.redisKey, JSON.stringify(profile))
+ .llen(this.redisKey)
+ .exec();
- if (!result) {
- this.logger.error({ profile }, 'Failed to add profile to Redis');
- return;
- }
+ if (!result) {
+ this.logger.error({ profile }, 'Failed to add profile to Redis');
+ return;
+ }
- const bufferLength = (result?.[2]?.[1] as number) ?? 0;
- if (bufferLength >= this.batchSize) {
- await this.tryFlush();
+ const bufferLength = (result?.[1]?.[1] as number) ?? 0;
+ if (bufferLength >= this.batchSize) {
+ await this.tryFlush({ trigger: 'add' });
+ }
+ } catch (error) {
+ this.logger.error({ err: error, profile }, 'Failed to add profile');
}
- } catch (error) {
- this.logger.error({ err: error, profile }, 'Failed to add profile');
- }
+ });
}
private mergeProfiles(
@@ -204,116 +205,112 @@ export class ProfileBuffer extends BaseBuffer {
return result;
}
- async processBuffer() {
- try {
- this.logger.debug('Starting profile buffer processing');
- const rawProfiles = await this.redis.lrange(
- this.redisKey,
- 0,
- this.batchSize - 1
- );
-
- if (rawProfiles.length === 0) {
- this.logger.debug('No profiles to process');
- return;
- }
+ protected getRedisListKey(): string {
+ return this.redisKey;
+ }
- const parsedProfiles = rawProfiles
- .map((p) => getSafeJson<IClickhouseProfile>(p))
- .filter(Boolean) as IClickhouseProfile[];
-
- // Merge within batch: collapse multiple updates for the same profile
- const mergedInBatch = new Map<string, IClickhouseProfile>();
- for (const profile of parsedProfiles) {
- const key = `${profile.project_id}:${profile.id}`;
- mergedInBatch.set(
- key,
- this.mergeProfiles(mergedInBatch.get(key) ?? null, profile)
- );
- }
+ async processBuffer() {
+ const lrangeStart = performance.now();
+ const rawProfiles = await this.redis.lrange(
+ this.redisKey,
+ 0,
+ this.batchSize - 1,
+ );
+ const lrangeMs = performance.now() - lrangeStart;
- const uniqueProfiles = Array.from(mergedInBatch.values());
+ if (rawProfiles.length === 0) {
+ this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
+ return;
+ }
- // Check Redis cache for all unique profiles in a single MGET
- const cacheKeys = uniqueProfiles.map((p) =>
- this.getProfileCacheKey({ profileId: p.id, projectId: p.project_id })
+ const parsedProfiles = rawProfiles
+ .map((p) => getSafeJson<IClickhouseProfile>(p))
+ .filter(Boolean) as IClickhouseProfile[];
+
+ // Merge within batch: collapse multiple updates for the same profile
+ const mergedInBatch = new Map<string, IClickhouseProfile>();
+ for (const profile of parsedProfiles) {
+ const key = `${profile.project_id}:${profile.id}`;
+ mergedInBatch.set(
+ key,
+ this.mergeProfiles(mergedInBatch.get(key) ?? null, profile),
);
- const cacheResults = await this.redis.mget(...cacheKeys);
-
- const existingByKey = new Map<string, IClickhouseProfile>();
- const cacheMisses: IClickhouseProfile[] = [];
- for (let i = 0; i < uniqueProfiles.length; i++) {
- const uniqueProfile = uniqueProfiles[i];
- if (uniqueProfile) {
- const key = `${uniqueProfile.project_id}:${uniqueProfile.id}`;
- const cached = cacheResults[i]
- ? getSafeJson<IClickhouseProfile>(cacheResults[i]!)
- : null;
- if (cached) {
- existingByKey.set(key, cached);
- } else {
- cacheMisses.push(uniqueProfile);
- }
- }
- }
+ }
- // Fetch cache misses from ClickHouse in bounded chunks
- if (cacheMisses.length > 0) {
- const clickhouseResults =
- await this.batchFetchFromClickhouse(cacheMisses);
- for (const [key, profile] of clickhouseResults) {
- existingByKey.set(key, profile);
+ const uniqueProfiles = Array.from(mergedInBatch.values());
+
+ // Check Redis cache for all unique profiles in a single MGET
+ const cacheKeys = uniqueProfiles.map((p) =>
+ this.getProfileCacheKey({ profileId: p.id, projectId: p.project_id }),
+ );
+ const cacheResults = await this.redis.mget(...cacheKeys);
+
+ const existingByKey = new Map<string, IClickhouseProfile>();
+ const cacheMisses: IClickhouseProfile[] = [];
+ for (let i = 0; i < uniqueProfiles.length; i++) {
+ const uniqueProfile = uniqueProfiles[i];
+ if (uniqueProfile) {
+ const key = `${uniqueProfile.project_id}:${uniqueProfile.id}`;
+ const cached = cacheResults[i]
+ ? getSafeJson<IClickhouseProfile>(cacheResults[i]!)
+ : null;
+ if (cached) {
+ existingByKey.set(key, cached);
+ } else {
+ cacheMisses.push(uniqueProfile);
}
}
+ }
- // Final merge: in-batch profile + existing (from cache or ClickHouse)
- const toInsert: IClickhouseProfile[] = [];
- const multi = this.redis.multi();
-
- for (const profile of uniqueProfiles) {
- const key = `${profile.project_id}:${profile.id}`;
- const merged = this.mergeProfiles(
- existingByKey.get(key) ?? null,
- profile
- );
- toInsert.push(merged);
- multi.set(
- this.getProfileCacheKey({
- projectId: profile.project_id,
- profileId: profile.id,
- }),
- JSON.stringify(merged),
- 'EX',
- this.ttlInSeconds
- );
+ // Fetch cache misses from ClickHouse in bounded chunks
+ if (cacheMisses.length > 0) {
+ const clickhouseResults =
+ await this.batchFetchFromClickhouse(cacheMisses);
+ for (const [key, profile] of clickhouseResults) {
+ existingByKey.set(key, profile);
}
+ }
- for (const chunk of this.chunks(toInsert, this.chunkSize)) {
- await ch.insert({
- table: TABLE_NAMES.profiles,
- values: chunk,
- format: 'JSONEachRow',
- });
- }
+ // Final merge: in-batch profile + existing (from cache or ClickHouse)
+ const toInsert: IClickhouseProfile[] = [];
+ const multi = this.redis.multi();
- multi
- .ltrim(this.redisKey, rawProfiles.length, -1)
- .decrby(this.bufferCounterKey, rawProfiles.length);
- await multi.exec();
-
- this.logger.debug(
- {
- totalProfiles: rawProfiles.length,
- uniqueProfiles: uniqueProfiles.length,
- },
- 'Successfully completed profile processing'
+ for (const profile of uniqueProfiles) {
+ const key = `${profile.project_id}:${profile.id}`;
+ const merged = this.mergeProfiles(
+ existingByKey.get(key) ?? null,
+ profile,
+ );
+ toInsert.push(merged);
+ multi.set(
+ this.getProfileCacheKey({
+ projectId: profile.project_id,
+ profileId: profile.id,
+ }),
+ JSON.stringify(merged),
+ 'EX',
+ this.ttlInSeconds,
);
- } catch (error) {
- this.logger.error({ err: error }, 'Failed to process buffer');
}
- }
- getBufferSize() {
- return this.getBufferSizeWithCounter(() => this.redis.llen(this.redisKey));
+ const chStart = performance.now();
+ for (const chunk of this.chunks(toInsert, this.chunkSize)) {
+ await ch.insert({
+ table: TABLE_NAMES.profiles,
+ values: chunk,
+ format: 'JSONEachRow',
+ });
+ }
+ const chInsertMs = performance.now() - chStart;
+
+ const trimStart = performance.now();
+ multi.ltrim(this.redisKey, rawProfiles.length, -1);
+ await multi.exec();
+ const trimMs = performance.now() - trimStart;
+
+ this.reportFlushStats({
+ rowsProcessed: rawProfiles.length,
+ phases: { lrangeMs, chInsertMs, trimMs },
+ });
}
}
diff --git a/packages/db/src/buffers/replay-buffer.ts b/packages/db/src/buffers/replay-buffer.ts
index 31dfa98e5..03112cd5c 100644
--- a/packages/db/src/buffers/replay-buffer.ts
+++ b/packages/db/src/buffers/replay-buffer.ts
@@ -34,62 +34,66 @@ export class ReplayBuffer extends BaseBuffer {
}
async add(chunk: IClickhouseSessionReplayChunk) {
- try {
- const redis = getRedisCache();
- const result = await redis
- .multi()
- .rpush(this.redisKey, JSON.stringify(chunk))
- .incr(this.bufferCounterKey)
- .llen(this.redisKey)
- .exec();
+ 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?.[2]?.[1] as number) ?? 0;
- if (bufferLength >= this.batchSize) {
- await this.tryFlush();
+ const bufferLength = (result?.[1]?.[1] as number) ?? 0;
+ if (bufferLength >= this.batchSize) {
+ await this.tryFlush({ trigger: 'add' });
+ }
+ } catch (error) {
+ this.logger.error(
+ { err: error },
+ 'Failed to add replay chunk to buffer',
+ );
}
- } catch (error) {
- this.logger.error(
- { err: error },
- 'Failed to add replay chunk to buffer',
- );
- }
+ });
+ }
+
+
+ protected getRedisListKey(): string {
+ return this.redisKey;
}
async processBuffer() {
const redis = getRedisCache();
- try {
- const items = await redis.lrange(this.redisKey, 0, this.batchSize - 1);
-
- if (items.length === 0) {
- return;
- }
- const chunks = items
- .map((item) => getSafeJson<IClickhouseSessionReplayChunk>(item))
- .filter((item): item is IClickhouseSessionReplayChunk => item != null);
+ const lrangeStart = performance.now();
+ const items = await redis.lrange(this.redisKey, 0, this.batchSize - 1);
+ const lrangeMs = performance.now() - lrangeStart;
- for (const chunk of this.chunks(chunks, this.chunkSize)) {
- await ch.insert({
- table: TABLE_NAMES.session_replay_chunks,
- values: chunk,
- format: 'JSONEachRow',
- });
- }
+ if (items.length === 0) {
+ this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
+ return;
+ }
- await redis
- .multi()
- .ltrim(this.redisKey, items.length, -1)
- .decrby(this.bufferCounterKey, items.length)
- .exec();
+ const chunks = items
+ .map((item) => getSafeJson<IClickhouseSessionReplayChunk>(item))
+ .filter((item): item is IClickhouseSessionReplayChunk => item != null);
- this.logger.debug({ count: items.length }, 'Processed replay chunks');
- } catch (error) {
- this.logger.error({ err: error }, 'Failed to process replay buffer');
+ const chStart = performance.now();
+ for (const chunk of this.chunks(chunks, this.chunkSize)) {
+ await ch.insert({
+ table: TABLE_NAMES.session_replay_chunks,
+ values: chunk,
+ format: 'JSONEachRow',
+ });
}
- }
+ const chInsertMs = performance.now() - chStart;
- async getBufferSize() {
- const redis = getRedisCache();
- return this.getBufferSizeWithCounter(() => redis.llen(this.redisKey));
+ 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 },
+ });
}
}
diff --git a/packages/db/src/buffers/session-buffer.test.ts b/packages/db/src/buffers/session-buffer.test.ts
index f140ff002..da95fda2b 100644
--- a/packages/db/src/buffers/session-buffer.test.ts
+++ b/packages/db/src/buffers/session-buffer.test.ts
@@ -112,9 +112,12 @@ describe('SessionBuffer', () => {
.spyOn(ch, 'insert')
.mockRejectedValueOnce(new Error('ClickHouse unavailable'));
- await sessionBuffer.processBuffer();
-
- // Sessions must still be in the queue — not lost
+ // Errors now propagate to tryFlush (which handles them by resyncing the
+ // counter). processBuffer no longer swallows — we still verify the
+ // safety property: the queue is preserved.
+ await expect(sessionBuffer.processBuffer()).rejects.toThrow(
+ 'ClickHouse unavailable',
+ );
expect(await sessionBuffer.getBufferSize()).toBe(1);
insertSpy.mockRestore();
diff --git a/packages/db/src/buffers/session-buffer.ts b/packages/db/src/buffers/session-buffer.ts
index b061898d5..2e8c6a424 100644
--- a/packages/db/src/buffers/session-buffer.ts
+++ b/packages/db/src/buffers/session-buffer.ts
@@ -192,6 +192,10 @@ export class SessionBuffer extends BaseBuffer {
];
}
+ protected getRedisListKey(): string {
+ return this.redisKey;
+ }
+
async add(event: IClickhouseEvent) {
if (!event.session_id) {
return;
@@ -201,89 +205,87 @@ export class SessionBuffer extends BaseBuffer {
return;
}
- try {
- // Plural since we will delete the old session with sign column
- const sessions = await this.getSession(event);
- const [newSession] = sessions;
-
- const multi = this.redis.multi();
- multi.set(
- `session:${newSession.id}`,
- JSON.stringify(newSession),
- 'EX',
- 60 * 60
- );
- if (newSession.profile_id) {
+ return this.timeAdd(async () => {
+ try {
+ // Plural since we will delete the old session with sign column
+ const sessions = await this.getSession(event);
+ const [newSession] = sessions;
+
+ const multi = this.redis.multi();
multi.set(
- `session:${newSession.project_id}:${newSession.profile_id}`,
- newSession.id,
+ `session:${newSession.id}`,
+ JSON.stringify(newSession),
'EX',
- 60 * 60
+ 60 * 60,
);
- }
- for (const session of sessions) {
- multi.rpush(this.redisKey, JSON.stringify(session));
- }
- // Increment counter by number of sessions added
- multi.incrby(this.bufferCounterKey, sessions.length);
- await multi.exec();
+ if (newSession.profile_id) {
+ multi.set(
+ `session:${newSession.project_id}:${newSession.profile_id}`,
+ newSession.id,
+ 'EX',
+ 60 * 60,
+ );
+ }
+ for (const session of sessions) {
+ multi.rpush(this.redisKey, JSON.stringify(session));
+ }
+ // Append LLEN at the end so we can read ground-truth queue length
+ // from the exec result without an extra round-trip.
+ multi.llen(this.redisKey);
+ const result = await multi.exec();
- // Check buffer length using counter
- const bufferLength = await this.getBufferSize();
+ const llenIndex = (result?.length ?? 1) - 1;
+ const bufferLength = (result?.[llenIndex]?.[1] as number) ?? 0;
- if (bufferLength >= this.batchSize) {
- await this.tryFlush();
+ if (bufferLength >= this.batchSize) {
+ await this.tryFlush({ trigger: 'add' });
+ }
+ } catch (error) {
+ this.logger.error({ err: error }, 'Failed to add session');
}
- } catch (error) {
- this.logger.error({ err: error }, 'Failed to add session');
- }
+ });
}
async processBuffer() {
- try {
- // Get events from the start without removing them
- const events = await this.redis.lrange(
- this.redisKey,
- 0,
- this.batchSize - 1
- );
-
- if (events.length === 0) {
- return;
- }
-
- const sessions = events
- .map((e) => getSafeJson<IClickhouseSession>(e))
- .map((session) => {
- return {
- ...session,
- duration: Math.max(0, session?.duration || 0),
- };
- });
-
- for (const chunk of this.chunks(sessions, this.chunkSize)) {
- // Insert to ClickHouse
- await ch.insert({
- table: TABLE_NAMES.sessions,
- values: chunk,
- format: 'JSONEachRow',
- });
- }
-
- // Only remove events after successful insert and update counter
- const multi = this.redis.multi();
- multi
- .ltrim(this.redisKey, events.length, -1)
- .decrby(this.bufferCounterKey, events.length);
- await multi.exec();
+ const lrangeStart = performance.now();
+ const events = await this.redis.lrange(
+ this.redisKey,
+ 0,
+ this.batchSize - 1
+ );
+ const lrangeMs = performance.now() - lrangeStart;
+
+ if (events.length === 0) {
+ this.reportFlushStats({ rowsProcessed: 0, phases: { lrangeMs } });
+ return;
+ }
- this.logger.debug({ count: events.length }, 'Processed sessions');
- } catch (error) {
- this.logger.error({ err: error }, 'Failed to process buffer');
+ const sessions = events
+ .map((e) => getSafeJson<IClickhouseSession>(e))
+ .map((session) => {
+ return {
+ ...session,
+ duration: Math.max(0, session?.duration || 0),
+ };
+ });
+
+ const chStart = performance.now();
+ for (const chunk of this.chunks(sessions, this.chunkSize)) {
+ await ch.insert({
+ table: TABLE_NAMES.sessions,
+ values: chunk,
+ format: 'JSONEachRow',
+ });
}
- }
+ const chInsertMs = performance.now() - chStart;
- getBufferSize() {
- return this.getBufferSizeWithCounter(() => this.redis.llen(this.redisKey));
+ const trimStart = performance.now();
+ await this.redis.ltrim(this.redisKey, events.length, -1);
+ const trimMs = performance.now() - trimStart;
+
+ this.reportFlushStats({
+ rowsProcessed: events.length,
+ phases: { lrangeMs, chInsertMs, trimMs },
+ });
}
}