🪢 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(web): publish event-loop delay for autoscaling (#17632)
Valery Meleshkin0939038a7c6b
diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.mdindex d58793d6c3..72b7a947ce 100644--- a/packages/shared/AGENTS.md+++ b/packages/shared/AGENTS.md@@ -18,6 +18,9 @@- Main exports: `src/index.ts`- DB clients and types: `src/db.ts`- Server exports: `src/server/index.ts`+- CloudWatch metrics: `recordGauge` batches values; windowed measurements can+ call `flushMetricsToCloudWatch` from the server barrel after recording to+ submit them before the next gauge replaces the cached value.- Server cache utilities: `src/server/cache/*`- Domain model types: `src/domain/*`- Repository layer: `src/server/repositories/*`diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.tsindex c0378ba300..6ebdd743f8 100644--- a/packages/shared/src/server/instrumentation/index.ts+++ b/packages/shared/src/server/instrumentation/index.ts@@ -273,7 +273,7 @@ const sendCloudWatchMetric = (key: string, value: number, replace: boolean) => {};// Flush all cached metrics in a single API call-const flushMetricsToCloudWatch = () => {+export const flushMetricsToCloudWatch = () => {if (Object.keys(metricCache).length === 0) return;lastFlushTime = Date.now();diff --git a/web/src/__tests__/server/unit/eventLoopMetrics.servertest.ts b/web/src/__tests__/server/unit/eventLoopMetrics.servertest.tsnew file mode 100644index 0000000000..7a395d7018--- /dev/null+++ b/web/src/__tests__/server/unit/eventLoopMetrics.servertest.ts@@ -0,0 +1,67 @@+import { createRequire } from "node:module";+import { afterEach, expect, it, vi } from "vitest";++const percentile = vi.hoisted(() => vi.fn(() => 1_800_000_000));+vi.mock("node:perf_hooks", () => ({+ monitorEventLoopDelay: () => ({+ count: 1,+ enable() {},+ disable() {},+ reset() {},+ percentile,+ }),+}));+// Use the real metric cache and publisher without loading unrelated server clients.+vi.mock(+ "@langfuse/shared/src/server",+ () => import("../../../../../packages/shared/src/server/instrumentation"),+);++let stop: (() => void) | undefined;+afterEach(() => {+ stop?.();+ vi.useRealTimers();+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+});++it("delivers a stalled window even when another metric just flushed, then delivers recovery", async () => {+ vi.stubEnv("ENABLE_AWS_CLOUDWATCH_METRIC_PUBLISHING", "true");+ vi.stubEnv("OTEL_SERVICE_NAME", "web-test");+ vi.resetModules();+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));+ const requireFromShared = createRequire(+ new URL("../../../../../packages/shared/package.json", import.meta.url),+ );+ const { CloudWatchClient } = requireFromShared("@aws-sdk/client-cloudwatch");+ const send = vi+ .spyOn(CloudWatchClient.prototype, "send")+ .mockResolvedValue({});+ const { recordGauge } = await import("@langfuse/shared/src/server");+ const { startEventLoopMetrics, stopEventLoopMetrics } =+ await import("@/src/utils/eventLoopMetrics");+ stop = stopEventLoopMetrics;+ startEventLoopMetrics();++ vi.advanceTimersByTime(29_999);+ recordGauge("unrelated", 1);+ vi.advanceTimersByTime(1);+ percentile.mockReturnValue(20_000_000);+ vi.advanceTimersByTime(30_000);++ for (const value of [1800, 20]) {+ expect(send).toHaveBeenCalledWith(+ expect.objectContaining({+ input: expect.objectContaining({+ MetricData: expect.arrayContaining([+ {+ MetricName: "langfuse.web-test.event_loop.delay.p95",+ Value: value,+ },+ ]),+ }),+ }),+ );+ }+});diff --git a/web/src/instrumentation.ts b/web/src/instrumentation.tsindex 36b824f130..cfcb804f27 100644--- a/web/src/instrumentation.ts+++ b/web/src/instrumentation.ts@@ -29,6 +29,8 @@ export async function register() {await drainAndClose();},});+ const { startEventLoopMetrics } = await import("./utils/eventLoopMetrics");+ startEventLoopMetrics();}if (isNodeRuntime && isInitLoadingEnabled) {diff --git a/web/src/utils/eventLoopMetrics.ts b/web/src/utils/eventLoopMetrics.tsnew file mode 100644index 0000000000..3a71a28fb2--- /dev/null+++ b/web/src/utils/eventLoopMetrics.ts@@ -0,0 +1,48 @@+import { monitorEventLoopDelay } from "node:perf_hooks";+import { env } from "@/src/env.mjs";+import { env as sharedEnv } from "@langfuse/shared/src/env";+import {+ flushMetricsToCloudWatch,+ recordGauge,+} from "@langfuse/shared/src/server";++let stopMonitoring: (() => void) | undefined;++export function startEventLoopMetrics() {+ if (+ stopMonitoring ||+ sharedEnv.ENABLE_AWS_CLOUDWATCH_METRIC_PUBLISHING !== "true"+ ) {+ return;+ }++ // Report raw timer delay, including the approximately 20 ms sampling floor.+ const histogram = monitorEventLoopDelay({ resolution: 20 });+ histogram.enable();+ const timer = setInterval(() => {+ // Empty windows must not publish a healthy value to an autoscaler.+ if (histogram.count === 0) return;+ const delayMs = histogram.percentile(95) / 1_000_000;+ histogram.reset();+ // CloudWatch gauges do not retain tags; the service must be in the name+ // so independent web services never share an autoscaling signal.+ recordGauge(+ `langfuse.${env.OTEL_SERVICE_NAME}.event_loop.delay.p95`,+ delayMs,+ { unit: "millisecond" },+ );+ // Publish this window before a later gauge can replace it in the cache.+ flushMetricsToCloudWatch();+ }, 30_000);+ timer.unref();++ stopMonitoring = () => {+ clearInterval(timer);+ histogram.disable();+ };+}++export function stopEventLoopMetrics() {+ stopMonitoring?.();+ stopMonitoring = undefined;+}diff --git a/web/src/utils/shutdown.ts b/web/src/utils/shutdown.tsindex 33d21efe8f..bd1f59729c 100644--- a/web/src/utils/shutdown.ts+++ b/web/src/utils/shutdown.ts@@ -11,6 +11,7 @@ import {} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";+import { stopEventLoopMetrics } from "./eventLoopMetrics";const TIMEOUT = 110_000;@@ -40,6 +41,7 @@ export const drainAndClose = (): Promise<void> => {return drainPromise;}setSigtermReceived();+ stopEventLoopMetrics();drainPromise = new Promise<void>((resolve) => {setTimeout(async () => {