Skip to content

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

feat: redirect ingestion traffic for specific projects to secondary queue (#4792)

Max Deichmann87acc4f7f318
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 4ba10fc398..2475751fe3 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -112,6 +112,7 @@ export enum QueueName {
DatasetRunItemUpsert = "dataset-run-item-upsert-queue",
BatchExport = "batch-export-queue",
IngestionQueue = "ingestion-queue", // Process single events with S3-merge
+ IngestionSecondaryQueue = "secondary-ingestion-queue", // Separates high priority + high throughput projects from other projects.
LegacyIngestionQueue = "legacy-ingestion-queue", // Used for batch processing of Ingestion
CloudUsageMeteringQueue = "cloud-usage-metering-queue",
ExperimentCreate = "experiment-create-queue",
@@ -129,6 +130,7 @@ export enum QueueJobs {
LegacyIngestionJob = "legacy-ingestion-job",
CloudUsageMeteringJob = "cloud-usage-metering-job",
IngestionJob = "ingestion-job",
+ IngestionSecondaryJob = "secondary-ingestion-job",
ExperimentCreateJob = "experiment-create-job",
PostHogIntegrationJob = "posthog-integration-job",
PostHogIntegrationProcessingJob = "posthog-integration-processing-job",
@@ -183,6 +185,12 @@ export type TQueueJobTypes = {
payload: IngestionEventQueueType;
name: QueueJobs.IngestionJob;
};
+ [QueueName.IngestionSecondaryQueue]: {
+ timestamp: Date;
+ id: string;
+ payload: IngestionEventQueueType;
+ name: QueueJobs.IngestionJob;
+ };
[QueueName.ExperimentCreate]: {
timestamp: Date;
id: string;
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index 48071f45a9..b7ae7f0006 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -5,7 +5,7 @@ import { CloudUsageMeteringQueue } from "./cloudUsageMeteringQueue";
import { DatasetRunItemUpsertQueue } from "./datasetRunItemUpsert";
import { EvalExecutionQueue } from "./evalExecutionQueue";
import { ExperimentCreateQueue } from "./experimentCreateQueue";
-import { IngestionQueue } from "./ingestionQueue";
+import { IngestionQueue, SecondaryIngestionQueue } from "./ingestionQueue";
import { LegacyIngestionQueue } from "./legacyIngestion";
import { TraceUpsertQueue } from "./traceUpsert";
import { TraceDeleteQueue } from "./traceDelete";
@@ -39,6 +39,8 @@ export function getQueue(queueName: QueueName): Queue | null {
return PostHogIntegrationQueue.getInstance();
case QueueName.PostHogIntegrationProcessingQueue:
return PostHogIntegrationProcessingQueue.getInstance();
+ case QueueName.IngestionSecondaryQueue:
+ return SecondaryIngestionQueue.getInstance();
default:
const exhaustiveCheckDefault: never = queueName;
throw new Error(`Queue ${queueName} not found`);
diff --git a/packages/shared/src/server/redis/ingestionQueue.ts b/packages/shared/src/server/redis/ingestionQueue.ts
index 7d4fc7b9bb..229c25dc8c 100644
--- a/packages/shared/src/server/redis/ingestionQueue.ts
+++ b/packages/shared/src/server/redis/ingestionQueue.ts
@@ -43,3 +43,45 @@ export class IngestionQueue {
return IngestionQueue.instance;
}
}
+
+export class SecondaryIngestionQueue {
+ private static instance: Queue<
+ TQueueJobTypes[QueueName.IngestionSecondaryQueue]
+ > | null = null;
+
+ public static getInstance(): Queue<
+ TQueueJobTypes[QueueName.IngestionSecondaryQueue]
+ > | null {
+ if (SecondaryIngestionQueue.instance)
+ return SecondaryIngestionQueue.instance;
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ SecondaryIngestionQueue.instance = newRedis
+ ? new Queue<TQueueJobTypes[QueueName.IngestionSecondaryQueue]>(
+ QueueName.IngestionSecondaryQueue,
+ {
+ connection: newRedis,
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100_000,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ },
+ )
+ : null;
+
+ SecondaryIngestionQueue.instance?.on("error", (err) => {
+ logger.error("SecondaryIngestionQueue error", err);
+ });
+
+ return SecondaryIngestionQueue.instance;
+ }
+}
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 04f5b8c510..4a5df7b400 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -26,7 +26,7 @@ import {
PostHogIntegrationQueue,
} from "@langfuse/shared/src/server";
import { env } from "./env";
-import { ingestionQueueProcessor } from "./queues/ingestionQueue";
+import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";
import { BackgroundMigrationManager } from "./backgroundMigrations/backgroundMigrationManager";
import { experimentCreateQueueProcessor } from "./queues/experimentQueue";
import { traceDeleteProcessor } from "./queues/traceDelete";
@@ -123,9 +123,24 @@ if (env.QUEUE_CONSUMER_BATCH_EXPORT_QUEUE_IS_ENABLED === "true") {
}
if (env.QUEUE_CONSUMER_INGESTION_QUEUE_IS_ENABLED === "true") {
- WorkerManager.register(QueueName.IngestionQueue, ingestionQueueProcessor, {
- concurrency: env.LANGFUSE_INGESTION_QUEUE_PROCESSING_CONCURRENCY,
- });
+ WorkerManager.register(
+ QueueName.IngestionQueue,
+ ingestionQueueProcessorBuilder(true), // this might redirect to secondary queue
+ {
+ concurrency: env.LANGFUSE_INGESTION_QUEUE_PROCESSING_CONCURRENCY,
+ },
+ );
+}
+
+if (env.QUEUE_CONSUMER_INGESTION_QUEUE_IS_ENABLED === "true") {
+ WorkerManager.register(
+ QueueName.IngestionSecondaryQueue,
+ ingestionQueueProcessorBuilder(false),
+ {
+ concurrency:
+ env.LANGFUSE_INGESTION_SECONDARY_QUEUE_PROCESSING_CONCURRENCY,
+ },
+ );
}
if (
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 8e9dbd2daa..796cf09af5 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -49,6 +49,11 @@ const EnvSchema = z.object({
.number()
.positive()
.default(20),
+ LANGFUSE_INGESTION_SECONDARY_QUEUE_PROCESSING_CONCURRENCY: z.coerce
+ .number()
+ .positive()
+ .default(5),
+ LANGFUSE_SECONDARY_INGESTION_QUEUE_ENABLED_PROJECT_IDS: z.string().optional(),
LANGFUSE_INGESTION_CLICKHOUSE_WRITE_BATCH_SIZE: z.coerce
.number()
.positive()
diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.ts
index edda34607a..c9f56a1b10 100644
--- a/worker/src/queues/ingestionQueue.ts
+++ b/worker/src/queues/ingestionQueue.ts
@@ -11,6 +11,7 @@ import {
clickhouseClient,
getClickhouseEntityType,
getCurrentSpan,
+ getQueue,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
@@ -34,78 +35,106 @@ const getS3StorageServiceClient = (bucketName: string): StorageService => {
return s3StorageServiceClient;
};
-export const ingestionQueueProcessor: Processor = async (
- job: Job<TQueueJobTypes[QueueName.IngestionQueue]>,
-) => {
- try {
- 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.eventBodyId",
- job.data.payload.data.eventBodyId,
- );
- span.setAttribute(
- "messaging.bullmq.job.input.type",
- job.data.payload.data.type,
+export const ingestionQueueProcessorBuilder = (
+ enableRedirectToSecondaryQueue: boolean,
+): Processor => {
+ const projectIdsToRedirectToSecondaryQueue =
+ env.LANGFUSE_SECONDARY_INGESTION_QUEUE_ENABLED_PROJECT_IDS?.split(",") ??
+ [];
+
+ return async (job: Job<TQueueJobTypes[QueueName.IngestionQueue]>) => {
+ try {
+ 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.eventBodyId",
+ job.data.payload.data.eventBodyId,
+ );
+ span.setAttribute(
+ "messaging.bullmq.job.input.type",
+ job.data.payload.data.type,
+ );
+ }
+
+ if (
+ enableRedirectToSecondaryQueue &&
+ projectIdsToRedirectToSecondaryQueue.includes(
+ job.data.payload.authCheck.scope.projectId,
+ )
+ ) {
+ logger.debug(
+ `Redirecting ingestion event to secondary queue for project ${job.data.payload.authCheck.scope.projectId}`,
+ );
+ const secondaryQueue = getQueue(QueueName.IngestionSecondaryQueue);
+ if (secondaryQueue) {
+ await secondaryQueue.add(QueueName.IngestionSecondaryQueue, job.data);
+ // If we don't redirect, we continue with the ingestion. Otherwise, we finish here.
+ return;
+ }
+ }
+
+ const s3Client = getS3StorageServiceClient(
+ env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
);
- }
- const s3Client = getS3StorageServiceClient(
- env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,
- );
+ logger.info(
+ `Processing ingestion event ${
+ enableRedirectToSecondaryQueue ? "" : "secondary"
+ }`,
+ {
+ projectId: job.data.payload.authCheck.scope.projectId,
+ payload: job.data.payload.data,
+ },
+ );
- logger.info("Processing ingestion event", {
- projectId: job.data.payload.authCheck.scope.projectId,
- payload: job.data.payload.data,
- });
+ // Download all events from folder into a local array
+ const eventFiles = await s3Client.listFiles(
+ `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${getClickhouseEntityType(job.data.payload.data.type)}/${job.data.payload.data.eventBodyId}/`,
+ );
- // Download all events from folder into a local array
- const eventFiles = await s3Client.listFiles(
- `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${getClickhouseEntityType(job.data.payload.data.type)}/${job.data.payload.data.eventBodyId}/`,
- );
+ const events: IngestionEventType[] = (
+ await Promise.all(
+ eventFiles.map(async (key) => {
+ const file = await s3Client.download(key);
+ const parsedFile = JSON.parse(file);
+ return Array.isArray(parsedFile) ? parsedFile : [parsedFile];
+ }),
+ )
+ ).flat();
- const events: IngestionEventType[] = (
- await Promise.all(
- eventFiles.map(async (key) => {
- const file = await s3Client.download(key);
- const parsedFile = JSON.parse(file);
- return Array.isArray(parsedFile) ? parsedFile : [parsedFile];
- }),
- )
- ).flat();
+ if (events.length === 0) {
+ logger.warn(
+ `No events found for project ${job.data.payload.authCheck.scope.projectId} and event ${job.data.payload.data.eventBodyId}`,
+ );
+ return;
+ }
- if (events.length === 0) {
- logger.warn(
- `No events found for project ${job.data.payload.authCheck.scope.projectId} and event ${job.data.payload.data.eventBodyId}`,
+ // Perform merge of those events
+ if (!redis) throw new Error("Redis not available");
+ if (!prisma) throw new Error("Prisma not available");
+ await new IngestionService(
+ redis,
+ prisma,
+ ClickhouseWriter.getInstance(),
+ clickhouseClient(),
+ ).mergeAndWrite(
+ getClickhouseEntityType(events[0].type),
+ job.data.payload.authCheck.scope.projectId,
+ job.data.payload.data.eventBodyId,
+ events,
+ );
+ } catch (e) {
+ logger.error(
+ `Failed job ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,
+ e,
);
- return;
+ traceException(e);
+ throw e;
}
-
- // Perform merge of those events
- if (!redis) throw new Error("Redis not available");
- if (!prisma) throw new Error("Prisma not available");
- await new IngestionService(
- redis,
- prisma,
- ClickhouseWriter.getInstance(),
- clickhouseClient(),
- ).mergeAndWrite(
- getClickhouseEntityType(events[0].type),
- job.data.payload.authCheck.scope.projectId,
- job.data.payload.data.eventBodyId,
- events,
- );
- } catch (e) {
- logger.error(
- `Failed job ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,
- e,
- );
- traceException(e);
- throw e;
- }
+ };
};