Skip to content

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

feat(cloud): add billing alerts (#7903)

Steffen Schmitz5612c6a9a59f
diff --git a/packages/shared/src/interfaces/cloudConfigSchema.ts b/packages/shared/src/interfaces/cloudConfigSchema.ts
index b1aa7bff72..cf4c4556cc 100644
--- a/packages/shared/src/interfaces/cloudConfigSchema.ts
+++ b/packages/shared/src/interfaces/cloudConfigSchema.ts
@@ -18,6 +18,21 @@ export const CloudConfigSchema = z.object({
// custom rate limits for an organization
rateLimitOverrides: CloudConfigRateLimit.optional(),
+
+ // billing alert configuration
+ usageAlerts: z
+ .object({
+ enabled: z.boolean().default(true),
+ type: z.enum(["STRIPE"]).default("STRIPE"),
+ threshold: z.number().int().positive(),
+ alertId: z.string(), // Alert ID for tracking
+ meterId: z.string(), // Meter ID for usage tracking
+ notifications: z.object({
+ email: z.boolean().default(true),
+ recipients: z.array(z.string().email()).default([]),
+ }),
+ })
+ .optional(),
});
export type CloudConfigSchema = z.infer<typeof CloudConfigSchema>;
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 467f2ddf8f..1038837942 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -2,6 +2,7 @@ export * from "./services/StorageService";
export * from "./services/email/organizationInvitation/sendMembershipInvitationEmail";
export * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";
export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";
+export * from "./services/email/billingAlert/sendBillingAlertEmail";
export * from "./services/PromptService";
export * from "./services/PromptService/types";
export * from "./services/traces-ui-table-service";
diff --git a/packages/shared/src/server/services/email/billingAlert/BillingAlertEmailTemplate.tsx b/packages/shared/src/server/services/email/billingAlert/BillingAlertEmailTemplate.tsx
new file mode 100644
index 0000000000..237fa174c1
--- /dev/null
+++ b/packages/shared/src/server/services/email/billingAlert/BillingAlertEmailTemplate.tsx
@@ -0,0 +1,134 @@
+import React from "react";
+import {
+ Body,
+ Button,
+ Container,
+ Head,
+ Heading,
+ Hr,
+ Html,
+ Img,
+ Preview,
+ Section,
+ Text,
+ Tailwind,
+ Row,
+ Column,
+} from "@react-email/components";
+
+interface BillingAlertEmailProps {
+ organizationName: string;
+ currentUsage: number;
+ threshold: number;
+ billingUrl: string;
+ receiverEmail: string;
+}
+
+export const BillingAlertEmailTemplate = ({
+ organizationName,
+ currentUsage,
+ threshold,
+ billingUrl,
+ receiverEmail,
+}: BillingAlertEmailProps) => {
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ Your Langfuse Cloud usage is {`${currentUsage}`} events for the current
+ billing period
+ </Preview>
+ <Tailwind>
+ <Body className="bg-background my-auto mx-auto font-sans">
+ <Container className="mx-auto my-10 w-[465px] rounded border border-solid border-[#eaeaea] p-5">
+ <Section className="mt-8">
+ <Img
+ src="https://static.langfuse.com/langfuse_logo_transactional_email.png"
+ width="40"
+ height="40"
+ alt="Langfuse"
+ className="mx-auto my-0"
+ />
+ </Section>
+
+ <Section>
+ <Heading className="mx-0 my-[30px] p-0 text-center text-2xl font-normal text-black">
+ Usage Threshold Exceeded
+ </Heading>
+ <Text className="text-gray-700 text-sm leading-6">
+ Your organization &quot;{organizationName}&quot; has exceeded
+ the configured billing threshold
+ </Text>
+ </Section>
+
+ <Section className="mt-8">
+ <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
+ <Row>
+ <Column className="text-center">
+ <Text className="text-gray-600 text-sm font-medium m-0 mb-1">
+ Current Usage (# Events)
+ </Text>
+ <Text className="text-2xl font-bold text-gray-900 m-0">
+ {currentUsage}
+ </Text>
+ </Column>
+ <Column className="text-center">
+ <Text className="text-gray-600 text-sm font-medium m-0 mb-1">
+ Alert Threshold (# Events)
+ </Text>
+ <Text className="text-2xl font-bold text-gray-900 m-0">
+ {threshold}
+ </Text>
+ </Column>
+ </Row>
+ </div>
+ </Section>
+
+ <Section className="mt-8 text-center">
+ <Button
+ className="rounded bg-black px-5 py-3 text-center text-xs font-semibold text-white no-underline"
+ href={billingUrl}
+ >
+ View Billing Page and Manage Alerts
+ </Button>
+ </Section>
+
+ <Section className="mt-8">
+ <Heading className="text-black text-[18px] font-semibold">
+ What happens next?
+ </Heading>
+ <Text className="text-gray-700 text-sm leading-6">
+ • Your current billing cycle continues normally
+ <br />
+ • Charges will appear on your next invoice
+ <br />
+ • You can adjust usage or modify alert thresholds
+ <br />• Contact support if you have questions about your bill
+ </Text>
+ </Section>
+
+ <Hr className="border border-solid border-[#eaeaea] my-[26px] mx-0 w-full" />
+
+ <Section>
+ <Text className="text-[#666666] text-[12px] leading-[24px]">
+ This email was sent to {receiverEmail} regarding billing alerts
+ for &quot;{organizationName}&quot;.
+ </Text>
+ <Text className="text-[#666666] text-[12px] leading-[24px]">
+ Questions? Contact us at{" "}
+ <a
+ href="mailto:[email protected]"
+ className="text-blue-600 no-underline"
+ >
+ </a>
+ </Text>
+ </Section>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+};
+
+export default BillingAlertEmailTemplate;
diff --git a/packages/shared/src/server/services/email/billingAlert/sendBillingAlertEmail.ts b/packages/shared/src/server/services/email/billingAlert/sendBillingAlertEmail.ts
new file mode 100644
index 0000000000..14cd9fbe93
--- /dev/null
+++ b/packages/shared/src/server/services/email/billingAlert/sendBillingAlertEmail.ts
@@ -0,0 +1,59 @@
+import { createTransport } from "nodemailer";
+import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";
+import { render } from "@react-email/render";
+import { BillingAlertEmailTemplate } from "./BillingAlertEmailTemplate";
+import { logger } from "../../../logger";
+
+export interface BillingAlertEmailProps {
+ env: Partial<
+ Record<"EMAIL_FROM_ADDRESS" | "SMTP_CONNECTION_URL", string | undefined>
+ >;
+ organizationName: string;
+ currentUsage: number;
+ threshold: number;
+ billingUrl: string;
+ receiverEmail: string;
+}
+
+export const sendBillingAlertEmail = async ({
+ env,
+ organizationName,
+ currentUsage,
+ threshold,
+ billingUrl,
+ receiverEmail,
+}: BillingAlertEmailProps) => {
+ if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {
+ logger.error(
+ "Missing environment variables for sending billing alert email.",
+ );
+ return;
+ }
+
+ try {
+ const mailer = createTransport(parseConnectionUrl(env.SMTP_CONNECTION_URL));
+
+ const emailSubject = `Langfuse Cloud Billing Alert: ${organizationName} usage exceeded ${threshold} events`;
+ const emailHtml = await render(
+ BillingAlertEmailTemplate({
+ organizationName,
+ currentUsage,
+ threshold,
+ billingUrl,
+ receiverEmail,
+ }),
+ );
+
+ await mailer.sendMail({
+ to: receiverEmail,
+ from: {
+ address: env.EMAIL_FROM_ADDRESS,
+ name: "Langfuse",
+ },
+ subject: emailSubject,
+ html: emailHtml,
+ });
+ } catch (error) {
+ logger.error(`Failed to send billing alert email`, error);
+ }
+};
diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsx
index 6c4d1c06ce..7b807ebaf5 100644
--- a/web/src/ee/features/billing/components/BillingSettings.tsx
+++ b/web/src/ee/features/billing/components/BillingSettings.tsx
@@ -31,6 +31,7 @@ import { toast } from "sonner";
import { ActionButton } from "@/src/components/ActionButton";
import { useState } from "react";
import { chatAvailable, openChat } from "@/src/features/support-chat/PlainChat";
+import { UsageAlerts } from "./UsageAlerts";
export const BillingSettings = () => {
const router = useRouter();
@@ -41,6 +42,7 @@ export const BillingSettings = () => {
});
const entitled = useHasEntitlement("cloud-billing");
+ const isUsageAlertEntitled = useHasEntitlement("cloud-usage-alerts");
if (!entitled) return null;
if (!hasAccess)
@@ -56,7 +58,10 @@ export const BillingSettings = () => {
return (
<div>
<Header title="Usage & Billing" />
- <OrganizationUsageChart />
+ <div className="space-y-6">
+ <OrganizationUsageChart />
+ {isUsageAlertEntitled && orgId && <UsageAlerts orgId={orgId} />}
+ </div>
</div>
);
};
diff --git a/web/src/ee/features/billing/components/UsageAlerts.tsx b/web/src/ee/features/billing/components/UsageAlerts.tsx
new file mode 100644
index 0000000000..1b400fc951
--- /dev/null
+++ b/web/src/ee/features/billing/components/UsageAlerts.tsx
@@ -0,0 +1,321 @@
+import React, { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import Link from "next/link";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod/v4";
+import { api } from "@/src/utils/api";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/src/components/ui/card";
+import { Button } from "@/src/components/ui/button";
+import { Input } from "@/src/components/ui/input";
+import { Switch } from "@/src/components/ui/switch";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { toast } from "sonner";
+import { Bell, Plus, X } from "lucide-react";
+
+const usageAlertsSchema = z.object({
+ enabled: z.boolean(),
+ threshold: z.number().int().positive(),
+ notifications: z.object({
+ email: z.boolean(),
+ recipients: z.array(z.string().email()),
+ }),
+});
+
+type UsageAlertsFormData = z.infer<typeof usageAlertsSchema>;
+
+export function UsageAlerts({ orgId }: { orgId: string }) {
+ const [newRecipient, setNewRecipient] = useState("");
+ const [isAddingRecipient, setIsAddingRecipient] = useState(false);
+
+ const {
+ data: usageAlerts,
+ isLoading,
+ refetch,
+ } = api.cloudBilling.getUsageAlerts.useQuery(
+ { orgId },
+ { enabled: Boolean(orgId) },
+ );
+
+ const upsertUsageAlerts = api.cloudBilling.upsertUsageAlerts.useMutation({
+ onSuccess: () => {
+ toast.success("Usage alerts updated", {
+ description: "Your usage alert settings have been saved successfully.",
+ });
+ refetch();
+ },
+ onError: (error) => {
+ toast.error("Failed to update usage alerts", {
+ description: error.message,
+ });
+ },
+ });
+
+ const form = useForm<UsageAlertsFormData>({
+ resolver: zodResolver(usageAlertsSchema),
+ defaultValues: {
+ enabled: false,
+ threshold: 100000,
+ notifications: {
+ email: true,
+ recipients: [],
+ },
+ },
+ });
+
+ useEffect(() => {
+ // Overwrite from with existing usage alerts if available
+ if (usageAlerts) {
+ form.reset({
+ enabled: usageAlerts.enabled,
+ threshold: usageAlerts.threshold,
+ notifications: {
+ email: usageAlerts.notifications.email,
+ recipients: usageAlerts.notifications.recipients || [],
+ },
+ });
+ }
+ }, [usageAlerts, form]);
+
+ const onSubmit = (data: UsageAlertsFormData) => {
+ upsertUsageAlerts.mutate({
+ orgId,
+ usageAlerts: data,
+ });
+ };
+
+ const addRecipient = () => {
+ if (!newRecipient.trim()) return;
+
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ if (!emailRegex.test(newRecipient)) {
+ toast.error("Invalid email address", {
+ description: "Please enter a valid email address.",
+ });
+ return;
+ }
+
+ const currentRecipients = form.getValues("notifications.recipients");
+ if (currentRecipients.includes(newRecipient)) {
+ toast.error("Email already added", {
+ description: "This email address is already in the recipient list.",
+ });
+ return;
+ }
+
+ form.setValue("notifications.recipients", [
+ ...currentRecipients,
+ newRecipient,
+ ]);
+ setNewRecipient("");
+ setIsAddingRecipient(false);
+ };
+
+ const removeRecipient = (emailToRemove: string) => {
+ const currentRecipients = form.getValues("notifications.recipients");
+ form.setValue(
+ "notifications.recipients",
+ currentRecipients.filter((email) => email !== emailToRemove),
+ );
+ };
+
+ const recipients = form.watch("notifications.recipients");
+ const isEnabled = form.watch("enabled");
+
+ if (isLoading) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <Bell className="h-5 w-5" />
+ Usage Alerts
+ </CardTitle>
+ <CardDescription>Loading usage alert settings...</CardDescription>
+ </CardHeader>
+ </Card>
+ );
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <div className="flex items-start justify-between">
+ <div className="pr-8">
+ <CardTitle className="flex items-center gap-2">
+ <Bell className="h-5 w-5" />
+ Usage Alerts
+ </CardTitle>
+ <CardDescription className="mt-2">
+ Get notified when your usage exceeds a specified threshold to
+ avoid billing surprises. The alert triggers at most once per
+ billing cycle and will only consider &quot;future&quot; usage from
+ the time of creation or last update.
+ </CardDescription>
+ </div>
+ <Form {...form}>
+ <FormField
+ control={form.control}
+ name="enabled"
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ </Form>
+ </div>
+ </CardHeader>
+ <CardContent>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
+ {isEnabled && (
+ <>
+ <FormField
+ control={form.control}
+ name="threshold"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Threshold Amount</FormLabel>
+ <FormControl>
+ <div className="flex items-center space-x-2">
+ <Input
+ type="number"
+ placeholder="100000"
+ {...field}
+ onChange={(e) =>
+ field.onChange(Number(e.target.value))
+ }
+ className="flex-1"
+ />
+ <span className="text-sm text-muted-foreground">
+ Events
+ </span>
+ </div>
+ </FormControl>
+ <FormDescription>
+ You&apos;ll receive an alert when your usage exceeds
+ this number of events in your billing period. Go to our{" "}
+ <Link
+ href={
+ "https://langfuse.com/pricing?calculatorOpen=true"
+ }
+ target="_blank"
+ className="underline"
+ >
+ pricing calculator
+ </Link>{" "}
+ to translate events into cost.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <div className="space-y-4">
+ <div>
+ <h4 className="mb-2 text-sm font-medium">
+ Email Recipients
+ </h4>
+ <p className="mb-3 text-sm text-muted-foreground">
+ Organization admins will automatically receive alerts. Add
+ additional recipients below.
+ </p>
+
+ <div className="space-y-2">
+ {recipients.map((email, index) => (
+ <div
+ key={index}
+ className="flex items-center justify-between rounded-md border p-2"
+ >
+ <span className="text-sm">{email}</span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => removeRecipient(email)}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ ))}
+
+ {isAddingRecipient ? (
+ <div className="flex items-center space-x-2">
+ <Input
+ type="email"
+ placeholder="Enter email address"
+ value={newRecipient}
+ onChange={(e) => setNewRecipient(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ addRecipient();
+ }
+ }}
+ className="flex-1"
+ />
+ <Button
+ type="button"
+ size="sm"
+ onClick={addRecipient}
+ >
+ Add
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setIsAddingRecipient(false);
+ setNewRecipient("");
+ }}
+ >
+ Cancel
+ </Button>
+ </div>
+ ) : (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setIsAddingRecipient(true)}
+ className="w-full"
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ Add Recipient
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+
+ <div className="flex justify-end">
+ <Button type="submit" disabled={upsertUsageAlerts.isLoading}>
+ {upsertUsageAlerts.isLoading ? "Saving..." : "Save Changes"}
+ </Button>
+ </div>
+ </form>
+ </Form>
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/ee/features/billing/server/cloudBillingRouter.ts b/web/src/ee/features/billing/server/cloudBillingRouter.ts
index 46d9c1d617..46557fdcdf 100644
--- a/web/src/ee/features/billing/server/cloudBillingRouter.ts
+++ b/web/src/ee/features/billing/server/cloudBillingRouter.ts
@@ -18,6 +18,7 @@ import {
getTraceCountOfProjectsSinceCreationDate,
logger,
} from "@langfuse/shared/src/server";
+import { UsageAlertService } from "./usageAlertService";
export const cloudBillingRouter = createTRPCRouter({
createStripeCheckoutSession: protectedOrganizationProcedure
@@ -448,4 +449,211 @@ export const cloudBillingRouter = createTRPCRouter({
usageType: "units",
};
}),
+ getUsageAlerts: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+
+ const org = await ctx.prisma.organization.findUnique({
+ where: {
+ id: input.orgId,
+ },
+ });
+ if (!org) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Organization not found",
+ });
+ }
+
+ const parsedOrg = parseDbOrg(org);
+ return parsedOrg.cloudConfig?.usageAlerts || null;
+ }),
+ upsertUsageAlerts: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ usageAlerts: z.object({
+ enabled: z.boolean(),
+ threshold: z.number().int().positive(),
+ notifications: z.object({
+ email: z.boolean().default(true),
+ recipients: z.array(z.string().email()),
+ }),
+ }),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+
+ const org = await ctx.prisma.organization.findUnique({
+ where: {
+ id: input.orgId,
+ },
+ });
+ if (!org) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Organization not found",
+ });
+ }
+
+ const parsedOrg = parseDbOrg(org);
+ const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
+ const subscriptionId =
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+ const currentAlerts = parsedOrg.cloudConfig?.usageAlerts;
+
+ if (!stripeCustomerId || !subscriptionId) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Organization must have a Stripe customer with active subscription to configure usage alerts",
+ });
+ }
+
+ if (!stripeClient) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Stripe client not initialized",
+ });
+ }
+
+ let updatedAlerts = input.usageAlerts;
+
+ // Get the meterId for the given subscription
+ const subscription =
+ await stripeClient.subscriptions.retrieve(subscriptionId);
+ if (!subscription) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Stripe subscription not found",
+ });
+ }
+ const meterId = subscription.items.data.filter((subItem) =>
+ Boolean(subItem.plan.meter),
+ )[0]?.plan.meter;
+
+ try {
+ const updatedUsageAlertConfig = {
+ enabled: updatedAlerts.enabled,
+ type: "STRIPE",
+ threshold: updatedAlerts.threshold,
+ alertId: currentAlerts?.alertId ?? null, // Keep the existing alert ID if it exists
+ meterId: meterId ?? null, // Use the meter ID from the subscription
+ notifications: {
+ email: updatedAlerts.notifications.email,
+ recipients: updatedAlerts.notifications.recipients,
+ },
+ };
+
+ // Disable the usage alert if it got disabled
+ if (
+ !updatedAlerts.enabled &&
+ currentAlerts?.alertId &&
+ currentAlerts?.enabled
+ ) {
+ await UsageAlertService.getInstance({
+ stripeClient,
+ }).deactivate({ id: currentAlerts?.alertId });
+ }
+
+ // If there is no existing alert, create a new one
+ if (!currentAlerts?.alertId) {
+ const alert = await UsageAlertService.getInstance({
+ stripeClient,
+ }).create({
+ orgId: input.orgId,
+ customerId: stripeCustomerId,
+ meterId,
+ amount: updatedAlerts.threshold,
+ });
+ updatedUsageAlertConfig.alertId = alert.id;
+ }
+
+ // If there is an existing alert with a different amount or meterId, replace it
+ if (
+ updatedAlerts.enabled &&
+ currentAlerts?.alertId &&
+ (currentAlerts?.threshold !== updatedAlerts.threshold ||
+ currentAlerts.meterId !== meterId)
+ ) {
+ const alert = await UsageAlertService.getInstance({
+ stripeClient,
+ }).recreate({
+ orgId: input.orgId,
+ customerId: stripeCustomerId,
+ meterId,
+ existingAlertId: currentAlerts.alertId,
+ amount: updatedAlerts.threshold,
+ });
+ updatedUsageAlertConfig.alertId = alert.id;
+ }
+
+ // If there is an existing, inactive alert, reactivate it
+ if (
+ updatedAlerts.enabled &&
+ currentAlerts?.alertId &&
+ !currentAlerts.enabled
+ ) {
+ await UsageAlertService.getInstance({
+ stripeClient,
+ }).activate({ id: currentAlerts.alertId });
+ }
+
+ // Update organization with new usage alerts configuration
+ const newCloudConfig = {
+ ...parsedOrg.cloudConfig,
+ usageAlerts: updatedUsageAlertConfig,
+ };
+
+ const updatedOrg = await ctx.prisma.organization.update({
+ where: {
+ id: input.orgId,
+ },
+ data: {
+ cloudConfig: newCloudConfig,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ orgId: input.orgId,
+ resourceType: "organization",
+ resourceId: input.orgId,
+ action: "updateUsageAlerts",
+ before: org,
+ after: updatedOrg,
+ });
+
+ return updatedAlerts;
+ } catch (error) {
+ logger.error("Failed to update usage alerts", {
+ error,
+ orgId: input.orgId,
+ });
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Failed to update usage alerts",
+ });
+ }
+ }),
});
diff --git a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts b/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts
index 610193c515..041bc6688a 100644
--- a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts
+++ b/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts
@@ -14,6 +14,9 @@ import {
} from "@langfuse/shared";
import { traceException, redis, logger } from "@langfuse/shared/src/server";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
+import { sendBillingAlertEmail } from "@langfuse/shared/src/server";
+import { Role } from "@langfuse/shared";
+import { UsageAlertService } from "@/src/ee/features/billing/server/usageAlertService";
/*
* Sign-up endpoint (email/password users), creates user in database.
@@ -88,6 +91,20 @@ export async function stripeWebhookApiHandler(req: NextRequest) {
});
await handleSubscriptionChanged(deletedSubscription, "deleted");
break;
+ case "invoice.created":
+ const invoiceData = event.data.object;
+ logger.info("[Stripe Webhook] Start invoice.created", {
+ payload: invoiceData,
+ });
+ await handleInvoiceCreated(invoiceData);
+ break;
+ case "billing.alert.triggered":
+ const alertData = event.data.object;
+ logger.info("[Stripe Webhook] Start billing.alert.triggered", {
+ payload: alertData,
+ });
+ await handleBillingAlertTriggered(alertData);
+ break;
default:
logger.warn(`Unhandled event type ${event.type}`);
}
@@ -227,22 +244,24 @@ async function handleSubscriptionChanged(
// update the cloud config with the product ID
if (action === "created" || action === "updated") {
+ let updatedCloudConfig = {
+ ...parsedOrg.cloudConfig,
+ stripe: {
+ ...parsedOrg.cloudConfig?.stripe,
+ ...CloudConfigSchema.shape.stripe.parse({
+ activeProductId: productId,
+ activeSubscriptionId: subscriptionId,
+ customerId: customerId,
+ }),
+ },
+ };
+
await prisma.organization.update({
where: {
id: parsedOrg.id,
},
data: {
- cloudConfig: {
- ...parsedOrg.cloudConfig,
- stripe: {
- ...parsedOrg.cloudConfig?.stripe,
- ...CloudConfigSchema.shape.stripe.parse({
- activeProductId: productId,
- activeSubscriptionId: subscriptionId,
- customerId: customerId,
- }),
- },
- },
+ cloudConfig: updatedCloudConfig,
},
});
} else if (action === "deleted") {
@@ -271,3 +290,261 @@ async function handleSubscriptionChanged(
return;
}
+
+async function handleBillingAlertTriggered(
+ alertData: Stripe.Billing.AlertTriggered,
+) {
+ try {
+ // Find organization by Stripe customer ID
+ const customerId = alertData.customer;
+ if (!customerId) {
+ logger.error("[Stripe Webhook] No customer ID found in usage alert");
+ return;
+ }
+
+ const organization = await prisma.organization.findFirst({
+ where: {
+ cloudConfig: {
+ path: ["stripe", "customerId"],
+ equals: customerId,
+ },
+ },
+ });
+
+ if (!organization) {
+ logger.warn(
+ "[Stripe Webhook] Organization not found for customer ID - Potentially received the webhook on wrong environment",
+ {
+ customerId,
+ },
+ );
+ return;
+ }
+
+ const parsedOrg = parseDbOrg(organization);
+ const usageAlerts = parsedOrg.cloudConfig?.usageAlerts;
+
+ if (!usageAlerts || !usageAlerts.enabled) {
+ logger.info(
+ "[Stripe Webhook] Usage alerts not enabled for organization",
+ {
+ orgId: organization.id,
+ },
+ );
+ return;
+ }
+
+ // Extract usage information from alert data
+ const usageAmount = alertData.value;
+ const threshold = usageAlerts.threshold;
+
+ // Send email notifications if enabled
+ if (usageAlerts.notifications.email) {
+ await sendBillingAlertNotifications({
+ organization,
+ usageAlerts,
+ usageAmount,
+ threshold,
+ alertId: alertData.alert.id,
+ });
+ }
+
+ logger.info("[Stripe Webhook] Usage alert triggered successfully", {
+ organizationId: organization.id,
+ organizationName: organization.name,
+ usageAmount,
+ threshold,
+ alertId: alertData.alert.id,
+ });
+ } catch (error) {
+ logger.error("[Stripe Webhook] Error processing usage alert", {
+ error,
+ alertId: alertData.alert.id,
+ });
+ traceException("[Stripe Webhook] Error processing usage alert");
+ }
+}
+
+async function sendBillingAlertNotifications({
+ organization,
+ usageAlerts,
+ usageAmount,
+ threshold,
+ alertId,
+}: {
+ organization: Organization;
+ usageAlerts: NonNullable<
+ ReturnType<typeof parseDbOrg>["cloudConfig"]
+ >["usageAlerts"];
+ usageAmount: number;
+ threshold: number;
+ alertId: string;
+}) {
+ try {
+ // Get organization admins and owners
+ const adminMembers = await prisma.organizationMembership.findMany({
+ where: {
+ orgId: organization.id,
+ role: {
+ in: [Role.ADMIN, Role.OWNER],
+ },
+ },
+ include: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ // Collect all recipients
+ const recipients = new Set<string>();
+
+ // Add admin/owner emails
+ adminMembers.forEach((member) => {
+ if (member.user.email) {
+ recipients.add(member.user.email);
+ }
+ });
+
+ // Add additional recipients from settings
+ if (usageAlerts?.notifications.recipients) {
+ usageAlerts.notifications.recipients.forEach((email) => {
+ recipients.add(email);
+ });
+ }
+
+ // Generate URLs
+ const billingUrl = `${env.NEXTAUTH_URL}/organization/${organization.id}/settings/billing`;
+
+ // Send email to all recipients
+ const emailPromises = Array.from(recipients).map(async (email) => {
+ try {
+ await sendBillingAlertEmail({
+ env,
+ organizationName: organization.name,
+ currentUsage: usageAmount,
+ threshold,
+ billingUrl,
+ receiverEmail: email,
+ });
+
+ logger.info("[Stripe Webhook] Usage alert email sent", {
+ organizationId: organization.id,
+ recipientEmail: email,
+ alertId,
+ });
+ } catch (error) {
+ logger.error("[Stripe Webhook] Failed to send usage alert email", {
+ organizationId: organization.id,
+ recipientEmail: email,
+ alertId,
+ error,
+ });
+ }
+ });
+
+ await Promise.all(emailPromises);
+
+ logger.info("[Stripe Webhook] Billing alert notifications sent", {
+ organizationId: organization.id,
+ recipientCount: recipients.size,
+ alertId,
+ });
+ } catch (error) {
+ logger.error("[Stripe Webhook] Error sending usage alert notifications", {
+ organizationId: organization.id,
+ alertId,
+ error,
+ });
+ }
+}
+
+/**
+ * Whenever a stripe invoice is created, we recreate the usage alert.
+ * This is necessary, because usage alerts trigger only once globally and with this setup,
+ * we can ensure that they trigger once per billing period.
+ * @param invoice
+ */
+async function handleInvoiceCreated(invoice: Stripe.Invoice): Promise<void> {
+ try {
+ // Find organization by Stripe customer ID
+ const customerId =
+ typeof invoice.customer === "string"
+ ? invoice.customer
+ : invoice.customer?.id;
+ if (!customerId) {
+ logger.error(
+ "[Stripe Webhook] No customer ID found in invoice created event",
+ );
+ return;
+ }
+
+ const organization = await prisma.organization.findFirst({
+ where: {
+ cloudConfig: {
+ path: ["stripe", "customerId"],
+ equals: customerId,
+ },
+ },
+ });
+
+ if (!organization) {
+ logger.warn(
+ "[Stripe Webhook] Organization not found for customer ID - Potentially received the webhook on wrong environment",
+ {
+ customerId,
+ },
+ );
+ return;
+ }
+
+ const parsedOrg = parseDbOrg(organization);
+ const usageAlerts = parsedOrg.cloudConfig?.usageAlerts;
+
+ if (!usageAlerts || !usageAlerts.enabled) {
+ logger.info(
+ "[Stripe Webhook] Usage alerts not enabled for organization - skipping recreation",
+ {
+ orgId: organization.id,
+ },
+ );
+ return;
+ }
+
+ const updatedAlert = await UsageAlertService.getInstance({
+ stripeClient,
+ }).recreate({
+ orgId: parsedOrg.id,
+ customerId: customerId,
+ meterId: usageAlerts.meterId,
+ existingAlertId: usageAlerts.alertId,
+ amount: usageAlerts.threshold,
+ });
+ // We can use ! here as we'd never reach this point if the fields are undefined
+ parsedOrg.cloudConfig!.usageAlerts!.alertId = updatedAlert.id;
+
+ await prisma.organization.update({
+ where: {
+ id: parsedOrg.id,
+ },
+ data: {
+ cloudConfig: parsedOrg.cloudConfig!,
+ },
+ });
+ logger.info(
+ `[Stripe Webhook] Recreated usage alert for ${parsedOrg.id} after invoice creation`,
+ {
+ orgId: parsedOrg.id,
+ alertId: updatedAlert.id,
+ },
+ );
+ } catch (error) {
+ logger.error("[Stripe Webhook] Error handling invoice created", {
+ error,
+ invoiceId: invoice.id,
+ });
+ traceException("[Stripe Webhook] Error handling invoice created");
+ }
+}
diff --git a/web/src/ee/features/billing/server/usageAlertService.ts b/web/src/ee/features/billing/server/usageAlertService.ts
new file mode 100644
index 0000000000..142aa11d38
--- /dev/null
+++ b/web/src/ee/features/billing/server/usageAlertService.ts
@@ -0,0 +1,116 @@
+import type Stripe from "stripe";
+import { TRPCError } from "@trpc/server";
+
+export interface UsageAlertServiceConfig {
+ stripeClient?: Stripe;
+}
+
+class UsageAlertService {
+ private stripeClient: Stripe;
+
+ private static instance: UsageAlertService;
+
+ public static getInstance(
+ config: UsageAlertServiceConfig,
+ ): UsageAlertService {
+ if (!config || !config.stripeClient) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Stripe client is required and cannot be empty",
+ });
+ }
+ if (!UsageAlertService.instance) {
+ UsageAlertService.instance = new UsageAlertService(config);
+ }
+ return UsageAlertService.instance;
+ }
+
+ constructor(config: UsageAlertServiceConfig) {
+ if (!config.stripeClient) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Stripe client is required and cannot be empty",
+ });
+ }
+ this.stripeClient = config.stripeClient;
+ }
+
+ public async create({
+ orgId,
+ customerId,
+ meterId,
+ amount,
+ }: {
+ orgId: string;
+ customerId: string;
+ meterId: string | null | undefined;
+ amount: number;
+ }) {
+ if (!meterId) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: "Meter ID is required to create a usage alert",
+ });
+ }
+
+ return this.stripeClient.billing.alerts.create({
+ title: `Usage Alert ${orgId}`,
+ alert_type: "usage_threshold",
+ usage_threshold: {
+ filters: [
+ {
+ type: "customer",
+ customer: customerId,
+ },
+ ],
+ gte: amount,
+ meter: meterId,
+ recurrence: "one_time",
+ },
+ });
+ }
+
+ public async recreate({
+ orgId,
+ customerId,
+ meterId,
+ existingAlertId,
+ amount,
+ }: {
+ orgId: string;
+ customerId: string;
+ meterId: string | null | undefined;
+ existingAlertId: string;
+ amount: number;
+ }) {
+ if (!meterId) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: "Meter ID is required to recreate a usage alert",
+ });
+ }
+ if (!existingAlertId) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: "Existing alert ID is required to recreate a usage alert",
+ });
+ }
+
+ // Deactivate the existing alert
+ await this.stripeClient.billing.alerts.archive(existingAlertId);
+
+ // Create a new alert with the same meter ID and updated amount
+ return this.create({ orgId, customerId, meterId, amount });
+ }
+
+ public async activate({ id }: { id: string }) {
+ return this.stripeClient.billing.alerts.activate(id);
+ }
+
+ public async deactivate({ id }: { id: string }) {
+ return this.stripeClient.billing.alerts.deactivate(id);
+ }
+}
+
+// Export the service class for testing purposes
+export { UsageAlertService };
diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.ts
index 5716a71ed6..d1eab4969a 100644
--- a/web/src/features/entitlements/constants/entitlements.ts
+++ b/web/src/features/entitlements/constants/entitlements.ts
@@ -5,6 +5,7 @@ const entitlements = [
// features
"rbac-project-roles",
"cloud-billing",
+ "cloud-usage-alerts",
"cloud-multi-tenant-sso",
"self-host-ui-customization",
"self-host-allowed-organization-creators",
@@ -61,7 +62,7 @@ export const entitlementAccess: Record<
},
},
"cloud:core": {
- entitlements: [...cloudAllPlansEntitlements],
+ entitlements: [...cloudAllPlansEntitlements, "cloud-usage-alerts"],
entitlementLimits: {
"organization-member-count": false,
"data-access-days": 90,
@@ -71,7 +72,7 @@ export const entitlementAccess: Record<
},
},
"cloud:pro": {
- entitlements: [...cloudAllPlansEntitlements],
+ entitlements: [...cloudAllPlansEntitlements, "cloud-usage-alerts"],
entitlementLimits: {
"annotation-queue-count": false,
"organization-member-count": false,
@@ -90,6 +91,7 @@ export const entitlementAccess: Record<
"prompt-protected-labels",
"admin-api",
"scheduled-blob-exports",
+ "cloud-usage-alerts",
],
entitlementLimits: {
"annotation-queue-count": false,
@@ -109,6 +111,7 @@ export const entitlementAccess: Record<
"prompt-protected-labels",
"admin-api",
"scheduled-blob-exports",
+ "cloud-usage-alerts",
],
entitlementLimits: {
"annotation-queue-count": false,