🪢 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): enhance free tier usage emails with pricing, reset dates, and CRM integration (#9547)
Michael Fröhlicha2da9a51b379
diff --git a/.env.dev.example b/.env.dev.exampleindex bbe8d382ee..01503dcad4 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -33,6 +33,7 @@ SALT="salt"EMAIL_FROM_ADDRESS="" # Defines the email address to use as the from address.SMTP_CONNECTION_URL="" # Defines the connection url for smtp server.+CLOUD_CRM_EMAIL="" # Optional BCC address for usage threshold emails (e.g., for CRM integration like HubSpot)# S3 Batch ExportsLANGFUSE_S3_BATCH_EXPORT_ENABLED=truediff --git a/.env.prod.example b/.env.prod.exampleindex a7989f48db..7b3f2ee60b 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -275,6 +275,8 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# QUEUE_CONSUMER_FREE_TIER_USAGE_THRESHOLD_QUEUE_IS_ENABLED=true# Enable enforcement: send emails and block orgs that exceed free tier limits (default: false)# LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED=false+# Optional BCC address for usage threshold emails (e.g., for CRM integration like HubSpot)+# CLOUD_CRM_EMAIL=# Stripe# STRIPE_SECRET_KEY=diff --git a/packages/shared/src/server/services/email/usageThresholdSuspension/UsageThresholdSuspensionEmailTemplate.tsx b/packages/shared/src/server/services/email/usageThresholdSuspension/UsageThresholdSuspensionEmailTemplate.tsxindex f056a47c37..c5907611ba 100644--- a/packages/shared/src/server/services/email/usageThresholdSuspension/UsageThresholdSuspensionEmailTemplate.tsx+++ b/packages/shared/src/server/services/email/usageThresholdSuspension/UsageThresholdSuspensionEmailTemplate.tsx@@ -20,6 +20,7 @@ interface UsageThresholdSuspensionEmailProps {limit: number;billingUrl: string;receiverEmail: string;+ resetDate: string; // ISO date string}export const UsageThresholdSuspensionEmailTemplate = ({@@ -28,7 +29,15 @@ export const UsageThresholdSuspensionEmailTemplate = ({limit,billingUrl,receiverEmail,+ resetDate,}: UsageThresholdSuspensionEmailProps) => {+ // Format reset date as "January 15, 2024"+ const formattedResetDate = new Date(resetDate).toLocaleDateString("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric",+ timeZone: "UTC",+ });return (<Html><Head />@@ -105,10 +114,36 @@ export const UsageThresholdSuspensionEmailTemplate = ({How to resolve:</Heading><Text className="text-gray-700 text-sm leading-6">- • <strong>Upgrade plan</strong> for unlimited events and premium- features- <br />• Or contact support for custom plans and enterprise- options+ • <strong>Upgrade now</strong> to resume ingestion immediately+ <br />• Or wait until your usage limit resets on{" "}+ <strong>{formattedResetDate}</strong>+ <br />• Contact support for custom plans and enterprise options+ </Text>+ </Section>++ <Section className="mt-8">+ <Heading className="text-black text-[18px] font-semibold">+ Upgrade to Core at only $29/month+ </Heading>+ <Text className="text-gray-700 text-sm leading-6">+ When you upgrade, you can:+ <br />+ • Add unlimited number of users+ <br />+ • Retain data for 90 days+ <br />+ • Access unlimited evaluators+ <br />• Get support via Email/Chat+ </Text>+ <Text className="text-gray-700 text-sm leading-6 mt-4">+ <strong>Startup Program:</strong> Eligible startups get 50% off+ for their first year.{" "}+ <a+ href="https://langfuse.com/startups"+ className="text-blue-600 underline"+ >+ Learn more →+ </a></Text></Section>diff --git a/packages/shared/src/server/services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail.ts b/packages/shared/src/server/services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail.tsindex 88f1fe2102..6f27250357 100644--- a/packages/shared/src/server/services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail.ts+++ b/packages/shared/src/server/services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail.ts@@ -3,11 +3,15 @@ import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";import { render } from "@react-email/render";import { UsageThresholdSuspensionEmailTemplate } from "./UsageThresholdSuspensionEmailTemplate";import { logger } from "../../../logger";+import { z } from "zod/v4";export interface UsageThresholdSuspensionEmailProps {env: Partial<Record<- "EMAIL_FROM_ADDRESS" | "SMTP_CONNECTION_URL" | "NEXTAUTH_URL",+ | "EMAIL_FROM_ADDRESS"+ | "SMTP_CONNECTION_URL"+ | "NEXTAUTH_URL"+ | "CLOUD_CRM_EMAIL",string | undefined>>;@@ -16,6 +20,7 @@ export interface UsageThresholdSuspensionEmailProps {limit: number;billingUrl: string;receiverEmail: string;+ resetDate: string; // ISO date string for when usage resets}export const sendUsageThresholdSuspensionEmail = async ({@@ -25,6 +30,7 @@ export const sendUsageThresholdSuspensionEmail = async ({limit,billingUrl,receiverEmail,+ resetDate,}: UsageThresholdSuspensionEmailProps) => {if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {logger.error(@@ -44,10 +50,11 @@ export const sendUsageThresholdSuspensionEmail = async ({limit,billingUrl,receiverEmail,+ resetDate,}),);- await mailer.sendMail({+ const mailOptions: any = {to: receiverEmail,from: {address: env.EMAIL_FROM_ADDRESS,@@ -56,7 +63,24 @@ export const sendUsageThresholdSuspensionEmail = async ({replyTo: "[email protected]",subject: emailSubject,html: emailHtml,- });+ };++ // Add BCC if configured (optional, for CRM integration)+ if (env.CLOUD_CRM_EMAIL) {+ // Validate email format to prevent email header injection+ const emailSchema = z.string().email();+ const validationResult = emailSchema.safeParse(env.CLOUD_CRM_EMAIL);++ if (validationResult.success) {+ mailOptions.bcc = validationResult.data;+ } else {+ logger.warn(+ `Invalid CLOUD_CRM_EMAIL format: ${env.CLOUD_CRM_EMAIL}. Skipping BCC.`,+ );+ }+ }++ await mailer.sendMail(mailOptions);} catch (error) {logger.error(`Failed to send ingestion suspended email`, error);}diff --git a/packages/shared/src/server/services/email/usageThresholdWarning/UsageThresholdWarningEmailTemplate.tsx b/packages/shared/src/server/services/email/usageThresholdWarning/UsageThresholdWarningEmailTemplate.tsxindex d10db97a14..486605805f 100644--- a/packages/shared/src/server/services/email/usageThresholdWarning/UsageThresholdWarningEmailTemplate.tsx+++ b/packages/shared/src/server/services/email/usageThresholdWarning/UsageThresholdWarningEmailTemplate.tsx@@ -22,6 +22,7 @@ interface UsageThresholdWarningEmailProps {limit: number;billingUrl: string;receiverEmail: string;+ resetDate: string; // ISO date string}export const UsageThresholdWarningEmailTemplate = ({@@ -30,7 +31,15 @@ export const UsageThresholdWarningEmailTemplate = ({limit,billingUrl,receiverEmail,+ resetDate,}: UsageThresholdWarningEmailProps) => {+ // Format reset date as "January 15, 2024"+ const formattedResetDate = new Date(resetDate).toLocaleDateString("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric",+ timeZone: "UTC",+ });return (<Html><Head />@@ -104,7 +113,34 @@ export const UsageThresholdWarningEmailTemplate = ({<br />• Ingestion will soon be suspended and incoming observations,traces, and scores will be dropped unless you upgrade- <br />• Upgrade now for unlimited events and premium features+ <br />• Your usage limit resets on{" "}+ <strong>{formattedResetDate}</strong>+ </Text>+ </Section>++ <Section className="mt-8">+ <Heading className="text-black text-[18px] font-semibold">+ Upgrade to Core at only $29/month+ </Heading>+ <Text className="text-gray-700 text-sm leading-6">+ When you upgrade, you can:+ <br />+ • Add unlimited number of users+ <br />+ • Retain data for 90 days+ <br />+ • Access unlimited evaluators+ <br />• Get support via Email/Chat+ </Text>+ <Text className="text-gray-700 text-sm leading-6 mt-4">+ <strong>Startup Program:</strong> Eligible startups get 50% off+ for their first year.{" "}+ <a+ href="https://langfuse.com/startups"+ className="text-blue-600 underline"+ >+ Learn more →+ </a></Text></Section>diff --git a/packages/shared/src/server/services/email/usageThresholdWarning/sendUsageThresholdWarningEmail.ts b/packages/shared/src/server/services/email/usageThresholdWarning/sendUsageThresholdWarningEmail.tsindex 69ac8b13d2..6651302742 100644--- a/packages/shared/src/server/services/email/usageThresholdWarning/sendUsageThresholdWarningEmail.ts+++ b/packages/shared/src/server/services/email/usageThresholdWarning/sendUsageThresholdWarningEmail.ts@@ -3,11 +3,15 @@ import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";import { render } from "@react-email/render";import { UsageThresholdWarningEmailTemplate } from "./UsageThresholdWarningEmailTemplate";import { logger } from "../../../logger";+import { z } from "zod/v4";export interface UsageThresholdWarningEmailProps {env: Partial<Record<- "EMAIL_FROM_ADDRESS" | "SMTP_CONNECTION_URL" | "NEXTAUTH_URL",+ | "EMAIL_FROM_ADDRESS"+ | "SMTP_CONNECTION_URL"+ | "NEXTAUTH_URL"+ | "CLOUD_CRM_EMAIL",string | undefined>>;@@ -16,6 +20,7 @@ export interface UsageThresholdWarningEmailProps {limit: number;billingUrl: string;receiverEmail: string;+ resetDate: string; // ISO date string for when usage resets}export const sendUsageThresholdWarningEmail = async ({@@ -25,6 +30,7 @@ export const sendUsageThresholdWarningEmail = async ({limit,billingUrl,receiverEmail,+ resetDate,}: UsageThresholdWarningEmailProps) => {if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {logger.error(@@ -44,10 +50,11 @@ export const sendUsageThresholdWarningEmail = async ({limit,billingUrl,receiverEmail,+ resetDate,}),);- await mailer.sendMail({+ const mailOptions: any = {to: receiverEmail,from: {address: env.EMAIL_FROM_ADDRESS,@@ -56,7 +63,24 @@ export const sendUsageThresholdWarningEmail = async ({replyTo: "[email protected]",subject: emailSubject,html: emailHtml,- });+ };++ // Add BCC if configured (optional, for CRM integration)+ if (env.CLOUD_CRM_EMAIL) {+ // Validate email format to prevent email header injection+ const emailSchema = z.string().email();+ const validationResult = emailSchema.safeParse(env.CLOUD_CRM_EMAIL);++ if (validationResult.success) {+ mailOptions.bcc = validationResult.data;+ } else {+ logger.warn(+ `Invalid CLOUD_CRM_EMAIL format: ${env.CLOUD_CRM_EMAIL}. Skipping BCC.`,+ );+ }+ }++ await mailer.sendMail(mailOptions);} catch (error) {logger.error(`Failed to send usage notification email`, error);}diff --git a/packages/shared/src/server/utils/billingCycleHelpers.ts b/packages/shared/src/server/utils/billingCycleHelpers.tsindex 7070cb780a..8deca867ce 100644--- a/packages/shared/src/server/utils/billingCycleHelpers.ts+++ b/packages/shared/src/server/utils/billingCycleHelpers.ts@@ -90,6 +90,51 @@ export function getBillingCycleStart(return currentMonthCycleStart;}+/**+ * Calculate the billing cycle end date (when the usage limit resets)+ *+ * Returns the start of the next billing cycle, which is when the current cycle ends+ * and usage is reset.+ *+ * Example: If anchor is Jan 15 and reference is Jan 20:+ * - Current cycle start: Jan 15+ * - Next cycle start (reset date): Feb 15+ *+ * Handles month boundaries correctly (e.g., 31st → 28/29/30 for shorter months)+ *+ * @param org - Organization with billing cycle anchor+ * @param referenceDate - The current date (typically "now")+ * @returns Date when the usage limit resets (start of next billing cycle)+ */+export function getBillingCycleEnd(+ org: Organization,+ referenceDate: Date,+): Date {+ // Get the current cycle start using existing function+ const currentCycleStart = getBillingCycleStart(org, referenceDate);+ const anchor = getBillingCycleAnchor(org);+ const dayOfMonth = anchor.getUTCDate();++ // Calculate next month's cycle day (one month after current cycle start)+ const nextMonthDate = new Date(+ Date.UTC(+ currentCycleStart.getUTCFullYear(),+ currentCycleStart.getUTCMonth() + 1,+ 1,+ ),+ );+ const daysInNextMonth = getDaysInMonth(nextMonthDate);+ const adjustedDay = Math.min(dayOfMonth, daysInNextMonth);++ return new Date(+ Date.UTC(+ nextMonthDate.getUTCFullYear(),+ nextMonthDate.getUTCMonth(),+ adjustedDay,+ ),+ );+}+/*** Calculate the maximum number of days to look back for a billing cycle*diff --git a/web/src/__tests__/billingCycleHelpers.servertest.ts b/web/src/__tests__/billingCycleHelpers.servertest.tsindex ef359722b9..3609967550 100644--- a/web/src/__tests__/billingCycleHelpers.servertest.ts+++ b/web/src/__tests__/billingCycleHelpers.servertest.ts@@ -2,6 +2,7 @@import {getBillingCycleAnchor,getBillingCycleStart,+ getBillingCycleEnd,getDaysToLookBack,startOfDayUTC,endOfDayUTC,@@ -176,6 +177,125 @@ describe("getBillingCycleStart", () => {});});+describe("getBillingCycleEnd", () => {+ it("returns next month's cycle start for standard day", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // Jan 20 reference → next cycle is Feb 15+ expect(getBillingCycleEnd(org, new Date("2024-01-20T10:00:00Z"))).toEqual(+ new Date("2024-02-15T00:00:00Z"),+ );++ // Feb 20 reference → next cycle is March 15+ expect(getBillingCycleEnd(org, new Date("2024-02-20T10:00:00Z"))).toEqual(+ new Date("2024-03-15T00:00:00Z"),+ );+ });++ it("handles 31st anchor → adjusts to last day of shorter months", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-31T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // Jan 15 reference (before first cycle) → next cycle is Jan 31+ expect(getBillingCycleEnd(org, new Date("2024-01-15T10:00:00Z"))).toEqual(+ new Date("2024-01-31T00:00:00Z"),+ );++ // March 15 reference (in Feb-Mar cycle) → next cycle is March 31+ expect(getBillingCycleEnd(org, new Date("2024-03-15T10:00:00Z"))).toEqual(+ new Date("2024-03-31T00:00:00Z"),+ );++ // April 15 reference (in March-April cycle) → next cycle is April 30+ expect(getBillingCycleEnd(org, new Date("2024-04-15T10:00:00Z"))).toEqual(+ new Date("2024-04-30T00:00:00Z"),+ );+ });++ it("handles reference date on cycle day → returns next month", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // Reference on Feb 15 exactly → next cycle is March 15+ expect(getBillingCycleEnd(org, new Date("2024-02-15T00:00:00Z"))).toEqual(+ new Date("2024-03-15T00:00:00Z"),+ );+ });++ it("handles reference date after cycle day in current month", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // Jan 5 (before cycle day 15) → next cycle is Jan 15+ expect(getBillingCycleEnd(org, new Date("2024-01-05T10:00:00Z"))).toEqual(+ new Date("2024-01-15T00:00:00Z"),+ );+ });++ it("handles leap year February correctly", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-31T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // 2024 is leap year - Feb 15 reference (in Jan-Feb cycle) → next cycle is Feb 29+ expect(getBillingCycleEnd(org, new Date("2024-02-15T10:00:00Z"))).toEqual(+ new Date("2024-02-29T00:00:00Z"),+ );++ // 2025 is not leap year+ const org2025 = {+ ...org,+ cloudBillingCycleAnchor: new Date("2025-01-31T00:00:00Z"),+ } as Organization;++ // Feb 15 2025 reference → next cycle is Feb 28 (non-leap year)+ expect(+ getBillingCycleEnd(org2025, new Date("2025-02-15T10:00:00Z")),+ ).toEqual(new Date("2025-02-28T00:00:00Z"));+ });++ it("handles year boundary", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-12-15T00:00:00Z"),+ createdAt: new Date("2024-12-01T00:00:00Z"),+ } as Organization;++ // Dec 20 reference → next cycle is Jan 15 next year+ expect(getBillingCycleEnd(org, new Date("2024-12-20T10:00:00Z"))).toEqual(+ new Date("2025-01-15T00:00:00Z"),+ );+ });++ it("uses createdAt as fallback when cloudBillingCycleAnchor is null", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: null,+ createdAt: new Date("2024-01-15T10:30:00Z"),+ } as Organization;++ // Feb 20 reference → next cycle is March 15+ expect(getBillingCycleEnd(org, new Date("2024-02-20T10:00:00Z"))).toEqual(+ new Date("2024-03-15T00:00:00Z"),+ );+ });+});+describe("getDaysToLookBack", () => {it("returns days in previous month for March reference (leap year)", () => {// March 2024, previous month is Feb with 29 days (leap year)diff --git a/worker/src/ee/usageThresholds/thresholdProcessing.ts b/worker/src/ee/usageThresholds/thresholdProcessing.tsindex d7cba18a16..aec432db8b 100644--- a/worker/src/ee/usageThresholds/thresholdProcessing.ts+++ b/worker/src/ee/usageThresholds/thresholdProcessing.ts@@ -8,6 +8,7 @@ import {invalidateCachedOrgApiKeys,recordIncrement,traceException,+ getBillingCycleEnd,} from "@langfuse/shared/src/server";import {NOTIFICATION_THRESHOLDS,@@ -51,6 +52,7 @@ async function sendThresholdNotificationEmail(org: Organization | ParsedOrganization,threshold: NotificationThreshold,cumulativeUsage: number,+ resetDate: Date,): Promise<{ emailSent: boolean; emailFailed: boolean }> {let emailSent = false;let emailFailed = false;@@ -90,6 +92,7 @@ async function sendThresholdNotificationEmail(limit: MAX_EVENTS_FREE_PLAN,billingUrl,receiverEmail: email,+ resetDate: resetDate.toISOString(),});logger.info(@@ -155,6 +158,7 @@ async function sendThresholdNotificationEmail(async function sendBlockingNotificationEmail(org: Organization | ParsedOrganization,cumulativeUsage: number,+ resetDate: Date,): Promise<{ emailSent: boolean; emailFailed: boolean }> {let emailSent = false;let emailFailed = false;@@ -194,6 +198,7 @@ async function sendBlockingNotificationEmail(limit: MAX_EVENTS_FREE_PLAN,billingUrl,receiverEmail: email,+ resetDate: resetDate.toISOString(),});logger.info(@@ -351,6 +356,9 @@ export async function processThresholds(// Check for state transitionconst stateTransitioned = previousState !== currentState;+ // Calculate reset date for emails+ const resetDate = getBillingCycleEnd(org, new Date());+if (stateTransitioned && currentState === "BLOCKED") {// Transitioning to BLOCKED state - send blocking emailrecordIncrement(@@ -363,6 +371,7 @@ export async function processThresholds(const emailResult = await sendBlockingNotificationEmail(org,cumulativeUsage,+ resetDate,);emailSent = emailResult.emailSent;emailFailed = emailResult.emailFailed;@@ -383,6 +392,7 @@ export async function processThresholds(org,highestCrossedThreshold,cumulativeUsage,+ resetDate,);emailSent = emailResult.emailSent;emailFailed = emailResult.emailFailed;diff --git a/worker/src/env.ts b/worker/src/env.tsindex 038e8eca96..383ed0477d 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -65,6 +65,7 @@ const EnvSchema = z.object({.default(50_000),EMAIL_FROM_ADDRESS: z.string().optional(),SMTP_CONNECTION_URL: z.string().optional(),+ CLOUD_CRM_EMAIL: z.string().optional(),LANGFUSE_OTEL_INGESTION_QUEUE_PROCESSING_CONCURRENCY: z.coerce.number().positive()diff --git a/worker/src/scripts/send-test-threshold-emails.ts b/worker/src/scripts/send-test-threshold-emails.tsindex a311e17c37..57aee855f7 100644--- a/worker/src/scripts/send-test-threshold-emails.ts+++ b/worker/src/scripts/send-test-threshold-emails.ts@@ -24,6 +24,11 @@ const TEST_ORG_NAME = "Test Organization";const BILLING_URL ="http://localhost:3000/organization/test-org-id/settings/billing";+// Calculate a reset date 30 days from now+const resetDate = new Date();+resetDate.setDate(resetDate.getDate() + 30);+const RESET_DATE = resetDate.toISOString();+const main = async () => {// Check if TEST_EMAILS is emptyif (TEST_EMAILS.length === 0) {@@ -51,12 +56,14 @@ const main = async () => {EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,NEXTAUTH_URL: env.NEXTAUTH_URL,+ CLOUD_CRM_EMAIL: env.CLOUD_CRM_EMAIL,},organizationName: TEST_ORG_NAME,currentUsage: 52_347,limit: 50_000,billingUrl: BILLING_URL,receiverEmail: email,+ resetDate: RESET_DATE,});console.log(" ✓ Warning email sent");@@ -67,12 +74,14 @@ const main = async () => {EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,NEXTAUTH_URL: env.NEXTAUTH_URL,+ CLOUD_CRM_EMAIL: env.CLOUD_CRM_EMAIL,},organizationName: TEST_ORG_NAME,currentUsage: 203_891,limit: 50_000,billingUrl: BILLING_URL,receiverEmail: email,+ resetDate: RESET_DATE,});console.log(" ✓ Blocking email sent");}