Skip to content

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

fix: db connections worker (#1714)

Max Deichmann7cf604707038
diff --git a/worker/src/__tests__/redis-consumer.test.ts b/worker/src/__tests__/redis-consumer.test.ts
index 7e4be69adb..e371dd385b 100644
--- a/worker/src/__tests__/redis-consumer.test.ts
+++ b/worker/src/__tests__/redis-consumer.test.ts
@@ -3,6 +3,8 @@ import { evalQueue } from "../api";
import { QueueJobs, TraceUpsertEvent } from "@langfuse/shared";
import { randomUUID } from "crypto";
import { z } from "zod";
+import logger from "../logger";
+import { evalJobCreator } from "../redis/consumer";
describe("handle redis events", () => {
test("handle redis job succeeding", async () => {
@@ -16,6 +18,11 @@ describe("handle redis events", () => {
},
}));
+ // this activates the consumer
+ evalJobCreator?.on("completed", (job, err) => {
+ logger.info(`Eval Job with id ${job?.id} completed`);
+ });
+
expect(evalQueue).toBeDefined();
const job = await evalQueue?.add(QueueJobs.TraceUpsert, {
diff --git a/worker/src/api/index.ts b/worker/src/api/index.ts
index c3385bb021..1ab664112a 100644
--- a/worker/src/api/index.ts
+++ b/worker/src/api/index.ts
@@ -3,7 +3,7 @@ import emojis from "./emojis";
import { z } from "zod";
import logger from "../logger";
import { Queue } from "bullmq";
-import { redis } from "../redis/consumer";
+import { redis } from "../redis/redis";
import { randomUUID } from "crypto";
import basicAuth from "express-basic-auth";
import { env } from "../env";
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 9db923b0f1..c5f8c975ec 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -17,7 +17,7 @@ import helmet from "helmet";
const app = express();
-const isSentryEnabled = Boolean(env.SENTRY_DSN);
+const isSentryEnabled = String(env.SENTRY_DSN) !== undefined;
if (isSentryEnabled) {
Sentry.init({
@@ -40,6 +40,7 @@ if (isSentryEnabled) {
// TracingHandler creates a trace for every incoming request
app.use(Sentry.Handlers.tracingHandler());
+ logger.info("Sentry enabled");
}
app.use(helmet());
diff --git a/worker/src/instrumentation.ts b/worker/src/instrumentation.ts
new file mode 100644
index 0000000000..20962222d9
--- /dev/null
+++ b/worker/src/instrumentation.ts
@@ -0,0 +1,17 @@
+import { env } from "./env";
+import * as Sentry from "@sentry/node";
+
+type CallbackAsyncFn<T> = (span?: Sentry.Span) => Promise<T>;
+
+export async function instrumentAsync<T>(
+ ctx: { name: string },
+ callback: CallbackAsyncFn<T>
+): Promise<T> {
+ if (env.SENTRY_DSN) {
+ return Sentry.startSpan(ctx, async (span) => {
+ return callback(span);
+ });
+ } else {
+ return callback();
+ }
+}
diff --git a/worker/src/redis/consumer.ts b/worker/src/redis/consumer.ts
index 9eef682429..49d2931f52 100644
--- a/worker/src/redis/consumer.ts
+++ b/worker/src/redis/consumer.ts
@@ -1,32 +1,11 @@
-import Redis from "ioredis";
import { Job, Queue, Worker } from "bullmq";
import { QueueName, TQueueJobTypes } from "@langfuse/shared";
import { evaluate, createEvalJobs } from "../eval-service";
-import { env } from "../env";
import { kyselyPrisma } from "@langfuse/shared/src/db";
import logger from "../logger";
import { sql } from "kysely";
-
-const createRedisClient = () => {
- try {
- return new Redis({
- host: env.REDIS_HOST,
- port: env.REDIS_PORT,
- password: env.REDIS_AUTH,
- maxRetriesPerRequest: null, // Set to `null` to disable retrying
- });
- } catch (e) {
- logger.error(e, "Failed to connect to redis");
- return null;
- }
-};
-
-declare global {
- // eslint-disable-next-line no-var
- var redis: undefined | ReturnType<typeof createRedisClient>;
-}
-
-export const redis = globalThis.redis ?? createRedisClient();
+import { redis } from "./redis";
+import { instrumentAsync } from "../instrumentation";
export const evalQueue = redis
? new Queue<TQueueJobTypes[QueueName.EvaluationExecution]>(
@@ -41,25 +20,27 @@ export const evalJobCreator = redis
? new Worker<TQueueJobTypes[QueueName.TraceUpsert]>(
QueueName.TraceUpsert,
async (job: Job<TQueueJobTypes[QueueName.TraceUpsert]>) => {
- try {
- logger.info("Executing Evaluation Job", job.data);
-
- await createEvalJobs({ data: job.data.payload });
- return true;
- } catch (e) {
- logger.error(
- e,
- `Failed job Evaluation for traceId ${job.data.payload.data.traceId}`
- );
- throw e;
- }
+ return instrumentAsync({ name: "evalJobCreator" }, async (span) => {
+ try {
+ await createEvalJobs({ data: job.data.payload });
+ return true;
+ } catch (e) {
+ logger.error(
+ e,
+ `Failed job Evaluation for traceId ${job.data.payload.data.traceId}`
+ );
+ throw e;
+ } finally {
+ span?.end();
+ }
+ });
},
{
connection: redis,
- concurrency: 50,
+ concurrency: 20,
limiter: {
- // execute 100 calls in 1000ms
- max: 50,
+ // execute 75 calls in 1000ms
+ max: 75,
duration: 1000,
},
}
@@ -70,29 +51,33 @@ export const evalJobExecutor = redis
? new Worker<TQueueJobTypes[QueueName.EvaluationExecution]>(
QueueName.EvaluationExecution,
async (job: Job<TQueueJobTypes[QueueName.EvaluationExecution]>) => {
- try {
- logger.info("Executing Evaluation Execution Job", job.data);
- await evaluate({ data: job.data.payload });
- return true;
- } catch (e) {
- logger.error(
- e,
- `Failed Evaluation_Execution job for id ${job.data.payload.data.jobExecutionId}`
- );
- await kyselyPrisma.$kysely
- .updateTable("job_executions")
- .set("status", sql`'ERROR'::"JobExecutionStatus"`)
- .set("end_time", new Date())
- .set("error", JSON.stringify(e))
- .where("id", "=", job.data.payload.data.jobExecutionId)
- .where("project_id", "=", job.data.payload.data.projectId)
- .execute();
- throw e;
- }
+ return instrumentAsync({ name: "evalJobExecutor" }, async (span) => {
+ try {
+ logger.info("Executing Evaluation Execution Job", job.data);
+ await evaluate({ data: job.data.payload });
+ return true;
+ } catch (e) {
+ logger.error(
+ e,
+ `Failed Evaluation_Execution job for id ${job.data.payload.data.jobExecutionId}`
+ );
+ await kyselyPrisma.$kysely
+ .updateTable("job_executions")
+ .set("status", sql`'ERROR'::"JobExecutionStatus"`)
+ .set("end_time", new Date())
+ .set("error", JSON.stringify(e))
+ .where("id", "=", job.data.payload.data.jobExecutionId)
+ .where("project_id", "=", job.data.payload.data.projectId)
+ .execute();
+ throw e;
+ } finally {
+ span?.end();
+ }
+ });
},
{
connection: redis,
- concurrency: 20,
+ concurrency: 10,
limiter: {
// execute 20 llm calls in 5 seconds
max: 20,
diff --git a/worker/src/redis/redis.ts b/worker/src/redis/redis.ts
new file mode 100644
index 0000000000..1704f34f20
--- /dev/null
+++ b/worker/src/redis/redis.ts
@@ -0,0 +1,26 @@
+import Redis from "ioredis";
+import { env } from "../env";
+import logger from "../logger";
+
+const createRedisClient = () => {
+ try {
+ return new Redis({
+ host: env.REDIS_HOST,
+ port: env.REDIS_PORT,
+ password: env.REDIS_AUTH,
+ maxRetriesPerRequest: null, // Set to `null` to disable retrying
+ });
+ } catch (e) {
+ logger.error(e, "Failed to connect to redis");
+ return null;
+ }
+};
+
+declare global {
+ // eslint-disable-next-line no-var
+ var redis: undefined | ReturnType<typeof createRedisClient>;
+}
+
+export const redis = globalThis.redis ?? createRedisClient();
+
+if (env.NODE_ENV !== "production") globalThis.redis = redis;