Skip to content

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

feat: fallback to synchronous ingestion if queue unavailable (#3196)

Steffen Schmitzfe63704508b6
diff --git a/packages/shared/src/server/redis/legacy-ingestion.ts b/packages/shared/src/server/redis/legacy-ingestion.ts
index bba8445108..5b2a29bb65 100644
--- a/packages/shared/src/server/redis/legacy-ingestion.ts
+++ b/packages/shared/src/server/redis/legacy-ingestion.ts
@@ -2,28 +2,32 @@ import { Queue } from "bullmq";
import { QueueName, TQueueJobTypes } from "../queues";
import { createNewRedisInstance } from "./redis";
-let legacyIngestionQueue: Queue<
- TQueueJobTypes[QueueName.LegacyIngestionQueue]
-> | null = null;
+export class LegacyIngestionQueue {
+ private static instance: Queue<
+ TQueueJobTypes[QueueName.LegacyIngestionQueue]
+ > | null = null;
-export const getLegacyIngestionQueue = () => {
- if (legacyIngestionQueue) return legacyIngestionQueue;
+ public static getInstance(): Queue<
+ TQueueJobTypes[QueueName.LegacyIngestionQueue]
+ > | null {
+ if (LegacyIngestionQueue.instance) return LegacyIngestionQueue.instance;
- const newRedis = createNewRedisInstance();
+ const newRedis = createNewRedisInstance({ enableOfflineQueue: false });
- legacyIngestionQueue = newRedis
- ? new Queue<TQueueJobTypes[QueueName.LegacyIngestionQueue]>(
- QueueName.LegacyIngestionQueue,
- {
- connection: newRedis,
- defaultJobOptions: {
- removeOnComplete: true,
- removeOnFail: 100,
- attempts: 5,
+ LegacyIngestionQueue.instance = newRedis
+ ? new Queue<TQueueJobTypes[QueueName.LegacyIngestionQueue]>(
+ QueueName.LegacyIngestionQueue,
+ {
+ connection: newRedis,
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100,
+ attempts: 5,
+ },
},
- }
- )
- : null;
+ )
+ : null;
- return legacyIngestionQueue;
-};
+ return LegacyIngestionQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/redis/redis.ts b/packages/shared/src/server/redis/redis.ts
index 83f36c723b..8cb65938e5 100644
--- a/packages/shared/src/server/redis/redis.ts
+++ b/packages/shared/src/server/redis/redis.ts
@@ -1,11 +1,14 @@
-import Redis from "ioredis";
+import Redis, { RedisOptions } from "ioredis";
import { env } from "../../env";
-export const createNewRedisInstance = () => {
+export const createNewRedisInstance = (
+ additionalOptions: Partial<RedisOptions> = {},
+) => {
return env.REDIS_CONNECTION_STRING
? new Redis(env.REDIS_CONNECTION_STRING, {
maxRetriesPerRequest: null,
enableAutoPipelining: env.REDIS_ENABLE_AUTO_PIPELINING === "true",
+ ...additionalOptions,
})
: env.REDIS_HOST
? new Redis({
@@ -14,6 +17,7 @@ export const createNewRedisInstance = () => {
password: String(env.REDIS_AUTH),
maxRetriesPerRequest: null, // Set to `null` to disable retrying
enableAutoPipelining: env.REDIS_ENABLE_AUTO_PIPELINING === "true",
+ ...additionalOptions,
})
: null;
};
diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.ts
index 9000273d4a..48cff7a71b 100644
--- a/web/src/features/public-api/server/RateLimitService.ts
+++ b/web/src/features/public-api/server/RateLimitService.ts
@@ -15,7 +15,7 @@ import {
import { type NextApiResponse } from "next";
// Business Logic
-// - rate limit strategy is based on org-id, org plan, and resources. Rate limits are appliead in buckets of minutes.
+// - rate limit strategy is based on org-id, org plan, and resources. Rate limits are applied in buckets of minutes.
// - rate limits are not applied for self hosters and are also not applied when Redis is not available
// - infos for rate-limits are taken from the API access scope. Info for this scope is stored alongside API Keys in Redis for efficient access.
// - isRateLimited returns false for self-hosters
diff --git a/web/src/features/telemetry/index.ts b/web/src/features/telemetry/index.ts
index b5ad19dee4..bda9cfbdf5 100644
--- a/web/src/features/telemetry/index.ts
+++ b/web/src/features/telemetry/index.ts
@@ -13,7 +13,7 @@ export async function telemetry() {
try {
// Only run in prod
if (process.env.NODE_ENV !== "production") return;
- // Do not run in Lanfuse cloud, separate telemetry is used
+ // Do not run in Langfuse cloud, separate telemetry is used
if (process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined) return;
// Check if telemetry is not disabled, except for EE
if (
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index e83ded3ef2..5130c55093 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -3,7 +3,6 @@ import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { LangfuseNotFoundError, InternalServerError } from "@langfuse/shared";
import {
- getLegacyIngestionQueue,
eventTypes,
ingestionEvent,
traceException,
@@ -13,6 +12,7 @@ import {
handleBatch,
recordIncrement,
getCurrentSpan,
+ LegacyIngestionQueue,
} from "@langfuse/shared/src/server";
import {
SdkLogProcessor,
@@ -141,43 +141,54 @@ export default async function handler(
if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" && redis) {
// this function MUST NOT return but send the HTTP response directly
- const queue = getLegacyIngestionQueue();
+ const queue = LegacyIngestionQueue.getInstance();
if (queue) {
// still need to check auth scope for all events individually
const failedAccessScope = accessCheckPerEvent(sortedBatch, authCheck);
- await queue.add(
- QueueJobs.LegacyIngestionJob,
- {
- payload: { data: sortedBatch, authCheck: authCheck },
- id: randomUUID(),
- timestamp: new Date(),
- name: QueueJobs.LegacyIngestionJob as const,
- },
- {
- removeOnFail: 1_000_000,
- removeOnComplete: true,
- attempts: 5,
- backoff: {
- type: "exponential",
- delay: 1000,
+ let addToQueueFailed = false;
+ try {
+ await queue.add(
+ QueueJobs.LegacyIngestionJob,
+ {
+ payload: { data: sortedBatch, authCheck: authCheck },
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.LegacyIngestionJob as const,
},
- },
- );
+ {
+ removeOnFail: 1_000_000,
+ removeOnComplete: true,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 1000,
+ },
+ },
+ );
+ } catch (e: unknown) {
+ console.warn(
+ "Failed to add batch to queue, falling back to sync processing",
+ e,
+ );
+ addToQueueFailed = true;
+ }
- return handleBatchResult(
- [
- ...validationErrors,
- ...failedAccessScope.map((e) => ({
- id: e.id,
- error: "Access Scope Denied",
- })),
- ], // we are not sending additional server errors to the client in case of early return
- sortedBatch.map((event) => ({ id: event.id, result: event })),
- res,
- );
+ if (!addToQueueFailed) {
+ return handleBatchResult(
+ [
+ ...validationErrors,
+ ...failedAccessScope.map((e) => ({
+ id: e.id,
+ error: "Access Scope Denied",
+ })),
+ ], // we are not sending additional server errors to the client in case of early return
+ sortedBatch.map((event) => ({ id: event.id, result: event })),
+ res,
+ );
+ }
} else {
console.error(
"Ingestion queue not initialized, falling back to sync processing",
diff --git a/worker/src/queues/legacyIngestionQueue.ts b/worker/src/queues/legacyIngestionQueue.ts
index 06d6727869..ad7b40c727 100644
--- a/worker/src/queues/legacyIngestionQueue.ts
+++ b/worker/src/queues/legacyIngestionQueue.ts
@@ -1,7 +1,7 @@
import { Job, Worker } from "bullmq";
import {
traceException,
- getLegacyIngestionQueue,
+ LegacyIngestionQueue,
instrumentAsync,
QueueName,
recordIncrement,
@@ -36,13 +36,13 @@ const createLegacyIngestionExecutor = () => {
try {
const startTime = Date.now();
logger.info(
- `Processing legacy ingestion for payload ${JSON.stringify(job.data.payload)}`
+ `Processing legacy ingestion for payload ${JSON.stringify(job.data.payload)}`,
);
// Log wait time
const waitTime = Date.now() - job.timestamp;
logger.debug(
- `Received flush request after ${waitTime} ms for ${job.data.payload.authCheck.scope.projectId}`
+ `Received flush request after ${waitTime} ms for ${job.data.payload.authCheck.scope.projectId}`,
);
recordIncrement("legacy_ingestion_processing_request");
@@ -53,17 +53,17 @@ const createLegacyIngestionExecutor = () => {
const result = await handleBatch(
job.data.payload.data,
job.data.payload.authCheck,
- tokenCount
+ tokenCount,
);
// send out REDIS requests to worker for all trace types
await sendToWorkerIfEnvironmentConfigured(
result.results,
- job.data.payload.authCheck.scope.projectId
+ job.data.payload.authCheck.scope.projectId,
);
// Log queue size
- await getLegacyIngestionQueue()
+ await LegacyIngestionQueue.getInstance()
?.count()
.then((count) => {
logger.info(`Legacy Ingestion flush queue length: ${count}`);
@@ -76,23 +76,23 @@ const createLegacyIngestionExecutor = () => {
recordHistogram(
"legacy_ingestion_processing_time",
Date.now() - startTime,
- { unit: "milliseconds" }
+ { unit: "milliseconds" },
);
} catch (e) {
logger.error(
e,
- `Failed job Evaluation for traceId ${job.data.payload} ${e}`
+ `Failed job Evaluation for traceId ${job.data.payload} ${e}`,
);
traceException(e);
throw e;
}
- }
+ },
);
},
{
connection: redisInstance,
concurrency: env.LANGFUSE_LEGACY_INGESTION_WORKER_CONCURRENCY, // n ingestion batches at a time
- }
+ },
);
}
return null;