🪢 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
feat: add custom rate limits for organisations (#2976)
Max Deichmann8fae4f305113
diff --git a/.env.prod.example b/.env.prod.exampleindex 5cdb488426..d59ad34ed2 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -175,6 +175,9 @@ ENCRYPTION_KEY="0000000000000000000000000000000000000000000000000000000000000000# LANGFUSE_CACHE_PROMPT_ENABLED=# LANGFUSE_CACHE_PROMPT_TTL_SECONDS=+# Rate limiting+# LANGFUSE_RATE_LIMITS_ENABLED=+# Stripe# STRIPE_SECRET_KEY=# STRIPE_WEBHOOK_SIGNING_SECRET=diff --git a/web/src/features/entitlements/constants/plans.ts b/packages/shared/src/features/entitlements/plans.tssimilarity index 82%rename from web/src/features/entitlements/constants/plans.tsrename to packages/shared/src/features/entitlements/plans.tsindex cd1da760aa..4edbfbfe54 100644--- a/web/src/features/entitlements/constants/plans.ts+++ b/packages/shared/src/features/entitlements/plans.ts@@ -12,3 +12,6 @@ export const plans = Object.keys(planLabels) as Plan[];// This function is kept here to ensure consistency when updating plan names in the future.export const isCloudPlan = (plan: Plan) => plan.startsWith("cloud");++export const isPlan = (value: string): value is Plan =>+ plans.includes(value as Plan);diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 329205d8c1..946edcabda 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -15,6 +15,8 @@ export * from "./utils/zod";export * from "./utils/json";export * from "./utils/objects";export * from "./utils/typeChecks";+export * from "./features/entitlements/plans";+export * from "./interfaces/rate-limits";export { env } from "./env";// llm apidiff --git a/packages/shared/src/interfaces/cloudConfigSchema.ts b/packages/shared/src/interfaces/cloudConfigSchema.tsindex cd6f5be8bc..1159b7d9f8 100644--- a/packages/shared/src/interfaces/cloudConfigSchema.ts+++ b/packages/shared/src/interfaces/cloudConfigSchema.ts@@ -1,4 +1,5 @@import { z } from "zod";+import { CloudConfigRateLimit } from "./rate-limits";export const CloudConfigSchema = z.object({plan: z.enum(["Hobby", "Pro", "Team", "Enterprise"]).optional(),@@ -13,5 +14,9 @@ export const CloudConfigSchema = z.object({activeProductId: z.string().optional(),}).optional(),++ // custom rate limits for an organization+ rateLimitOverrides: CloudConfigRateLimit.nullable(),});+export type CloudConfigSchema = z.infer<typeof CloudConfigSchema>;diff --git a/packages/shared/src/interfaces/rate-limits.ts b/packages/shared/src/interfaces/rate-limits.tsnew file mode 100644index 0000000000..866487851b--- /dev/null+++ b/packages/shared/src/interfaces/rate-limits.ts@@ -0,0 +1,30 @@+import z from "zod";+import { ApiAccessScope } from "../server";++export const RateLimitResource = z.enum([+ "ingestion",+ "public-api",+ "public-api-metrics",+ "prompts",+]);++// result of the rate limit check.+export type RateLimitResult = {+ resource: z.infer<typeof RateLimitResource>;+ points: number;+ scope: ApiAccessScope;++ // from rate-limiter-flexible+ remainingPoints: number;+ msBeforeNext: number;+ consumedPoints: number;+ isFirstInDuration: boolean;+};++export const RateLimitConfig = z.object({+ points: z.number().nullish(),+ durationInSec: z.number().nullish(),+ resource: RateLimitResource,+});++export const CloudConfigRateLimit = z.array(RateLimitConfig);diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex 2aa8cb5d66..b684c67072 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -1,3 +1,30 @@+import z from "zod";+import { Plan, plans } from "../../features/entitlements/plans";+import { CloudConfigRateLimit } from "../../interfaces/rate-limits";++export const OrgEnrichedApiKey = z.object({+ id: z.string(),+ note: z.string().nullable(),+ publicKey: z.string(),+ displaySecretKey: z.string(),+ createdAt: z.string().datetime().nullable(),+ lastUsedAt: z.string().datetime().nullable(),+ expiresAt: z.string().datetime().nullable(),+ projectId: z.string(),+ fastHashedSecretKey: z.string(),+ hashedSecretKey: z.string(),+ orgId: z.string(),+ plan: z.enum(plans as unknown as [string, ...string[]]),+ rateLimitOverrides: CloudConfigRateLimit.nullish(),+});++export const API_KEY_NON_EXISTENT = "api-key-non-existent";++export const CachedApiKey = z.union([+ OrgEnrichedApiKey,+ z.literal(API_KEY_NON_EXISTENT),+]);+export type AuthHeaderVerificationResult =| AuthHeaderValidVerificationResult| {@@ -13,4 +40,7 @@ export type AuthHeaderValidVerificationResult = {export type ApiAccessScope = {projectId: string;accessLevel: "all" | "scores";+ orgId: string;+ plan: Plan;+ rateLimitOverrides: z.infer<typeof CloudConfigRateLimit>;};diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex e493cdf145..a1bf0238f2 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -1,5 +1,7 @@import { z } from "zod";import { ingestionBatchEvent } from ".";+import { isPlan } from "../features/entitlements/plans";+import { CloudConfigRateLimit } from "../interfaces/rate-limits";export enum EventName {TraceUpsert = "TraceUpsert",@@ -16,6 +18,11 @@ export const LegacyIngestionEvent = z.object({scope: z.object({projectId: z.string(),accessLevel: z.enum(["all", "scores"]),+ orgId: z.string(),+ plan: z.string().refine((value) => isPlan(value), {+ message: "Invalid plan type",+ }),+ rateLimitOverrides: CloudConfigRateLimit.nullish(),}),}),});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f775653cc7..c52b205383 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -567,6 +567,9 @@ importers:prisma:specifier: ^5.13.0version: 5.13.0+ rate-limiter-flexible:+ specifier: ^5.0.3+ version: 5.0.3react:specifier: 18.2.0version: 18.2.0@@ -9842,6 +9845,9 @@ packages:resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-lWx2y8NBVlTOLPyqs+6y7dxfEpT6YFqKy3MzWbCy95sTTOhOuxufP2QvRyOHpfXpB9OUJPbVLybw3z3AVAS5fA==}+resolution: {integrity: sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==}engines: {node: '>= 0.8'}@@ -16685,11 +16691,11 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 20.10.5+ '@types/node': 20.14.8'@types/[email protected]':dependencies:- '@types/node': 20.10.5+ '@types/node': 20.14.8'@types/[email protected]':dependencies:@@ -16898,7 +16904,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 20.10.5+ '@types/node': 20.14.8'@types/[email protected]':dependencies:@@ -16949,7 +16955,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 20.10.5+ '@types/node': 20.14.8pg-protocol: 1.6.1pg-types: 2.2.0@@ -17012,7 +17018,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 20.10.5+ '@types/node': 20.14.8'@types/[email protected]': {}@@ -22985,6 +22991,8 @@ snapshots:+ [email protected]: {}+dependencies:bytes: 3.1.2diff --git a/web/package.json b/web/package.jsonindex 2d695f9169..d1b9607857 100644--- a/web/package.json+++ b/web/package.json@@ -119,6 +119,7 @@"posthog-node": "^3.6.3","prexit": "^2.2.0","prisma": "^5.13.0",+ "rate-limiter-flexible": "^5.0.3","react": "18.2.0","react-day-picker": "^8.10.1","react-dom": "18.2.0",diff --git a/web/src/__e2e__/api.servertest.ts b/web/src/__e2e__/api.servertest.tsindex ea748d5f88..25a70326d5 100644--- a/web/src/__e2e__/api.servertest.ts+++ b/web/src/__e2e__/api.servertest.ts@@ -1,8 +1,7 @@import { v4 } from "uuid";-import { JobExecutionStatus, prisma } from "@langfuse/shared/src/db";-import { redis } from "@langfuse/shared/src/server";+import { JobExecutionStatus, Prisma, prisma } from "@langfuse/shared/src/db";+import { OrgEnrichedApiKey, redis } from "@langfuse/shared/src/server";import waitForExpect from "wait-for-expect";-import { ApiKeyZod } from "@/src/features/public-api/server/apiAuth";const generateAuth = (username: string, password: string) => {const auth = Buffer.from(`${username}:${password}`).toString("base64");@@ -38,6 +37,14 @@ describe("Health endpoints", () => {});describe("Ingestion Pipeline", () => {+ beforeEach(async () => {+ // clear the redis cache+ const keys = await redis?.keys("*");+ if (keys && keys.length > 0) {+ await redis?.del(keys);+ }+ });+it("ingest a trace", async () => {const traceId = v4();const spanId = v4();@@ -118,7 +125,7 @@ describe("Ingestion Pipeline", () => {expect(redisKeys?.length).toBe(1);const redisValue = await redis?.get(redisKeys![0]);- const llmApiKey = ApiKeyZod.parse(JSON.parse(redisValue!));+ const llmApiKey = OrgEnrichedApiKey.parse(JSON.parse(redisValue!));expect(llmApiKey.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");});@@ -143,6 +150,91 @@ describe("Ingestion Pipeline", () => {expect(response.status).toBe(207);}, 25000);++ it("rate limit ingestion", async () => {+ // update the org in the database and set the rate limit to 1 for ingestion+ const org = await prisma.organization.findUnique({+ where: {+ id: "seed-org-id",+ },+ });+ await prisma.organization.update({+ where: {+ id: "seed-org-id",+ },+ data: {+ cloudConfig: {+ ...(typeof org?.cloudConfig === "object" ? org.cloudConfig : {}),+ rateLimitOverrides: [+ {+ resource: "ingestion",+ points: 1,+ durationInSec: 60,+ },+ ],+ },+ },+ });++ const traceId = v4();+ const spanId = v4();++ const event = {+ batch: [+ {+ id: v4(),+ type: "trace-create",+ timestamp: new Date().toISOString(),+ body: {+ name: "test trace",+ id: traceId,+ userId: "user-1", // triggers the eval+ },+ },+ {+ id: v4(),+ type: "span-create",+ timestamp: new Date().toISOString(),+ body: {+ id: spanId,+ traceId: traceId,+ name: "test span",+ },+ },+ ],+ };+ // Arrange+ const url = "http://localhost:3000/api/public/ingestion";++ // Act+ let responses = [];+ for (let i = 0; i < 10; i++) {+ responses.push(+ await fetch(url, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: userApiKeyAuth,+ },+ body: JSON.stringify(event),+ }),+ );+ }++ // check that at least one of the responses is a 429+ const rateLimitedResponse = responses.find((r) => r.status === 429);+ expect(rateLimitedResponse).not.toBeNull();++ // revert the rate limit on the org+ await prisma.organization.update({+ where: {+ id: "seed-org-id",+ },+ data: {+ cloudConfig: org?.cloudConfig ?? Prisma.JsonNull,+ },+ });+ });});describe("Prompts endpoint", () => {diff --git a/web/src/__tests__/api-auth.servertest.ts b/web/src/__tests__/api-auth.servertest.tsindex 2c5d8373bb..6c75863477 100644--- a/web/src/__tests__/api-auth.servertest.ts+++ b/web/src/__tests__/api-auth.servertest.ts@@ -1,14 +1,12 @@import {getDisplaySecretKey,hashSecretKey,+ OrgEnrichedApiKey,} from "@langfuse/shared/src/server";-import {- ApiAuthService,- ApiKeyZod,-} from "@/src/features/public-api/server/apiAuth";-import { type PrismaClient, prisma } from "@langfuse/shared/src/db";+import { Prisma, type PrismaClient, prisma } from "@langfuse/shared/src/db";import { Redis } from "ioredis";import { env } from "@/src/env.mjs";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";describe("Authenticate API calls", () => {beforeEach(async () => {@@ -149,6 +147,25 @@ describe("Authenticate API calls", () => {it("should create new api key and read from cache", async () => {await createAPIKey();+ // update the organization with a cloud config+ await prisma.organization.update({+ where: { id: "seed-org-id" },+ data: {+ cloudConfig: {+ rateLimitOverrides: [+ {+ resource: "public-api",+ points: 1000,+ durationInSec: 60,+ },+ {+ resource: "ingestion",+ },+ ],+ },+ },+ });+// first auth will generate the fast hashed api keyawait new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope("Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",@@ -177,12 +194,31 @@ describe("Authenticate API calls", () => {expect(cachedKey2).not.toBeNull();- const parsed = ApiKeyZod.parse(JSON.parse(cachedKey2!));+ const parsed = OrgEnrichedApiKey.parse(JSON.parse(cachedKey2!));expect(parsed).toEqual({...apiKey,+ orgId: "seed-org-id",+ plan: "cloud:hobby",+ rateLimitOverrides: [+ {+ resource: "public-api",+ points: 1000,+ durationInSec: 60,+ },+ {+ resource: "ingestion",+ },+ ],createdAt: apiKey?.createdAt.toISOString(),});++ await prisma.organization.update({+ where: { id: "seed-org-id" },+ data: {+ cloudConfig: Prisma.JsonNull,+ },+ });});it("searching for non-existing key stores flag in redis and fails auth", async () => {@@ -275,7 +311,7 @@ describe("Authenticate API calls", () => {);expect(cachedKey).not.toBeNull();- const parsed = ApiKeyZod.parse(JSON.parse(cachedKey!));+ const parsed = OrgEnrichedApiKey.parse(JSON.parse(cachedKey!));expect(parsed).toEqual({id: expect.any(String),@@ -288,6 +324,8 @@ describe("Authenticate API calls", () => {lastUsedAt: null,expiresAt: null,projectId: expect.any(String),+ orgId: "seed-org-id",+ plan: "cloud:hobby",});});@@ -372,10 +410,12 @@ describe("Authenticate API calls", () => {);expect(cachedKey).not.toBeNull();- const parsed = ApiKeyZod.parse(JSON.parse(cachedKey!));+ const parsed = OrgEnrichedApiKey.parse(JSON.parse(cachedKey!));expect(parsed).toEqual({...apiKey,+ orgId: "seed-org-id",+ plan: "cloud:hobby",createdAt: apiKey?.createdAt.toISOString(),});diff --git a/web/src/__tests__/rate-limit.servertest.ts b/web/src/__tests__/rate-limit.servertest.tsnew file mode 100644index 0000000000..f90f7241d3--- /dev/null+++ b/web/src/__tests__/rate-limit.servertest.ts@@ -0,0 +1,269 @@+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";+import { Redis } from "ioredis";++describe("RateLimitService", () => {+ const orgId = "seed-org-id";+ let redis: Redis;++ beforeAll(() => {+ redis = new Redis("redis://:[email protected]:6379", {+ maxRetriesPerRequest: null,+ });+ });++ afterAll(async () => {+ redis.disconnect();+ });++ beforeEach(async () => {+ expect(redis).toBeDefined();+ const keys = await redis?.keys("rate-limit*");+ if (keys && keys?.length > 0) {+ await redis?.del(keys);+ }+ });++ afterEach(async () => {+ const keys = await redis?.keys("rate-limit*");+ if (keys && keys.length > 0) {+ await redis?.del(keys);+ }+ });++ it("should rate limit", async () => {+ const scope = {+ orgId: orgId,+ plan: "cloud:hobby" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [],+ };++ const rateLimitService = new RateLimitService(redis!);+ const result = await rateLimitService.rateLimitRequest(scope, "public-api");++ expect(result?.res).toEqual({+ scope: scope,+ resource: "public-api",+ points: 1000,+ remainingPoints: 999,+ msBeforeNext: expect.any(Number),+ consumedPoints: 1,+ isFirstInDuration: true,+ });++ expect(result?.isRateLimited()).toBe(false);++ // check redis for the rate limit key+ const value = await redis.get("rate-limit:public-api:seed-org-id");++ expect(value).toBeDefined();+ expect(parseInt(value ?? "0")).toBeGreaterThan(0);+ });++ it("should increment the rate limit count", async () => {+ const scope = {+ orgId: orgId,+ plan: "cloud:hobby" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [],+ };++ const rateLimitService = new RateLimitService(redis!);+ await rateLimitService.rateLimitRequest(scope, "public-api");++ const result = await rateLimitService.rateLimitRequest(scope, "public-api");++ expect(result?.res).toEqual({+ scope: scope,+ resource: "public-api",+ points: 1000,+ remainingPoints: 998,+ msBeforeNext: expect.any(Number),+ consumedPoints: 2,+ isFirstInDuration: false,+ });+ expect(result?.isRateLimited()).toBe(false);+ });++ it("should reset the rate limit count after the window expires", async () => {+ const scope = {+ orgId: orgId,+ plan: "cloud:hobby" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [+ { resource: "public-api" as const, points: 100, durationInSec: 2 },+ ],+ };++ const rateLimitService = new RateLimitService(redis!);+ await rateLimitService.rateLimitRequest(scope, "public-api");++ const firstResult = await rateLimitService.rateLimitRequest(+ scope,+ "public-api",+ );+ expect(firstResult?.isRateLimited()).toBe(false);++ expect(firstResult?.res).toEqual({+ scope: scope,+ resource: "public-api",+ points: 100,+ remainingPoints: 98,+ msBeforeNext: expect.any(Number),+ consumedPoints: 2,+ isFirstInDuration: false,+ });++ await new Promise((resolve) => setTimeout(resolve, 3000));++ const secondResult = await rateLimitService.rateLimitRequest(+ scope,+ "public-api",+ );++ expect(secondResult?.res).toEqual({+ scope: scope,+ resource: "public-api",+ points: 100,+ remainingPoints: 99,+ msBeforeNext: expect.any(Number),+ consumedPoints: 1,+ isFirstInDuration: true,+ });++ expect(secondResult?.isRateLimited()).toBe(false);+ });++ it("should return false when rate limit is exceeded", async () => {+ const scope = {+ orgId: orgId,+ plan: "cloud:hobby" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [+ { resource: "public-api" as const, points: 5, durationInSec: 60 },+ ],+ };++ const rateLimitService = new RateLimitService(redis!);++ for (let i = 0; i < 5; i++) {+ await rateLimitService.rateLimitRequest(scope, "public-api");+ }++ const result = await rateLimitService.rateLimitRequest(scope, "public-api");++ expect(result?.res).toEqual({+ scope: scope,+ resource: "public-api",+ points: 5,+ remainingPoints: 0,+ msBeforeNext: expect.any(Number),+ consumedPoints: 6,+ isFirstInDuration: false,+ });+ expect(result?.isRateLimited()).toBe(true);+ });++ it("should apply rate limits with override for specific resource", async () => {+ const scope = {+ orgId: orgId,+ plan: "cloud:hobby" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [+ { resource: "public-api" as const, points: 5, durationInSec: 10 },+ ],+ };++ const rateLimitService = new RateLimitService(redis!);++ const result = await rateLimitService.rateLimitRequest(scope, "public-api");++ expect(result?.res).toEqual({+ scope: scope,+ resource: "public-api",+ points: 5,+ remainingPoints: 4,+ msBeforeNext: expect.any(Number),+ consumedPoints: 1,+ isFirstInDuration: true,+ });+ });++ it("should not apply rate limits for resource prompts", async () => {+ const scope = {+ orgId: orgId,+ plan: "cloud:hobby" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [+ { resource: "public-api" as const, points: 5, durationInSec: 10 },+ ],+ };++ const rateLimitService = new RateLimitService(redis!);++ const result = await rateLimitService.rateLimitRequest(scope, "prompts");++ expect(result?.res).toBeUndefined();+ expect(result?.isRateLimited()).toBe(false);+ });++ it("should not apply rate limits for ingestion when overridden to null in API key", async () => {+ const scope = {+ orgId: orgId,+ plan: "cloud:hobby" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [+ { resource: "ingestion" as const, points: null, durationInSec: null },+ ],+ };++ const rateLimitService = new RateLimitService(redis!);++ const result = await rateLimitService.rateLimitRequest(scope, "ingestion");++ expect(result?.res).toBeUndefined();+ });++ it("should not apply rate limits when redis is not defined", async () => {+ const scope = {+ orgId: orgId,+ plan: "cloud:hobby" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [+ { resource: "public-api" as const, points: 5, durationInSec: 10 },+ ],+ };++ const rateLimitService = new RateLimitService(null);++ const result = await rateLimitService.rateLimitRequest(scope, "public-api");++ expect(result?.res).toBeUndefined();+ expect(result?.isRateLimited()).toBe(false);+ });++ it("should not apply rate limits for OSS plan", async () => {+ const scope = {+ orgId: orgId,+ plan: "oss" as const,+ projectId: "test-project-id",+ accessLevel: "all" as const,+ rateLimitOverrides: [],+ };++ const rateLimitService = new RateLimitService(redis!);++ const result = await rateLimitService.rateLimitRequest(scope, "public-api");++ expect(result?.res).toBeUndefined();+ expect(result?.isRateLimited()).toBe(false);+ });+});diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsxindex 08d5060646..7eb102a0ef 100644--- a/web/src/ee/features/billing/components/BillingSettings.tsx+++ b/web/src/ee/features/billing/components/BillingSettings.tsx@@ -16,10 +16,7 @@ import { useQueryOrganization } from "@/src/features/organizations/hooks";import { Card } from "@/src/components/ui/card";import { numberFormatter, compactNumberFormatter } from "@/src/utils/numbers";import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";-import {- type Plan,- planLabels,-} from "@/src/features/entitlements/constants/plans";+import { type Plan, planLabels } from "@langfuse/shared";import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";import { useRouter } from "next/router";import {diff --git a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts b/web/src/ee/features/billing/server/stripeWebhookApiHandler.tsindex 55539e68ff..92ed431498 100644--- a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts+++ b/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts@@ -8,7 +8,8 @@ import { prisma } from "@langfuse/shared/src/db";import { stripeClient } from "@/src/ee/features/billing/utils/stripe";import type Stripe from "stripe";import { CloudConfigSchema, parseDbOrg } from "@langfuse/shared";-import { traceException } from "@langfuse/shared/src/server";+import { traceException, redis } from "@langfuse/shared/src/server";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";/** Sign-up endpoint (email/password users), creates user in database.@@ -227,5 +228,8 @@ async function handleSubscriptionChanged(});}+ // need to update the plan in the api keys+ await new ApiAuthService(prisma, redis).invalidateOrgApiKeys(parsedOrg.id);+return;}diff --git a/web/src/ee/features/billing/utils/stripeProducts.ts b/web/src/ee/features/billing/utils/stripeProducts.tsindex 9ae1f7d91d..ba1cedfdee 100644--- a/web/src/ee/features/billing/utils/stripeProducts.ts+++ b/web/src/ee/features/billing/utils/stripeProducts.ts@@ -1,5 +1,5 @@import { env } from "@/src/env.mjs";-import { type Plan } from "@/src/features/entitlements/constants/plans";+import { type Plan } from "@langfuse/shared";type StripeProduct = {stripeProductId: string;diff --git a/web/src/env.mjs b/web/src/env.mjsindex 687906376d..9b6ec348d0 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -170,6 +170,7 @@ export const env = createEnv({STRIPE_WEBHOOK_SIGNING_SECRET: z.string().optional(),SENTRY_AUTH_TOKEN: z.string().optional(),SENTRY_CSP_REPORT_URI: z.string().optional(),+ LANGFUSE_RATE_LIMITS_ENABLED: z.enum(["true", "false"]).default("true"),},/**@@ -319,6 +320,7 @@ export const env = createEnv({STRIPE_WEBHOOK_SIGNING_SECRET: process.env.STRIPE_WEBHOOK_SIGNING_SECRET,SENTRY_AUTH_TOKEN: process.env.SENTRY_AUTH_TOKEN,SENTRY_CSP_REPORT_URI: process.env.SENTRY_CSP_REPORT_URI,+ LANGFUSE_RATE_LIMITS_ENABLED: process.env.LANGFUSE_RATE_LIMITS_ENABLED,},// Skip validation in Docker builds// DOCKER_BUILD is set in Dockerfilediff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.tsindex 2c152b7b20..99c0caa813 100644--- a/web/src/features/entitlements/constants/entitlements.ts+++ b/web/src/features/entitlements/constants/entitlements.ts@@ -1,4 +1,4 @@-import { type Plan } from "@/src/features/entitlements/constants/plans";+import { type Plan } from "@langfuse/shared";const entitlements = [// featuresdiff --git a/web/src/features/entitlements/hooks.ts b/web/src/features/entitlements/hooks.tsindex 3972afad09..b71d156801 100644--- a/web/src/features/entitlements/hooks.ts+++ b/web/src/features/entitlements/hooks.ts@@ -2,7 +2,7 @@ import {entitlementAccess,type Entitlement,} from "@/src/features/entitlements/constants/entitlements";-import { type Plan } from "@/src/features/entitlements/constants/plans";+import { type Plan } from "@langfuse/shared";import { useSession } from "next-auth/react";import { useRouter } from "next/router";diff --git a/web/src/features/entitlements/server/getOrganizationPlan.ts b/web/src/features/entitlements/server/getOrganizationPlan.tsindex 0f23b44aa5..de9c8f07d0 100644--- a/web/src/features/entitlements/server/getOrganizationPlan.ts+++ b/web/src/features/entitlements/server/getOrganizationPlan.ts@@ -1,6 +1,6 @@import { mapStripeProductIdToPlan } from "@/src/ee/features/billing/utils/stripeProducts";import { env } from "@/src/env.mjs";-import { type Plan } from "@/src/features/entitlements/constants/plans";+import { type Plan } from "@langfuse/shared";import { type CloudConfigSchema } from "@langfuse/shared";/**diff --git a/web/src/features/organizations/components/ProjectOverview.tsx b/web/src/features/organizations/components/ProjectOverview.tsxindex 33fb1c22c6..3599f4da9d 100644--- a/web/src/features/organizations/components/ProjectOverview.tsx+++ b/web/src/features/organizations/components/ProjectOverview.tsx@@ -24,10 +24,7 @@ import {createOrganizationRoute,createProjectRoute,} from "@/src/features/setup/setupRoutes";-import {- isCloudPlan,- planLabels,-} from "@/src/features/entitlements/constants/plans";+import { isCloudPlan, planLabels } from "@langfuse/shared";const SingleOrganizationProjectOverview = ({orgId,diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.tsindex e63986f24c..0f99da601c 100644--- a/web/src/features/organizations/server/organizationRouter.ts+++ b/web/src/features/organizations/server/organizationRouter.ts@@ -8,6 +8,8 @@ import { organizationNameSchema } from "@/src/features/organizations/utils/organimport * as z from "zod";import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import { TRPCError } from "@trpc/server";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { redis } from "@langfuse/shared/src/server";export const organizationsRouter = createTRPCRouter({create: protectedProcedure@@ -115,6 +117,11 @@ export const organizationsRouter = createTRPCRouter({},});+ // the api keys contain which org they belong to, so we need to remove them from Redis+ await new ApiAuthService(ctx.prisma, redis).invalidateOrgApiKeys(+ input.orgId,+ );+await auditLog({session: ctx.session,resourceType: "organization",diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.tsindex 305ea87b1e..34b400832a 100644--- a/web/src/features/projects/server/projectsRouter.ts+++ b/web/src/features/projects/server/projectsRouter.ts@@ -9,6 +9,8 @@ import { TRPCError } from "@trpc/server";import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";import { auditLog } from "@/src/features/audit-logs/auditLog";import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { redis } from "@langfuse/shared/src/server";export const projectsRouter = createTRPCRouter({create: protectedOrganizationProcedure@@ -110,6 +112,11 @@ export const projectsRouter = createTRPCRouter({},});+ // API keys need to be deleted from cache. Otherwise, they will still be valid.+ await new ApiAuthService(ctx.prisma, redis).invalidateProjectApiKeys(+ input.projectId,+ );+return true;}),@@ -153,6 +160,7 @@ export const projectsRouter = createTRPCRouter({before: { orgId: ctx.session.orgId },after: { orgId: input.targetOrgId },});+await ctx.prisma.$transaction([ctx.prisma.projectMembership.deleteMany({where: {@@ -169,5 +177,11 @@ export const projectsRouter = createTRPCRouter({},}),]);++ // API keys need to be deleted from cache. Otherwise, they will still be valid.+ // It has to be called after the db is done to prevent new API keys from being cached.+ await new ApiAuthService(ctx.prisma, redis).invalidateProjectApiKeys(+ input.projectId,+ );}),});diff --git a/web/src/features/prompts/server/handlers/promptNameHandler.ts b/web/src/features/prompts/server/handlers/promptNameHandler.tsindex 10a3d68d16..cc00b2478d 100644--- a/web/src/features/prompts/server/handlers/promptNameHandler.ts+++ b/web/src/features/prompts/server/handlers/promptNameHandler.ts@@ -3,16 +3,27 @@ import type { NextApiRequest, NextApiResponse } from "next";import { getPromptByName } from "@/src/features/prompts/server/actions/getPromptByName";import { GetPromptByNameSchema } from "@/src/features/prompts/server/utils/validation";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-+import { redis } from "@langfuse/shared/src/server";import { authorizePromptRequestOrThrow } from "../utils/authorizePromptRequest";import { LangfuseNotFoundError } from "@langfuse/shared";import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";const getPromptNameHandler = async (req: NextApiRequest,res: NextApiResponse,) => {const authCheck = await authorizePromptRequestOrThrow(req);++ const rateLimitCheck = await new RateLimitService(redis).rateLimitRequest(+ authCheck.scope,+ "prompts",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+const { promptName, version, label } = GetPromptByNameSchema.parse(req.query);const prompt = await getPromptByName({diff --git a/web/src/features/prompts/server/handlers/promptsHandler.ts b/web/src/features/prompts/server/handlers/promptsHandler.tsindex 97f1b7ef56..5859c113b2 100644--- a/web/src/features/prompts/server/handlers/promptsHandler.ts+++ b/web/src/features/prompts/server/handlers/promptsHandler.ts@@ -8,12 +8,22 @@ import {} from "@/src/features/prompts/server/utils/validation";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { prisma } from "@langfuse/shared/src/db";-+import { redis } from "@langfuse/shared/src/server";import { authorizePromptRequestOrThrow } from "../utils/authorizePromptRequest";+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";const getPromptsHandler = async (req: NextApiRequest, res: NextApiResponse) => {const authCheck = await authorizePromptRequestOrThrow(req);+ const rateLimitCheck = await new RateLimitService(redis).rateLimitRequest(+ authCheck.scope,+ "prompts",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+const input = GetPromptsMetaSchema.parse(req.query);const promptsMetadata = await getPromptsMeta({...input,@@ -29,6 +39,15 @@ const postPromptsHandler = async () => {const authCheck = await authorizePromptRequestOrThrow(req);+ const rateLimitCheck = await new RateLimitService(redis).rateLimitRequest(+ authCheck.scope,+ "prompts",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+const input = CreatePromptSchema.parse(req.body);const createdPrompt = await createPrompt({...input,diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.tsnew file mode 100644index 0000000000..9000273d4a--- /dev/null+++ b/web/src/features/public-api/server/RateLimitService.ts@@ -0,0 +1,231 @@+import type Redis from "ioredis";+import { type z } from "zod";+import { RateLimiterRedis, RateLimiterRes } from "rate-limiter-flexible";+import { env } from "@/src/env.mjs";+import {+ type RateLimitResult,+ type RateLimitResource,+ type RateLimitConfig,+ type Plan,+} from "@langfuse/shared";+import {+ recordIncrement,+ type ApiAccessScope,+} from "@langfuse/shared/src/server";+import { type NextApiResponse } from "next";++// Business Logic+// - rate limit strategy is based on org-id, org plan, and resources. Rate limits are appliead in buckets of minutes.+// - rate limits are not applied for self hosters and are also not applied when Redis is not available+// - infos for rate-limits are taken from the API access scope. Info for this scope is stored alongside API Keys in Redis for efficient access.+// - isRateLimited returns false for self-hosters+// - sendRestResponseIfLimited sends a 429 response with headers if the rate limit is exceeded. Return this from the route handler.+export class RateLimitService {+ private redis: Redis | null;++ constructor(redis: Redis | null) {+ this.redis = redis;+ }++ async rateLimitRequest(+ scope: ApiAccessScope,+ resource: z.infer<typeof RateLimitResource>,+ ) {+ // if cloud config is not present, we don't apply rate limits and just return+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ return new RateLimitHelper(undefined);+ }++ if (env.LANGFUSE_RATE_LIMITS_ENABLED === "false") {+ return new RateLimitHelper(undefined);+ }++ if (!this.redis) {+ console.log("Rate limiting not available without Redis");+ return new RateLimitHelper(undefined);+ }++ return new RateLimitHelper(await this.checkRateLimit(scope, resource));+ }++ async checkRateLimit(+ scope: ApiAccessScope,+ resource: z.infer<typeof RateLimitResource>,+ ) {+ const effectiveConfig = getRateLimitConfig(scope, resource);++ // returning early if no rate limit is set+ if (+ !effectiveConfig ||+ !effectiveConfig.points ||+ !effectiveConfig.durationInSec+ ) {+ return;+ }++ const rateLimiter = new RateLimiterRedis({+ // Basic options+ points: effectiveConfig.points, // Number of points+ duration: effectiveConfig.durationInSec, // Per second(s)++ keyPrefix: this.rateLimitPrefix(resource), // must be unique for limiters with different purpose+ storeClient: this.redis,+ rejectIfRedisNotReady: true,+ });++ let res: RateLimitResult | undefined = undefined;+ try {+ // orgId used as key for different resources+ const libRes = await rateLimiter.consume(scope.orgId);+ res = {+ resource,+ scope,+ points: effectiveConfig.points,+ remainingPoints: libRes.remainingPoints,+ msBeforeNext: libRes.msBeforeNext,+ consumedPoints: libRes.consumedPoints,+ isFirstInDuration: libRes.isFirstInDuration,+ };+ } catch (err) {+ if (err instanceof RateLimiterRes) {+ // No points available or key is blocked+ res = {+ resource,+ scope,+ points: effectiveConfig.points,+ remainingPoints: err.remainingPoints,+ msBeforeNext: err.msBeforeNext,+ consumedPoints: err.consumedPoints,+ isFirstInDuration: err.isFirstInDuration,+ };+ } else {+ // Some other error occurred, rethrow it+ console.log("Internal Rate limit error", err);+ throw err;+ }+ }++ if (res.remainingPoints < 1) {+ recordIncrement("rate_limit_exceeded", 1, {+ orgId: scope.orgId,+ plan: scope.plan,+ resource: resource,+ });+ }++ return res;+ }++ rateLimitPrefix(resource: string) {+ return `rate-limit:${resource}`;+ }+}++export class RateLimitHelper {+ res: RateLimitResult | undefined;++ constructor(res: RateLimitResult | undefined) {+ this.res = res;+ }++ isRateLimited() {+ return this.res ? this.res.remainingPoints < 1 : false;+ }++ sendRestResponseIfLimited(nextResponse: NextApiResponse) {+ if (!this.res || !this.isRateLimited()) {+ console.error(+ "Trying to send rate limit response without being limited.",+ );+ throw new Error(+ "Trying to send rate limit response without being limited.",+ );+ }+ return sendRateLimitResponse(nextResponse, this.res);+ }+}++export const sendRateLimitResponse = (+ res: NextApiResponse,+ rateLimitRes: RateLimitResult,+) => {+ const httpHeader = createHttpHeaderFromRateLimit(rateLimitRes);++ for (const [header, value] of Object.entries(httpHeader)) {+ res.setHeader(header, value);+ }++ res.status(429).end("429 - rate limit exceeded");+};++const createHttpHeaderFromRateLimit = (res: RateLimitResult) => {+ return {+ "Retry-After": res.msBeforeNext / 1000,+ "X-RateLimit-Limit": res.points,+ "X-RateLimit-Remaining": res.remainingPoints,+ "X-RateLimit-Reset": new Date(Date.now() + res.msBeforeNext).toString(),+ };+};++const getRateLimitConfig = (+ scope: ApiAccessScope,+ resource: z.infer<typeof RateLimitResource>,+) => {+ const planBasedConfig = getPlanBasedRateLimitConfig(scope.plan, resource);+ const customConfig = scope.rateLimitOverrides?.find(+ (config) => config.resource === resource,+ );++ return customConfig || planBasedConfig;+};++const getPlanBasedRateLimitConfig = (+ plan: Plan,+ resource: z.infer<typeof RateLimitResource>,+): z.infer<typeof RateLimitConfig> => {+ switch (plan) {+ case "oss":+ case "self-hosted:enterprise":+ return { resource, points: null, durationInSec: null };+ case "cloud:hobby":+ case "cloud:pro":+ switch (resource) {+ case "ingestion":+ return { resource: "ingestion", points: 1000, durationInSec: 60 };+ case "prompts":+ return { resource: "prompts", points: null, durationInSec: null };+ case "public-api":+ return { resource: "public-api", points: 1000, durationInSec: 60 };+ case "public-api-metrics":+ return {+ resource: "public-api-metrics",+ points: 10,+ durationInSec: 60,+ };+ default:+ const exhaustiveCheckDefault: never = resource;+ throw new Error(`Unhandled resource case: ${exhaustiveCheckDefault}`);+ }+ case "cloud:team":+ switch (resource) {+ case "ingestion":+ return { resource: "ingestion", points: 5000, durationInSec: 60 };+ case "prompts":+ return { resource: "prompts", points: null, durationInSec: null };+ case "public-api":+ return { resource: "public-api", points: 1000, durationInSec: 60 };+ case "public-api-metrics":+ return {+ resource: "public-api-metrics",+ points: 10,+ durationInSec: 60,+ };+ default:+ const exhaustiveCheckTeam: never = resource;+ throw new Error(`Unhandled resource case: ${exhaustiveCheckTeam}`);+ }+ default:+ const exhaustiveCheck: never = plan;+ throw new Error(`Unhandled plan case: ${exhaustiveCheck}`);+ }+};diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 8e273cf723..0c235cf504 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -5,31 +5,20 @@ import {recordIncrement,verifySecretKey,type AuthHeaderVerificationResult,+ CachedApiKey,+ OrgEnrichedApiKey,} from "@langfuse/shared/src/server";-import { type PrismaClient, type ApiKey } from "@langfuse/shared/src/db";+import {+ type PrismaClient,+ type ApiKey,+ type Prisma,+} from "@langfuse/shared/src/db";import { isPrismaException } from "@/src/utils/exceptions";import { type Redis } from "ioredis";-import { z } from "zod";--export const ApiKeyZod = z.object({- id: z.string(),- note: z.string().nullable(),- publicKey: z.string(),- hashedSecretKey: z.string(),- fastHashedSecretKey: z.string().nullable(),- displaySecretKey: z.string(),- createdAt: z.string().datetime().nullable(),- lastUsedAt: z.string().datetime().nullable(),- expiresAt: z.string().datetime().nullable(),- projectId: z.string(),-});--const API_KEY_NON_EXISTENT = "api-key-non-existent";--export const CachedApiKey = z.union([- ApiKeyZod,- z.literal(API_KEY_NON_EXISTENT),-]);+import { getOrganizationPlan } from "@/src/features/entitlements/server/getOrganizationPlan";+import { API_KEY_NON_EXISTENT } from "@langfuse/shared/src/server";+import { type z } from "zod";+import { CloudConfigSchema, isPlan } from "@langfuse/shared";export class ApiAuthService {prisma: PrismaClient;@@ -40,6 +29,44 @@ export class ApiAuthService {this.redis = redis;}+ // this function needs to be called, when the organisation is updated+ // - when projects move across organisations, the orgId in the API key cache needs to be updated+ // - when the plan of the org changes, the plan in the API key cache needs to be updated as well+ private async invalidate(apiKeys: ApiKey[], identifier: string) {+ const hashKeys = apiKeys.map((key) => key.fastHashedSecretKey);++ if (this.redis) {+ console.log(`Invalidating API keys in redis for ${identifier}`);+ await this.redis.del(+ hashKeys+ .filter((hash): hash is string => Boolean(hash))+ .map((hash) => this.createRedisKey(hash)),+ );+ }+ }++ async invalidateOrgApiKeys(orgId: string) {+ const apiKeys = await this.prisma.apiKey.findMany({+ where: {+ project: {+ orgId: orgId,+ },+ },+ });++ await this.invalidate(apiKeys, `org ${orgId}`);+ }++ async invalidateProjectApiKeys(projectId: string) {+ const apiKeys = await this.prisma.apiKey.findMany({+ where: {+ projectId: projectId,+ },+ });++ await this.invalidate(apiKeys, `project ${projectId}`);+ }+async deleteApiKey(id: string, projectId: string) {// Make sure the API key exists and belongs to the project the user has access toconst apiKey = await this.prisma.apiKey.findFirstOrThrow({@@ -87,16 +114,18 @@ export class ApiAuthService {const hashFromProvidedKey = createShaHash(secretKey, salt);// fetches by redis if available, fallback to postgres+ // api key from redis doesconst apiKey = await this.fetchApiKeyAndAddToRedis(hashFromProvidedKey);- let projectId = apiKey?.projectId;+ let finalApiKey = apiKey;if (!apiKey || !apiKey.fastHashedSecretKey) {- const dbKey = await this.prisma.apiKey.findUnique({+ const slowKey = await this.prisma.apiKey.findUnique({where: { publicKey },+ include: { project: { include: { organization: true } } },});- if (!dbKey) {+ if (!slowKey) {console.error("No key found for public key", publicKey);if (this.redis) {console.log(@@ -112,7 +141,7 @@ export class ApiAuthService {const isValid = await verifySecretKey(secretKey,- dbKey.hashedSecretKey,+ slowKey.hashedSecretKey,);if (!isValid) {@@ -128,21 +157,34 @@ export class ApiAuthService {fastHashedSecretKey: shaKey,},});- projectId = dbKey.projectId;+ finalApiKey = convertToRedisRepresentation({+ ...slowKey,+ fastHashedSecretKey: shaKey,+ });}- if (!projectId) {+ if (!finalApiKey) {console.log("No project id found for key", publicKey);throw new Error("Invalid credentials");}- addUserToSpan({ projectId });+ addUserToSpan({ projectId: finalApiKey.projectId });++ const plan = finalApiKey.plan;++ if (!isPlan(plan)) {+ console.error("Invalid plan type for key", finalApiKey.plan);+ throw new Error("Invalid credentials");+ }return {validKey: true,scope: {- projectId: projectId,+ projectId: finalApiKey.projectId,accessLevel: "all",+ orgId: finalApiKey.orgId,+ plan: plan,+ rateLimitOverrides: finalApiKey.rateLimitOverrides ?? [],},};}@@ -154,17 +196,25 @@ export class ApiAuthService {addUserToSpan({ projectId: dbKey.projectId });+ const cloudConfig = dbKey.project.organization.cloudConfig+ ? CloudConfigSchema.parse(dbKey.project.organization.cloudConfig)+ : undefined;+return {validKey: true,scope: {projectId: dbKey.projectId,accessLevel: "scores",+ orgId: dbKey.project.organization.id,+ plan: getOrganizationPlan(cloudConfig),+ rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],},};}} catch (error: unknown) {console.error(`Error verifying auth header: ${error instanceof Error ? error.message : null}`,+ error,);if (isPrismaException(error)) {@@ -199,6 +249,7 @@ export class ApiAuthService {async findDbKeyOrThrow(publicKey: string) {const dbKey = await this.prisma.apiKey.findUnique({where: { publicKey },+ include: { project: { include: { organization: true } } },});if (!dbKey) {console.log("No api key found for public key:", publicKey);@@ -225,21 +276,27 @@ export class ApiAuthService {recordIncrement("api_key_cache_miss", 1);// if redis not available or object not found, try the database- const apiKey = await this.prisma.apiKey.findUnique({+ const apiKeyAndOrganisation = await this.prisma.apiKey.findUnique({where: { fastHashedSecretKey: hash },+ include: { project: { include: { organization: true } } },});// add the key to redis for future use if available, this does not throw// only do so if the new hashkey exists already.- if (apiKey && apiKey.fastHashedSecretKey) {- await this.addApiKeyToRedis(hash, apiKey);+ if (apiKeyAndOrganisation && apiKeyAndOrganisation.fastHashedSecretKey) {+ await this.addApiKeyToRedis(+ hash,+ convertToRedisRepresentation(apiKeyAndOrganisation),+ );}- return apiKey;+ return apiKeyAndOrganisation+ ? convertToRedisRepresentation(apiKeyAndOrganisation)+ : null;}async addApiKeyToRedis(hash: string,- apiKey: ApiKey | typeof API_KEY_NON_EXISTENT,+ newApiKey: z.infer<typeof OrgEnrichedApiKey> | typeof API_KEY_NON_EXISTENT,) {if (!this.redis || env.LANGFUSE_CACHE_API_KEY_ENABLED !== "true") {return;@@ -248,7 +305,7 @@ export class ApiAuthService {try {await this.redis.set(this.createRedisKey(hash),- JSON.stringify(apiKey),+ JSON.stringify(newApiKey),"EX",env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS, // redis API is in seconds);@@ -296,3 +353,43 @@ export class ApiAuthService {return `api-key:${hash}`;}}++export const convertToRedisRepresentation = (+ apiKeyAndOrganisation: ApiKey & {+ project: {+ id: string;+ organization: {+ id: string;+ name: string;+ createdAt: Date;+ updatedAt: Date;+ cloudConfig: Prisma.JsonValue;+ };+ };+ },+) => {+ const {+ project: {+ organization: { id: orgId, cloudConfig: cloudConfig },+ },+ } = apiKeyAndOrganisation;++ const parsedCloudConfig = cloudConfig+ ? CloudConfigSchema.parse(cloudConfig)+ : undefined;++ const newApiKey = OrgEnrichedApiKey.parse({+ ...apiKeyAndOrganisation,+ createdAt: apiKeyAndOrganisation.createdAt?.toISOString(),+ orgId,+ plan: getOrganizationPlan(parsedCloudConfig),+ rateLimitOverrides: parsedCloudConfig?.rateLimitOverrides,+ });++ if (!orgId) {+ console.error("No organization found for key");+ throw new Error("Invalid credentials");+ }++ return newApiKey;+};diff --git a/web/src/features/public-api/server/createAuthedAPIRoute.ts b/web/src/features/public-api/server/createAuthedAPIRoute.tsindex 8992fa71af..f5da5b14e4 100644--- a/web/src/features/public-api/server/createAuthedAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedAPIRoute.ts@@ -7,6 +7,8 @@ import {type AuthHeaderValidVerificationResult,traceException,} from "@langfuse/shared/src/server";+import { type RateLimitResource } from "@langfuse/shared";+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";type RouteConfig<TQuery extends ZodType<any>,@@ -18,6 +20,7 @@ type RouteConfig<bodySchema?: TBody;responseSchema: TResponse;successStatusCode?: number;+ rateLimitRessource?: z.infer<typeof RateLimitResource>; // defaults to public-apifn: (params: {query: z.infer<TQuery>;body: z.infer<TBody>;@@ -50,6 +53,17 @@ export const createAuthedAPIRoute = <return;}+ const rateLimitResponse = await new RateLimitService(+ redis,+ ).rateLimitRequest(+ auth.scope,+ routeConfig.rateLimitRessource || "public-api",+ );++ if (rateLimitResponse?.isRateLimited()) {+ return rateLimitResponse.sendRestResponseIfLimited(res);+ }+console.log("Request to route ",routeConfig.name,diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex b551f5a483..e83ded3ef2 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -1,4 +1,3 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";@@ -40,6 +39,8 @@ import {import { randomUUID } from "crypto";import { prisma } from "@langfuse/shared/src/db";import { tokenCount } from "@/src/features/ingest/usage";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";export const config = {api: {@@ -65,6 +66,15 @@ export default async function handler(if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);+ const rateLimitCheck = await new RateLimitService(redis).rateLimitRequest(+ authCheck.scope,+ "ingestion",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+const batchType = z.object({batch: z.array(z.unknown()),metadata: jsonSchema.nullish(),diff --git a/web/src/pages/api/public/metrics/daily.ts b/web/src/pages/api/public/metrics/daily.tsindex ddb13a195e..1bc99bc05c 100644--- a/web/src/pages/api/public/metrics/daily.ts+++ b/web/src/pages/api/public/metrics/daily.ts@@ -12,6 +12,7 @@ export default withMiddlewares({name: "Get Daily Metrics",querySchema: GetMetricsDailyV1Query,responseSchema: GetMetricsDailyV1Response,+ rateLimitRessource: "public-api-metrics",fn: async ({ query, auth }) => {const traceNameCondition = query.traceName? Prisma.sql`AND t.name = ${query.traceName}`diff --git a/web/src/pages/api/public/projects.ts b/web/src/pages/api/public/projects.tsindex 15340a2be8..7c05f78344 100644--- a/web/src/pages/api/public/projects.ts+++ b/web/src/pages/api/public/projects.ts@@ -5,6 +5,7 @@ import { isPrismaException } from "@/src/utils/exceptions";import { redis } from "@langfuse/shared/src/server";import { type NextApiRequest, type NextApiResponse } from "next";+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";export default async function handler(req: NextApiRequest,@@ -31,6 +32,15 @@ export default async function handler(},});+ const rateLimitCheck = await new RateLimitService(redis).rateLimitRequest(+ authCheck.scope,+ "public-api",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+return res.status(200).json({data: projects.map((project) => ({id: project.id,diff --git a/web/src/pages/api/public/prompts.ts b/web/src/pages/api/public/prompts.tsindex 54a6afa780..f4694f7aa1 100644--- a/web/src/pages/api/public/prompts.ts+++ b/web/src/pages/api/public/prompts.ts@@ -24,6 +24,7 @@ import {traceException,} from "@langfuse/shared/src/server";import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";export default async function handler(req: NextApiRequest,@@ -51,6 +52,15 @@ export default async function handler(const promptName = searchParams.name;const version = searchParams.version ?? undefined;+ const rateLimitCheck = await new RateLimitService(redis).rateLimitRequest(+ authCheck.scope,+ "prompts",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+const promptService = new PromptService(prisma, redis, recordIncrement);let prompt: Prompt | null = null;diff --git a/web/src/pages/api/public/users.ts b/web/src/pages/api/public/users.tsindex 1d54de539d..5dfd47c479 100644--- a/web/src/pages/api/public/users.ts+++ b/web/src/pages/api/public/users.ts@@ -11,6 +11,7 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { paginationZod } from "@langfuse/shared";import { isPrismaException } from "@/src/utils/exceptions";import { redis } from "@langfuse/shared/src/server";+import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";const GetUsersSchema = z.object({...paginationZod,@@ -41,6 +42,15 @@ export default async function handler(});}+ const rateLimitCheck = await new RateLimitService(redis).rateLimitRequest(+ authCheck.scope,+ "public-api",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+const obj = GetUsersSchema.parse(req.query); // uses query and not bodyconst users = await prisma.$queryRaw`diff --git a/web/src/pages/api/trpc/[trpc].ts b/web/src/pages/api/trpc/[trpc].tsindex b53666e885..2e552e1df0 100644--- a/web/src/pages/api/trpc/[trpc].ts+++ b/web/src/pages/api/trpc/[trpc].ts@@ -1,6 +1,7 @@import { createNextApiHandler } from "@trpc/server/adapters/next";import { createTRPCContext } from "@/src/server/api/trpc";import { appRouter } from "@/src/server/api/root";+import { traceException } from "@langfuse/shared/src/server";export const config = {maxDuration: 240,@@ -12,5 +13,6 @@ export default createNextApiHandler({createContext: createTRPCContext,onError: ({ path, error }) => {console.error(`❌ tRPC failed on ${path ?? "<no-path>"}: ${error.message}`);+ traceException(error);},});diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex 63fc40bbed..0a3ff7adc3 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -7,7 +7,7 @@ import {} from "@langfuse/shared/src/db";import { type Flags } from "@/src/features/feature-flags/types";import { type CloudConfigSchema } from "@langfuse/shared";-import { type Plan } from "@/src/features/entitlements/constants/plans";+import { type Plan } from "@langfuse/shared";/*** Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`diff --git a/worker/src/queues/legacyIngestionQueue.ts b/worker/src/queues/legacyIngestionQueue.tsindex 101a1af168..61cd5108aa 100644--- a/worker/src/queues/legacyIngestionQueue.ts+++ b/worker/src/queues/legacyIngestionQueue.ts@@ -19,6 +19,7 @@ import {import { tokenCount } from "../features/tokenisation/usage";import { env } from "../env";import { SpanKind } from "@opentelemetry/api";+import { isPlan } from "@langfuse/shared";const createLegacyIngestionExecutor = () => {const redisInstance = createNewRedisInstance();@@ -50,9 +51,27 @@ const createLegacyIngestionExecutor = () => {unit: "milliseconds",});+ const plan = job.data.payload.authCheck.scope.plan;+ if (!isPlan(plan)) {+ logger.error(+ `Invalid plan type for project ${job.data.payload.authCheck.scope.projectId}`+ );+ return;+ }+const result = await handleBatch(job.data.payload.data,- job.data.payload.authCheck,+ {+ ...job.data.payload.authCheck,+ scope: {+ ...job.data.payload.authCheck.scope,+ plan,+ rateLimitOverrides: job.data.payload.authCheck.scope+ .rateLimitOverrides+ ? job.data.payload.authCheck.scope.rateLimitOverrides+ : [],+ },+ },tokenCount);