🪢 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(worker): add opt-in queue-consumption liveness health check (LFE-13685) (#15512)
Steffen Schmitz7f719433364f
diff --git a/worker/src/__tests__/queueConsumptionHealth.test.ts b/worker/src/__tests__/queueConsumptionHealth.test.tsnew file mode 100644index 0000000000..1e117fe61d--- /dev/null+++ b/worker/src/__tests__/queueConsumptionHealth.test.ts@@ -0,0 +1,126 @@+import { EventEmitter } from "node:events";++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { QueueName } from "@langfuse/shared/src/server";++import {+ getQueueConsumptionHealth,+ markQueueJobActivity,+ markQueueWorkerRegistered,+ resetQueueConsumptionStateForTest,+} from "../features/health/queueConsumption";+import { WorkerManager } from "../queues/workerManager";++// Replace the BullMQ Worker with an EventEmitter so WorkerManager.register can+// be exercised without Redis, and job pickup/completion can be simulated by+// emitting the corresponding worker events.+vi.mock("bullmq", async (importOriginal) => {+ const mod = await importOriginal<typeof import("bullmq")>();+ const { EventEmitter: Emitter } = await import("node:events");++ class FakeWorker extends Emitter {+ constructor(+ public readonly name: string,+ public readonly processor: unknown,+ public readonly opts: unknown,+ ) {+ super();+ }++ isRunning(): boolean {+ return true;+ }++ async close(): Promise<void> {}+ }++ return { ...mod, Worker: FakeWorker };+});++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const mod =+ await importOriginal<typeof import("@langfuse/shared/src/server")>();+ return {+ ...mod,+ createBullMQWorkerOptionsWithRedis: () => ({+ connection: {},+ prefix: "test",+ }),+ };+});++beforeEach(() => {+ resetQueueConsumptionStateForTest();+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));+});++afterEach(() => {+ vi.useRealTimers();+});++describe("queue consumption liveness", () => {+ it("flips stuck after the (default 60 min) threshold and recovers on activity", () => {+ markQueueWorkerRegistered();++ expect(getQueueConsumptionHealth().enabled).toBe(true);+ expect(getQueueConsumptionHealth().stuck).toBe(false);++ // Boot grace: measured from registration while no job has run yet.+ vi.setSystemTime(new Date("2026-01-01T00:59:00Z"));+ expect(getQueueConsumptionHealth().stuck).toBe(false);++ // A worker that never processes anything (e.g. booted wedged) is caught.+ vi.setSystemTime(new Date("2026-01-01T01:01:00Z"));+ expect(getQueueConsumptionHealth().stuck).toBe(true);++ markQueueJobActivity();+ expect(getQueueConsumptionHealth().stuck).toBe(false);+ });++ it("is never stuck without registered workers (API-only container)", () => {+ vi.setSystemTime(new Date("2026-01-02T00:00:00Z")); // far past any threshold++ const health = getQueueConsumptionHealth();+ expect(health.enabled).toBe(false);+ expect(health.stuck).toBe(false);+ });+});++describe("WorkerManager liveness wiring", () => {+ const getEmitter = (queueName: QueueName): EventEmitter =>+ WorkerManager.getWorker(queueName) as unknown as EventEmitter;++ it("marks registration and stamps activity on job pickup and completion", () => {+ WorkerManager.register(QueueName.NotificationQueue, async () => {});++ expect(getQueueConsumptionHealth().enabled).toBe(true);+ expect(getQueueConsumptionHealth().lastActivityAt).toBeNull();++ getEmitter(QueueName.NotificationQueue).emit("active");+ expect(getQueueConsumptionHealth().lastActivityAt).toBe(+ "2026-01-01T00:00:00.000Z",+ );++ // "completed" must stamp on its own: the timestamp advances past the+ // pickup stamp, so a long-running job refreshes liveness when it settles.+ vi.setSystemTime(new Date("2026-01-01T00:05:00Z"));+ getEmitter(QueueName.NotificationQueue).emit("completed");+ expect(getQueueConsumptionHealth().lastActivityAt).toBe(+ "2026-01-01T00:05:00.000Z",+ );+ });++ it("does not stamp activity on failed events (stalled-checker emits those)", () => {+ WorkerManager.register(QueueName.WebhookQueue, async () => {});++ getEmitter(QueueName.WebhookQueue).emit(+ "failed",+ undefined,+ new Error("stalled beyond limit"),+ );++ expect(getQueueConsumptionHealth().lastActivityAt).toBeNull();+ });+});diff --git a/worker/src/api/index.ts b/worker/src/api/index.tsindex f517fa53a3..367ac15d99 100644--- a/worker/src/api/index.ts+++ b/worker/src/api/index.ts@@ -11,6 +11,8 @@ router.get<{}, { status: string }>("/health", async (req, res) => {failOnSigterm: false,failIfEventPropagationStuck:req.query.failIfEventPropagationStuck === "true",+ failIfQueueConsumptionStuck:+ req.query.failIfQueueConsumptionStuck === "true",});} catch (e) {traceException(e);@@ -27,6 +29,8 @@ router.get<{}, { status: string }>("/ready", async (req, res) => {failOnSigterm: true,failIfEventPropagationStuck:req.query.failIfEventPropagationStuck === "true",+ failIfQueueConsumptionStuck:+ req.query.failIfQueueConsumptionStuck === "true",});} catch (e) {traceException(e);diff --git a/worker/src/env.ts b/worker/src/env.tsindex a9eb4375d4..bfb8d8b901 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -552,6 +552,21 @@ const EnvSchema = z.object({.int().default(15),+ // Liveness threshold for the opt-in ?failIfQueueConsumptionStuck=true health+ // check: fail once this container's BullMQ workers have neither picked up nor+ // completed a single job for this long. Default-on repeatable jobs keep a+ // healthy worker busy at least once per hour (blob storage integration+ // scheduler every 20 min, PostHog/Mixpanel schedulers hourly), so an hour of+ // total silence indicates a wedged worker.+ // In multi-replica deployments each scheduler tick lands+ // on only one replica — raise the threshold if replicas can legitimately sit+ // idle (no ingestion or other traffic) for extended periods.+ LANGFUSE_QUEUE_CONSUMPTION_STUCK_THRESHOLD_MINUTES: z.coerce+ .number()+ .positive()+ .int()+ .default(60),+LANGFUSE_WEBHOOK_QUEUE_PROCESSING_CONCURRENCY: z.coerce.number().positive()diff --git a/worker/src/features/health/index.ts b/worker/src/features/health/index.tsindex 4706211447..9c19189afd 100644--- a/worker/src/features/health/index.ts+++ b/worker/src/features/health/index.ts@@ -7,6 +7,7 @@ import {getLastProcessedPartition,getLastRunStartedAt,} from "../eventPropagation/handleEventPropagationJob";+import { getQueueConsumptionHealth } from "./queueConsumption";export type EventPropagationHealth = {/** Whether the dual-write / event-propagation job runs in this deployment. */@@ -133,6 +134,13 @@ type ContainerHealthOptions = {* pays the extra Redis lookups and only that probe forces a restart.*/failIfEventPropagationStuck?: boolean;+ /**+ * Also fail (503) when this container's BullMQ workers have not processed a+ * single job within LANGFUSE_QUEUE_CONSUMPTION_STUCK_THRESHOLD_MINUTES.+ * Opt-in via the ?failIfQueueConsumptionStuck=true query parameter so only a+ * probe that should force restarts evaluates it.+ */+ failIfQueueConsumptionStuck?: boolean;};/**@@ -142,7 +150,11 @@ export const checkContainerHealth = async (res: Response,options: ContainerHealthOptions,) => {- const { failOnSigterm, failIfEventPropagationStuck = false } = options;+ const {+ failOnSigterm,+ failIfEventPropagationStuck = false,+ failIfQueueConsumptionStuck = false,+ } = options;if (failOnSigterm && isSigtermReceived()) {logger.info(@@ -170,25 +182,41 @@ export const checkContainerHealth = async (),]);+ const failures: string[] = [];+ const details: Record<string, unknown> = {};+if (failIfEventPropagationStuck) {const eventPropagation = await getEventPropagationHealth();+ details.eventPropagation = eventPropagation;if (eventPropagation.stuck) {logger.warn(`Health check failed: event propagation stuck (last run ${eventPropagation.secondsSinceLastRun}s ago, threshold ${eventPropagation.thresholdSeconds}s)`,);- return res.status(503).json({- status: "Event propagation stuck",- eventPropagation,- });+ failures.push("Event propagation stuck");}- return res.json({- status: "ok",- eventPropagation,+ }++ if (failIfQueueConsumptionStuck) {+ const queueConsumption = getQueueConsumptionHealth();+ details.queueConsumption = queueConsumption;+ if (queueConsumption.stuck) {+ logger.warn(+ `Health check failed: queue consumption stuck (last job activity ${queueConsumption.secondsSinceLastActivity}s ago across ${queueConsumption.registeredWorkerCount} workers, threshold ${queueConsumption.thresholdSeconds}s)`,+ );+ failures.push("Queue consumption stuck");+ }+ }++ if (failures.length > 0) {+ return res.status(503).json({+ status: failures.join("; "),+ ...details,});}res.json({status: "ok",+ ...details,});};diff --git a/worker/src/features/health/queueConsumption.ts b/worker/src/features/health/queueConsumption.tsnew file mode 100644index 0000000000..e18d338b37--- /dev/null+++ b/worker/src/features/health/queueConsumption.ts@@ -0,0 +1,111 @@+import { env } from "../../env";++/**+ * In-memory liveness signal for this container's BullMQ queue consumers.+ *+ * After Redis lock loss BullMQ workers can wedge permanently: the process stays alive and+ * connectivity checks pass, but no queue picks up jobs ever again. Because+ * default-on repeatable jobs keep a healthy worker busy at+ * least once per hour, "no job activity for longer than the threshold" should be a+ * reliable per-container wedge signal that a liveness probe can act on.+ */++export type QueueConsumptionHealth = {+ /** Whether at least one BullMQ queue consumer is registered in this container. */+ enabled: boolean;+ /** Number of BullMQ workers registered in this container. */+ registeredWorkerCount: number;+ /** ISO timestamp of the first worker registration (observation baseline). */+ trackingSince: string | null;+ /** ISO timestamp of the last job pickup/completion, or null if none since boot. */+ lastActivityAt: string | null;+ /** Seconds since the last job activity, measured from registration if none yet. */+ secondsSinceLastActivity: number | null;+ /** Staleness threshold that flips `stuck` to true. */+ thresholdSeconds: number;+ /** True when no job activity happened within `thresholdSeconds`. */+ stuck: boolean;+};++let registeredWorkerCount = 0;+let trackingSinceMs: number | null = null;+let lastActivityMs: number | null = null;++/** Called by WorkerManager.register for every successfully registered worker. */+export const markQueueWorkerRegistered = (): void => {+ registeredWorkerCount += 1;+ if (trackingSinceMs === null) {+ trackingSinceMs = Date.now();+ }+};++/** Called on every BullMQ job pickup ("active") and completion ("completed"). */+export const markQueueJobActivity = (): void => {+ lastActivityMs = Date.now();+};++/** Test-only: module state is global, so tests must reset between cases. */+export const resetQueueConsumptionStateForTest = (): void => {+ registeredWorkerCount = 0;+ trackingSinceMs = null;+ lastActivityMs = null;+};++/**+ * `stuck` measures from the LATER of registration time and last job activity:+ * a fresh boot gets a full threshold of grace before the probe may fail, and a+ * container without any registered consumers (API-only) is never stuck.+ */+export const evaluateQueueConsumptionStuck = (input: {+ nowMs: number;+ registeredWorkerCount: number;+ trackingSinceMs: number | null;+ lastActivityMs: number | null;+ thresholdSeconds: number;+}): QueueConsumptionHealth => {+ const { nowMs, thresholdSeconds } = input;++ const enabled =+ input.registeredWorkerCount > 0 && input.trackingSinceMs !== null;++ const referenceMs = enabled+ ? Math.max(input.trackingSinceMs!, input.lastActivityMs ?? 0)+ : null;++ const secondsSinceLastActivity =+ referenceMs !== null+ ? Math.max(0, Math.round((nowMs - referenceMs) / 1000))+ : null;++ const stuck =+ enabled &&+ secondsSinceLastActivity !== null &&+ secondsSinceLastActivity > thresholdSeconds;++ return {+ enabled,+ registeredWorkerCount: input.registeredWorkerCount,+ trackingSince:+ input.trackingSinceMs !== null+ ? new Date(input.trackingSinceMs).toISOString()+ : null,+ lastActivityAt:+ input.lastActivityMs !== null+ ? new Date(input.lastActivityMs).toISOString()+ : null,+ secondsSinceLastActivity,+ thresholdSeconds,+ stuck,+ };+};++/** Evaluate this container's queue-consumption health. Purely in-memory. */+export const getQueueConsumptionHealth = (): QueueConsumptionHealth =>+ evaluateQueueConsumptionStuck({+ nowMs: Date.now(),+ registeredWorkerCount,+ trackingSinceMs,+ lastActivityMs,+ thresholdSeconds:+ env.LANGFUSE_QUEUE_CONSUMPTION_STUCK_THRESHOLD_MINUTES * 60,+ });diff --git a/worker/src/queues/workerManager.ts b/worker/src/queues/workerManager.tsindex 0faaee4856..80857beab5 100644--- a/worker/src/queues/workerManager.ts+++ b/worker/src/queues/workerManager.ts@@ -10,6 +10,10 @@ import {recordIncrement,traceException,} from "@langfuse/shared/src/server";+import {+ markQueueJobActivity,+ markQueueWorkerRegistered,+} from "../features/health/queueConsumption";import { WORKER_HOST_ID } from "../utils/hostId";import { SHARDED_QUEUE_BASE_NAMES } from "./shardedQueueRegistry";@@ -147,8 +151,16 @@ export class WorkerManager {},);WorkerManager.workers[queueName] = worker;+ markQueueWorkerRegistered();logger.info(`${queueName} executor started: ${worker.isRunning()}`);+ // Liveness signal for the ?failIfQueueConsumptionStuck=true health check.+ // "active" and "completed" prove this container's consumption loop is+ // alive; "failed" is excluded because the stalled-checker emits it for+ // jobs this container never picked up.+ worker.on("active", markQueueJobActivity);+ worker.on("completed", markQueueJobActivity);+const { baseMetric, shardTag } = WorkerManager.resolveMetricInfo(queueName);// Add error handling