Skip to content

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

chore(worker): unify export volume into one egress-cost metric (LFE-10508) (#14548)

Niklas Semmler891f630ead1e
diff --git a/worker/src/__tests__/exportVolumeMetric.test.ts b/worker/src/__tests__/exportVolumeMetric.test.ts
new file mode 100644
index 0000000000..a2bd557c49
--- /dev/null
+++ b/worker/src/__tests__/exportVolumeMetric.test.ts
@@ -0,0 +1,59 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+const recordIncrement = vi.fn();
+vi.mock("@langfuse/shared/src/server", () => ({
+ recordIncrement: (...args: unknown[]) => recordIncrement(...args),
+}));
+
+import {
+ recordExportVolume,
+ EXPORT_VOLUME_METRIC,
+} from "../services/exportVolumeMetric";
+
+describe("recordExportVolume", () => {
+ beforeEach(() => recordIncrement.mockClear());
+
+ it("emits the unified metric with the byte value", () => {
+ recordExportVolume({
+ integration: "mixpanel",
+ bytes: 1234,
+ projectId: "p1",
+ });
+ expect(recordIncrement).toHaveBeenCalledWith(EXPORT_VOLUME_METRIC, 1234, {
+ integration: "mixpanel",
+ projectId: "p1",
+ });
+ });
+
+ it("includes blob dimensions and omits undefined tags", () => {
+ recordExportVolume({
+ integration: "blob_storage",
+ bytes: 42,
+ projectId: "p2",
+ destinationType: "S3",
+ source: "json-gzip",
+ table: "traces",
+ path: "standard",
+ });
+ expect(recordIncrement).toHaveBeenCalledWith(EXPORT_VOLUME_METRIC, 42, {
+ integration: "blob_storage",
+ projectId: "p2",
+ destination_type: "S3",
+ source: "json-gzip",
+ table: "traces",
+ path: "standard",
+ });
+ });
+
+ it("omits API-integration tags that are not provided", () => {
+ recordExportVolume({
+ integration: "posthog",
+ bytes: 7,
+ projectId: "p3",
+ });
+ const tags = recordIncrement.mock.calls[0][2];
+ expect(tags).not.toHaveProperty("destination_type");
+ expect(tags).not.toHaveProperty("source");
+ expect(tags).not.toHaveProperty("table");
+ });
+});
diff --git a/worker/src/__tests__/mixpanelExportVolume.test.ts b/worker/src/__tests__/mixpanelExportVolume.test.ts
new file mode 100644
index 0000000000..1269ded69c
--- /dev/null
+++ b/worker/src/__tests__/mixpanelExportVolume.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { gzipSync } from "zlib";
+import { MixpanelClient } from "../features/mixpanel/mixpanelClient";
+import type { MixpanelEvent } from "../features/mixpanel/transformers";
+
+describe("MixpanelClient export volume", () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValue({ ok: true, json: async () => ({}) });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("accumulates gzipped on-wire bytes across sendBatch chunks", async () => {
+ const client = new MixpanelClient({ projectToken: "t", region: "api" });
+
+ // > batchSize (1000) so flush() splits into two sendBatch chunks.
+ const total = 1500;
+ const events: MixpanelEvent[] = Array.from(
+ { length: total },
+ (_, i) =>
+ ({
+ event: "trace",
+ properties: { token: "t", distinct_id: String(i), $insert_id: i },
+ }) as unknown as MixpanelEvent,
+ );
+ events.forEach((e) => client.addEvent(e));
+
+ await client.flush();
+
+ const expected =
+ gzipSync(JSON.stringify(events.slice(0, 1000))).length +
+ gzipSync(JSON.stringify(events.slice(1000))).length;
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(client.getSerializedBytes()).toBe(expected);
+ });
+});
diff --git a/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts b/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts
index 2a79af9251..e98c512e0c 100644
--- a/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts
+++ b/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts
@@ -59,6 +59,7 @@ vi.mock("../features/mixpanel/mixpanelClient", () => ({
h.timeline.push("flush");
});
getBatchSize = vi.fn().mockReturnValue(0);
+ getSerializedBytes = vi.fn().mockReturnValue(0);
constructor() {
h.constructed.push(this);
}
@@ -102,6 +103,7 @@ vi.mock("@langfuse/shared/src/db", () => ({
vi.mock("@langfuse/shared/src/server", () => ({
QueueName: { MixpanelIntegrationProcessingQueue: "mixpanel" },
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ recordIncrement: vi.fn(),
getCurrentSpan: vi.fn(() => undefined),
getTracesForAnalyticsIntegrations: vi.fn(() => h.fakeStream("traces")),
getGenerationsForAnalyticsIntegrations: vi.fn(() =>
diff --git a/worker/src/__tests__/posthogExportVolume.test.ts b/worker/src/__tests__/posthogExportVolume.test.ts
new file mode 100644
index 0000000000..6b9c44f95d
--- /dev/null
+++ b/worker/src/__tests__/posthogExportVolume.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { countingFetch } from "../features/posthog/handlePostHogIntegrationProjectJob";
+
+describe("countingFetch (posthog export volume)", () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValue({ status: 200 });
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("counts /batch/ string and Blob bodies, ignores /flags/, forwards all", async () => {
+ const volume = { bytes: 0 };
+ const wrapped = countingFetch(volume)!;
+
+ await wrapped("https://app.posthog.com/batch/", {
+ method: "POST",
+ headers: {},
+ body: "abcd",
+ });
+ expect(volume.bytes).toBe(4);
+
+ await wrapped("https://app.posthog.com/batch/", {
+ method: "POST",
+ headers: {},
+ body: new Blob([new Uint8Array(10)]),
+ });
+ expect(volume.bytes).toBe(14);
+
+ // Feature-flag traffic must not be counted as export egress.
+ await wrapped("https://app.posthog.com/flags/?v=2", {
+ method: "POST",
+ headers: {},
+ body: "ignored",
+ });
+ expect(volume.bytes).toBe(14);
+
+ // Every request is still forwarded to the underlying fetch.
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+});
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index 1e6d832ebf..1267b8109d 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -59,6 +59,7 @@ import { env as sharedEnv } from "@langfuse/shared/src/env";
import { randomUUID } from "crypto";
import { SpanKind } from "@opentelemetry/api";
import { env, v4AllowPreviewOptIn } from "../../env";
+import { recordExportVolume } from "../../services/exportVolumeMetric";
export const BlobExportFormat = {
JSON_RAW: "json-raw",
@@ -556,7 +557,9 @@ const processBlobStorageExport = async (config: {
);
recordGauge(
"langfuse.blobstorage.export_heartbeat.serialized_bytes",
- serializedCounter.bytes,
+ compressedCounter
+ ? compressedCounter.bytes
+ : serializedCounter.bytes,
heartbeatTags,
);
}, HEARTBEAT_INTERVAL_MS);
@@ -785,28 +788,21 @@ const processBlobStorageExport = async (config: {
const exportFormat = parquetEligible
? BlobExportFormat.PARQUET
: resolveBlobExportFormat(config.fileType, config.compressed);
- const byteTags = {
- table: config.table,
+ // Unified export-volume metric: the actual uploaded volume per
+ // source (post-gzip size for compressed formats, raw/parquet size
+ // otherwise). destination_type (S3 / S3_COMPATIBLE / AZURE_*) splits
+ // the egress by data-transfer cost in the Datadog dashboard.
+ recordExportVolume({
+ integration: "blob_storage",
+ bytes: compressedCounter
+ ? compressedCounter.bytes
+ : serializedCounter.bytes,
projectId: config.projectId,
- path: exportPath,
+ destinationType: config.type,
source: exportFormat,
- // Integration type (S3 / S3_COMPATIBLE / AZURE_BLOB_STORAGE) as the
- // destination, so export volume can be split by data-transfer cost
- // in the Datadog dashboard (native AWS S3 vs. external egress).
- destination_type: config.type,
- };
- recordIncrement(
- "langfuse.blob_export.serialized_bytes",
- serializedCounter.bytes,
- byteTags,
- );
- if (compressedCounter && gzipStats) {
- recordIncrement(
- "langfuse.blob_export.compressed_bytes",
- compressedCounter.bytes,
- { ...byteTags, gzipLevel: gzipStats.level },
- );
- }
+ table: config.table,
+ path: exportPath,
+ });
const uploadDurationMs = uploadDurationMsFinal;
const chReadMs = Math.round(
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
index ef737572d9..40b2ff60ed 100644
--- a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
@@ -12,6 +12,7 @@ import {
} from "@langfuse/shared/src/server";
import { decrypt } from "@langfuse/shared/encryption";
import { MixpanelClient } from "./mixpanelClient";
+import { recordExportVolume } from "../../services/exportVolumeMetric";
import {
transformTraceForMixpanel,
transformGenerationForMixpanel,
@@ -284,6 +285,12 @@ export const handleMixpanelIntegrationProjectJob = async (
lastSyncAt: executionConfig.maxTimestamp,
},
});
+ // Record gzipped on-wire export volume once the run has succeeded.
+ recordExportVolume({
+ integration: "mixpanel",
+ bytes: mixpanel.getSerializedBytes(),
+ projectId,
+ });
logger.info(
`[MIXPANEL] Mixpanel integration processing complete for project ${projectId}`,
);
diff --git a/worker/src/features/mixpanel/mixpanelClient.ts b/worker/src/features/mixpanel/mixpanelClient.ts
index 19853d845a..bc90ae0d17 100644
--- a/worker/src/features/mixpanel/mixpanelClient.ts
+++ b/worker/src/features/mixpanel/mixpanelClient.ts
@@ -15,11 +15,20 @@ export class MixpanelClient {
private config: MixpanelClientConfig;
private batch: MixpanelEvent[] = [];
private batchSize = 1000; // Similar to PostHog's flushAt setting
+ // Gzipped on-wire bytes sent so far, for the export-volume metric.
+ private serializedBytes = 0;
constructor(config: MixpanelClientConfig) {
this.config = config;
}
+ /**
+ * Total gzipped on-wire bytes sent to Mixpanel across all flushes.
+ */
+ public getSerializedBytes(): number {
+ return this.serializedBytes;
+ }
+
/**
* Add an event to the batch
*/
@@ -58,6 +67,8 @@ export class MixpanelClient {
// Compress the body with gzip
const compressedBody = gzipSync(body);
+ // Count the gzipped payload as on-wire export volume (sent below).
+ this.serializedBytes += compressedBody.length;
// Create Basic Auth header (token as username, empty password)
const authHeader = `Basic ${Buffer.from(`${this.config.projectToken}:`).toString("base64")}`;
diff --git a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
index 0ed15abd83..de76928ccf 100644
--- a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
+++ b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
@@ -19,6 +19,7 @@ import {
} from "./transformers";
import { decrypt } from "@langfuse/shared/encryption";
import { PostHog } from "posthog-node";
+import { recordExportVolume } from "../../services/exportVolumeMetric";
type PostHogExecutionConfig = {
projectId: string;
@@ -31,12 +32,43 @@ type PostHogExecutionConfig = {
// `grace_hash` (slower, but spills to disk) on retries so an OOM on the first
// attempt recovers without manual intervention while healthy syncs stay fast.
useGraceHash: boolean;
+ // Shared accumulator for gzipped on-wire upload volume, written by the
+ // fetch wrapper on each client and read once the run succeeds.
+ volume: { bytes: number };
};
const postHogSettings = {
flushAt: 1000,
};
+type PostHogClientOptions = NonNullable<
+ ConstructorParameters<typeof PostHog>[1]
+>;
+
+// Wrap the SDK's fetch transport to count gzipped on-wire upload volume for
+// the export-volume metric. The SDK gzips the /batch/ body by default and also
+// calls /flags/, so only /batch/ request bodies are measured (LFE-10508).
+export const countingFetch =
+ (volume: { bytes: number }): PostHogClientOptions["fetch"] =>
+ (url, options) => {
+ if (url.endsWith("/batch/")) {
+ const body = options.body;
+ if (typeof body === "string") {
+ volume.bytes += Buffer.byteLength(body);
+ } else if (body instanceof Blob) {
+ volume.bytes += body.size;
+ } else {
+ // The SDK sends gzipped Blob bodies today; warn (rather than silently
+ // counting 0) if a future SDK version uses another body type, so the
+ // export-volume under-reporting is observable.
+ logger.warn(
+ `[POSTHOG] Unexpected /batch/ body type "${typeof body}"; export volume under-reported`,
+ );
+ }
+ }
+ return globalThis.fetch(url, options as RequestInit);
+ };
+
const processPostHogTraces = async (config: PostHogExecutionConfig) => {
const traces = getTracesForAnalyticsIntegrations(
config.projectId,
@@ -54,6 +86,7 @@ const processPostHogTraces = async (config: PostHogExecutionConfig) => {
const posthog = new PostHog(config.decryptedPostHogApiKey, {
host: config.postHogHost,
...postHogSettings,
+ fetch: countingFetch(config.volume),
});
let sendError: Error | undefined;
@@ -102,6 +135,7 @@ const processPostHogGenerations = async (config: PostHogExecutionConfig) => {
const posthog = new PostHog(config.decryptedPostHogApiKey, {
host: config.postHogHost,
...postHogSettings,
+ fetch: countingFetch(config.volume),
});
let sendError: Error | undefined;
@@ -150,6 +184,7 @@ const processPostHogScores = async (config: PostHogExecutionConfig) => {
const posthog = new PostHog(config.decryptedPostHogApiKey, {
host: config.postHogHost,
...postHogSettings,
+ fetch: countingFetch(config.volume),
});
let sendError: Error | undefined;
@@ -197,6 +232,7 @@ const processPostHogEvents = async (config: PostHogExecutionConfig) => {
const posthog = new PostHog(config.decryptedPostHogApiKey, {
host: config.postHogHost,
...postHogSettings,
+ fetch: countingFetch(config.volume),
});
let sendError: Error | undefined;
@@ -324,6 +360,7 @@ export const handlePostHogIntegrationProjectJob = async (
decryptedPostHogApiKey: decrypt(postHogIntegration.encryptedPosthogApiKey),
postHogHost: postHogIntegration.posthogHostName,
useGraceHash: job.attemptsMade > 0,
+ volume: { bytes: 0 },
};
try {
@@ -362,6 +399,12 @@ export const handlePostHogIntegrationProjectJob = async (
lastSyncAt: executionConfig.maxTimestamp,
},
});
+ // Record gzipped on-wire export volume once the run has succeeded.
+ recordExportVolume({
+ integration: "posthog",
+ bytes: executionConfig.volume.bytes,
+ projectId,
+ });
logger.info(
`[POSTHOG] PostHog integration processing complete for project ${projectId}`,
);
diff --git a/worker/src/services/exportVolumeMetric.ts b/worker/src/services/exportVolumeMetric.ts
new file mode 100644
index 0000000000..c31dcc369f
--- /dev/null
+++ b/worker/src/services/exportVolumeMetric.ts
@@ -0,0 +1,41 @@
+import { recordIncrement } from "@langfuse/shared/src/server";
+
+export const EXPORT_VOLUME_METRIC = "langfuse.export.serialized_bytes";
+
+export type ExportIntegration = "blob_storage" | "posthog" | "mixpanel";
+
+type ExportVolume = {
+ integration: ExportIntegration;
+ // Gzipped on-wire bytes the integration shipped this run.
+ bytes: number;
+ projectId: string;
+ // Egress-cost classification; blob only (S3 / S3_COMPATIBLE / AZURE_*).
+ destinationType?: string;
+ // Blob-only dimensions: export format, table, and codepath.
+ source?: string;
+ table?: string;
+ path?: string;
+};
+
+/**
+ * Single metric for total outbound export volume, so egress can be summed
+ * across integrations and split by `integration` / `destination_type` for
+ * cost. Undefined tags are omitted so each integration sets only the
+ * dimensions it has.
+ */
+export const recordExportVolume = ({
+ integration,
+ bytes,
+ projectId,
+ destinationType,
+ source,
+ table,
+ path,
+}: ExportVolume): void => {
+ const tags: Record<string, string> = { integration, projectId };
+ if (destinationType !== undefined) tags.destination_type = destinationType;
+ if (source !== undefined) tags.source = source;
+ if (table !== undefined) tags.table = table;
+ if (path !== undefined) tags.path = path;
+ recordIncrement(EXPORT_VOLUME_METRIC, bytes, tags);
+};