Skip to content

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

feat(worker): add event-propagation stuck health check (#14680)

Steffen Schmitz589dc7123e68
diff --git a/worker/src/__tests__/eventPropagationHealth.test.ts b/worker/src/__tests__/eventPropagationHealth.test.ts
new file mode 100644
index 0000000000..eff4a9f1e5
--- /dev/null
+++ b/worker/src/__tests__/eventPropagationHealth.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from "vitest";
+
+import { evaluateEventPropagationStuck } from "../features/health";
+
+describe("evaluateEventPropagationStuck", () => {
+ const nowMs = 1_700_000_000_000;
+ const thresholdSeconds = 15 * 60;
+
+ it("is not stuck when the last run started recently", () => {
+ const result = evaluateEventPropagationStuck({
+ enabled: true,
+ nowMs,
+ lastRunStartedAtMs: nowMs - 60_000, // 1 min ago
+ lastProcessedPartition: null,
+ thresholdSeconds,
+ });
+
+ expect(result.stuck).toBe(false);
+ expect(result.secondsSinceLastRun).toBe(60);
+ expect(result.lastRunStartedAt).toBe(
+ new Date(nowMs - 60_000).toISOString(),
+ );
+ });
+
+ it("is stuck when the last run started longer ago than the threshold", () => {
+ const result = evaluateEventPropagationStuck({
+ enabled: true,
+ nowMs,
+ lastRunStartedAtMs: nowMs - 20 * 60_000, // 20 min ago > 15 min
+ lastProcessedPartition: null,
+ thresholdSeconds,
+ });
+
+ expect(result.stuck).toBe(true);
+ expect(result.secondsSinceLastRun).toBe(1200);
+ });
+
+ it("is not stuck exactly at the threshold (strictly greater than)", () => {
+ const result = evaluateEventPropagationStuck({
+ enabled: true,
+ nowMs,
+ lastRunStartedAtMs: nowMs - thresholdSeconds * 1000,
+ lastProcessedPartition: null,
+ thresholdSeconds,
+ });
+
+ expect(result.secondsSinceLastRun).toBe(thresholdSeconds);
+ expect(result.stuck).toBe(false);
+ });
+
+ it("is not stuck when the job has never run yet (no heartbeat key)", () => {
+ const result = evaluateEventPropagationStuck({
+ enabled: true,
+ nowMs,
+ lastRunStartedAtMs: null,
+ lastProcessedPartition: null,
+ thresholdSeconds,
+ });
+
+ expect(result.stuck).toBe(false);
+ expect(result.secondsSinceLastRun).toBeNull();
+ expect(result.lastRunStartedAt).toBeNull();
+ });
+
+ it("is never stuck when event propagation is disabled, even if very stale", () => {
+ const result = evaluateEventPropagationStuck({
+ enabled: false,
+ nowMs,
+ lastRunStartedAtMs: nowMs - 60 * 60_000, // 1 hour ago
+ lastProcessedPartition: null,
+ thresholdSeconds,
+ });
+
+ expect(result.stuck).toBe(false);
+ expect(result.enabled).toBe(false);
+ });
+
+ it("reports the propagation delay but does NOT let it drive stuck", () => {
+ // A large propagation delay ("behind") combined with a recent run start
+ // ("running") must stay healthy — restart would not help a slow backlog.
+ const result = evaluateEventPropagationStuck({
+ enabled: true,
+ nowMs,
+ lastRunStartedAtMs: nowMs - 30_000, // ran 30s ago -> not stuck
+ lastProcessedPartition: new Date(nowMs - 45 * 60_000).toISOString(), // 45 min behind
+ thresholdSeconds,
+ });
+
+ expect(result.propagationDelaySeconds).toBe(45 * 60);
+ expect(result.stuck).toBe(false);
+ });
+
+ it("leaves the propagation delay null for an unparsable cursor value", () => {
+ const result = evaluateEventPropagationStuck({
+ enabled: true,
+ nowMs,
+ lastRunStartedAtMs: nowMs - 30_000,
+ lastProcessedPartition: "not-a-date",
+ thresholdSeconds,
+ });
+
+ expect(result.propagationDelaySeconds).toBeNull();
+ });
+});
diff --git a/worker/src/api/index.ts b/worker/src/api/index.ts
index e172fb55bb..f517fa53a3 100644
--- a/worker/src/api/index.ts
+++ b/worker/src/api/index.ts
@@ -5,9 +5,13 @@ import { checkContainerHealth } from "../features/health";
import { logger } from "@langfuse/shared/src/server";
const router = express.Router();
-router.get<{}, { status: string }>("/health", async (_req, res) => {
+router.get<{}, { status: string }>("/health", async (req, res) => {
try {
- await checkContainerHealth(res, false);
+ await checkContainerHealth(res, {
+ failOnSigterm: false,
+ failIfEventPropagationStuck:
+ req.query.failIfEventPropagationStuck === "true",
+ });
} catch (e) {
traceException(e);
logger.error("Health check failed", e);
@@ -17,9 +21,13 @@ router.get<{}, { status: string }>("/health", async (_req, res) => {
}
});
-router.get<{}, { status: string }>("/ready", async (_req, res) => {
+router.get<{}, { status: string }>("/ready", async (req, res) => {
try {
- await checkContainerHealth(res, true);
+ await checkContainerHealth(res, {
+ failOnSigterm: true,
+ failIfEventPropagationStuck:
+ req.query.failIfEventPropagationStuck === "true",
+ });
} catch (e) {
traceException(e);
logger.error("Readiness check failed", e);
diff --git a/worker/src/env.ts b/worker/src/env.ts
index acdd8543a1..5517cb5e5b 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -495,6 +495,25 @@ const EnvSchema = z.object({
.int()
.default(10),
+ // Health-check threshold for the event-propagation ("dual write") job. When a
+ // client opts in via /api/health?failIfEventPropagationStuck=true, the check
+ // returns 503 if the heartbeat has not been refreshed within this many minutes,
+ // letting k8s liveness probes restart a container whose global-concurrency
+ // slot is wedged. The heartbeat is refreshed at the top of every invocation and
+ // per-chunk during the experiment backfill, so the threshold only needs to
+ // exceed the longest un-heartbeated step — a single CH INSERT (request_timeout
+ // 10 min). 15 min leaves headroom.
+ //
+ // Probes using this flag MUST set initialDelaySeconds >= 60s (one cron cycle):
+ // the heartbeat is only refreshed when the minute-boundary cron next runs, so a
+ // just-restarted (or just-re-enabled) container can carry a stale value until
+ // then. A shorter delay can crash-loop the very restart this check triggers.
+ LANGFUSE_EVENT_PROPAGATION_STUCK_THRESHOLD_MINUTES: z.coerce
+ .number()
+ .positive()
+ .int()
+ .default(15),
+
LANGFUSE_WEBHOOK_QUEUE_PROCESSING_CONCURRENCY: z.coerce
.number()
.positive()
diff --git a/worker/src/features/eventPropagation/handleEventPropagationJob.ts b/worker/src/features/eventPropagation/handleEventPropagationJob.ts
index 818f2a8914..e81a1b18f7 100644
--- a/worker/src/features/eventPropagation/handleEventPropagationJob.ts
+++ b/worker/src/features/eventPropagation/handleEventPropagationJob.ts
@@ -15,6 +15,43 @@ import { env } from "../../env";
const LAST_PROCESSED_PARTITION_KEY =
"langfuse:event-propagation:last-processed-partition";
+const LAST_RUN_STARTED_AT_KEY =
+ "langfuse:event-propagation:last-run-started-at";
+
+/**
+ * Record (in Redis) that a propagation run just started. Written at the top of
+ * every job invocation — including the no-op "nothing to process" path — and
+ * refreshed per-chunk as the experiment backfill progresses (both run under the
+ * same global-concurrency-1 slot), so its freshness reflects "the slot is still
+ * being worked / the queue is still being drained", independent of whether the
+ * cursor advanced. The health check uses staleness of this value to detect a
+ * wedged global-concurrency slot. Stored as epoch millis.
+ */
+export const updateLastRunStartedAt = async (): Promise<void> => {
+ try {
+ await redis!.set(LAST_RUN_STARTED_AT_KEY, Date.now().toString());
+ } catch (error) {
+ // Don't throw - a failed heartbeat write must not fail the job itself.
+ logger.error("[DUAL WRITE] Failed to update last run started at", error);
+ }
+};
+
+/**
+ * Read the last-run-started-at heartbeat (epoch millis) from Redis.
+ * Returns null if the job has never run yet or if Redis is unavailable.
+ */
+export const getLastRunStartedAt = async (): Promise<number | null> => {
+ try {
+ const value = await redis!.get(LAST_RUN_STARTED_AT_KEY);
+ if (value === null) return null;
+ const parsed = Number(value);
+ return Number.isNaN(parsed) ? null : parsed;
+ } catch (error) {
+ logger.error("[DUAL WRITE] Failed to get last run started at", error);
+ return null;
+ }
+};
+
/**
* Get the last processed partition timestamp from Redis.
* Returns null if no partition has been processed yet or if Redis is unavailable.
@@ -63,6 +100,10 @@ export const handleEventPropagationJob = async (
job.data.id,
);
+ // Heartbeat: record that a run started so the health check can detect a wedged
+ // (never-invoked) job even when the cursor legitimately has nothing to advance.
+ await updateLastRunStartedAt();
+
try {
// Step 1: Get the last processed partition from Redis and find the next one to process
const lastProcessedPartition = await getLastProcessedPartition();
diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
index 87236410ca..d4c2057810 100644
--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts
+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
@@ -10,6 +10,7 @@ import {
import { env } from "../../env";
import { ClickhouseWriter, TableName } from "../../services/ClickhouseWriter";
import { chunk } from "lodash";
+import { updateLastRunStartedAt } from "./handleEventPropagationJob";
const EXPERIMENT_BACKFILL_TIMESTAMP_KEY =
"langfuse:event-propagation:experiment-backfill:last-run";
@@ -924,6 +925,12 @@ async function processExperimentBackfill(
`[EXPERIMENT BACKFILL] Processing chunk ${i + 1}/${chunks.length} with ${driChunk.length} items`,
);
+ // Refresh the event-propagation heartbeat as each chunk begins. The backfill
+ // runs in the same global-concurrency-1 invocation as handleEventPropagationJob
+ // but can loop for minutes over a backlog; without this a long-but-live
+ // backfill would let the heartbeat go stale and trip the stuck health check.
+ await updateLastRunStartedAt();
+
// Extract project and trace IDs for this chunk
const projectIds = [...new Set(driChunk.map((dri) => dri.project_id))];
const traceIds = [...new Set(driChunk.map((dri) => dri.trace_id))];
diff --git a/worker/src/features/health/index.ts b/worker/src/features/health/index.ts
index 90a266fc60..e6deb7072f 100644
--- a/worker/src/features/health/index.ts
+++ b/worker/src/features/health/index.ts
@@ -2,14 +2,145 @@ import { prisma } from "@langfuse/shared/src/db";
import { logger, redis } from "@langfuse/shared/src/server";
import { Response } from "express";
+import { env } from "../../env";
+import {
+ getLastProcessedPartition,
+ getLastRunStartedAt,
+} from "../eventPropagation/handleEventPropagationJob";
+
+export type EventPropagationHealth = {
+ /** Whether the dual-write / event-propagation job runs in this deployment. */
+ enabled: boolean;
+ /** ISO timestamp of the last run start, or null if it has not run yet. */
+ lastRunStartedAt: string | null;
+ /** Seconds since the last run started, or null if it has not run yet. */
+ secondsSinceLastRun: number | null;
+ /** Informational: seconds between now and the last processed partition. */
+ propagationDelaySeconds: number | null;
+ /** Raw cursor value (partition timestamp) for debugging. */
+ lastProcessedPartition: string | null;
+ /** Staleness threshold that flips `stuck` to true. */
+ thresholdSeconds: number;
+ /** True when the job has not started a run within `thresholdSeconds`. */
+ stuck: boolean;
+};
+
+const isEventPropagationEnabled = (): boolean =>
+ env.QUEUE_CONSUMER_EVENT_PROPAGATION_QUEUE_IS_ENABLED === "true" &&
+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "dual";
+
+/**
+ * `stuck` is intentionally only true when we have a reading that exceeds the
+ * threshold. A missing heartbeat (job never ran yet — e.g. fresh boot or during
+ * a rollout) is treated as NOT stuck to avoid restart loops before the first
+ * scheduled run. A disabled job is never stuck.
+ */
+export const evaluateEventPropagationStuck = (input: {
+ enabled: boolean;
+ nowMs: number;
+ lastRunStartedAtMs: number | null;
+ lastProcessedPartition: string | null;
+ thresholdSeconds: number;
+}): EventPropagationHealth => {
+ const {
+ enabled,
+ nowMs,
+ lastRunStartedAtMs,
+ lastProcessedPartition,
+ thresholdSeconds,
+ } = input;
+
+ const secondsSinceLastRun =
+ lastRunStartedAtMs !== null
+ ? Math.max(0, Math.round((nowMs - lastRunStartedAtMs) / 1000))
+ : null;
+
+ let propagationDelaySeconds: number | null = null;
+ if (lastProcessedPartition) {
+ const partitionMs = new Date(lastProcessedPartition).getTime();
+ if (!Number.isNaN(partitionMs)) {
+ propagationDelaySeconds = Math.max(
+ 0,
+ Math.round((nowMs - partitionMs) / 1000),
+ );
+ }
+ }
+
+ const stuck =
+ enabled &&
+ secondsSinceLastRun !== null &&
+ secondsSinceLastRun > thresholdSeconds;
+
+ return {
+ enabled,
+ lastRunStartedAt:
+ lastRunStartedAtMs !== null
+ ? new Date(lastRunStartedAtMs).toISOString()
+ : null,
+ secondsSinceLastRun,
+ propagationDelaySeconds,
+ lastProcessedPartition: lastProcessedPartition ?? null,
+ thresholdSeconds,
+ stuck,
+ };
+};
+
+/**
+ * Fetch event-propagation health from Redis (cursor + run heartbeat) and
+ * evaluate it. Redis-only: no ClickHouse query, so it is cheap enough to run on
+ * every health probe.
+ */
+export const getEventPropagationHealth =
+ async (): Promise<EventPropagationHealth> => {
+ const thresholdSeconds =
+ env.LANGFUSE_EVENT_PROPAGATION_STUCK_THRESHOLD_MINUTES * 60;
+
+ if (!isEventPropagationEnabled()) {
+ return {
+ enabled: false,
+ lastRunStartedAt: null,
+ secondsSinceLastRun: null,
+ propagationDelaySeconds: null,
+ lastProcessedPartition: null,
+ thresholdSeconds,
+ stuck: false,
+ };
+ }
+
+ const [lastRunStartedAtMs, lastProcessedPartition] = await Promise.all([
+ getLastRunStartedAt(),
+ getLastProcessedPartition(),
+ ]);
+
+ return evaluateEventPropagationStuck({
+ enabled: true,
+ nowMs: Date.now(),
+ lastRunStartedAtMs,
+ lastProcessedPartition,
+ thresholdSeconds,
+ });
+ };
+
+type ContainerHealthOptions = {
+ /** Fail (500) once a SIGTERM/SIGINT has been received (readiness only). */
+ failOnSigterm: boolean;
+ /**
+ * Also fail (503) when the event-propagation job is stuck. Opt-in via the
+ * ?failIfEventPropagationStuck=true query parameter so only a dedicated probe
+ * pays the extra Redis lookups and only that probe forces a restart.
+ */
+ failIfEventPropagationStuck?: boolean;
+};
+
/**
* Check the health of the container.
- * If failOnSigterm is true, the health check will fail if a SIGTERM signal has been received.
*/
export const checkContainerHealth = async (
res: Response,
- failOnSigterm: boolean,
+ options: ContainerHealthOptions,
) => {
+ const { failOnSigterm, failIfEventPropagationStuck = false } = options;
+
if (failOnSigterm && isSigtermReceived()) {
logger.info(
"Health check failed: SIGTERM / SIGINT received, shutting down.",
@@ -36,6 +167,23 @@ export const checkContainerHealth = async (
),
]);
+ if (failIfEventPropagationStuck) {
+ const eventPropagation = await getEventPropagationHealth();
+ 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,
+ });
+ }
+ return res.json({
+ status: "ok",
+ eventPropagation,
+ });
+ }
+
res.json({
status: "ok",
});