Skip to content

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

perf: instrument async clickhouse tasks (#2834)

Max Deichmanndd90a28d1c9e
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 8fa5c971c5..0ff4c42a72 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -1,4 +1,4 @@
-import "./instrumentation"; // this is required to make instrumentation work
+import "./sentry"; // this is required to make instrumentation work
import express from "express";
import cors from "cors";
import * as Sentry from "@sentry/node";
diff --git a/worker/src/instrumentation.ts b/worker/src/instrumentation.ts
index 0f1e7180a8..218ee37831 100644
--- a/worker/src/instrumentation.ts
+++ b/worker/src/instrumentation.ts
@@ -1,30 +1,5 @@
-import { nodeProfilingIntegration } from "@sentry/profiling-node";
-import { env } from "./env";
import * as Sentry from "@sentry/node";
-
-require("dd-trace").init({
- profiling: true,
- runtimeMetrics: true,
-});
-
-Sentry.init({
- dsn: String(env.SENTRY_DSN),
- integrations: [
- Sentry.httpIntegration(),
- Sentry.expressIntegration(),
- nodeProfilingIntegration(),
- Sentry.redisIntegration(),
- Sentry.prismaIntegration(),
- ],
-
- // Add Tracing by setting tracesSampleRate
- // We recommend adjusting this value in production
- tracesSampleRate: env.LANGFUSE_TRACING_SAMPLE_RATE,
-
- // Set sampling rate for profiling
- // This is relative to tracesSampleRate
- profilesSampleRate: 0.1,
-});
+import { env } from "./env";
type CallbackFn<T> = (span?: Sentry.Span) => T;
diff --git a/worker/src/queues/ingestionFlushQueue.ts b/worker/src/queues/ingestionFlushQueue.ts
index 174a2f0165..8b00ae0ec7 100644
--- a/worker/src/queues/ingestionFlushQueue.ts
+++ b/worker/src/queues/ingestionFlushQueue.ts
@@ -9,6 +9,7 @@ import { env } from "../env";
import logger from "../logger";
import { ClickhouseWriter } from "../services/ClickhouseWriter";
import { IngestionService } from "../services/IngestionService";
+import { instrumentAsync } from "../instrumentation";
export type IngestionFlushQueue = Queue<null>;
@@ -28,62 +29,71 @@ export const flushIngestionQueueExecutor = redis
? new Worker(
QueueName.IngestionFlushQueue,
async (job) => {
- if (job.name === QueueJobs.FlushIngestionEntity) {
- const projectEntityId = job.id;
- if (!projectEntityId) {
- throw new Error("ProjectEntity ID not provided");
- }
+ return instrumentAsync(
+ { name: "flush-ingestion-consumer" },
+ async () => {
+ if (job.name === QueueJobs.FlushIngestionEntity) {
+ const projectEntityId = job.id;
+ if (!projectEntityId) {
+ throw new Error("ProjectEntity ID not provided");
+ }
- // Log wait time
- const waitTime = Date.now() - job.timestamp;
- logger.debug(
- `Received flush request after ${waitTime} ms for ${projectEntityId}`
- );
- Sentry.metrics.distribution("ingestion_flush_wait_time", waitTime, {
- unit: "milliseconds",
- });
+ // Log wait time
+ const waitTime = Date.now() - job.timestamp;
+ logger.debug(
+ `Received flush request after ${waitTime} ms for ${projectEntityId}`
+ );
+ Sentry.metrics.distribution(
+ "ingestion_flush_wait_time",
+ waitTime,
+ {
+ unit: "milliseconds",
+ }
+ );
- // Check dependencies
- if (!redis) throw new Error("Redis not available");
- if (!prisma) throw new Error("Prisma not available");
- if (!ingestionFlushQueue)
- throw new Error("Ingestion flush queue not available");
+ // Check dependencies
+ if (!redis) throw new Error("Redis not available");
+ if (!prisma) throw new Error("Prisma not available");
+ if (!ingestionFlushQueue)
+ throw new Error("Ingestion flush queue not available");
- // Flush ingestion buffer
- const processingStartTime = Date.now();
+ // Flush ingestion buffer
+ const processingStartTime = Date.now();
- await new IngestionService(
- redis,
- prisma,
- ingestionFlushQueue,
- ClickhouseWriter.getInstance(),
- clickhouseClient,
- env.LANGFUSE_INGESTION_BUFFER_TTL_SECONDS
- ).flush(projectEntityId);
+ await new IngestionService(
+ redis,
+ prisma,
+ ingestionFlushQueue,
+ ClickhouseWriter.getInstance(),
+ clickhouseClient,
+ env.LANGFUSE_INGESTION_BUFFER_TTL_SECONDS
+ ).flush(projectEntityId);
- // Log processing time
- const processingTime = Date.now() - processingStartTime;
- logger.debug(
- `Prepared and scheduled CH-write in ${processingTime} ms for ${projectEntityId}`
- );
- Sentry.metrics.distribution(
- "ingestion_flush_processing_time",
- processingTime,
- { unit: "milliseconds" }
- );
+ // Log processing time
+ const processingTime = Date.now() - processingStartTime;
+ logger.debug(
+ `Prepared and scheduled CH-write in ${processingTime} ms for ${projectEntityId}`
+ );
+ Sentry.metrics.distribution(
+ "ingestion_flush_processing_time",
+ processingTime,
+ { unit: "milliseconds" }
+ );
- // Log queue size
- await ingestionFlushQueue
- .count()
- .then((count) => {
- logger.debug(`Ingestion flush queue length: ${count}`);
- Sentry.metrics.gauge("ingestion_flush_queue_length", count, {
- unit: "records",
- });
- return count;
- })
- .catch();
- }
+ // Log queue size
+ await ingestionFlushQueue
+ .count()
+ .then((count) => {
+ logger.debug(`Ingestion flush queue length: ${count}`);
+ Sentry.metrics.gauge("ingestion_flush_queue_length", count, {
+ unit: "records",
+ });
+ return count;
+ })
+ .catch();
+ }
+ }
+ );
},
{
connection: redis,
diff --git a/worker/src/sentry.ts b/worker/src/sentry.ts
new file mode 100644
index 0000000000..ddf0bc35d1
--- /dev/null
+++ b/worker/src/sentry.ts
@@ -0,0 +1,27 @@
+import * as Sentry from "@sentry/node";
+import { nodeProfilingIntegration } from "@sentry/profiling-node";
+import { env } from "./env";
+
+require("dd-trace").init({
+ profiling: true,
+ runtimeMetrics: true,
+});
+
+Sentry.init({
+ dsn: String(env.SENTRY_DSN),
+ integrations: [
+ Sentry.httpIntegration(),
+ Sentry.expressIntegration(),
+ nodeProfilingIntegration(),
+ Sentry.redisIntegration(),
+ Sentry.prismaIntegration(),
+ ],
+
+ // Add Tracing by setting tracesSampleRate
+ // We recommend adjusting this value in production
+ tracesSampleRate: env.LANGFUSE_TRACING_SAMPLE_RATE,
+
+ // Set sampling rate for profiling
+ // This is relative to tracesSampleRate
+ profilesSampleRate: 0.1,
+});
diff --git a/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts b/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts
index dc77e19274..4f7d80eda8 100644
--- a/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts
+++ b/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts
@@ -13,6 +13,7 @@ vi.mock("@sentry/node", () => ({
distribution: vi.fn(),
gauge: vi.fn(),
},
+ init: vi.fn(),
}));
vi.mock("../../env", () => ({
diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.ts
index 424a8e71df..16f3eb9ac7 100644
--- a/worker/src/services/ClickhouseWriter/index.ts
+++ b/worker/src/services/ClickhouseWriter/index.ts
@@ -8,6 +8,7 @@ import * as Sentry from "@sentry/node";
import { env } from "../../env";
import logger from "../../logger";
+import { instrumentAsync } from "../../instrumentation";
export class ClickhouseWriter {
private static instance: ClickhouseWriter | null = null;
@@ -75,12 +76,14 @@ export class ClickhouseWriter {
}
private async flushAll(fullQueue = false) {
- await Promise.all([
- this.flush(TableName.Traces, fullQueue),
- this.flush(TableName.Scores, fullQueue),
- this.flush(TableName.Observations, fullQueue),
- ]).catch((err) => {
- logger.error("ClickhouseWriter.flushAll", err);
+ return instrumentAsync({ name: "write-to-clickhouse" }, async () => {
+ await Promise.all([
+ this.flush(TableName.Traces, fullQueue),
+ this.flush(TableName.Scores, fullQueue),
+ this.flush(TableName.Observations, fullQueue),
+ ]).catch((err) => {
+ logger.error("ClickhouseWriter.flushAll", err);
+ });
});
}