🪢 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
fix(billing): implement chunked updates for free tier usage tracking (#9549)
Michael Fröhlich1354e0937f3a
diff --git a/worker/src/__tests__/thresholdProcessing.test.ts b/worker/src/__tests__/thresholdProcessing.test.tsindex 7d754b4f75..9b15c793cb 100644--- a/worker/src/__tests__/thresholdProcessing.test.ts+++ b/worker/src/__tests__/thresholdProcessing.test.ts@@ -62,61 +62,57 @@ describe("processThresholds", () => {it("detects first notification threshold crossing (50k)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 0 });- await processThresholds(org, 50_000);-- // Verify update was called with WARNING state (even though no emails sent due to empty admin list)- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 50_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ const result = await processThresholds(org, 50_000);++ // Verify updateData contains WARNING state (even though no emails sent due to empty admin list)+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 50_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});it("detects second notification threshold crossing (100k)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 60_000 });- await processThresholds(org, 100_000);+ const result = await processThresholds(org, 100_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 100_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 100_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});it("detects blocking threshold crossing (250k)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 150_000 });- await processThresholds(org, 250_000);+ const result = await processThresholds(org, 250_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 250_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "BLOCKED",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ shouldInvalidateCache: true, // Blocking state changed});});it("does not trigger when usage below threshold", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 0 });- await processThresholds(org, 40_000);+ const result = await processThresholds(org, 40_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 40_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: null,- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 40_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ shouldInvalidateCache: false,});});@@ -126,16 +122,15 @@ describe("processThresholds", () => {cloudFreeTierUsageThresholdState: "WARNING", // Already in WARNING state});- await processThresholds(org, 70_000);+ const result = await processThresholds(org, 70_000);// State-based: Should maintain WARNING state (above 50k threshold)- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 70_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 70_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});});@@ -144,45 +139,42 @@ describe("processThresholds", () => {it("triggers exactly at threshold (50k)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 49_999 });- await processThresholds(org, 50_000);+ const result = await processThresholds(org, 50_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 50_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 50_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});it("triggers exactly at threshold (100k)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 99_999 });- await processThresholds(org, 100_000);+ const result = await processThresholds(org, 100_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 100_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 100_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});it("triggers exactly at threshold (250k)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 249_999 });- await processThresholds(org, 250_000);+ const result = await processThresholds(org, 250_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 250_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "BLOCKED",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ shouldInvalidateCache: true,});});});@@ -191,46 +183,43 @@ describe("processThresholds", () => {it("crosses both notification thresholds in one run (0 -> 150k)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 0 });- await processThresholds(org, 150_000);+ const result = await processThresholds(org, 150_000);// Should send notification for highest threshold (100k), not 50k- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 150_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 150_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});it("crosses all thresholds in one run (0 -> 250k)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 0 });- await processThresholds(org, 250_000);+ const result = await processThresholds(org, 250_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 250_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "BLOCKED",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ shouldInvalidateCache: true,});});it("crosses from 50k to 250k (skips intermediate notifications)", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: 50_000 });- await processThresholds(org, 250_000);+ const result = await processThresholds(org, 250_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 250_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "BLOCKED",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ shouldInvalidateCache: true,});});});@@ -243,16 +232,15 @@ describe("processThresholds", () => {});// Already processed 60k (past 50k threshold), now at 70k (still below 100k)- await processThresholds(org, 70_000);+ const result = await processThresholds(org, 70_000);// State-based: Should maintain WARNING state, not send email (no state transition)- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 70_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 70_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});@@ -263,16 +251,15 @@ describe("processThresholds", () => {});// Already blocked at 250k, now at 260k- await processThresholds(org, 260_000);+ const result = await processThresholds(org, 260_000);// State-based: Should maintain BLOCKED state, not send email (no state transition)- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 260_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "BLOCKED",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 260_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ shouldInvalidateCache: false,});});});@@ -281,30 +268,28 @@ describe("processThresholds", () => {it("treats null cloudCurrentCycleUsage as 0", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: null });- await processThresholds(org, 50_000);+ const result = await processThresholds(org, 50_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 50_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 50_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});it("treats undefined cloudCurrentCycleUsage as 0", async () => {const org = createMockOrg({ cloudCurrentCycleUsage: undefined as any });- await processThresholds(org, 50_000);+ const result = await processThresholds(org, 50_000);- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 50_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "WARNING",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 50_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ shouldInvalidateCache: false,});});});@@ -314,21 +299,19 @@ describe("processThresholds", () => {const org = createMockOrg({ cloudCurrentCycleUsage: 0 });const beforeTime = new Date();- await processThresholds(org, 30_000);+ const result = await processThresholds(org, 30_000);const afterTime = new Date();- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 30_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: null,- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 30_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ shouldInvalidateCache: false,});- const updateCall = mockOrgUpdate.mock.calls[0][0];- const updatedAt = updateCall.data.cloudBillingCycleUpdatedAt as Date;+ const updatedAt = result.updateData.cloudBillingCycleUpdatedAt;expect(updatedAt.getTime()).toBeGreaterThanOrEqual(beforeTime.getTime());expect(updatedAt.getTime()).toBeLessThanOrEqual(afterTime.getTime());@@ -354,13 +337,12 @@ describe("processThresholds", () => {const result = await processThresholdsDisabled(org, 250_000);// Should track usage but not set state- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 250_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: null,- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ shouldInvalidateCache: false,});// Should return ENFORCEMENT_DISABLED@@ -392,16 +374,15 @@ describe("processThresholds", () => {cloudFreeTierUsageThresholdState: "BLOCKED",});- await processThresholdsDisabled(org, 260_000);+ const result = await processThresholdsDisabled(org, 260_000);// Should clear the state when enforcement is disabled- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 260_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: null,- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 260_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ shouldInvalidateCache: false,});// Restore original env@@ -427,13 +408,12 @@ describe("processThresholds", () => {const result = await processThresholdsEnabled(org, 250_000);// Should enforce and block- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 250_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: "BLOCKED",- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ shouldInvalidateCache: true,});expect(result.actionTaken).toBe("BLOCKED");@@ -470,13 +450,12 @@ describe("processThresholds", () => {const result = await processThresholdsEnabled(org, 250_000);// Should not enforce for paid plan- expect(mockOrgUpdate).toHaveBeenCalledWith({- where: { id: "org-1" },- data: {- cloudCurrentCycleUsage: 250_000,- cloudBillingCycleUpdatedAt: expect.any(Date),- cloudFreeTierUsageThresholdState: null,- },+ expect(result.updateData).toEqual({+ orgId: "org-1",+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ shouldInvalidateCache: false,});expect(result.actionTaken).toBe("PAID_PLAN");diff --git a/worker/src/__tests__/usageThresholdCacheInvalidation.test.ts b/worker/src/__tests__/usageThresholdCacheInvalidation.test.tsindex 5aaa1b7dd4..53bc57a6f1 100644--- a/worker/src/__tests__/usageThresholdCacheInvalidation.test.ts+++ b/worker/src/__tests__/usageThresholdCacheInvalidation.test.ts@@ -8,6 +8,7 @@ import {createShaHash,} from "@langfuse/shared/src/server";import { processThresholds } from "../ee/usageThresholds/thresholdProcessing";+import { bulkUpdateOrganizations } from "../ee/usageThresholds/bulkUpdates";// Enable enforcement feature flag for testsvi.hoisted(() => {@@ -155,7 +156,10 @@ describe("Usage Threshold Cache Invalidation", () => {updatedAt: new Date("2024-01-01T00:00:00Z"),};- await processThresholds(org, 250_000); // Cross blocking threshold+ const result = await processThresholds(org, 250_000); // Cross blocking threshold++ // Execute bulk update to complete the process (including cache invalidation)+ await bulkUpdateOrganizations([result.updateData]);// Step 3: Verify cache was invalidatedconst cachedAfter = await redis.get(`api-key:${fastHashedKey}`);@@ -256,7 +260,10 @@ describe("Usage Threshold Cache Invalidation", () => {updatedAt: new Date("2024-01-01T00:00:00Z"),};- await processThresholds(org, 300_000); // Still high usage but paid plan+ const result = await processThresholds(org, 300_000); // Still high usage but paid plan++ // Execute bulk update to complete the process (including cache invalidation)+ await bulkUpdateOrganizations([result.updateData]);// Step 4: Verify cache was invalidatedconst cachedAfter = await redis.get(`api-key:${fastHashedKey}`);@@ -327,7 +334,10 @@ describe("Usage Threshold Cache Invalidation", () => {updatedAt: new Date("2024-01-01T00:00:00Z"),};- await processThresholds(org, 40_000); // Still below thresholds+ const result = await processThresholds(org, 40_000); // Still below thresholds++ // Execute bulk update to complete the process+ await bulkUpdateOrganizations([result.updateData]);// Step 3: Verify cache was NOT invalidated (state didn't change)const cachedAfter = await redis.get(`api-key:${fastHashedKey}`);@@ -440,7 +450,10 @@ describe("Usage Threshold Cache Invalidation", () => {updatedAt: new Date("2024-01-01T00:00:00Z"),};- await processThresholds(org, 250_000);+ const result = await processThresholds(org, 250_000);++ // Execute bulk update to complete the process (including cache invalidation)+ await bulkUpdateOrganizations([result.updateData]);// Verify both keys were invalidatedexpect(await redis.get(`api-key:${fastHashedKey1}`)).toBeNull();diff --git a/worker/src/ee/usageThresholds/bulkUpdates.ts b/worker/src/ee/usageThresholds/bulkUpdates.tsnew file mode 100644index 0000000000..604e324ad2--- /dev/null+++ b/worker/src/ee/usageThresholds/bulkUpdates.ts@@ -0,0 +1,248 @@+import { prisma } from "@langfuse/shared/src/db";+import {+ logger,+ invalidateCachedOrgApiKeys,+ traceException,+} from "@langfuse/shared/src/server";+import type { OrgUpdateData } from "./thresholdProcessing";++/**+ * Result of bulk update operation+ */+export type BulkUpdateResult = {+ successCount: number;+ failedCount: number;+ failedOrgIds: string[];+};++/**+ * Default chunk size for bulk operations+ * 1000 orgs per transaction provides good balance between:+ * - Reducing round trips (vs individual updates)+ * - Not overwhelming single transaction (vs all at once)+ * - Memory usage (~100KB per chunk)+ */+const DEFAULT_CHUNK_SIZE = 1000;++/**+ * Bulk update organizations with per-chunk transactions+ *+ * Behavior:+ * - Each chunk of org updates is executed within a single transaction+ * - If any update in the chunk fails, the entire chunk is rolled back+ * - Failed chunks are reported via traceException and all orgs in the chunk are marked failed+ * - Successful chunks commit all org updates in that chunk+ *+ * @param updates - Array of org update data+ * @param chunkSize - Optional chunk size (default: 1000)+ * @returns Summary of successful/failed updates+ */+export async function bulkUpdateOrganizations(+ updates: OrgUpdateData[],+ chunkSize: number = DEFAULT_CHUNK_SIZE,+): Promise<BulkUpdateResult> {+ if (updates.length === 0) {+ return { successCount: 0, failedCount: 0, failedOrgIds: [] };+ }++ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Starting bulk update (Transaction) for ${updates.length} organizations in chunks of ${chunkSize}`,+ );++ let successCount = 0;+ const failedOrgIds: string[] = [];++ // Split into chunks+ for (let i = 0; i < updates.length; i += chunkSize) {+ const chunk = updates.slice(i, i + chunkSize);+ const chunkNumber = Math.floor(i / chunkSize) + 1;+ const totalChunks = Math.ceil(updates.length / chunkSize);++ try {+ // Execute all updates in this chunk within a single transaction+ await prisma.$transaction(+ chunk.map((update) =>+ prisma.organization.update({+ where: { id: update.orgId },+ data: {+ cloudCurrentCycleUsage: update.cloudCurrentCycleUsage,+ cloudBillingCycleUpdatedAt: update.cloudBillingCycleUpdatedAt,+ cloudFreeTierUsageThresholdState:+ update.cloudFreeTierUsageThresholdState,+ },+ }),+ ),+ );++ successCount += chunk.length;++ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Chunk ${chunkNumber}/${totalChunks}: ${chunk.length} succeeded`,+ );++ // Invalidate caches for orgs in this successful chunk that need it+ const orgsNeedingCacheInvalidation = chunk.filter(+ (u) => u.shouldInvalidateCache,+ );++ for (const update of orgsNeedingCacheInvalidation) {+ try {+ await invalidateCachedOrgApiKeys(update.orgId);+ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Invalidated API key cache for org ${update.orgId}`,+ );+ } catch (cacheError) {+ // Cache invalidation failure shouldn't fail the update+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] Failed to invalidate cache for org ${update.orgId}`,+ cacheError,+ );+ traceException(cacheError);+ }+ }+ } catch (error) {+ // Entire chunk failed - report and mark all orgs in this chunk as failed+ traceException(error);+ const chunkOrgIds = chunk.map((u) => u.orgId);+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] Failed to update chunk ${chunkNumber}/${totalChunks} (Transaction)`,+ {+ chunkSize: chunk.length,+ chunkIndex: chunkNumber - 1,+ orgIds: chunkOrgIds,+ error,+ },+ );+ failedOrgIds.push(...chunkOrgIds);+ }+ }++ const failedCount = failedOrgIds.length;+ const result = { successCount, failedCount, failedOrgIds };++ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Bulk update (Promise.allSettled) completed`,+ result,+ );++ return result;+}++/**+ * Bulk update organizations using raw SQL batch UPDATE (single query per chunk)+ *+ * This is the Option 1 implementation using PostgreSQL VALUES clause for true bulk updates.+ * Much faster than Promise.allSettled but loses per-org error granularity.+ *+ * Error handling:+ * - Entire chunk succeeds or fails as a unit+ * - Failed chunks reported to Datadog via traceException+ * - Successful chunks are committed+ *+ * @param updates - Array of org update data+ * @param chunkSize - Optional chunk size (default: 10 for testing)+ * @returns Summary of successful/failed updates+ */+export async function bulkUpdateOrganizationsRawSQL(+ updates: OrgUpdateData[],+ chunkSize: number = DEFAULT_CHUNK_SIZE,+): Promise<BulkUpdateResult> {+ if (updates.length === 0) {+ return { successCount: 0, failedCount: 0, failedOrgIds: [] };+ }++ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Starting bulk update (Raw SQL) for ${updates.length} organizations in chunks of ${chunkSize}`,+ );++ let successCount = 0;+ const failedOrgIds: string[] = [];++ // Split into chunks+ for (let i = 0; i < updates.length; i += chunkSize) {+ const chunk = updates.slice(i, i + chunkSize);+ const chunkNumber = Math.floor(i / chunkSize) + 1;+ const totalChunks = Math.ceil(updates.length / chunkSize);++ try {+ // Build VALUES clause: (id, usage, updated_at, state)+ const valuesClauses = chunk+ .map((_, idx) => {+ const base = idx * 4; // 4 parameters per org+ return `($${base + 1}, $${base + 2}::integer, $${base + 3}::timestamptz, $${base + 4})`;+ })+ .join(", ");++ const params = chunk.flatMap((update) => [+ update.orgId,+ update.cloudCurrentCycleUsage,+ update.cloudBillingCycleUpdatedAt,+ update.cloudFreeTierUsageThresholdState,+ ]);++ // Execute single bulk UPDATE for entire chunk+ await prisma.$executeRawUnsafe(+ `UPDATE organizations AS o SET+ cloud_current_cycle_usage = v.usage::integer,+ cloud_billing_cycle_updated_at = v.updated_at::timestamptz,+ cloud_free_tier_usage_threshold_state = v.state+ FROM (VALUES ${valuesClauses}) AS v(id, usage, updated_at, state)+ WHERE o.id::text = v.id::text`,+ ...params,+ );++ successCount += chunk.length;++ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Chunk ${chunkNumber}/${totalChunks}: ${chunk.length} succeeded (Raw SQL)`,+ );++ // Handle cache invalidation for orgs in this successful chunk+ const orgsNeedingCacheInvalidation = chunk.filter(+ (u) => u.shouldInvalidateCache,+ );++ for (const update of orgsNeedingCacheInvalidation) {+ try {+ await invalidateCachedOrgApiKeys(update.orgId);+ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Invalidated API key cache for org ${update.orgId}`,+ );+ } catch (cacheError) {+ // Cache invalidation failure shouldn't fail the update+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] Failed to invalidate cache for org ${update.orgId}`,+ cacheError,+ );+ traceException(cacheError);+ }+ }+ } catch (error) {+ // Entire chunk failed - report to Datadog but continue processing+ traceException(error);++ const chunkOrgIds = chunk.map((u) => u.orgId);+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] Failed to update chunk ${chunkNumber}/${totalChunks} (Raw SQL)`,+ {+ chunkSize: chunk.length,+ chunkIndex: chunkNumber - 1,+ orgIds: chunkOrgIds,+ error,+ },+ );++ failedOrgIds.push(...chunkOrgIds);+ }+ }++ const failedCount = failedOrgIds.length;+ const result = { successCount, failedCount, failedOrgIds };++ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Bulk update (Raw SQL) completed`,+ result,+ );++ return result;+}diff --git a/worker/src/ee/usageThresholds/thresholdProcessing.ts b/worker/src/ee/usageThresholds/thresholdProcessing.tsindex aec432db8b..aff557f7aa 100644--- a/worker/src/ee/usageThresholds/thresholdProcessing.ts+++ b/worker/src/ee/usageThresholds/thresholdProcessing.ts@@ -5,7 +5,6 @@ import {sendUsageThresholdWarningEmail,sendUsageThresholdSuspensionEmail,logger,- invalidateCachedOrgApiKeys,recordIncrement,traceException,getBillingCycleEnd,@@ -253,6 +252,17 @@ async function sendBlockingNotificationEmail(return { emailSent, emailFailed };}+/**+ * Data needed to update an organization's usage tracking fields+ */+export type OrgUpdateData = {+ orgId: string;+ cloudCurrentCycleUsage: number;+ cloudBillingCycleUpdatedAt: Date;+ cloudFreeTierUsageThresholdState: string | null;+ shouldInvalidateCache: boolean; // For API key cache invalidation+};+/*** Action taken during threshold processing*/@@ -265,6 +275,7 @@ export type ThresholdProcessingResult = {| "NONE";emailSent: boolean;emailFailed: boolean;+ updateData: OrgUpdateData; // Update data to be executed in bulk};/**@@ -290,46 +301,46 @@ export async function processThresholds(): Promise<ThresholdProcessingResult> {// 1. Skip notifications if org is on a paid plan (check this first, regardless of enforcement flag)if (org.cloudConfig?.stripe?.activeSubscriptionId) {- await prisma.organization.update({- where: { id: org.id },- data: {- cloudCurrentCycleUsage: cumulativeUsage,- cloudBillingCycleUpdatedAt: new Date(),- cloudFreeTierUsageThresholdState: null,- },- });+ // Build update data+ const updateData: OrgUpdateData = {+ orgId: org.id,+ cloudCurrentCycleUsage: cumulativeUsage,+ cloudBillingCycleUpdatedAt: new Date(),+ cloudFreeTierUsageThresholdState: null,+ // If org was previously blocked, invalidate cache+ shouldInvalidateCache: org.cloudFreeTierUsageThresholdState === "BLOCKED",+ };- // If org was previously blocked, invalidate cache- if (org.cloudFreeTierUsageThresholdState === "BLOCKED") {+ if (updateData.shouldInvalidateCache) {logger.info(- `[FREE TIER USAGE THRESHOLDS] Org ${org.id} moved to paid plan, was previously blocked, invalidating API key cache`,+ `[FREE TIER USAGE THRESHOLDS] Org ${org.id} moved to paid plan, was previously blocked, will invalidate API key cache`,);- await invalidateCachedOrgApiKeys(org.id);}return {actionTaken: "PAID_PLAN",emailSent: false,emailFailed: false,+ updateData,};}// 2. Check if enforcement is enabled (only for free tier orgs)if (env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED !== "true") {// Always track usage even when enforcement is disabled- await prisma.organization.update({- where: { id: org.id },- data: {- cloudCurrentCycleUsage: cumulativeUsage,- cloudBillingCycleUpdatedAt: new Date(),- cloudFreeTierUsageThresholdState: null,- },- });+ const updateData: OrgUpdateData = {+ orgId: org.id,+ cloudCurrentCycleUsage: cumulativeUsage,+ cloudBillingCycleUpdatedAt: new Date(),+ cloudFreeTierUsageThresholdState: null,+ shouldInvalidateCache: false,+ };return {actionTaken: "ENFORCEMENT_DISABLED",emailSent: false,emailFailed: false,+ updateData,};}@@ -398,28 +409,26 @@ export async function processThresholds(emailFailed = emailResult.emailFailed;}- // 6. Update last processed usage in DB with current state- await prisma.organization.update({- where: { id: org.id },- data: {- cloudCurrentCycleUsage: cumulativeUsage,- cloudBillingCycleUpdatedAt: new Date(), // Stored as UTC in timestamptz column- cloudFreeTierUsageThresholdState: currentState,- },- });-- // 7. Invalidate API key cache if blocking state changed+ // 6. Determine if API key cache should be invalidatedconst blockingStateChanged =(previousState === "BLOCKED" && currentState !== "BLOCKED") ||(previousState !== "BLOCKED" && currentState === "BLOCKED");if (blockingStateChanged) {logger.info(- `[FREE TIER USAGE THRESHOLDS] Blocking state changed for org ${org.id}, invalidating API key cache`,+ `[FREE TIER USAGE THRESHOLDS] Blocking state changed for org ${org.id}, will invalidate API key cache`,);- await invalidateCachedOrgApiKeys(org.id);}+ // 7. Build update data (to be executed in bulk)+ const updateData: OrgUpdateData = {+ orgId: org.id,+ cloudCurrentCycleUsage: cumulativeUsage,+ cloudBillingCycleUpdatedAt: new Date(), // Stored as UTC in timestamptz column+ cloudFreeTierUsageThresholdState: currentState,+ shouldInvalidateCache: blockingStateChanged,+ };+// 8. Return result for metrics trackingconst actionTaken =currentState === "BLOCKED"@@ -431,5 +440,6 @@ export async function processThresholds(actionTaken,emailSent,emailFailed,+ updateData,};}diff --git a/worker/src/ee/usageThresholds/usageAggregation.ts b/worker/src/ee/usageThresholds/usageAggregation.tsindex 0ee51d5086..4887e45d30 100644--- a/worker/src/ee/usageThresholds/usageAggregation.ts+++ b/worker/src/ee/usageThresholds/usageAggregation.ts@@ -16,7 +16,9 @@ import { logger } from "@langfuse/shared/src/server";import {processThresholds,type ThresholdProcessingResult,+ type OrgUpdateData,} from "./thresholdProcessing";+import { bulkUpdateOrganizationsRawSQL } from "./bulkUpdates";/*** Map of projectId to orgId@@ -144,7 +146,12 @@ function aggregateByOrg(/*** Statistics returned from usage aggregation processing*/-export type UsageAggregationStats = {};+export type UsageAggregationStats = {+ totalOrgsProcessed: number;+ totalOrgsUpdatedSuccessfully: number;+ totalOrgsFailed: number;+ failedOrgIds: string[];+};/*** Main orchestrator: Process usage aggregation for all organizations@@ -199,7 +206,12 @@ export async function processUsageAggregationForAllOrgs(}// Initialize statistics tracking- const stats: UsageAggregationStats = {};+ const stats: UsageAggregationStats = {+ totalOrgsProcessed: 0,+ totalOrgsUpdatedSuccessfully: 0,+ totalOrgsFailed: 0,+ failedOrgIds: [],+ };// Calculate how many days to look back (based on previous month's length)const daysToLookBack = getDaysToLookBack(normalizedReferenceDate);@@ -251,6 +263,9 @@ export async function processUsageAggregationForAllOrgs(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) {@@ -259,6 +274,9 @@ export async function processUsageAggregationForAllOrgs(state.total,);+ // Collect the update data for bulk processing+ updatesToProcess.push(result.updateData);+// Track statistics with incrementsrecordIncrement("langfuse.queue.usage_threshold_queue.total_orgs", 1, {unit: "organizations",@@ -285,6 +303,30 @@ export async function processUsageAggregationForAllOrgs(}}+ // Execute bulk update after processing all orgs for this day+ if (updatesToProcess.length > 0) {+ const bulkResult = await bulkUpdateOrganizationsRawSQL(updatesToProcess);++ 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 progressif (onProgress) {const progress = (daysAgo + 1) / totalDays;