Skip to content

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

perf: upload otel ingestion payloads as batch to blob storage (#8893)

Steffen Schmitz3e23f0c58e31
diff --git a/.env.dev-redis-cluster.example b/.env.dev-redis-cluster.example
index 9458a5e651..bb0b0707fc 100644
--- a/.env.dev-redis-cluster.example
+++ b/.env.dev-redis-cluster.example
@@ -76,6 +76,7 @@ REDIS_AUTH="bitnami"
REDIS_CLUSTER_ENABLED="true"
REDIS_CLUSTER_NODES="127.0.0.1:6370,127.0.0.1:6371,127.0.0.1:6372,127.0.0.1:6373,127.0.0.1:6374,127.0.0.1:6375"
LANGFUSE_INGESTION_QUEUE_SHARD_COUNT=8
+LANGFUSE_OTEL_INGESTION_QUEUE_SHARD_COUNT=4
LANGFUSE_TRACE_UPSERT_QUEUE_SHARD_COUNT=4
# openssl rand -hex 32 used only here
@@ -88,3 +89,5 @@ NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES="true"
LANGFUSE_EXPERIMENT_INSERT_INTO_TRACES_TABLE="false"
LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT="true"
+
+LANGFUSE_EXPERIMENT_USE_OTEL_INGESTION_QUEUE="true"
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 8c5daf7c1c..e936fb74dc 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -50,6 +50,10 @@ const EnvSchema = z.object({
.nonnegative()
.default(15_000),
LANGFUSE_INGESTION_QUEUE_SHARD_COUNT: z.coerce.number().positive().default(1),
+ LANGFUSE_OTEL_INGESTION_QUEUE_SHARD_COUNT: z.coerce
+ .number()
+ .positive()
+ .default(1),
LANGFUSE_TRACE_UPSERT_QUEUE_SHARD_COUNT: z.coerce
.number()
.positive()
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 253c8bdce5..d5252588de 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -37,6 +37,7 @@ export * from "./redis/projectDelete";
export * from "./redis/scoreDelete";
export * from "./redis/datasetDelete";
export * from "./redis/datasetRunItemUpsert";
+export * from "./redis/otelIngestionQueue";
export * from "./redis/batchExport";
export * from "./redis/batchActionQueue";
export * from "./redis/ingestionQueue";
@@ -71,6 +72,7 @@ export * from "./services/DefaultEvaluationModelService";
export * from "./clickhouse/measureAndReturn";
export * from "./services/SlackService";
export * from "./tableMappings";
+export * from "./otel";
export * from "./data-deletion/ingestionFileDeletion";
export * from "./s3";
diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.ts
index ea9ed2afdf..2bea1ab272 100644
--- a/packages/shared/src/server/ingestion/processEventBatch.ts
+++ b/packages/shared/src/server/ingestion/processEventBatch.ts
@@ -322,7 +322,7 @@ export const processEventBatch = async (
},
{ delay: getDelay(delay, source) },
)
- : Promise.reject("Failed to instantiate queue");
+ : Promise.reject("Failed to instantiate ingestion queue");
}),
);
diff --git a/web/src/features/otel/server/ObservationTypeMapper.ts b/packages/shared/src/server/otel/ObservationTypeMapper.ts
similarity index 98%
rename from web/src/features/otel/server/ObservationTypeMapper.ts
rename to packages/shared/src/server/otel/ObservationTypeMapper.ts
index 81f0e4e934..a437a47835 100644
--- a/web/src/features/otel/server/ObservationTypeMapper.ts
+++ b/packages/shared/src/server/otel/ObservationTypeMapper.ts
@@ -1,5 +1,6 @@
+/* eslint-disable no-unused-vars */
import { LangfuseOtelSpanAttributes } from "./attributes";
-import { type ObservationType, ObservationTypeDomain } from "@langfuse/shared";
+import { type ObservationType, ObservationTypeDomain } from "../../";
type LangfuseObservationType = keyof typeof ObservationType;
@@ -91,6 +92,7 @@ class CustomAttributeMapper implements ObservationTypeMapper {
if (
result &&
+ typeof result === "string" &&
ObservationTypeDomain.safeParse(result.toUpperCase()).success
) {
return result;
diff --git a/web/src/features/otel/server/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
similarity index 95%
rename from web/src/features/otel/server/OtelIngestionProcessor.ts
rename to packages/shared/src/server/otel/OtelIngestionProcessor.ts
index 26dce0f4fb..8a93b4a3ce 100644
--- a/web/src/features/otel/server/OtelIngestionProcessor.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
@@ -4,7 +4,7 @@ import {
ForbiddenError,
ObservationLevel,
ObservationTypeDomain,
-} from "@langfuse/shared";
+} from "../../";
import {
type TraceEventType,
type IngestionEventType,
@@ -13,10 +13,14 @@ import {
instrumentAsync,
recordIncrement,
traceException,
-} from "@langfuse/shared/src/server";
+ getS3EventStorageClient,
+ QueueJobs,
+} from "../";
import { LangfuseOtelSpanAttributes } from "./attributes";
import { ObservationTypeMapperRegistry } from "./ObservationTypeMapper";
+import { env } from "../../env";
+import { OtelIngestionQueue } from "../redis/otelIngestionQueue";
// Type definitions for internal processor state
interface TraceState {
@@ -111,6 +115,50 @@ export class OtelIngestionProcessor {
this.publicKey = config.publicKey;
}
+ /**
+ * Returns the current time as yyyy/mm/dd/hh/mm`.
+ */
+ private getCurrentTimePath(): string {
+ const now = new Date();
+ return `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, "0")}/${String(now.getDate()).padStart(2, "0")}/${String(now.getHours()).padStart(2, "0")}/${String(now.getMinutes()).padStart(2, "0")}`;
+ }
+
+ /**
+ * Uploads a batch of resourceSpans to blob storage and adds a job to process them
+ * into the otel-ingestion-queue.
+ */
+ async publishToOtelIngestionQueue(resourceSpans: ResourceSpan[]) {
+ const fileKey = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}otel/${this.projectId}/${this.getCurrentTimePath()}/${randomUUID()}.json`;
+
+ // Upload to S3
+ await getS3EventStorageClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ ).uploadJson(fileKey, resourceSpans as Record<string, unknown>[]);
+
+ // Add queue job
+ const queue = OtelIngestionQueue.getInstance({});
+ return queue
+ ? queue.add(QueueJobs.OtelIngestionJob, {
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.OtelIngestionJob as const,
+ payload: {
+ data: {
+ fileKey,
+ publicKey: this.publicKey,
+ },
+ authCheck: {
+ validKey: true,
+ scope: {
+ projectId: this.projectId,
+ accessLevel: "project" as const,
+ },
+ },
+ },
+ })
+ : Promise.reject("Failed to instantiate otel ingestion queue");
+ }
+
/**
* Process resource spans and convert them to Langfuse ingestion events.
* Handles trace deduplication automatically using internal state.
@@ -641,9 +689,15 @@ export class OtelIngestionProcessor {
}),
};
- const observationType = observationTypeMapper
- .mapToObservationType(attributes, resourceAttributes, scopeSpan?.scope)
- ?.toLowerCase();
+ const mappedObservationType = observationTypeMapper.mapToObservationType(
+ attributes,
+ resourceAttributes,
+ scopeSpan?.scope,
+ );
+ const observationType =
+ mappedObservationType && typeof mappedObservationType === "string"
+ ? mappedObservationType.toLowerCase()
+ : undefined;
const isKnownObservationType =
observationType &&
@@ -1230,7 +1284,9 @@ export class OtelIngestionProcessor {
] as string,
),
);
- } catch {}
+ } catch {
+ // Fallthrough
+ }
}
// Vercel AI SDK
@@ -1356,7 +1412,9 @@ export class OtelIngestionProcessor {
LangfuseOtelSpanAttributes.OBSERVATION_USAGE_DETAILS
] as string,
);
- } catch {}
+ } catch {
+ // Fallthrough
+ }
}
if (instrumentationScopeName === "ai") {
@@ -1439,7 +1497,9 @@ export class OtelIngestionProcessor {
}
return usageDetails;
- } catch {}
+ } catch {
+ // Fallthrough
+ }
}
const usageDetails = Object.keys(attributes).filter(
@@ -1483,7 +1543,9 @@ export class OtelIngestionProcessor {
LangfuseOtelSpanAttributes.OBSERVATION_COST_DETAILS
] as string,
);
- } catch {}
+ } catch {
+ // Fallthrough
+ }
}
if (attributes["gen_ai.usage.cost"]) {
@@ -1502,7 +1564,9 @@ export class OtelIngestionProcessor {
LangfuseOtelSpanAttributes.OBSERVATION_COMPLETION_START_TIME
] as string,
);
- } catch {}
+ } catch {
+ // Fallthrough
+ }
// Vercel AI SDK
try {
@@ -1516,7 +1580,9 @@ export class OtelIngestionProcessor {
return new Date(startTimeUnix + msToFirstChunkNumber).toISOString();
}
- } catch {}
+ } catch {
+ // Fallthrough
+ }
return null;
}
@@ -1574,7 +1640,9 @@ export class OtelIngestionProcessor {
const parsed = JSON.parse(aiSDKPrompt as string);
return typeof parsed === "object" ? parsed : undefined;
- } catch {}
+ } catch {
+ // Fallthrough
+ }
}
/**
* Get a set of trace IDs that have been seen recently (from Redis cache).
diff --git a/web/src/features/otel/server/attributes.ts b/packages/shared/src/server/otel/attributes.ts
similarity index 97%
rename from web/src/features/otel/server/attributes.ts
rename to packages/shared/src/server/otel/attributes.ts
index f6d205b6ca..98151e9154 100644
--- a/web/src/features/otel/server/attributes.ts
+++ b/packages/shared/src/server/otel/attributes.ts
@@ -1,3 +1,4 @@
+/* eslint-disable no-unused-vars */
export enum LangfuseOtelSpanAttributes {
// Langfuse-Trace attributes
TRACE_NAME = "langfuse.trace.name",
diff --git a/packages/shared/src/server/otel/index.ts b/packages/shared/src/server/otel/index.ts
new file mode 100644
index 0000000000..745e24f072
--- /dev/null
+++ b/packages/shared/src/server/otel/index.ts
@@ -0,0 +1 @@
+export * from "./OtelIngestionProcessor";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 82d07e5da5..cf3085ad62 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -24,6 +24,20 @@ export const IngestionEvent = z.object({
}),
});
+export const OtelIngestionEvent = z.object({
+ data: z.object({
+ fileKey: z.string(),
+ publicKey: z.string().optional(),
+ }),
+ authCheck: z.object({
+ validKey: z.literal(true),
+ scope: z.object({
+ projectId: z.string(),
+ accessLevel: z.literal("project"),
+ }),
+ }),
+});
+
export const BatchExportJobSchema = z.object({
projectId: z.string(),
batchExportId: z.string(),
@@ -204,6 +218,7 @@ export type DatasetRunItemUpsertEventType = z.infer<
>;
export type EvalExecutionEventType = z.infer<typeof EvalExecutionEvent>;
export type IngestionEventQueueType = z.infer<typeof IngestionEvent>;
+export type OtelIngestionEventQueueType = z.infer<typeof OtelIngestionEvent>;
export type ExperimentCreateEventType = z.infer<
typeof ExperimentCreateEventSchema
>;
@@ -239,6 +254,7 @@ export enum QueueName {
EvaluationExecution = "evaluation-execution-queue", // Worker executes Evals
DatasetRunItemUpsert = "dataset-run-item-upsert-queue",
BatchExport = "batch-export-queue",
+ OtelIngestionQueue = "otel-ingestion-queue",
IngestionQueue = "ingestion-queue", // Process single events with S3-merge
IngestionSecondaryQueue = "secondary-ingestion-queue", // Separates high priority + high throughput projects from other projects.
CloudUsageMeteringQueue = "cloud-usage-metering-queue",
@@ -268,6 +284,7 @@ export enum QueueJobs {
EvaluationExecution = "evaluation-execution-job",
BatchExportJob = "batch-export-job",
CloudUsageMeteringJob = "cloud-usage-metering-job",
+ OtelIngestionJob = "otel-ingestion-job",
IngestionJob = "ingestion-job",
IngestionSecondaryJob = "secondary-ingestion-job",
ExperimentCreateJob = "experiment-create-job",
@@ -338,6 +355,12 @@ export type TQueueJobTypes = {
payload: BatchExportJobType;
name: QueueJobs.BatchExportJob;
};
+ [QueueName.OtelIngestionQueue]: {
+ timestamp: Date;
+ id: string;
+ payload: OtelIngestionEventQueueType;
+ name: QueueJobs.OtelIngestionJob;
+ };
[QueueName.IngestionQueue]: {
timestamp: Date;
id: string;
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index 046596c340..70fe2512c3 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -24,12 +24,14 @@ import { WebhookQueue } from "./webhookQueue";
import { EntityChangeQueue } from "./entityChangeQueue";
import { DatasetDeleteQueue } from "./datasetDelete";
-// IngestionQueue and TraceUpsert are sharded and require a sharding key
+// IngestionQueue, OtelIngestionQueue, and TraceUpsert are sharded and require a sharding key
// Use IngestionQueue.getInstance({ shardName: queueName }) or TraceUpsertQueue.getInstance({ shardName: queueName }) directly instead
export function getQueue(
queueName: Exclude<
QueueName,
- QueueName.IngestionQueue | QueueName.TraceUpsert
+ | QueueName.IngestionQueue
+ | QueueName.TraceUpsert
+ | QueueName.OtelIngestionQueue
>,
): Queue | null {
switch (queueName) {
diff --git a/packages/shared/src/server/redis/otelIngestionQueue.ts b/packages/shared/src/server/redis/otelIngestionQueue.ts
new file mode 100644
index 0000000000..a7b863bfef
--- /dev/null
+++ b/packages/shared/src/server/redis/otelIngestionQueue.ts
@@ -0,0 +1,97 @@
+import { Queue } from "bullmq";
+import { QueueName, TQueueJobTypes } from "../queues";
+import {
+ createNewRedisInstance,
+ redisQueueRetryOptions,
+ getQueuePrefix,
+} from "./redis";
+import { logger } from "../logger";
+import { getShardIndex } from "./sharding";
+import { env } from "../../env";
+import { randomUUID } from "crypto";
+
+export class OtelIngestionQueue {
+ private static instances: Map<
+ number,
+ Queue<TQueueJobTypes[QueueName.OtelIngestionQueue]> | null
+ > = new Map();
+
+ public static getShardNames() {
+ return Array.from(
+ { length: env.LANGFUSE_OTEL_INGESTION_QUEUE_SHARD_COUNT },
+ (_, i) => `${QueueName.OtelIngestionQueue}${i > 0 ? `-${i}` : ""}`,
+ );
+ }
+
+ static getShardIndexFromShardName(
+ shardName: string | undefined,
+ ): number | null {
+ if (!shardName) return null;
+
+ // Extract shard index from shard name
+ const shardIndex =
+ shardName === QueueName.OtelIngestionQueue
+ ? 0
+ : parseInt(
+ shardName.replace(`${QueueName.OtelIngestionQueue}-`, ""),
+ 10,
+ );
+
+ if (isNaN(shardIndex)) return null;
+ return shardIndex;
+ }
+
+ /**
+ * Get the otel ingestion queue instance for the given shard name. If not provided, uses a random shard.
+ * @param shardName - Name of the shard. Should be `otel-ingestion-queue-${shardIndex}` or plainly `otel-ingestion-queue` for the first shard.
+ */
+ public static getInstance({
+ shardName,
+ }: {
+ shardName?: string;
+ }): Queue<TQueueJobTypes[QueueName.OtelIngestionQueue]> | null {
+ const shardIndex =
+ OtelIngestionQueue.getShardIndexFromShardName(shardName) ??
+ (env.REDIS_CLUSTER_ENABLED === "true"
+ ? getShardIndex(
+ randomUUID(),
+ env.LANGFUSE_OTEL_INGESTION_QUEUE_SHARD_COUNT,
+ )
+ : 0);
+
+ // Check if we already have an instance for this shard
+ if (OtelIngestionQueue.instances.has(shardIndex)) {
+ return OtelIngestionQueue.instances.get(shardIndex) || null;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ const name = `${QueueName.OtelIngestionQueue}${shardIndex > 0 ? `-${shardIndex}` : ""}`;
+ const queueInstance = newRedis
+ ? new Queue<TQueueJobTypes[QueueName.OtelIngestionQueue]>(name, {
+ connection: newRedis,
+ prefix: getQueuePrefix(name),
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100_000,
+ attempts: 6,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ })
+ : null;
+
+ queueInstance?.on("error", (err) => {
+ logger.error(`OtelIngestionQueue shard ${shardIndex} error`, err);
+ });
+
+ OtelIngestionQueue.instances.set(shardIndex, queueInstance);
+
+ return queueInstance;
+ }
+}
diff --git a/web/src/__tests__/async/otel-api.servertest.ts b/web/src/__tests__/async/otel-api.servertest.ts
new file mode 100644
index 0000000000..75b9116a53
--- /dev/null
+++ b/web/src/__tests__/async/otel-api.servertest.ts
@@ -0,0 +1,213 @@
+import { makeAPICall } from "@/src/__tests__/test-utils";
+import waitForExpect from "wait-for-expect";
+import { getObservationById, getTraceById } from "@langfuse/shared/src/server";
+import { randomBytes } from "crypto";
+
+const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+describe("/api/public/otel/v1/traces API Endpoint", () => {
+ it("should process a json payload correctly", async () => {
+ const traceId = randomBytes(16);
+ const spanId = randomBytes(8);
+
+ const payload = {
+ resourceSpans: [
+ {
+ resource: {
+ attributes: [],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "langfuse-sdk",
+ version: "2.60.3",
+ attributes: [
+ {
+ key: "public_key",
+ value: { stringValue: "pk-lf-1234567890" },
+ },
+ ],
+ },
+ spans: [
+ {
+ traceId: {
+ type: "Buffer",
+ data: traceId,
+ },
+ spanId: {
+ type: "Buffer",
+ data: spanId,
+ },
+ name: "my-generation",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 466848096,
+ high: 406528574,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 467248096,
+ high: 406528574,
+ unsigned: true,
+ },
+ attributes: [],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ const response = await makeAPICall(
+ "POST",
+ "/api/public/otel/v1/traces",
+ payload,
+ );
+
+ expect(response.status).toBe(200);
+
+ await waitForExpect(async () => {
+ const trace = await getTraceById({
+ projectId,
+ traceId: traceId.toString("hex"),
+ });
+ expect(trace).toBeDefined();
+ expect(trace!.id).toBe(traceId.toString("hex"));
+
+ const observation = await getObservationById({
+ projectId,
+ id: spanId.toString("hex"),
+ });
+ expect(observation).toBeDefined();
+ expect(observation!.id).toBe(spanId.toString("hex"));
+ expect(observation!.name).toBe("my-generation");
+ }, 25_000);
+ }, 30_000);
+
+ it("should process a json payload with usage details correctly", async () => {
+ const traceId = randomBytes(16);
+ const spanId = randomBytes(8);
+
+ const payload = {
+ resourceSpans: [
+ {
+ resource: {
+ attributes: [],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "langfuse-sdk",
+ version: "2.60.3",
+ attributes: [
+ {
+ key: "public_key",
+ value: { stringValue: "pk-lf-1234567890" },
+ },
+ ],
+ },
+ spans: [
+ {
+ traceId: {
+ type: "Buffer",
+ data: traceId,
+ },
+ spanId: {
+ type: "Buffer",
+ data: spanId,
+ },
+ name: "my-generation",
+ kind: 1,
+ startTimeUnixNano: {
+ low: 466848096,
+ high: 406528574,
+ unsigned: true,
+ },
+ endTimeUnixNano: {
+ low: 467248096,
+ high: 406528574,
+ unsigned: true,
+ },
+ attributes: [
+ {
+ key: "langfuse.observation.input",
+ value: {
+ stringValue:
+ '[{"role": "system", "content": [{"type": "text", "text": "You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.\nTo do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.\nTo solve the task, you must plan forward to proceed in a series of steps, in a cycle of Thought, Code, and Observation sequences.\n\nAt each step, in the \'Thought:\' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.\nThen in the Code sequence you should write the code in simple Python. The code sequence must be opened with \'<code>\', and closed with \'</code>\'.\nDuring each intermediate step, you can use \'print()\' to save whatever important information you will then need.\nThese print outputs will then appear in the \'Observation:\' field, which will be available as input for the next step.\nIn the end you have to return a final answer using the `final_answer` tool.\n\nHere are a few examples using notional tools:\n---\nTask: \\"Generate an image of the oldest person in this document.\\"\n\nThought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.\n<code>\nanswer = document_qa(document=document, question=\\"Who is the oldest person mentioned?\\")\nprint(answer)\n</code>\nObservation: \\"The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland.\\"\n\nThought: I will now generate an image showcasing the oldest person.\n<code>\nimage = image_generator(\\"A portrait of John Doe, a 55-year-old man living in Canada.\\")\nfinal_answer(image)\n</code>\n\n---\nTask: \\"What is the result of the following operation: 5 + 3 + 1294.678?\\"\n\nThought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool\n<code>\nresult = 5 + 3 + 1294.678\nfinal_answer(result)\n</code>\n\n---\nTask:\n\\"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.\nYou have been provided with these additional arguments, that you can access using the keys as variables in your python code:\n{\'question\': \'Quel est l\'animal sur l\'image?\', \'image\': \'path/to/image.jpg\'}\\"\n\nThought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.\n<code>\ntranslated_question = translator(question=question, src_lang=\\"French\\", tgt_lang=\\"English\\")\nprint(f\\"The translated question is {translated_question}.\\")\nanswer = image_qa(image=image, question=translated_question)\nfinal_answer(f\\"The answer is {answer}\\")\n</code>\n\n---\nTask:\nIn a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.\nWhat does he say was the consequence of Einstein learning too much math on his creativity, in one word?\n\nThought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.\n<code>\npages = web_search(query=\\"1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein\\")\nprint(pages)\n</code>\nObservation:\nNo result found for query \\"1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein\\".\n\nThought: The query was maybe too restrictive and did not find any results. Let\'s try again with a broader query.\n<code>\npages = web_search(query=\\"1979 interview Stanislaus Ulam\\")\nprint(pages)\n</code>\nObservation:\nFound 6 pages:\n[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)\n\n[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)\n\n(truncated)\n\nThought: I will read the first 2 pages to know more.\n<code>\nfor url in [\\"https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/\\", \\"https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/\\"]:\n whole_page = visit_webpage(url)\n print(whole_page)\n print(\\"\\\n\\" + \\"=\\"*80 + \\"\\\n\\") # Print separator between pages\n</code>\nObservation:\nManhattan Project Locations:\nLos Alamos, NM\nStanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at\n(truncated)\n\nThought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: \\"He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity.\\" Let\'s answer in one word.\n<code>\nfinal_answer(\\"diminished\\")\n</code>\n\n---\nTask: \\"Which city has the highest population: Guangzhou or Shanghai?\\"\n\nThought: I need to get the populations for both cities and compare them: I will use the tool `web_search` to get the population of both cities.\n<code>\nfor city in [\\"Guangzhou\\", \\"Shanghai\\"]:\n print(f\\"Population {city}:\\", web_search(f\\"{city} population\\")\n</code>\nObservation:\nPopulation Guangzhou: [\'Guangzhou has a population of 15 million inhabitants as of 2021.\']\nPopulation Shanghai: \'26 million (2019)\'\n\nThought: Now I know that Shanghai has the highest population.\n<code>\nfinal_answer(\\"Shanghai\\")\n</code>\n\n---\nTask: \\"What is the current age of the pope, raised to the power 0.36?\\"\n\nThought: I will use the tool `wikipedia_search` to get the age of the pope, and confirm that with a web search.\n<code>\npope_age_wiki = wikipedia_search(query=\\"current pope age\\")\nprint(\\"Pope age as per wikipedia:\\", pope_age_wiki)\npope_age_search = web_search(query=\\"current pope age\\")\nprint(\\"Pope age as per google search:\\", pope_age_search)\n</code>\nObservation:\nPope age: \\"The pope Francis is currently 88 years old.\\"\n\nThought: I know that the pope is 88 years old. Let\'s compute the result using python code.\n<code>\npope_current_age = 88 ** 0.36\nfinal_answer(pope_current_age)\n</code>\n\nAbove example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools, behaving like regular python functions:\n<code>\ndef web_search(query: string) -> string:\n \\"\\"\\"Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results.\n\n Args:\n query: The search query to perform.\n \\"\\"\\"\n\ndef final_answer(answer: any) -> any:\n \\"\\"\\"Provides a final answer to the given problem.\n\n Args:\n answer: The final answer to the problem\n \\"\\"\\"\n\n</code>\n\nHere are the rules you should always follow to solve your task:\n1. Always provide a \'Thought:\' sequence, and a \'<code>\' sequence ending with \'</code>\', else you will fail.\n2. Use only variables that you have defined!\n3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in \'answer = wikipedia_search({\'query\': \\"What is the place where James Bond lives?\\"})\', but use the arguments directly as in \'answer = wikipedia_search(query=\\"What is the place where James Bond lives?\\")\'.\n4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to wikipedia_search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.\n5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.\n6. Don\'t name any new variable with the same name as a tool: for instance don\'t name a variable \'final_answer\'.\n7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.\n8. You can use imports in your code, but only from the following list of modules: [\'collections\', \'datetime\', \'itertools\', \'math\', \'queue\', \'random\', \'re\', \'stat\', \'statistics\', \'time\', \'unicodedata\']\n9. The state persists between code executions: so if in one step you\'ve created variables or imported modules, these will all persist.\n10. Don\'t give up! You\'re in charge of solving the task, not providing directions to solve it.\n\nNow Begin!"}]}, {"role": "user", "content": [{"type": "text", "text": "New task:\n\nWho won the chess world championship in 2024?\n"}]}]',
+ },
+ },
+ {
+ key: "langfuse.observation.model.parameters",
+ value: {
+ stringValue:
+ '{"temperature": 1, "max_tokens": "Infinity", "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0}',
+ },
+ },
+ {
+ key: "langfuse.observation.type",
+ value: {
+ stringValue: "generation",
+ },
+ },
+ {
+ key: "langfuse.observation.output",
+ value: {
+ stringValue:
+ '{"role": "assistant", "content": "Thought: To find out who won the chess world championship in 2024, I will use the `wikipedia_search` tool to search for the information about the chess world championship in 2024. Once I have the relevant information, I will extract the name of the winner.\n\n<code>\ninformation = wikipedia_search(query=\\"Chess World Championship 2024\\")\nprint(information)\n"}',
+ },
+ },
+ {
+ key: "langfuse.observation.model.name",
+ value: {
+ stringValue: "gpt-3.5-turbo-0125",
+ },
+ },
+ {
+ key: "langfuse.observation.usage_details",
+ value: {
+ stringValue:
+ '{"completion_tokens": 80, "prompt_tokens": 1957, "total_tokens": 2037, "completion_tokens_details": {"accepted_prediction_tokens": 0, "audio_tokens": 0, "reasoning_tokens": 0, "rejected_prediction_tokens": 0}, "prompt_tokens_details": {"audio_tokens": 0, "cached_tokens": 0}}',
+ },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ };
+
+ const response = await makeAPICall(
+ "POST",
+ "/api/public/otel/v1/traces",
+ payload,
+ );
+
+ expect(response.status).toBe(200);
+
+ await waitForExpect(async () => {
+ const trace = await getTraceById({
+ projectId,
+ traceId: traceId.toString("hex"),
+ });
+ expect(trace).toBeDefined();
+ expect(trace!.id).toBe(traceId.toString("hex"));
+
+ const observation = await getObservationById({
+ projectId,
+ id: spanId.toString("hex"),
+ fetchWithInputOutput: true,
+ });
+ expect(observation).toBeDefined();
+ expect(observation!.id).toBe(spanId.toString("hex"));
+ expect(observation!.name).toBe("my-generation");
+ expect(observation!.output).toContain("chess world championship");
+ expect(observation!.totalCost).toBeCloseTo(0.0010985);
+ expect(observation!.totalUsage).toBe(2037);
+ }, 25_000);
+ }, 30_000);
+});
diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
index 15442c7eff..8f1e2ef2a7 100644
--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
@@ -1,5 +1,7 @@
-import { OtelIngestionProcessor } from "@/src/features/otel/server/OtelIngestionProcessor";
-import { createIngestionEventSchema } from "@langfuse/shared/src/server";
+import {
+ OtelIngestionProcessor,
+ createIngestionEventSchema,
+} from "@langfuse/shared/src/server";
// Test helper function to maintain backward compatibility with existing tests
// This mimics the old convertOtelSpanToIngestionEvent function signature
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index 27d2179ed7..4cd2c48c54 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -6,6 +6,7 @@ import {
getQueue,
IngestionQueue,
logger,
+ OtelIngestionQueue,
QueueName,
TraceUpsertQueue,
} from "@langfuse/shared/src/server";
@@ -123,12 +124,16 @@ export const getQueues = () => {
? IngestionQueue.getInstance({ shardName: queueName })
: queueName.startsWith(QueueName.TraceUpsert)
? TraceUpsertQueue.getInstance({ shardName: queueName })
- : getQueue(
- queueName as Exclude<
- QueueName,
- QueueName.IngestionQueue | QueueName.TraceUpsert
- >,
- ),
+ : queueName.startsWith(QueueName.OtelIngestionQueue)
+ ? OtelIngestionQueue.getInstance({ shardName: queueName })
+ : getQueue(
+ queueName as Exclude<
+ QueueName,
+ | QueueName.IngestionQueue
+ | QueueName.TraceUpsert
+ | QueueName.OtelIngestionQueue
+ >,
+ ),
);
};
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 9f0504a080..24269237a1 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -165,6 +165,11 @@ export const env = createEnv({
OTEL_SERVICE_NAME: z.string().default("web"),
OTEL_TRACE_SAMPLING_RATIO: z.coerce.number().gt(0).lte(1).default(1),
+ LANGFUSE_EXPERIMENT_USE_OTEL_INGESTION_QUEUE: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_EXPERIMENT_OTEL_INGESTION_QUEUE_PROJECT_IDS: z.string().optional(),
+
// clickhouse
CLICKHOUSE_URL: z.string().url(),
CLICKHOUSE_CLUSTER_NAME: z.string().default("default"),
@@ -441,6 +446,11 @@ export const env = createEnv({
OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,
OTEL_TRACE_SAMPLING_RATIO: process.env.OTEL_TRACE_SAMPLING_RATIO,
+ LANGFUSE_EXPERIMENT_USE_OTEL_INGESTION_QUEUE:
+ process.env.LANGFUSE_EXPERIMENT_USE_OTEL_INGESTION_QUEUE,
+ LANGFUSE_EXPERIMENT_OTEL_INGESTION_QUEUE_PROJECT_IDS:
+ process.env.LANGFUSE_EXPERIMENT_OTEL_INGESTION_QUEUE_PROJECT_IDS,
+
// S3 media upload
LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH:
process.env.LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH,
diff --git a/web/src/pages/api/admin/bullmq/index.ts b/web/src/pages/api/admin/bullmq/index.ts
index 88fb4bb8a0..d9db374033 100644
--- a/web/src/pages/api/admin/bullmq/index.ts
+++ b/web/src/pages/api/admin/bullmq/index.ts
@@ -7,6 +7,7 @@ import {
IngestionQueue,
TraceUpsertQueue,
IngestionEvent,
+ OtelIngestionQueue,
} from "@langfuse/shared/src/server";
import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";
@@ -60,6 +61,7 @@ export default async function handler(
const queues: string[] = Object.values(QueueName);
queues.push(...IngestionQueue.getShardNames());
queues.push(...TraceUpsertQueue.getShardNames());
+ queues.push(...OtelIngestionQueue.getShardNames());
const queueCounts = await Promise.all(
queues.map(async (queueName) => {
try {
@@ -68,11 +70,15 @@ export default async function handler(
queue = IngestionQueue.getInstance({ shardName: queueName });
} else if (queueName.startsWith(QueueName.TraceUpsert)) {
queue = TraceUpsertQueue.getInstance({ shardName: queueName });
+ } else if (queueName.startsWith(QueueName.OtelIngestionQueue)) {
+ queue = OtelIngestionQueue.getInstance({ shardName: queueName });
} else {
queue = getQueue(
queueName as Exclude<
QueueName,
- QueueName.IngestionQueue | QueueName.TraceUpsert
+ | QueueName.IngestionQueue
+ | QueueName.TraceUpsert
+ | QueueName.OtelIngestionQueue
>,
);
}
@@ -105,11 +111,15 @@ export default async function handler(
queue = IngestionQueue.getInstance({ shardName: queueName });
} else if (queueName.startsWith(QueueName.TraceUpsert)) {
queue = TraceUpsertQueue.getInstance({ shardName: queueName });
+ } else if (queueName.startsWith(QueueName.OtelIngestionQueue)) {
+ queue = OtelIngestionQueue.getInstance({ shardName: queueName });
} else {
queue = getQueue(
queueName as Exclude<
QueueName,
- QueueName.IngestionQueue | QueueName.TraceUpsert
+ | QueueName.IngestionQueue
+ | QueueName.TraceUpsert
+ | QueueName.OtelIngestionQueue
>,
);
}
@@ -152,11 +162,15 @@ export default async function handler(
queue = IngestionQueue.getInstance({ shardName: queueName });
} else if (queueName.startsWith(QueueName.TraceUpsert)) {
queue = TraceUpsertQueue.getInstance({ shardName: queueName });
+ } else if (queueName.startsWith(QueueName.OtelIngestionQueue)) {
+ queue = OtelIngestionQueue.getInstance({ shardName: queueName });
} else {
queue = getQueue(
queueName as Exclude<
QueueName,
- QueueName.IngestionQueue | QueueName.TraceUpsert
+ | QueueName.IngestionQueue
+ | QueueName.TraceUpsert
+ | QueueName.OtelIngestionQueue
>,
);
}
diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.ts
index 03e6f812c2..be9ee85d66 100644
--- a/web/src/pages/api/public/otel/v1/traces/index.ts
+++ b/web/src/pages/api/public/otel/v1/traces/index.ts
@@ -4,11 +4,12 @@ import {
type IngestionEventType,
logger,
processEventBatch,
+ OtelIngestionProcessor,
} from "@langfuse/shared/src/server";
import { z } from "zod/v4";
import { $root } from "@/src/pages/api/public/otel/otlp-proto/generated/root";
-import { OtelIngestionProcessor } from "@/src/features/otel/server/OtelIngestionProcessor";
import { gunzip } from "node:zlib";
+import { env } from "@/src/env.mjs";
export const config = {
api: {
@@ -89,17 +90,34 @@ export default withMiddlewares({
}
}
- // Create and process OTEL resource spans to ingestion events
const processor = new OtelIngestionProcessor({
projectId: auth.scope.projectId,
publicKey: auth.scope.publicKey,
});
- const events: IngestionEventType[] =
- await processor.processToIngestionEvents(resourceSpans);
- // We set a delay of 0 for OTel, as we never expect updates.
- // We also set the source to "otel" which helps us with metric tracking and skipping list calls for S3.
- return processEventBatch(events, auth, { delay: 0, source: "otel" });
+ // At this point, we have the raw OpenTelemetry Span body. Traditionally, we separated this within the web
+ // container into individual traces and observations with the native Langfuse format before passing them into
+ // the processEventBatch function.
+ // To reduce the number of S3 interactions, we upload the full batch to S3 if `LANGFUSE_EXPERIMENT_USE_OTEL_INGESTION_QUEUE`
+ // is set to `true`. The OtelIngestionProcessor logic will then move into the worker container where observations
+ // are handled as-is and traces are being reprocessed as they are being processed today.
+ const projectIdsToUseOtelBatch =
+ env.LANGFUSE_EXPERIMENT_OTEL_INGESTION_QUEUE_PROJECT_IDS?.split(",") ??
+ [];
+ if (
+ env.LANGFUSE_EXPERIMENT_USE_OTEL_INGESTION_QUEUE === "true" ||
+ projectIdsToUseOtelBatch.includes(auth.scope.projectId)
+ ) {
+ return processor.publishToOtelIngestionQueue(resourceSpans);
+ } else {
+ // Create and process OTEL resource spans to ingestion events
+ const events: IngestionEventType[] =
+ await processor.processToIngestionEvents(resourceSpans);
+
+ // We set a delay of 0 for OTel, as we never expect updates.
+ // We also set the source to "otel" which helps us with metric tracking and skipping list calls for S3.
+ return processEventBatch(events, auth, { delay: 0, source: "otel" });
+ }
},
}),
});
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 3a0530a670..5ed634d5d8 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -29,6 +29,7 @@ import {
BlobStorageIntegrationQueue,
DeadLetterRetryQueue,
IngestionQueue,
+ OtelIngestionQueue,
TraceUpsertQueue,
} from "@langfuse/shared/src/server";
import { env } from "./env";
@@ -59,6 +60,7 @@ import { DlqRetryService } from "./services/dlq/dlqRetryService";
import { entityChangeQueueProcessor } from "./queues/entityChangeQueue";
import { webhookProcessor } from "./queues/webhooks";
import { datasetDeleteProcessor } from "./queues/datasetDelete";
+import { otelIngestionQueueProcessor } from "./queues/otelIngestionQueue";
const app = express();
@@ -236,6 +238,20 @@ if (env.QUEUE_CONSUMER_BATCH_ACTION_QUEUE_IS_ENABLED === "true") {
);
}
+if (env.QUEUE_CONSUMER_OTEL_INGESTION_QUEUE_IS_ENABLED === "true") {
+ // Register workers for all ingestion queue shards
+ const shardNames = OtelIngestionQueue.getShardNames();
+ shardNames.forEach((shardName) => {
+ WorkerManager.register(
+ shardName as QueueName,
+ otelIngestionQueueProcessor,
+ {
+ concurrency: env.LANGFUSE_OTEL_INGESTION_QUEUE_PROCESSING_CONCURRENCY,
+ },
+ );
+ });
+}
+
if (env.QUEUE_CONSUMER_INGESTION_QUEUE_IS_ENABLED === "true") {
// Register workers for all ingestion queue shards
const shardNames = IngestionQueue.getShardNames();
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 8487ac64e8..e089f2e609 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -59,6 +59,10 @@ const EnvSchema = z.object({
.default(50_000),
EMAIL_FROM_ADDRESS: z.string().optional(),
SMTP_CONNECTION_URL: z.string().optional(),
+ LANGFUSE_OTEL_INGESTION_QUEUE_PROCESSING_CONCURRENCY: z.coerce
+ .number()
+ .positive()
+ .default(5),
LANGFUSE_INGESTION_QUEUE_PROCESSING_CONCURRENCY: z.coerce
.number()
.positive()
@@ -182,6 +186,9 @@ const EnvSchema = z.object({
QUEUE_CONSUMER_BLOB_STORAGE_INTEGRATION_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
+ QUEUE_CONSUMER_OTEL_INGESTION_QUEUE_IS_ENABLED: z
+ .enum(["true", "false"])
+ .default("true"),
QUEUE_CONSUMER_INGESTION_SECONDARY_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.ts
new file mode 100644
index 0000000000..0c31f378dc
--- /dev/null
+++ b/worker/src/queues/otelIngestionQueue.ts
@@ -0,0 +1,146 @@
+import { Job, Processor } from "bullmq";
+import {
+ clickhouseClient,
+ createIngestionEventSchema,
+ getClickhouseEntityType,
+ getCurrentSpan,
+ getS3EventStorageClient,
+ type IngestionEventType,
+ logger,
+ OtelIngestionProcessor,
+ processEventBatch,
+ QueueName,
+ recordDistribution,
+ recordHistogram,
+ recordIncrement,
+ redis,
+ TQueueJobTypes,
+ traceException,
+} from "@langfuse/shared/src/server";
+import { env } from "../env";
+import { IngestionService } from "../services/IngestionService";
+import { prisma } from "@langfuse/shared/src/db";
+import { ClickhouseWriter } from "../services/ClickhouseWriter";
+
+export const otelIngestionQueueProcessor: Processor = async (
+ job: Job<TQueueJobTypes[QueueName.OtelIngestionQueue]>,
+): Promise<void> => {
+ try {
+ const projectId = job.data.payload.authCheck.scope.projectId;
+ const publicKey = job.data.payload.data.publicKey;
+ const fileKey = job.data.payload.data.fileKey;
+ const auth = job.data.payload.authCheck;
+
+ const span = getCurrentSpan();
+ if (span) {
+ span.setAttribute("messaging.bullmq.job.input.id", job.data.id);
+ span.setAttribute(
+ "messaging.bullmq.job.input.projectId",
+ job.data.payload.authCheck.scope.projectId,
+ );
+ span.setAttribute(
+ "messaging.bullmq.job.input.fileKey",
+ job.data.payload.data.fileKey,
+ );
+ }
+ logger.debug(`Processing ${fileKey} for project ${projectId}`);
+
+ // TODO: Do we need to add these files into the blob_storage_file_log?
+ // We could recommend lifecycle rules due to the immutability properties.
+ // Otherwise, we'd probably have to upsert one row per generated event further below.
+ // Easy change, but needs alignment.
+
+ // Download file from blob storage
+ const resourceSpans = await getS3EventStorageClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
+ ).download(fileKey);
+
+ recordHistogram(
+ "langfuse.ingestion.s3_file_size_bytes",
+ resourceSpans.length, // At this point it's still a string.
+ {
+ skippedS3List: "true",
+ otel: "true",
+ },
+ );
+
+ // Generate events via OtelIngestionProcessor
+ const processor = new OtelIngestionProcessor({
+ projectId,
+ publicKey,
+ });
+ const events: IngestionEventType[] =
+ await processor.processToIngestionEvents(JSON.parse(resourceSpans));
+ // Here, we split the events into observations and non-observations.
+ // Observations go into the IngestionService directly whereas the non-observations make another run through the processEventBatch method.
+ const traces = events.filter(
+ (e) => getClickhouseEntityType(e.type) !== "observation",
+ );
+ // We need to parse each incoming observation through our ingestion schema to make use of its included transformations.
+ const ingestionSchema = createIngestionEventSchema();
+ const observations = events
+ .filter((e) => getClickhouseEntityType(e.type) === "observation")
+ .map((o) => ingestionSchema.safeParse(o))
+ .flatMap((o) => {
+ if (!o.success) {
+ logger.warn(`Failed to parse otel observation: ${o.error}`, o.error);
+ return [];
+ }
+ return [o.data];
+ });
+
+ // In the next row, we only consider observations. The traces will be recorded in processEventBatch.
+ recordIncrement("langfuse.ingestion.event", observations.length, {
+ source: "otel",
+ });
+ // Record more stats specific to the Otel processing
+ recordDistribution("langfuse.ingestion.otel.trace_count", traces.length);
+ recordDistribution(
+ "langfuse.ingestion.otel.observation_count",
+ observations.length,
+ );
+ span?.setAttribute("langfuse.ingestion.otel.trace_count", traces.length);
+ span?.setAttribute(
+ "langfuse.ingestion.otel.observation_count",
+ observations.length,
+ );
+
+ // Ensure required infra config is present
+ if (!redis) throw new Error("Redis not available");
+ if (!prisma) throw new Error("Prisma not available");
+
+ const ingestionService = new IngestionService(
+ redis,
+ prisma,
+ ClickhouseWriter.getInstance(),
+ clickhouseClient(),
+ );
+
+ // Running everything concurrently might be detrimental to the event loop, but has probably
+ // the highest possible throughput. Therefore, we start with a Promise.all.
+ // If necessary, we may use a for each instead.
+ await Promise.all(
+ [
+ // Process traces
+ processEventBatch(traces, auth, { delay: 0, source: "otel" }),
+ // Process observations
+ observations.map((observation) =>
+ ingestionService.mergeAndWrite(
+ getClickhouseEntityType(observation.type),
+ auth.scope.projectId,
+ observation.body.id || "", // id is always defined for observations
+ new Date(), // Use the current timestamp as event time
+ [observation],
+ ),
+ ),
+ ].flat(),
+ );
+ } catch (e) {
+ logger.error(
+ `Failed job otel ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,
+ e,
+ );
+ traceException(e);
+ throw e;
+ }
+};
diff --git a/worker/src/queues/workerManager.ts b/worker/src/queues/workerManager.ts
index 47a453a7d1..29eb39e69f 100644
--- a/worker/src/queues/workerManager.ts
+++ b/worker/src/queues/workerManager.ts
@@ -8,6 +8,7 @@ import {
QueueName,
IngestionQueue,
TraceUpsertQueue,
+ OtelIngestionQueue,
recordGauge,
recordHistogram,
recordIncrement,
@@ -38,12 +39,16 @@ export class WorkerManager {
? IngestionQueue.getInstance({ shardName: queueName })
: queueName.startsWith(QueueName.TraceUpsert)
? TraceUpsertQueue.getInstance({ shardName: queueName })
- : getQueue(
- queueName as Exclude<
- QueueName,
- QueueName.IngestionQueue | QueueName.TraceUpsert
- >,
- );
+ : queueName.startsWith(QueueName.OtelIngestionQueue)
+ ? OtelIngestionQueue.getInstance({ shardName: queueName })
+ : getQueue(
+ queueName as Exclude<
+ QueueName,
+ | QueueName.IngestionQueue
+ | QueueName.TraceUpsert
+ | QueueName.OtelIngestionQueue
+ >,
+ );
Promise.allSettled([
// Here we only consider waiting jobs instead of the default ("waiting" or "delayed"
// or "prioritized" or "waiting-children") that count provides