Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(worker): throttle Mixpanel integration exports (#13958)

Nikhil543465bcd16a
diff --git a/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts b/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts
new file mode 100644
index 0000000000..2a79af9251
--- /dev/null
+++ b/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts
@@ -0,0 +1,150 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+
+/**
+ * Regression tests for the Mixpanel analytics export throttling fix (issue #12786).
+ *
+ * The original implementation built one MixpanelClient per stream and ran all
+ * streams concurrently via Promise.all, producing an unbounded export burst that
+ * overwhelmed the target. This mirrors the PostHog fix in PR #13773 for Mixpanel:
+ * 1. a single reused client per job,
+ * 2. sequential stream execution (max concurrency 1), and
+ * 3. a configurable inter-flush delay (LANGFUSE_MIXPANEL_FLUSH_DELAY_MS).
+ *
+ * NOTE: unlike the posthog-node SDK, the custom MixpanelClient has no background
+ * flush timer, so no shutdown()/timer-cleanup is required here.
+ */
+
+// vi.mock factories are hoisted above module scope, so all shared mutable state
+// the factories touch must live inside vi.hoisted().
+const h = vi.hoisted(() => {
+ const timeline: string[] = [];
+ const constructed: unknown[] = [];
+ const state = { activeStreams: 0, maxConcurrentStreams: 0 };
+
+ // A fake async stream that records start/end on the shared timeline and yields
+ // with a yield point in between, so concurrent (Promise.all) execution would
+ // interleave and trip the max-concurrency assertion.
+ function fakeStream(label: string) {
+ return (async function* () {
+ state.activeStreams++;
+ state.maxConcurrentStreams = Math.max(
+ state.maxConcurrentStreams,
+ state.activeStreams,
+ );
+ timeline.push(`${label}:start`);
+ await Promise.resolve();
+ yield { langfuse_id: `${label}-1` };
+ await Promise.resolve();
+ yield { langfuse_id: `${label}-2` };
+ timeline.push(`${label}:end`);
+ state.activeStreams--;
+ })();
+ }
+
+ const mixpanelIntegrationUpdate = vi.fn();
+
+ return {
+ timeline,
+ constructed,
+ state,
+ fakeStream,
+ mixpanelIntegrationUpdate,
+ };
+});
+
+vi.mock("../features/mixpanel/mixpanelClient", () => ({
+ MixpanelClient: class {
+ addEvent = vi.fn();
+ flush = vi.fn().mockImplementation(async () => {
+ h.timeline.push("flush");
+ });
+ getBatchSize = vi.fn().mockReturnValue(0);
+ constructor() {
+ h.constructed.push(this);
+ }
+ },
+}));
+
+vi.mock("../features/mixpanel/transformers", () => ({
+ transformTraceForMixpanel: vi.fn((e) => e),
+ transformGenerationForMixpanel: vi.fn((e) => e),
+ transformScoreForMixpanel: vi.fn((e) => e),
+ transformEventForMixpanel: vi.fn((e) => e),
+}));
+
+vi.mock("@langfuse/shared/encryption", () => ({
+ decrypt: vi.fn(() => "decrypted-token"),
+}));
+
+// Keep the throttle delay out of the unit test (real value defaults to 500ms).
+// Path is relative to this test file -> resolves to worker/src/env.
+vi.mock("../env", () => ({
+ env: { LANGFUSE_MIXPANEL_FLUSH_DELAY_MS: 0 },
+}));
+
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: {
+ mixpanelIntegration: {
+ findFirst: vi.fn(async () => ({
+ projectId: "project-1",
+ enabled: true,
+ exportSource: "TRACES_OBSERVATIONS_EVENTS",
+ mixpanelRegion: "api",
+ encryptedMixpanelProjectToken: "enc",
+ lastSyncAt: new Date("2024-01-01"),
+ project: { name: "Test Project" },
+ })),
+ update: h.mixpanelIntegrationUpdate,
+ },
+ },
+}));
+
+vi.mock("@langfuse/shared/src/server", () => ({
+ QueueName: { MixpanelIntegrationProcessingQueue: "mixpanel" },
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ getCurrentSpan: vi.fn(() => undefined),
+ getTracesForAnalyticsIntegrations: vi.fn(() => h.fakeStream("traces")),
+ getGenerationsForAnalyticsIntegrations: vi.fn(() =>
+ h.fakeStream("generations"),
+ ),
+ getScoresForAnalyticsIntegrations: vi.fn(() => h.fakeStream("scores")),
+ getEventsForAnalyticsIntegrations: vi.fn(() => h.fakeStream("events")),
+}));
+
+// Import after mocks are registered.
+import { handleMixpanelIntegrationProjectJob } from "../features/mixpanel/handleMixpanelIntegrationProjectJob";
+
+function makeJob() {
+ return {
+ data: { id: "job-1", payload: { projectId: "project-1" } },
+ attemptsMade: 0,
+ } as unknown as Parameters<typeof handleMixpanelIntegrationProjectJob>[0];
+}
+
+describe("handleMixpanelIntegrationProjectJob throttling (issue #12786)", () => {
+ beforeEach(() => {
+ h.timeline.length = 0;
+ h.constructed.length = 0;
+ h.state.activeStreams = 0;
+ h.state.maxConcurrentStreams = 0;
+ h.mixpanelIntegrationUpdate.mockClear();
+ });
+
+ it("reuses a single MixpanelClient for the whole job", async () => {
+ await handleMixpanelIntegrationProjectJob(makeJob());
+ expect(h.constructed.length).toBe(1);
+ });
+
+ it("runs export streams sequentially (no concurrent streams)", async () => {
+ await handleMixpanelIntegrationProjectJob(makeJob());
+ // Each stream must fully finish before the next starts.
+ expect(h.state.maxConcurrentStreams).toBe(1);
+ // Timeline never has two starts without an intervening end.
+ let open = 0;
+ for (const entry of h.timeline) {
+ if (entry.endsWith(":start")) open++;
+ if (entry.endsWith(":end")) open--;
+ expect(open).toBeLessThanOrEqual(1);
+ }
+ });
+});
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 9fd110eff3..7abd03aaa0 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -122,6 +122,9 @@ const EnvSchema = z.object({
.default(25),
LANGFUSE_TRACE_DELETE_CONCURRENCY: z.coerce.number().positive().default(1),
LANGFUSE_SCORE_DELETE_CONCURRENCY: z.coerce.number().positive().default(1),
+ // Delay (ms) inserted after each Mixpanel flush to throttle analytics exports
+ // and avoid overwhelming the target instance (see issue #12786).
+ LANGFUSE_MIXPANEL_FLUSH_DELAY_MS: z.coerce.number().min(0).default(500),
LANGFUSE_DATASET_DELETE_CONCURRENCY: z.coerce.number().positive().default(1),
LANGFUSE_PROJECT_DELETE_CONCURRENCY: z.coerce.number().positive().default(1),
LANGFUSE_EVAL_EXECUTION_WORKER_CONCURRENCY: z.coerce
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
index bb85732dfd..ef737572d9 100644
--- a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
@@ -18,6 +18,25 @@ import {
transformScoreForMixpanel,
transformEventForMixpanel,
} from "./transformers";
+import { env } from "../../env";
+
+const sleep = (ms: number) =>
+ ms > 0
+ ? new Promise((resolve) => setTimeout(resolve, ms))
+ : Promise.resolve();
+
+// Throttle exports after each flush so a single project sync cannot burst the
+// target Mixpanel instance with an unbounded event rate (issue #12786).
+const flushWithDelay = async (mixpanel: MixpanelClient) => {
+ // flush() is a no-op on an empty batch, so only throttle when we actually
+ // sent something. Avoids a wasted delay when the terminal flush has nothing
+ // left to send (e.g. event count is an exact multiple of the flush size).
+ const hadEvents = mixpanel.getBatchSize() > 0;
+ await mixpanel.flush();
+ if (hadEvents) {
+ await sleep(env.LANGFUSE_MIXPANEL_FLUSH_DELAY_MS);
+ }
+};
type MixpanelExecutionConfig = {
projectId: string;
@@ -32,7 +51,10 @@ type MixpanelExecutionConfig = {
useGraceHash: boolean;
};
-const processMixpanelTraces = async (config: MixpanelExecutionConfig) => {
+const processMixpanelTraces = async (
+ mixpanel: MixpanelClient,
+ config: MixpanelExecutionConfig,
+) => {
const traces = getTracesForAnalyticsIntegrations(
config.projectId,
config.projectName,
@@ -45,11 +67,6 @@ const processMixpanelTraces = async (config: MixpanelExecutionConfig) => {
`[MIXPANEL] Sending traces for project ${config.projectId} to Mixpanel`,
);
- const mixpanel = new MixpanelClient({
- projectToken: config.decryptedMixpanelProjectToken,
- region: config.mixpanelRegion,
- });
-
let count = 0;
for await (const trace of traces) {
count++;
@@ -57,19 +74,22 @@ const processMixpanelTraces = async (config: MixpanelExecutionConfig) => {
mixpanel.addEvent(event);
if (count % 1000 === 0) {
- await mixpanel.flush();
+ await flushWithDelay(mixpanel);
logger.info(
`[MIXPANEL] Sent ${count} traces to Mixpanel for project ${config.projectId}`,
);
}
}
- await mixpanel.flush();
+ await flushWithDelay(mixpanel);
logger.info(
`[MIXPANEL] Sent ${count} traces to Mixpanel for project ${config.projectId}`,
);
};
-const processMixpanelGenerations = async (config: MixpanelExecutionConfig) => {
+const processMixpanelGenerations = async (
+ mixpanel: MixpanelClient,
+ config: MixpanelExecutionConfig,
+) => {
const generations = getGenerationsForAnalyticsIntegrations(
config.projectId,
config.projectName,
@@ -82,11 +102,6 @@ const processMixpanelGenerations = async (config: MixpanelExecutionConfig) => {
`[MIXPANEL] Sending generations for project ${config.projectId} to Mixpanel`,
);
- const mixpanel = new MixpanelClient({
- projectToken: config.decryptedMixpanelProjectToken,
- region: config.mixpanelRegion,
- });
-
let count = 0;
for await (const generation of generations) {
count++;
@@ -94,19 +109,22 @@ const processMixpanelGenerations = async (config: MixpanelExecutionConfig) => {
mixpanel.addEvent(event);
if (count % 1000 === 0) {
- await mixpanel.flush();
+ await flushWithDelay(mixpanel);
logger.info(
`[MIXPANEL] Sent ${count} generations to Mixpanel for project ${config.projectId}`,
);
}
}
- await mixpanel.flush();
+ await flushWithDelay(mixpanel);
logger.info(
`[MIXPANEL] Sent ${count} generations to Mixpanel for project ${config.projectId}`,
);
};
-const processMixpanelScores = async (config: MixpanelExecutionConfig) => {
+const processMixpanelScores = async (
+ mixpanel: MixpanelClient,
+ config: MixpanelExecutionConfig,
+) => {
const scores = getScoresForAnalyticsIntegrations(
config.projectId,
config.projectName,
@@ -119,11 +137,6 @@ const processMixpanelScores = async (config: MixpanelExecutionConfig) => {
`[MIXPANEL] Sending scores for project ${config.projectId} to Mixpanel`,
);
- const mixpanel = new MixpanelClient({
- projectToken: config.decryptedMixpanelProjectToken,
- region: config.mixpanelRegion,
- });
-
let count = 0;
for await (const score of scores) {
count++;
@@ -131,19 +144,22 @@ const processMixpanelScores = async (config: MixpanelExecutionConfig) => {
mixpanel.addEvent(event);
if (count % 1000 === 0) {
- await mixpanel.flush();
+ await flushWithDelay(mixpanel);
logger.info(
`[MIXPANEL] Sent ${count} scores to Mixpanel for project ${config.projectId}`,
);
}
}
- await mixpanel.flush();
+ await flushWithDelay(mixpanel);
logger.info(
`[MIXPANEL] Sent ${count} scores to Mixpanel for project ${config.projectId}`,
);
};
-const processMixpanelEvents = async (config: MixpanelExecutionConfig) => {
+const processMixpanelEvents = async (
+ mixpanel: MixpanelClient,
+ config: MixpanelExecutionConfig,
+) => {
const events = getEventsForAnalyticsIntegrations(
config.projectId,
config.projectName,
@@ -155,11 +171,6 @@ const processMixpanelEvents = async (config: MixpanelExecutionConfig) => {
`[MIXPANEL] Sending events for project ${config.projectId} to Mixpanel`,
);
- const mixpanel = new MixpanelClient({
- projectToken: config.decryptedMixpanelProjectToken,
- region: config.mixpanelRegion,
- });
-
let count = 0;
for await (const analyticsEvent of events) {
count++;
@@ -167,13 +178,13 @@ const processMixpanelEvents = async (config: MixpanelExecutionConfig) => {
mixpanel.addEvent(event);
if (count % 1000 === 0) {
- await mixpanel.flush();
+ await flushWithDelay(mixpanel);
logger.info(
`[MIXPANEL] Sent ${count} events to Mixpanel for project ${config.projectId}`,
);
}
}
- await mixpanel.flush();
+ await flushWithDelay(mixpanel);
logger.info(
`[MIXPANEL] Sent ${count} events to Mixpanel for project ${config.projectId}`,
);
@@ -236,20 +247,24 @@ export const handleMixpanelIntegrationProjectJob = async (
};
try {
- const processPromises: Promise<void>[] = [];
+ // Reuse a single client and run streams sequentially so the per-job export
+ // rate stays bounded. Running the streams in parallel with one client each
+ // produced an unbounded burst that overwhelmed the target (issue #12786).
+ const mixpanel = new MixpanelClient({
+ projectToken: executionConfig.decryptedMixpanelProjectToken,
+ region: executionConfig.mixpanelRegion,
+ });
// Always include scores
- processPromises.push(processMixpanelScores(executionConfig));
+ await processMixpanelScores(mixpanel, executionConfig);
// Traces and observations - for TRACES_OBSERVATIONS and TRACES_OBSERVATIONS_EVENTS
if (
mixpanelIntegration.exportSource === "TRACES_OBSERVATIONS" ||
mixpanelIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"
) {
- processPromises.push(
- processMixpanelTraces(executionConfig),
- processMixpanelGenerations(executionConfig),
- );
+ await processMixpanelTraces(mixpanel, executionConfig);
+ await processMixpanelGenerations(mixpanel, executionConfig);
}
// Events - for EVENTS and TRACES_OBSERVATIONS_EVENTS
@@ -257,11 +272,9 @@ export const handleMixpanelIntegrationProjectJob = async (
mixpanelIntegration.exportSource === "EVENTS" ||
mixpanelIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"
) {
- processPromises.push(processMixpanelEvents(executionConfig));
+ await processMixpanelEvents(mixpanel, executionConfig);
}
- await Promise.all(processPromises);
-
// Update the last run information for the mixpanelIntegration record.
await prisma.mixpanelIntegration.update({
where: {