Skip to content

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

fix: yield for event loop

Carl-Gerhard Lindesvärd7dc230603dbd
diff --git a/packages/db/src/buffers/base-buffer.ts b/packages/db/src/buffers/base-buffer.ts
index 0d092cf4e..523e2f3b1 100644
--- a/packages/db/src/buffers/base-buffer.ts
+++ b/packages/db/src/buffers/base-buffer.ts
@@ -118,6 +118,20 @@ export class BaseBuffer {
throw new Error(`${this.name}: subclass must override getRedisListKey()`);
}
+ /**
+ * Yield control back to the event loop. Use periodically inside CPU-bound
+ * loops (parse / merge / sort over N items) so other awaiters — incoming
+ * add() calls, BullMQ heartbeats, the /healthz endpoint — can make
+ * progress instead of waiting hundreds of milliseconds for the loop to
+ * monopolise itself on one flush.
+ *
+ * Costs ~1ms per call (one event-loop tick); use every 500–1000 items,
+ * not every iteration.
+ */
+ protected yieldToEventLoop(): Promise<void> {
+ return new Promise((resolve) => setImmediate(resolve));
+ }
+
protected chunks<T>(items: T[], size: number) {
const chunks = [];
for (let i = 0; i < items.length; i += size) {
diff --git a/packages/db/src/buffers/event-buffer.ts b/packages/db/src/buffers/event-buffer.ts
index 9b7e4b30a..8073e3097 100644
--- a/packages/db/src/buffers/event-buffer.ts
+++ b/packages/db/src/buffers/event-buffer.ts
@@ -146,15 +146,22 @@ export class EventBuffer extends BaseBuffer {
return;
}
+ // Parse with periodic yields. Event batches can be very large
+ // (EVENT_BUFFER_BATCH_SIZE defaults to 4000 but is often set to
+ // 100k in prod). Yielding every 1000 items keeps the event loop
+ // responsive without measurable throughput impact.
const eventsToClickhouse: IClickhouseEvent[] = [];
- for (const eventStr of queueEvents) {
- const event = getSafeJson<IClickhouseEvent>(eventStr);
+ for (let i = 0; i < queueEvents.length; i++) {
+ const event = getSafeJson<IClickhouseEvent>(queueEvents[i]!);
if (event) {
if (!Array.isArray(event.groups)) {
event.groups = [];
}
eventsToClickhouse.push(event);
}
+ if ((i + 1) % 1000 === 0) {
+ await this.yieldToEventLoop();
+ }
}
if (eventsToClickhouse.length === 0) {
@@ -162,12 +169,6 @@ export class EventBuffer extends BaseBuffer {
return;
}
- eventsToClickhouse.sort(
- (a, b) =>
- new Date(a.created_at || 0).getTime() -
- new Date(b.created_at || 0).getTime()
- );
-
const chStart = performance.now();
await this.parallelLimit(
this.chunks(eventsToClickhouse, this.chunkSize),
diff --git a/packages/db/src/buffers/profile-buffer.ts b/packages/db/src/buffers/profile-buffer.ts
index e90d3fb66..a9fc0297c 100644
--- a/packages/db/src/buffers/profile-buffer.ts
+++ b/packages/db/src/buffers/profile-buffer.ts
@@ -259,18 +259,24 @@ export class ProfileBuffer extends BaseBuffer {
return;
}
- const parsedProfiles = rawProfiles
- .map((p) => getSafeJson<IClickhouseProfile>(p))
- .filter(Boolean) as IClickhouseProfile[];
-
- // Merge within batch: collapse multiple updates for the same profile
+ // Parse + merge within batch in a single pass. Yields back to the
+ // event loop every 500 items so concurrent add() calls and BullMQ
+ // heartbeats can make progress while the merge churns through 10k+
+ // profiles. The merge step is the hottest CPU stage of any buffer —
+ // deepMergeObjects recursively combines nested `properties` objects
+ // and was previously responsible for ~500ms event-loop blocks.
const mergedInBatch = new Map<string, IClickhouseProfile>();
- for (const profile of parsedProfiles) {
+ for (let i = 0; i < rawProfiles.length; i++) {
+ const profile = getSafeJson<IClickhouseProfile>(rawProfiles[i]!);
+ if (!profile) continue;
const key = `${profile.project_id}:${profile.id}`;
mergedInBatch.set(
key,
- this.mergeProfiles(mergedInBatch.get(key) ?? null, profile)
+ this.mergeProfiles(mergedInBatch.get(key) ?? null, profile),
);
+ if ((i + 1) % 500 === 0) {
+ await this.yieldToEventLoop();
+ }
}
const uniqueProfiles = Array.from(mergedInBatch.values());
@@ -313,15 +319,18 @@ export class ProfileBuffer extends BaseBuffer {
}
}
- // Final merge: in-batch profile + existing (from cache or ClickHouse)
+ // Final merge: in-batch profile + existing (from cache or ClickHouse).
+ // Second heavy stage — same deepMergeObjects call per unique profile,
+ // so the same yield-every-500 pattern applies.
const toInsert: IClickhouseProfile[] = [];
const multi = this.redis.multi();
- for (const profile of uniqueProfiles) {
+ for (let i = 0; i < uniqueProfiles.length; i++) {
+ const profile = uniqueProfiles[i]!;
const key = `${profile.project_id}:${profile.id}`;
const merged = this.mergeProfiles(
existingByKey.get(key) ?? null,
- profile
+ profile,
);
toInsert.push(merged);
multi.set(
@@ -331,8 +340,11 @@ export class ProfileBuffer extends BaseBuffer {
}),
JSON.stringify(merged),
'EX',
- this.ttlInSeconds
+ this.ttlInSeconds,
);
+ if ((i + 1) % 500 === 0) {
+ await this.yieldToEventLoop();
+ }
}
const chStart = performance.now();
diff --git a/packages/db/src/buffers/replay-buffer.ts b/packages/db/src/buffers/replay-buffer.ts
index 7c3aecc56..cf7569ba9 100644
--- a/packages/db/src/buffers/replay-buffer.ts
+++ b/packages/db/src/buffers/replay-buffer.ts
@@ -72,9 +72,18 @@ export class ReplayBuffer extends BaseBuffer {
return;
}
- const chunks = items
- .map((item) => getSafeJson<IClickhouseSessionReplayChunk>(item))
- .filter((item): item is IClickhouseSessionReplayChunk => item != null);
+ // Parse rrweb chunks with periodic yields. Each chunk's `payload`
+ // field is a large JSON blob (~10-100KB) so JSON.parse is expensive
+ // per item. Yield every 100 items to keep the event loop responsive
+ // during big flushes.
+ const chunks: IClickhouseSessionReplayChunk[] = [];
+ for (let i = 0; i < items.length; i++) {
+ const parsed = getSafeJson<IClickhouseSessionReplayChunk>(items[i]!);
+ if (parsed != null) chunks.push(parsed);
+ if ((i + 1) % 100 === 0) {
+ await this.yieldToEventLoop();
+ }
+ }
const chStart = performance.now();
await this.parallelLimit(this.chunks(chunks, this.chunkSize), (chunk) =>