Skip to content

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

chore(worker): harden cloud free tier usage threshold job (#13322)

Steffen Schmitz76b019cdfef2
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 7f61f077f3..2946d90c99 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -2019,6 +2019,7 @@ export const getObservationCountsByProjectAndDay = async ({
startDate: convertDateToClickhouseDateTime(startDate),
endDate: convertDateToClickhouseDateTime(endDate),
},
+ clickhouseConfigs: { request_timeout: 120_000 },
tags: {
feature: "tracing",
type: "observation",
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 5d2e5a57ad..cbf07eff9e 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -2281,6 +2281,7 @@ export const getScoreCountsByProjectAndDay = async ({
endDate: convertDateToClickhouseDateTime(endDate),
dataTypes: LISTABLE_SCORE_TYPES,
},
+ clickhouseConfigs: { request_timeout: 120_000 },
tags: {
feature: "tracing",
type: "score",
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 3b7a749032..92abdb1aa9 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -1641,6 +1641,7 @@ export const getTraceCountsByProjectAndDay = async ({
startDate: convertDateToClickhouseDateTime(startDate),
endDate: convertDateToClickhouseDateTime(endDate),
},
+ clickhouseConfigs: { request_timeout: 120_000 },
tags: {
feature: "tracing",
type: "trace",
diff --git a/worker/src/ee/usageThresholds/usageAggregation.ts b/worker/src/ee/usageThresholds/usageAggregation.ts
index 2b3829866e..815e4caccc 100644
--- a/worker/src/ee/usageThresholds/usageAggregation.ts
+++ b/worker/src/ee/usageThresholds/usageAggregation.ts
@@ -8,10 +8,12 @@ import {
endOfDayUTC,
getDaysToLookBack,
recordIncrement,
+ instrumentAsync,
} from "@langfuse/shared/src/server";
import { parseDbOrg, type ParsedOrganization } from "@langfuse/shared";
import { logger } from "@langfuse/shared/src/server";
+import { backOff } from "exponential-backoff";
import {
processThresholds,
@@ -20,6 +22,23 @@ import {
} from "./thresholdProcessing";
import { bulkUpdateOrganizationsRawSQL } from "./bulkUpdates";
+const DAILY_QUERY_MAX_ATTEMPTS = 3;
+
+async function withRetry<T>(label: string, fn: () => Promise<T>): Promise<T> {
+ return backOff(fn, {
+ numOfAttempts: DAILY_QUERY_MAX_ATTEMPTS,
+ startingDelay: 500,
+ timeMultiple: 2,
+ retry: (error: Error, attemptNumber: number) => {
+ logger.warn(
+ `[FREE TIER USAGE THRESHOLDS] ${label} failed (attempt ${attemptNumber}/${DAILY_QUERY_MAX_ATTEMPTS}): ${error.message}`,
+ { error: error.message, attemptNumber },
+ );
+ return attemptNumber < DAILY_QUERY_MAX_ATTEMPTS;
+ },
+ });
+}
+
/**
* Map of projectId to orgId
*/
@@ -230,102 +249,135 @@ export async function processUsageAggregationForAllOrgs(
const dayEnd =
daysAgo === 0 ? normalizedReferenceDate : endOfDayUTC(dayDate);
- // Fetch counts from Clickhouse (3 queries for ALL projects)
- const [traceCounts, obsCounts, scoreCounts] = await Promise.all([
- getTraceCountsByProjectAndDay({ startDate: dayStart, endDate: dayEnd }),
- getObservationCountsByProjectAndDay({
- startDate: dayStart,
- endDate: dayEnd,
- }),
- getScoreCountsByProjectAndDay({ startDate: dayStart, endDate: dayEnd }),
- ]);
-
- // Aggregate to org level
- const orgDailyCounts = aggregateByOrg(
- traceCounts,
- obsCounts,
- scoreCounts,
- projectToOrgMap,
- );
-
- // Accumulate for all orgs and previous days
- for (const [orgId, counts] of Object.entries(orgDailyCounts)) {
- const state = usageByOrgMap[orgId];
- if (state) {
- state.traces += counts.traces;
- state.observations += counts.observations;
- state.scores += counts.scores;
- state.total += counts.total;
- }
- }
-
- // Process orgs with billing cycle starting THIS day
const dayDateString = dayStart.toISOString().split("T")[0];
- const orgsToProcess = orgsByBillingStartMap.get(dayDateString) || [];
-
- // Collect updates instead of executing immediately
- const updatesToProcess: OrgUpdateData[] = [];
- for (const org of orgsToProcess) {
- const state = usageByOrgMap[org.id];
- if (state) {
- const result: ThresholdProcessingResult = await processThresholds(
- org,
- state.total,
+ await instrumentAsync(
+ { name: "cloud-free-tier-usage-threshold-day" },
+ async (span) => {
+ span.setAttribute(
+ "langfuse.free_tier.dayStart",
+ dayStart.toISOString(),
+ );
+ span.setAttribute("langfuse.free_tier.dayEnd", dayEnd.toISOString());
+ span.setAttribute("langfuse.free_tier.dayDate", dayDateString);
+ span.setAttribute("langfuse.free_tier.daysAgo", daysAgo);
+
+ // Fetch counts from Clickhouse (3 queries for ALL projects).
+ // Each query gets an extended timeout and automatic retries — a single
+ // re-run is cheap compared to failing the whole job.
+ const [traceCounts, obsCounts, scoreCounts] = await Promise.all([
+ withRetry("getTraceCountsByProjectAndDay", () =>
+ getTraceCountsByProjectAndDay({
+ startDate: dayStart,
+ endDate: dayEnd,
+ }),
+ ),
+ withRetry("getObservationCountsByProjectAndDay", () =>
+ getObservationCountsByProjectAndDay({
+ startDate: dayStart,
+ endDate: dayEnd,
+ }),
+ ),
+ withRetry("getScoreCountsByProjectAndDay", () =>
+ getScoreCountsByProjectAndDay({
+ startDate: dayStart,
+ endDate: dayEnd,
+ }),
+ ),
+ ]);
+
+ // Aggregate to org level
+ const orgDailyCounts = aggregateByOrg(
+ traceCounts,
+ obsCounts,
+ scoreCounts,
+ projectToOrgMap,
);
- // Collect the update data for bulk processing
- updatesToProcess.push(result.updateData);
-
- // Track statistics with increments
- recordIncrement("langfuse.queue.usage_threshold_queue.total_orgs", 1, {
- unit: "organizations",
- });
-
- if (result.actionTaken === "PAID_PLAN") {
- recordIncrement(
- "langfuse.queue.usage_threshold_queue.paid_plan_orgs",
- 1,
- {
- unit: "organizations",
- },
- );
- } else {
- // Count as free tier if not paid plan
- recordIncrement(
- "langfuse.queue.usage_threshold_queue.free_tier_orgs",
- 1,
- {
- unit: "organizations",
- },
- );
+ // Accumulate for all orgs and previous days
+ for (const [orgId, counts] of Object.entries(orgDailyCounts)) {
+ const state = usageByOrgMap[orgId];
+ if (state) {
+ state.traces += counts.traces;
+ state.observations += counts.observations;
+ state.scores += counts.scores;
+ state.total += counts.total;
+ }
}
- }
- }
- // Execute bulk update after processing all orgs for this day
- if (updatesToProcess.length > 0) {
- const bulkResult = await bulkUpdateOrganizationsRawSQL(updatesToProcess);
+ // Process orgs with billing cycle starting THIS day
+ const orgsToProcess = orgsByBillingStartMap.get(dayDateString) || [];
+
+ // Collect updates instead of executing immediately
+ const updatesToProcess: OrgUpdateData[] = [];
+
+ for (const org of orgsToProcess) {
+ const state = usageByOrgMap[org.id];
+ if (state) {
+ const result: ThresholdProcessingResult = await processThresholds(
+ org,
+ state.total,
+ );
+
+ // Collect the update data for bulk processing
+ updatesToProcess.push(result.updateData);
+
+ // Track statistics with increments
+ recordIncrement(
+ "langfuse.queue.usage_threshold_queue.total_orgs",
+ 1,
+ {
+ unit: "organizations",
+ },
+ );
+
+ if (result.actionTaken === "PAID_PLAN") {
+ recordIncrement(
+ "langfuse.queue.usage_threshold_queue.paid_plan_orgs",
+ 1,
+ {
+ unit: "organizations",
+ },
+ );
+ } else {
+ // Count as free tier if not paid plan
+ recordIncrement(
+ "langfuse.queue.usage_threshold_queue.free_tier_orgs",
+ 1,
+ {
+ unit: "organizations",
+ },
+ );
+ }
+ }
+ }
- logger.info(
- `[FREE TIER USAGE THRESHOLDS] Day ${dayDateString}: Bulk updated ${bulkResult.successCount} orgs, ${bulkResult.failedCount} failed`,
- );
+ // Execute bulk update after processing all orgs for this day
+ if (updatesToProcess.length > 0) {
+ const bulkResult =
+ await bulkUpdateOrganizationsRawSQL(updatesToProcess);
- // Track bulk update statistics
- stats.totalOrgsProcessed += updatesToProcess.length;
- stats.totalOrgsUpdatedSuccessfully += bulkResult.successCount;
- stats.totalOrgsFailed += bulkResult.failedCount;
- stats.failedOrgIds.push(...bulkResult.failedOrgIds);
-
- // Track bulk update failures metric
- if (bulkResult.failedCount > 0) {
- recordIncrement(
- "langfuse.queue.usage_threshold_queue.bulk_update_failures",
- bulkResult.failedCount,
- { unit: "organizations" },
- );
- }
- }
+ logger.info(
+ `[FREE TIER USAGE THRESHOLDS] Day ${dayDateString}: Bulk updated ${bulkResult.successCount} orgs, ${bulkResult.failedCount} failed`,
+ );
+
+ // Track bulk update statistics
+ stats.totalOrgsProcessed += updatesToProcess.length;
+ stats.totalOrgsUpdatedSuccessfully += bulkResult.successCount;
+ stats.totalOrgsFailed += bulkResult.failedCount;
+ stats.failedOrgIds.push(...bulkResult.failedOrgIds);
+
+ // Track bulk update failures metric
+ if (bulkResult.failedCount > 0) {
+ recordIncrement(
+ "langfuse.queue.usage_threshold_queue.bulk_update_failures",
+ bulkResult.failedCount,
+ { unit: "organizations" },
+ );
+ }
+ }
+ },
+ );
// Update progress
if (onProgress) {
diff --git a/worker/src/queues/cloudFreeTierUsageThresholdQueue.ts b/worker/src/queues/cloudFreeTierUsageThresholdQueue.ts
index 3fc6b4a349..7161d50763 100644
--- a/worker/src/queues/cloudFreeTierUsageThresholdQueue.ts
+++ b/worker/src/queues/cloudFreeTierUsageThresholdQueue.ts
@@ -1,36 +1,50 @@
import { Processor } from "bullmq";
-import { logger, QueueJobs } from "@langfuse/shared/src/server";
+import {
+ instrumentAsync,
+ logger,
+ QueueJobs,
+} from "@langfuse/shared/src/server";
import { handleCloudFreeTierUsageThresholdJob } from "../ee/usageThresholds/handleCloudFreeTierUsageThresholdJob";
+import { SpanKind } from "@opentelemetry/api";
export const cloudFreeTierUsageThresholdQueueProcessor: Processor = async (
job,
) => {
if (job.name === QueueJobs.CloudFreeTierUsageThresholdJob) {
- logger.info(
- "[CloudFreeTierUsageThresholdJob] Executing Free Tier Usage Threshold Job",
+ return await instrumentAsync(
{
- jobId: job.id,
- jobName: job.name,
- jobData: job.data,
- timestamp: new Date().toISOString(),
- opts: {
- repeat: job.opts.repeat,
- jobId: job.opts.jobId,
- },
+ name: "process cloud-free-tier-usage-threshold",
+ startNewTrace: true,
+ spanKind: SpanKind.CONSUMER,
+ },
+ async () => {
+ logger.info(
+ "[CloudFreeTierUsageThresholdJob] Executing Free Tier Usage Threshold Job",
+ {
+ jobId: job.id,
+ jobName: job.name,
+ jobData: job.data,
+ timestamp: new Date().toISOString(),
+ opts: {
+ repeat: job.opts.repeat,
+ jobId: job.opts.jobId,
+ },
+ },
+ );
+ try {
+ return await handleCloudFreeTierUsageThresholdJob(job);
+ } catch (error) {
+ logger.error(
+ "[CloudFreeTierUsageThresholdJob] Error executing Free Tier Usage Threshold Job",
+ {
+ jobId: job.id,
+ error: error,
+ timestamp: new Date().toISOString(),
+ },
+ );
+ throw error;
+ }
},
);
- try {
- return await handleCloudFreeTierUsageThresholdJob(job);
- } catch (error) {
- logger.error(
- "[CloudFreeTierUsageThresholdJob] Error executing Free Tier Usage Threshold Job",
- {
- jobId: job.id,
- error: error,
- timestamp: new Date().toISOString(),
- },
- );
- throw error;
- }
}
};