Skip to content

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

feat: QueueMetricsRunner collects queue metrics on a fixed schedule and aggegates sharded queue metrics (#13231)

Valery Meleshkin3089778d7db2
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 76ea1478f0..ad58fbc834 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -89,6 +89,7 @@ import { MediaRetentionCleaner } from "./features/media-retention-cleaner";
import { BatchTraceDeletionCleaner } from "./features/batch-trace-deletion-cleaner";
import { BatchProjectMediaCleaner } from "./features/batch-project-media-cleaner";
import { BatchProjectBlobCleaner } from "./features/batch-project-blob-cleaner";
+import { QueueMetricsRunner } from "./features/queue-metrics-runner";
const app = express();
@@ -667,6 +668,14 @@ if (env.LANGFUSE_BATCH_TRACE_DELETION_CLEANER_ENABLED === "true") {
batchTraceDeletionCleaner.start();
}
+// Queue metrics background reporter
+export let queueMetricsRunner: QueueMetricsRunner | null = null;
+
+if (env.LANGFUSE_QUEUE_METRICS_ENABLED === "true") {
+ queueMetricsRunner = new QueueMetricsRunner();
+ queueMetricsRunner.start();
+}
+
process.on("SIGINT", () => onShutdown("SIGINT"));
process.on("SIGTERM", () => onShutdown("SIGTERM"));
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 4c3dd138e8..8a4260b640 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -448,6 +448,8 @@ const EnvSchema = z.object({
.min(0)
.max(1)
.default(0.3), // Probability for recording sharded queue depth metrics
+ LANGFUSE_QUEUE_METRICS_INTERVAL_MS: z.coerce.number().min(100).default(1000),
+ LANGFUSE_QUEUE_METRICS_ENABLED: z.enum(["true", "false"]).default("true"),
});
export const env: z.infer<typeof EnvSchema> =
diff --git a/worker/src/features/queue-metrics-runner/index.ts b/worker/src/features/queue-metrics-runner/index.ts
new file mode 100644
index 0000000000..e970c7b4d7
--- /dev/null
+++ b/worker/src/features/queue-metrics-runner/index.ts
@@ -0,0 +1,175 @@
+import { Queue } from "bullmq";
+
+import {
+ QueueName,
+ convertQueueNameToMetricName,
+ recordGauge,
+ logger,
+} from "@langfuse/shared/src/server";
+
+import { PeriodicRunner } from "../../utils/PeriodicRunner";
+import { env } from "../../env";
+import { WorkerManager } from "../../queues/workerManager";
+import {
+ SHARDED_QUEUES,
+ SHARDED_QUEUE_BASE_NAMES,
+ resolveQueueInstance,
+} from "../../queues/shardedQueueRegistry";
+
+type DepthType = "waiting" | "failed" | "active";
+
+async function collectDepth(
+ queue: Queue,
+): Promise<Record<DepthType, number> | null> {
+ // Include "paused" to match getWaitingCount() semantics (which sums waiting + paused)
+ const counts = await queue.getJobCounts(
+ "waiting",
+ "paused",
+ "failed",
+ "active",
+ );
+ return {
+ waiting: (counts.waiting ?? 0) + (counts.paused ?? 0),
+ failed: counts.failed ?? 0,
+ active: counts.active ?? 0,
+ };
+}
+
+function emitDepth(
+ metricBase: string,
+ depths: Record<DepthType, number>,
+ tags?: Record<string, string>,
+): void {
+ for (const type of ["waiting", "failed", "active"] as const) {
+ recordGauge(metricBase + ".depth", depths[type], {
+ ...tags,
+ type,
+ unit: "records",
+ });
+ }
+}
+
+export class QueueMetricsRunner extends PeriodicRunner {
+ protected get name(): string {
+ return "queue-metrics-runner";
+ }
+
+ protected get defaultIntervalMs(): number {
+ return env.LANGFUSE_QUEUE_METRICS_INTERVAL_MS;
+ }
+
+ protected async execute(): Promise<void> {
+ // Only poll queues that have registered workers. This avoids calling
+ // getInstance() on queues this worker doesn't consume, which would
+ // create unnecessary Redis connections and can trigger side effects
+ // (e.g. CloudUsageMeteringQueue.getInstance() enqueues cron jobs).
+ const registeredNames = new Set(WorkerManager.getRegisteredQueueNames());
+ const promises: Promise<void>[] = [];
+
+ // Non-sharded queues: only poll queues with registered workers
+ for (const queueName of Object.values(QueueName)) {
+ if (SHARDED_QUEUE_BASE_NAMES.has(queueName)) continue;
+ if (!registeredNames.has(queueName)) continue;
+
+ const queue = resolveQueueInstance(queueName);
+ if (!queue) continue;
+
+ const metricBase = convertQueueNameToMetricName(queueName);
+
+ promises.push(
+ collectDepth(queue)
+ .then((depths) => {
+ if (depths) {
+ emitDepth(metricBase, depths);
+ // Old-style metrics for backward compatibility.
+ // These duplicate what workerManager.metricWrapper emits on job
+ // completion. Both sources coexist during migration — once dashboards
+ // switch to the new .depth metrics, remove all but .depth
+ recordGauge(metricBase + ".length", depths.waiting, {
+ unit: "records",
+ });
+ recordGauge(metricBase + ".dlq_length", depths.failed, {
+ unit: "records",
+ });
+ recordGauge(metricBase + ".active", depths.active, {
+ unit: "records",
+ });
+ }
+ })
+ .catch((err) => {
+ logger.error(
+ `Queue metrics: failed to collect depth for ${queueName}`,
+ err,
+ );
+ }),
+ );
+ }
+
+ // Sharded queues: only poll shards with registered workers
+ for (const config of SHARDED_QUEUES) {
+ const shardNames = config
+ .getShardNames()
+ .filter((name) => registeredNames.has(name));
+ if (shardNames.length === 0) continue;
+
+ const metricBase = convertQueueNameToMetricName(config.baseQueueName);
+
+ const shardPromises = shardNames.map((shardName) => {
+ const queue = config.getInstance(shardName);
+ if (!queue) return Promise.resolve(null);
+
+ return collectDepth(queue)
+ .then((depths) => {
+ if (depths) {
+ emitDepth(metricBase, depths, {
+ shard: shardName,
+ });
+ }
+ return depths;
+ })
+ .catch((err) => {
+ logger.error(
+ `Queue metrics: failed to collect depth for ${shardName}`,
+ err,
+ );
+ return null;
+ });
+ });
+
+ // Emit aggregate depth across all shards (shard:"all") once per-shard collection settles.
+ // If some shards failed, extrapolate from the successful ones to avoid under-reporting.
+ promises.push(
+ Promise.allSettled(shardPromises).then((results) => {
+ const aggregate: Record<DepthType, number> = {
+ waiting: 0,
+ failed: 0,
+ active: 0,
+ };
+
+ let succeededCount = 0;
+ for (const result of results) {
+ if (result.status === "fulfilled" && result.value) {
+ aggregate.waiting += result.value.waiting;
+ aggregate.failed += result.value.failed;
+ aggregate.active += result.value.active;
+ succeededCount++;
+ }
+ }
+
+ if (succeededCount === 0) return;
+
+ if (succeededCount < results.length) {
+ const scale = results.length / succeededCount;
+ aggregate.waiting = Math.round(aggregate.waiting * scale);
+ aggregate.failed = Math.round(aggregate.failed * scale);
+ aggregate.active = Math.round(aggregate.active * scale);
+ }
+
+ emitDepth(metricBase, aggregate, { shard: "all" });
+ }),
+ );
+ }
+
+ await Promise.allSettled(promises);
+ }
+}
diff --git a/worker/src/queues/shardedQueueRegistry.ts b/worker/src/queues/shardedQueueRegistry.ts
new file mode 100644
index 0000000000..8ab55218db
--- /dev/null
+++ b/worker/src/queues/shardedQueueRegistry.ts
@@ -0,0 +1,92 @@
+import { Queue } from "bullmq";
+
+import {
+ QueueName,
+ getQueue,
+ IngestionQueue,
+ SecondaryIngestionQueue,
+ OtelIngestionQueue,
+ TraceUpsertQueue,
+ EvalExecutionQueue,
+ SecondaryEvalExecutionQueue,
+ LLMAsJudgeExecutionQueue,
+} from "@langfuse/shared/src/server";
+
+export type ShardedQueueDef = {
+ baseQueueName: QueueName;
+ getShardNames: () => string[];
+ getInstance: (shardName: string) => Queue | null;
+};
+
+export const SHARDED_QUEUES: ShardedQueueDef[] = [
+ {
+ baseQueueName: QueueName.IngestionQueue,
+ getShardNames: () => IngestionQueue.getShardNames(),
+ getInstance: (shard) => IngestionQueue.getInstance({ shardName: shard }),
+ },
+ {
+ baseQueueName: QueueName.IngestionSecondaryQueue,
+ getShardNames: () => SecondaryIngestionQueue.getShardNames(),
+ getInstance: (shard) =>
+ SecondaryIngestionQueue.getInstance({ shardName: shard }),
+ },
+ {
+ baseQueueName: QueueName.OtelIngestionQueue,
+ getShardNames: () => OtelIngestionQueue.getShardNames(),
+ getInstance: (shard) =>
+ OtelIngestionQueue.getInstance({ shardName: shard }),
+ },
+ {
+ baseQueueName: QueueName.TraceUpsert,
+ getShardNames: () => TraceUpsertQueue.getShardNames(),
+ getInstance: (shard) => TraceUpsertQueue.getInstance({ shardName: shard }),
+ },
+ {
+ baseQueueName: QueueName.EvaluationExecution,
+ getShardNames: () => EvalExecutionQueue.getShardNames(),
+ getInstance: (shard) =>
+ EvalExecutionQueue.getInstance({ shardName: shard }),
+ },
+ {
+ baseQueueName: QueueName.EvaluationExecutionSecondaryQueue,
+ getShardNames: () => SecondaryEvalExecutionQueue.getShardNames(),
+ getInstance: (shard) =>
+ SecondaryEvalExecutionQueue.getInstance({ shardName: shard }),
+ },
+ {
+ baseQueueName: QueueName.LLMAsJudgeExecution,
+ getShardNames: () => LLMAsJudgeExecutionQueue.getShardNames(),
+ getInstance: (shard) =>
+ LLMAsJudgeExecutionQueue.getInstance({ shardName: shard }),
+ },
+];
+
+export const SHARDED_QUEUE_BASE_NAMES = new Set<QueueName>(
+ SHARDED_QUEUES.map((q) => q.baseQueueName),
+);
+
+/**
+ * Resolve a queue name (possibly a shard name like "ingestion-queue-1") to its
+ * BullMQ Queue instance. Checks sharded queues first, then falls back to
+ * non-sharded getQueue().
+ */
+export function resolveQueueInstance(queueName: string): Queue | null {
+ for (const def of SHARDED_QUEUES) {
+ if (queueName.startsWith(def.baseQueueName)) {
+ return def.getInstance(queueName);
+ }
+ }
+
+ return getQueue(
+ queueName as Exclude<
+ QueueName,
+ | QueueName.IngestionQueue
+ | QueueName.IngestionSecondaryQueue
+ | QueueName.EvaluationExecution
+ | QueueName.EvaluationExecutionSecondaryQueue
+ | QueueName.LLMAsJudgeExecution
+ | QueueName.TraceUpsert
+ | QueueName.OtelIngestionQueue
+ >,
+ );
+}
diff --git a/worker/src/queues/workerManager.ts b/worker/src/queues/workerManager.ts
index 13650c7fb8..abce063797 100644
--- a/worker/src/queues/workerManager.ts
+++ b/worker/src/queues/workerManager.ts
@@ -1,18 +1,10 @@
import { Job, Processor, Worker, WorkerOptions } from "bullmq";
import {
- getQueue,
convertQueueNameToMetricName,
createNewRedisInstance,
getQueuePrefix,
logger,
QueueName,
- IngestionQueue,
- SecondaryIngestionQueue,
- TraceUpsertQueue,
- OtelIngestionQueue,
- EvalExecutionQueue,
- SecondaryEvalExecutionQueue,
- LLMAsJudgeExecutionQueue,
recordGauge,
recordHistogram,
recordIncrement,
@@ -20,6 +12,10 @@ import {
traceException,
} from "@langfuse/shared/src/server";
import { env } from "../env";
+import {
+ resolveQueueInstance,
+ SHARDED_QUEUE_BASE_NAMES,
+} from "./shardedQueueRegistry";
export class WorkerManager {
private static workers: { [key: string]: Worker } = {};
@@ -40,47 +36,15 @@ export class WorkerManager {
},
);
const result = await processor(job);
- const queue = queueName.startsWith(QueueName.IngestionQueue)
- ? IngestionQueue.getInstance({ shardName: queueName })
- : queueName.startsWith(QueueName.IngestionSecondaryQueue)
- ? SecondaryIngestionQueue.getInstance({ shardName: queueName })
- : queueName.startsWith(QueueName.TraceUpsert)
- ? TraceUpsertQueue.getInstance({ shardName: queueName })
- : queueName.startsWith(QueueName.OtelIngestionQueue)
- ? OtelIngestionQueue.getInstance({ shardName: queueName })
- : queueName.startsWith(QueueName.EvaluationExecution)
- ? EvalExecutionQueue.getInstance({ shardName: queueName })
- : queueName.startsWith(
- QueueName.EvaluationExecutionSecondaryQueue,
- )
- ? SecondaryEvalExecutionQueue.getInstance({
- shardName: queueName,
- })
- : queueName.startsWith(QueueName.LLMAsJudgeExecution)
- ? LLMAsJudgeExecutionQueue.getInstance({
- shardName: queueName,
- })
- : getQueue(
- queueName as Exclude<
- QueueName,
- | QueueName.IngestionQueue
- | QueueName.IngestionSecondaryQueue
- | QueueName.EvaluationExecution
- | QueueName.EvaluationExecutionSecondaryQueue
- | QueueName.LLMAsJudgeExecution
- | QueueName.TraceUpsert
- | QueueName.OtelIngestionQueue
- >,
- );
+ const queue = resolveQueueInstance(queueName);
// Sample queue depth gauges for sharded queues to reduce metric volume.
- const isShardedQueue =
- queueName.startsWith(QueueName.IngestionQueue) ||
- queueName.startsWith(QueueName.IngestionSecondaryQueue) ||
- queueName.startsWith(QueueName.TraceUpsert) ||
- queueName.startsWith(QueueName.OtelIngestionQueue) ||
- queueName.startsWith(QueueName.EvaluationExecution) ||
- queueName.startsWith(QueueName.EvaluationExecutionSecondaryQueue) ||
- queueName.startsWith(QueueName.LLMAsJudgeExecution);
+ let isShardedQueue = false;
+ for (const base of SHARDED_QUEUE_BASE_NAMES) {
+ if (queueName.startsWith(base)) {
+ isShardedQueue = true;
+ break;
+ }
+ }
const shouldSample =
!isShardedQueue ||
@@ -141,6 +105,10 @@ export class WorkerManager {
return WorkerManager.workers[queueName];
}
+ public static getRegisteredQueueNames(): string[] {
+ return Object.keys(WorkerManager.workers);
+ }
+
public static register(
queueName: QueueName,
processor: Processor,
diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.ts
index cdea33da41..d3bcd753ea 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -16,6 +16,7 @@ import {
batchProjectMediaCleaner,
batchProjectBlobCleaner,
batchTraceDeletionCleaner,
+ queueMetricsRunner,
} from "../app";
export const onShutdown: NodeJS.SignalsListener = async (signal) => {
@@ -48,6 +49,9 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {
// Stop batch trace deletion cleaner
batchTraceDeletionCleaner?.stop();
+ // Stop queue metrics runner
+ queueMetricsRunner?.stop();
+
// Shutdown workers (https://docs.bullmq.io/guide/going-to-production#gracefully-shut-down-workers)
await WorkerManager.closeWorkers();