🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: emit .rate and .time metrics with shard tags for DataDog aggregation (#13249)
Valery Meleshkin06ee77746a5b
diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.tsindex 61fd47d7c5..22818cd284 100644--- a/packages/shared/src/server/instrumentation/index.ts+++ b/packages/shared/src/server/instrumentation/index.ts@@ -288,6 +288,25 @@ const flushMetricsToCloudWatch = () => {});};+// Metrics ending with these suffixes have their tags flattened into the+// CloudWatch metric name (excluding "unit"). Other metrics are unaffected.+const CW_TAG_FLATTENED_SUFFIXES = [".depth", ".rate"];++function buildCloudWatchKey(+ stat: string,+ tags?: { [tag: string]: string | number },+): string {+ if (!tags || !CW_TAG_FLATTENED_SUFFIXES.some((s) => stat.endsWith(s))) {+ return stat;+ }+ const suffix = Object.entries(tags)+ .filter(([k]) => k !== "unit")+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([k, v]) => `${k}_${v}`)+ .join(".");+ return suffix ? `${stat}.${suffix}` : stat;+}+export const recordGauge = (stat: string,value?: number | undefined,@@ -298,19 +317,7 @@ export const recordGauge = (| undefined,) => {if (env.ENABLE_AWS_CLOUDWATCH_METRIC_PUBLISHING === "true") {- // For .depth metrics, flatten tags into the metric name so CloudWatch- // can distinguish e.g. depth.shard_all.type_waiting from depth.type_active.- // Other metrics are unaffected.- let cwKey = stat;- if (stat.endsWith(".depth") && tags) {- const suffix = Object.entries(tags)- .filter(([k]) => k !== "unit")- .sort(([a], [b]) => a.localeCompare(b))- .map(([k, v]) => `${k}_${v}`)- .join(".");- if (suffix) cwKey = `${stat}.${suffix}`;- }- sendCloudWatchMetric(cwKey, value ?? 0, true);+ sendCloudWatchMetric(buildCloudWatchKey(stat, tags), value ?? 0, true);}dd.dogstatsd.gauge(stat, value, tags);};@@ -321,7 +328,7 @@ export const recordIncrement = (tags?: { [tag: string]: string | number } | undefined,) => {if (env.ENABLE_AWS_CLOUDWATCH_METRIC_PUBLISHING === "true") {- sendCloudWatchMetric(stat, value ?? 1, false);+ sendCloudWatchMetric(buildCloudWatchKey(stat, tags), value ?? 1, false);}dd.dogstatsd.increment(stat, value, tags);};diff --git a/worker/src/queues/workerManager.ts b/worker/src/queues/workerManager.tsindex abce063797..6bd4934216 100644--- a/worker/src/queues/workerManager.ts+++ b/worker/src/queues/workerManager.ts@@ -20,76 +20,91 @@ import {export class WorkerManager {private static workers: { [key: string]: Worker } = {};+ private static resolveMetricInfo(queueName: QueueName): {+ baseMetric: string;+ shardTag: { shard: string } | undefined;+ } {+ for (const base of SHARDED_QUEUE_BASE_NAMES) {+ if (queueName.startsWith(base)) {+ return {+ baseMetric: convertQueueNameToMetricName(base),+ shardTag: { shard: queueName },+ };+ }+ }+ return {+ baseMetric: convertQueueNameToMetricName(queueName),+ shardTag: undefined,+ };+ }+private static metricWrapper(processor: Processor,queueName: QueueName,): Processor {+ const oldMetric = convertQueueNameToMetricName(queueName);+ const { baseMetric, shardTag } = WorkerManager.resolveMetricInfo(queueName);+return async (job: Job) => {const startTime = Date.now();const waitTime = Date.now() - job.timestamp;- recordIncrement(convertQueueNameToMetricName(queueName) + ".request");- recordHistogram(- convertQueueNameToMetricName(queueName) + ".wait_time",- waitTime,- {- unit: "milliseconds",- },- );++ recordIncrement(oldMetric + ".request");+ recordIncrement(baseMetric + ".rate", 1, {+ type: "request",+ ...shardTag,+ });++ recordHistogram(oldMetric + ".wait_time", waitTime, {+ unit: "milliseconds",+ });+ recordHistogram(baseMetric + ".time", waitTime, {+ type: "wait",+ unit: "milliseconds",+ ...shardTag,+ });+const result = await processor(job);+const queue = resolveQueueInstance(queueName);// Sample queue depth gauges for sharded queues to reduce metric volume.- let isShardedQueue = false;- for (const base of SHARDED_QUEUE_BASE_NAMES) {- if (queueName.startsWith(base)) {- isShardedQueue = true;- break;- }- }-const shouldSample =- !isShardedQueue ||- Math.random() < env.LANGFUSE_QUEUE_METRICS_SAMPLE_RATE;+ !shardTag || Math.random() < env.LANGFUSE_QUEUE_METRICS_SAMPLE_RATE;if (shouldSample) {Promise.allSettled([// Here we only consider waiting jobs instead of the default ("waiting" or "delayed"// or "prioritized" or "waiting-children") that count providesqueue?.getWaitingCount().then((count) => {- recordGauge(- convertQueueNameToMetricName(queueName) + ".length",- count,- {- unit: "records",- },- );+ recordGauge(oldMetric + ".length", count, {+ unit: "records",+ });}),queue?.getFailedCount().then((count) => {- recordGauge(- convertQueueNameToMetricName(queueName) + ".dlq_length",- count,- {- unit: "records",- },- );+ recordGauge(oldMetric + ".dlq_length", count, {+ unit: "records",+ });}),queue?.getActiveCount().then((count) => {- recordGauge(- convertQueueNameToMetricName(queueName) + ".active",- count,- {- unit: "records",- },- );+ recordGauge(oldMetric + ".active", count, {+ unit: "records",+ });}),]).catch((err) => {logger.error("Failed to record queue length", err);});}- recordHistogram(- convertQueueNameToMetricName(queueName) + ".processing_time",- Date.now() - startTime,- { unit: "milliseconds" },- );++ const processingTime = Date.now() - startTime;+ recordHistogram(oldMetric + ".processing_time", processingTime, {+ unit: "milliseconds",+ });+ recordHistogram(baseMetric + ".time", processingTime, {+ type: "processing",+ unit: "milliseconds",+ ...shardTag,+ });+return result;};}@@ -139,6 +154,9 @@ export class WorkerManager {WorkerManager.workers[queueName] = worker;logger.info(`${queueName} executor started: ${worker.isRunning()}`);+ const oldMetric = convertQueueNameToMetricName(queueName);+ const { baseMetric, shardTag } = WorkerManager.resolveMetricInfo(queueName);+// Add error handlingworker.on("failed", (job: Job | undefined, err: Error) => {logger.error(@@ -146,7 +164,11 @@ export class WorkerManager {err,);traceException(err);- recordIncrement(convertQueueNameToMetricName(queueName) + ".failed");+ recordIncrement(oldMetric + ".failed");+ recordIncrement(baseMetric + ".rate", 1, {+ type: "failed",+ ...shardTag,+ });});worker.on("error", (failedReason: Error) => {logger.error(@@ -154,7 +176,11 @@ export class WorkerManager {failedReason,);traceException(failedReason);- recordIncrement(convertQueueNameToMetricName(queueName) + ".error");+ recordIncrement(oldMetric + ".error");+ recordIncrement(baseMetric + ".rate", 1, {+ type: "error",+ ...shardTag,+ });});}}