Skip to content

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

fix(api): guide rate-limited users to v2 observations (#14360)

Max Deichmann43a10b5cd297
diff --git a/fern/apis/server/definition/sessions.yml b/fern/apis/server/definition/sessions.yml
index 5e06b2c355..69b1cec86e 100644
--- a/fern/apis/server/definition/sessions.yml
+++ b/fern/apis/server/definition/sessions.yml
@@ -7,7 +7,13 @@ service:
base-path: /api/public
endpoints:
list:
- docs: Get sessions
+ docs: |
+ Get sessions.
+
+ This legacy endpoint is not recommended for new data extraction workflows.
+ Use the v2 observations endpoint with a bounded time range and group rows by
+ `sessionId` instead:
+ `GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>`.
method: GET
path: /sessions
request:
@@ -31,7 +37,13 @@ service:
docs: Optional filter for sessions where the environment is one of the provided values.
response: PaginatedSessions
get:
- docs: Get a session. Please note that `traces` on this endpoint are not paginated, if you plan to fetch large sessions, consider `GET /api/public/traces?sessionId=<sessionId>`
+ docs: |
+ Get a session.
+
+ Please note that `traces` on this endpoint are not paginated. For large
+ sessions or new data extraction workflows, use the v2 observations endpoint
+ with a URL-encoded `sessionId` filter and a bounded time range:
+ `GET /api/public/v2/observations?filter=<sessionId filter>&fromStartTime=<from>&toStartTime=<to>`.
method: GET
path: /sessions/{sessionId}
path-parameters:
diff --git a/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts b/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
index a44b2059ad..a809358428 100644
--- a/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
+++ b/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
@@ -86,6 +86,21 @@ vi.mock("@/src/utils/exceptions", () => ({
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
describe("createAuthedProjectAPIRoute auth error handling", () => {
+ const validAuth = {
+ validKey: true,
+ scope: {
+ projectId: "project-1",
+ orgId: "org-1",
+ plan: "cloud:hobby",
+ accessLevel: "project",
+ rateLimitOverrides: [],
+ apiKeyId: "api-key-1",
+ publicKey: "pk-test",
+ isIngestionSuspended: false,
+ isInAppAgentKey: false,
+ },
+ };
+
beforeEach(() => {
vi.clearAllMocks();
mockIsPrismaException.mockReturnValue(false);
@@ -94,7 +109,14 @@ describe("createAuthedProjectAPIRoute auth error handling", () => {
});
});
- async function callRoute(options?: { useUnstableErrorContract?: boolean }) {
+ async function callRoute(options?: {
+ useUnstableErrorContract?: boolean;
+ rateLimitUpgradePath?: {
+ legacyEndpoint: string;
+ replacementEndpoint: string;
+ docsUrl: string;
+ };
+ }) {
const handler = createAuthedProjectAPIRoute({
name: "Test Route",
querySchema: z.object({}),
@@ -102,6 +124,7 @@ describe("createAuthedProjectAPIRoute auth error handling", () => {
errorContract: options?.useUnstableErrorContract
? "unstable-public-evals"
: undefined,
+ rateLimitUpgradePath: options?.rateLimitUpgradePath,
fn: async () => ({ ok: true as const }),
});
@@ -162,4 +185,53 @@ describe("createAuthedProjectAPIRoute auth error handling", () => {
});
expect(mockSendUnstablePublicApiErrorResponse).toHaveBeenCalledTimes(1);
});
+
+ it("keeps the shared rate limit response for routes without upgrade guidance", async () => {
+ const sendRestResponseIfLimited = vi.fn((res: NextApiResponse) => {
+ res.status(429).json({ message: "rate limited" });
+ });
+
+ mockVerifyAuthHeaderAndReturnScope.mockResolvedValueOnce(validAuth);
+ mockRateLimitRequest.mockResolvedValueOnce({
+ isRateLimited: () => true,
+ sendRestResponseIfLimited,
+ });
+
+ const res = await callRoute();
+
+ expect(res.statusCode).toBe(429);
+ expect(sendRestResponseIfLimited).toHaveBeenCalledWith(res, {
+ errorContract: undefined,
+ upgradePath: undefined,
+ });
+ });
+
+ it("passes upgrade guidance to the shared rate limit response", async () => {
+ const sendRestResponseIfLimited = vi.fn((res: NextApiResponse) => {
+ res.status(429).json({ message: "rate limited" });
+ });
+ const upgradePath = {
+ legacyEndpoint: "GET /api/public/traces",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>",
+ docsUrl:
+ "https://langfuse.com/docs/api-and-data-platform/features/observations-api",
+ };
+
+ mockVerifyAuthHeaderAndReturnScope.mockResolvedValueOnce(validAuth);
+ mockRateLimitRequest.mockResolvedValueOnce({
+ isRateLimited: () => true,
+ sendRestResponseIfLimited,
+ });
+
+ const res = await callRoute({
+ rateLimitUpgradePath: upgradePath,
+ });
+
+ expect(res.statusCode).toBe(429);
+ expect(sendRestResponseIfLimited).toHaveBeenCalledWith(res, {
+ errorContract: undefined,
+ upgradePath,
+ });
+ });
});
diff --git a/web/src/__tests__/server/unit/rate-limit-response.servertest.ts b/web/src/__tests__/server/unit/rate-limit-response.servertest.ts
new file mode 100644
index 0000000000..785c12b850
--- /dev/null
+++ b/web/src/__tests__/server/unit/rate-limit-response.servertest.ts
@@ -0,0 +1,209 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import { createMocks } from "node-mocks-http";
+import type { RateLimitResult } from "@langfuse/shared";
+
+const {
+ mockCreateUnstablePublicApiRateLimitError,
+ mockSendUnstablePublicApiErrorResponse,
+} = vi.hoisted(() => ({
+ mockCreateUnstablePublicApiRateLimitError: vi.fn(
+ (
+ rateLimitRes: RateLimitResult,
+ options?: {
+ errorContract?: string;
+ upgradePath?: { legacyEndpoint: string; replacementEndpoint: string };
+ },
+ ) => {
+ const message = options?.upgradePath
+ ? `Rate limit exceeded for ${options.upgradePath.legacyEndpoint}. Use ${options.upgradePath.replacementEndpoint} for high-volume reads.`
+ : "Rate limit exceeded";
+
+ return {
+ httpCode: 429,
+ code: "rate_limited",
+ message,
+ details: {
+ retryAfterSeconds: Math.ceil(rateLimitRes.msBeforeNext / 1000),
+ limit: rateLimitRes.points,
+ remaining: Math.max(0, rateLimitRes.remainingPoints),
+ resetAt: new Date(
+ Date.now() + rateLimitRes.msBeforeNext,
+ ).toISOString(),
+ },
+ };
+ },
+ ),
+ mockSendUnstablePublicApiErrorResponse: vi.fn((res, error) =>
+ res.status(error.httpCode).json({
+ message: error.message,
+ code: error.code,
+ ...(error.details !== undefined ? { details: error.details } : {}),
+ }),
+ ),
+}));
+
+vi.mock("@/src/env.mjs", () => ({
+ env: {
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "us",
+ LANGFUSE_RATE_LIMITS_ENABLED: "true",
+ },
+}));
+
+vi.mock("@langfuse/shared/src/env", () => ({
+ env: {
+ REDIS_KEY_PREFIX: undefined,
+ },
+}));
+
+vi.mock("@langfuse/shared/src/server", () => ({
+ redis: null,
+ recordIncrement: vi.fn(),
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+ createNewRedisInstance: vi.fn(),
+ redisQueueRetryOptions: {},
+ ClickHouseClientManager: {
+ getInstance: () => ({
+ closeAllConnections: vi.fn(async () => undefined),
+ }),
+ },
+}));
+
+vi.mock(
+ "@/src/features/public-api/server/unstable-public-api-error-contract",
+ () => ({
+ unstablePublicEvalsErrorContract: "unstable-public-evals",
+ createUnstablePublicApiRateLimitError:
+ mockCreateUnstablePublicApiRateLimitError,
+ sendUnstablePublicApiErrorResponse: mockSendUnstablePublicApiErrorResponse,
+ }),
+);
+
+import { sendRateLimitResponse } from "@/src/features/public-api/server/RateLimitService";
+
+describe("sendRateLimitResponse", () => {
+ const upgradePath = {
+ legacyEndpoint: "GET /api/public/traces",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>",
+ docsUrl:
+ "https://langfuse.com/docs/api-and-data-platform/features/observations-api",
+ };
+ const rateLimitResult = {
+ points: 10,
+ remainingPoints: -1,
+ msBeforeNext: 2500,
+ resource: "public-api",
+ scope: {
+ projectId: "project-1",
+ orgId: "org-1",
+ plan: "cloud:hobby",
+ accessLevel: "project",
+ rateLimitOverrides: [],
+ apiKeyId: "api-key-1",
+ publicKey: "pk-test",
+ isIngestionSuspended: false,
+ isInAppAgentKey: false,
+ },
+ consumedPoints: 11,
+ isFirstInDuration: false,
+ } satisfies RateLimitResult;
+
+ const createResponse = () =>
+ createMocks<NextApiRequest, NextApiResponse>({
+ method: "GET",
+ }).res;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("returns a generic structured rate limit error without an upgrade path", () => {
+ const res = createResponse();
+
+ sendRateLimitResponse(res, rateLimitResult);
+
+ expect(res.statusCode).toBe(429);
+ expect(res._getJSONData()).toEqual({
+ message: "Rate limit exceeded",
+ code: "rate_limited",
+ details: {
+ retryAfterSeconds: 3,
+ limit: 10,
+ remaining: 0,
+ resetAt: expect.any(String),
+ },
+ });
+ expect(res.getHeader("Retry-After")).toBe(3);
+ expect(res.getHeader("X-RateLimit-Limit")).toBe(10);
+ expect(res.getHeader("X-RateLimit-Remaining")).toBe(-1);
+ expect(mockCreateUnstablePublicApiRateLimitError).toHaveBeenCalledWith(
+ rateLimitResult,
+ {},
+ );
+ expect(mockSendUnstablePublicApiErrorResponse).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns upgrade guidance for stable responses with an upgrade path", () => {
+ const res = createResponse();
+
+ sendRateLimitResponse(res, rateLimitResult, { upgradePath });
+
+ expect(res.statusCode).toBe(429);
+ expect(res.getHeader("Retry-After")).toBe(3);
+ expect(res.getHeader("X-RateLimit-Limit")).toBe(10);
+ expect(res.getHeader("X-RateLimit-Remaining")).toBe(-1);
+ expect(res._getJSONData()).toEqual({
+ message:
+ "Rate limit exceeded for GET /api/public/traces. Use GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to> for high-volume reads.",
+ code: "rate_limited",
+ details: {
+ retryAfterSeconds: 3,
+ limit: 10,
+ remaining: 0,
+ resetAt: expect.any(String),
+ },
+ });
+ expect(mockCreateUnstablePublicApiRateLimitError).toHaveBeenCalledWith(
+ rateLimitResult,
+ {
+ upgradePath,
+ },
+ );
+ expect(mockSendUnstablePublicApiErrorResponse).toHaveBeenCalledTimes(1);
+ });
+
+ it("passes the error contract through when an upgrade path is present", () => {
+ const res = createResponse();
+
+ sendRateLimitResponse(res, rateLimitResult, {
+ errorContract: "unstable-public-evals",
+ upgradePath,
+ });
+
+ expect(mockCreateUnstablePublicApiRateLimitError).toHaveBeenCalledWith(
+ rateLimitResult,
+ {
+ errorContract: "unstable-public-evals",
+ upgradePath,
+ },
+ );
+ expect(mockSendUnstablePublicApiErrorResponse).toHaveBeenCalledTimes(1);
+ expect(res.statusCode).toBe(429);
+ expect(res._getJSONData()).toEqual({
+ message:
+ "Rate limit exceeded for GET /api/public/traces. Use GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to> for high-volume reads.",
+ code: "rate_limited",
+ details: {
+ retryAfterSeconds: 3,
+ limit: 10,
+ remaining: 0,
+ resetAt: expect.any(String),
+ },
+ });
+ });
+});
diff --git a/web/src/__tests__/server/unit/unstable-public-api-error-contract.servertest.ts b/web/src/__tests__/server/unit/unstable-public-api-error-contract.servertest.ts
new file mode 100644
index 0000000000..0f9c3a8ef7
--- /dev/null
+++ b/web/src/__tests__/server/unit/unstable-public-api-error-contract.servertest.ts
@@ -0,0 +1,49 @@
+import type { RateLimitResult } from "@langfuse/shared";
+import { createUnstablePublicApiRateLimitError } from "@/src/features/public-api/server/unstable-public-api-error-contract";
+
+describe("unstable public api error contract", () => {
+ it("supports upgrade path rate limit messages and clamps remaining points", () => {
+ const upgradePath = {
+ legacyEndpoint: "GET /api/public/traces",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>",
+ docsUrl:
+ "https://langfuse.com/docs/api-and-data-platform/features/observations-api",
+ };
+ const rateLimitResult = {
+ points: 10,
+ remainingPoints: -1,
+ msBeforeNext: 2500,
+ resource: "public-api",
+ scope: {
+ projectId: "project-1",
+ orgId: "org-1",
+ plan: "cloud:hobby",
+ accessLevel: "project",
+ rateLimitOverrides: [],
+ apiKeyId: "api-key-1",
+ publicKey: "pk-test",
+ isIngestionSuspended: false,
+ isInAppAgentKey: false,
+ },
+ consumedPoints: 11,
+ isFirstInDuration: false,
+ } satisfies RateLimitResult;
+
+ const error = createUnstablePublicApiRateLimitError(rateLimitResult, {
+ upgradePath,
+ });
+
+ expect(error.httpCode).toBe(429);
+ expect(error.code).toBe("rate_limited");
+ expect(error.message).toBe(
+ "Rate limit exceeded for GET /api/public/traces. Use GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to> for high-volume reads.",
+ );
+ expect(error.details).toEqual({
+ retryAfterSeconds: 3,
+ limit: 10,
+ remaining: 0,
+ resetAt: expect.any(String),
+ });
+ });
+});
diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.ts
index 6f62e19c31..43cc52dcb4 100644
--- a/web/src/features/public-api/server/RateLimitService.ts
+++ b/web/src/features/public-api/server/RateLimitService.ts
@@ -20,12 +20,29 @@ import { type NextApiResponse } from "next";
import {
createUnstablePublicApiRateLimitError,
sendUnstablePublicApiErrorResponse,
- unstablePublicEvalsErrorContract,
type PublicApiErrorContract,
} from "@/src/features/public-api/server/unstable-public-api-error-contract";
+import { type RateLimitUpgradePath } from "@/src/features/public-api/server/rateLimitUpgradePaths";
export const RATE_LIMIT_REDIS_KEY_PREFIX = "rate-limit";
+export type RateLimitResponseOptions = {
+ errorContract?: PublicApiErrorContract | undefined;
+ upgradePath?: RateLimitUpgradePath | undefined;
+};
+
+export type RateLimitResponseOptionsInput =
+ | PublicApiErrorContract
+ | RateLimitResponseOptions;
+
+const normalizeRateLimitResponseOptions = (
+ options?: RateLimitResponseOptionsInput,
+): RateLimitResponseOptions => {
+ return typeof options === "string"
+ ? { errorContract: options }
+ : (options ?? {});
+};
+
// Business Logic
// - rate limit strategy is based on org-id, org plan, and resources. Rate limits are applied in buckets of minutes.
// - rate limits are not applied for self hosters and are also not applied when Redis is not available
@@ -176,7 +193,7 @@ export class RateLimitHelper {
sendRestResponseIfLimited(
nextResponse: NextApiResponse,
- errorContract?: PublicApiErrorContract,
+ options?: RateLimitResponseOptionsInput,
) {
if (!this.res || !this.isRateLimited()) {
logger.error("Trying to send rate limit response without being limited.");
@@ -184,29 +201,26 @@ export class RateLimitHelper {
"Trying to send rate limit response without being limited.",
);
}
- return sendRateLimitResponse(nextResponse, this.res, errorContract);
+ return sendRateLimitResponse(nextResponse, this.res, options);
}
}
export const sendRateLimitResponse = (
res: NextApiResponse,
rateLimitRes: RateLimitResult,
- errorContract?: PublicApiErrorContract,
+ options?: RateLimitResponseOptionsInput,
) => {
+ const responseOptions = normalizeRateLimitResponseOptions(options);
const httpHeader = createHttpHeaderFromRateLimit(rateLimitRes);
for (const [header, value] of Object.entries(httpHeader)) {
res.setHeader(header, value);
}
- if (errorContract === unstablePublicEvalsErrorContract) {
- return sendUnstablePublicApiErrorResponse(
- res,
- createUnstablePublicApiRateLimitError(rateLimitRes),
- );
- }
-
- res.status(429).end("429 - rate limit exceeded");
+ return sendUnstablePublicApiErrorResponse(
+ res,
+ createUnstablePublicApiRateLimitError(rateLimitRes, responseOptions),
+ );
};
export const createHttpHeaderFromRateLimit = (res: RateLimitResult) => {
diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
index edad539320..cb67e9947f 100644
--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
@@ -12,6 +12,7 @@ import {
} from "@langfuse/shared/src/server";
import { type RateLimitResource } from "@langfuse/shared";
import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
+import { type RateLimitUpgradePath } from "@/src/features/public-api/server/rateLimitUpgradePaths";
import { contextWithLangfuseProps } from "@langfuse/shared/src/server";
import * as opentelemetry from "@opentelemetry/api";
import { env } from "@/src/env.mjs";
@@ -39,6 +40,7 @@ export type AuthedProjectAPIRouteConfig<
responseSchema: TResponse;
successStatusCode?: number;
rateLimitResource?: z.infer<typeof RateLimitResource>; // defaults to public-api
+ rateLimitUpgradePath?: RateLimitUpgradePath;
/**
* Allow authentication via ADMIN_API_KEY for self-hosted instances only.
* When enabled, the endpoint will accept admin API key authentication in addition to regular API keys.
@@ -364,10 +366,10 @@ export const createAuthedProjectAPIRoute = <
);
if (rateLimitResponse?.isRateLimited()) {
- return rateLimitResponse.sendRestResponseIfLimited(
- res,
- routeConfig.errorContract,
- );
+ return rateLimitResponse.sendRestResponseIfLimited(res, {
+ errorContract: routeConfig.errorContract,
+ upgradePath: routeConfig.rateLimitUpgradePath,
+ });
}
logger.debug(
diff --git a/web/src/features/public-api/server/rateLimitUpgradePaths.ts b/web/src/features/public-api/server/rateLimitUpgradePaths.ts
new file mode 100644
index 0000000000..dacbe960b8
--- /dev/null
+++ b/web/src/features/public-api/server/rateLimitUpgradePaths.ts
@@ -0,0 +1,53 @@
+export type RateLimitUpgradePath = {
+ legacyEndpoint: string;
+ replacementEndpoint: string;
+ docsUrl: string;
+};
+
+export const OBSERVATIONS_API_V2_DOCS_URL =
+ "https://langfuse.com/docs/api-and-data-platform/features/observations-api";
+
+export const legacyPublicApiRateLimitUpgradePaths = {
+ tracesList: {
+ legacyEndpoint: "GET /api/public/traces",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>",
+ docsUrl: OBSERVATIONS_API_V2_DOCS_URL,
+ },
+ traceGet: {
+ legacyEndpoint: "GET /api/public/traces/{traceId}",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?traceId={traceId}&fromStartTime=<from>&toStartTime=<to>",
+ docsUrl: OBSERVATIONS_API_V2_DOCS_URL,
+ },
+ observationsList: {
+ legacyEndpoint: "GET /api/public/observations",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>",
+ docsUrl: OBSERVATIONS_API_V2_DOCS_URL,
+ },
+ observationGet: {
+ legacyEndpoint: "GET /api/public/observations/{observationId}",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?filter=<urlencoded id filter>&fromStartTime=<from>&toStartTime=<to>",
+ docsUrl: OBSERVATIONS_API_V2_DOCS_URL,
+ },
+ sessionsList: {
+ legacyEndpoint: "GET /api/public/sessions",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>",
+ docsUrl: OBSERVATIONS_API_V2_DOCS_URL,
+ },
+ sessionGet: {
+ legacyEndpoint: "GET /api/public/sessions/{sessionId}",
+ replacementEndpoint:
+ "GET /api/public/v2/observations?filter=<urlencoded sessionId filter>&fromStartTime=<from>&toStartTime=<to>",
+ docsUrl: OBSERVATIONS_API_V2_DOCS_URL,
+ },
+} satisfies Record<string, RateLimitUpgradePath>;
+
+export const getRateLimitUpgradeMessage = ({
+ legacyEndpoint,
+ replacementEndpoint,
+}: RateLimitUpgradePath) =>
+ `Rate limit exceeded for ${legacyEndpoint}. Use ${replacementEndpoint} for high-volume reads.`;
diff --git a/web/src/features/public-api/server/unstable-public-api-error-contract.ts b/web/src/features/public-api/server/unstable-public-api-error-contract.ts
index 4ff2515843..6454d5bb63 100644
--- a/web/src/features/public-api/server/unstable-public-api-error-contract.ts
+++ b/web/src/features/public-api/server/unstable-public-api-error-contract.ts
@@ -16,6 +16,10 @@ import type {
UnstablePublicApiErrorCodeType,
UnstablePublicApiErrorDetailsType,
} from "@/src/features/public-api/shared/unstable-public-api-error-schema";
+import {
+ getRateLimitUpgradeMessage,
+ type RateLimitUpgradePath,
+} from "@/src/features/public-api/server/rateLimitUpgradePaths";
export const unstablePublicEvalsErrorContract = "unstable-public-evals";
export type PublicApiErrorContract = typeof unstablePublicEvalsErrorContract;
@@ -116,15 +120,21 @@ export function createUnstablePublicApiAuthError(params: {
export function createUnstablePublicApiRateLimitError(
rateLimitRes: RateLimitResult,
+ options?: {
+ errorContract?: PublicApiErrorContract;
+ upgradePath?: RateLimitUpgradePath;
+ },
) {
return createUnstablePublicApiError({
httpCode: 429,
code: "rate_limited",
- message: "Rate limit exceeded",
+ message: options?.upgradePath
+ ? getRateLimitUpgradeMessage(options.upgradePath)
+ : "Rate limit exceeded",
details: {
retryAfterSeconds: Math.ceil(rateLimitRes.msBeforeNext / 1000),
limit: rateLimitRes.points,
- remaining: rateLimitRes.remainingPoints,
+ remaining: Math.max(0, rateLimitRes.remainingPoints),
resetAt: new Date(Date.now() + rateLimitRes.msBeforeNext).toISOString(),
},
});
diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].ts
index 33d5cc426a..c02e658ecf 100644
--- a/web/src/pages/api/public/observations/[observationId].ts
+++ b/web/src/pages/api/public/observations/[observationId].ts
@@ -15,6 +15,7 @@ import {
getObservationById,
getObservationByIdFromEventsTable,
} from "@langfuse/shared/src/server";
+import { legacyPublicApiRateLimitUpgradePaths } from "@/src/features/public-api/server/rateLimitUpgradePaths";
export default withMiddlewares(
{
@@ -24,6 +25,7 @@ export default withMiddlewares(
rateLimitResource: "public-api-legacy",
querySchema: GetObservationV1Query,
responseSchema: GetObservationV1Response,
+ rateLimitUpgradePath: legacyPublicApiRateLimitUpgradePaths.observationGet,
rejectInEventsOnlyMode: true,
fn: async ({ query, auth }) => {
const clickhouseObservation = query.useEventsTable
diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.ts
index b0bf560565..32ac031208 100644
--- a/web/src/pages/api/public/observations/index.ts
+++ b/web/src/pages/api/public/observations/index.ts
@@ -19,6 +19,7 @@ import {
generateObservationsForPublicApi,
getObservationsCountForPublicApi,
} from "@/src/features/public-api/server/observations";
+import { legacyPublicApiRateLimitUpgradePaths } from "@/src/features/public-api/server/rateLimitUpgradePaths";
export default withMiddlewares(
{
@@ -28,6 +29,8 @@ export default withMiddlewares(
rateLimitResource: "public-api-legacy",
querySchema: GetObservationsV1Query,
responseSchema: GetObservationsV1Response,
+ rateLimitUpgradePath:
+ legacyPublicApiRateLimitUpgradePaths.observationsList,
rejectInEventsOnlyMode: true,
fn: async ({ query, auth }) => {
const filterProps = {
diff --git a/web/src/pages/api/public/sessions/[sessionId].ts b/web/src/pages/api/public/sessions/[sessionId].ts
index 55619b4a3e..31b873d73b 100644
--- a/web/src/pages/api/public/sessions/[sessionId].ts
+++ b/web/src/pages/api/public/sessions/[sessionId].ts
@@ -7,6 +7,7 @@ import { withMiddlewares } from "@/src/features/public-api/server/withMiddleware
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { LangfuseNotFoundError } from "@langfuse/shared";
import { getTracesBySessionId } from "@langfuse/shared/src/server";
+import { legacyPublicApiRateLimitUpgradePaths } from "@/src/features/public-api/server/rateLimitUpgradePaths";
export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
@@ -14,6 +15,7 @@ export default withMiddlewares({
rateLimitResource: "public-api-legacy",
querySchema: GetSessionV1Query,
responseSchema: GetSessionV1Response,
+ rateLimitUpgradePath: legacyPublicApiRateLimitUpgradePaths.sessionGet,
// Reads from the legacy traces ClickHouse table via getTracesBySessionId,
// which has no events_full fallback.
rejectInEventsOnlyMode: true,
diff --git a/web/src/pages/api/public/sessions/index.ts b/web/src/pages/api/public/sessions/index.ts
index 6d56faf0ec..61c8194e54 100644
--- a/web/src/pages/api/public/sessions/index.ts
+++ b/web/src/pages/api/public/sessions/index.ts
@@ -5,6 +5,7 @@ import {
} from "@/src/features/public-api/types/sessions";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+import { legacyPublicApiRateLimitUpgradePaths } from "@/src/features/public-api/server/rateLimitUpgradePaths";
export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
@@ -12,6 +13,7 @@ export default withMiddlewares({
rateLimitResource: "public-api-legacy",
querySchema: GetSessionsV1Query,
responseSchema: GetSessionsV1Response,
+ rateLimitUpgradePath: legacyPublicApiRateLimitUpgradePaths.sessionsList,
rejectInEventsOnlyMode: true,
fn: async ({ query, auth }) => {
const { fromTimestamp, toTimestamp, limit, page, environment } = query;
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index 06a09b65ff..3707d13ba8 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -27,6 +27,7 @@ import {
} from "@langfuse/shared/src/server";
import Decimal from "decimal.js";
import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { legacyPublicApiRateLimitUpgradePaths } from "@/src/features/public-api/server/rateLimitUpgradePaths";
export default withMiddlewares(
{
@@ -35,6 +36,7 @@ export default withMiddlewares(
rateLimitResource: "public-api-legacy",
querySchema: GetTraceV1Query,
responseSchema: GetTraceV1Response,
+ rateLimitUpgradePath: legacyPublicApiRateLimitUpgradePaths.traceGet,
rejectInEventsOnlyMode: true,
fn: async ({ query, auth }) => {
const { traceId } = query;
@@ -57,7 +59,7 @@ export default withMiddlewares(
const includeScores = requestedFields.includes("scores");
const includeMetrics = requestedFields.includes("metrics");
- // eslint-disable-next-line @typescript-eslint/no-deprecated
+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Legacy public API endpoint reads from the legacy traces table.
const trace = await getTraceById({
traceId,
projectId: auth.scope.projectId,
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
index ea0dd4bec1..87a8ff445e 100644
--- a/web/src/pages/api/public/traces/index.ts
+++ b/web/src/pages/api/public/traces/index.ts
@@ -30,6 +30,7 @@ import {
getTracesCountForPublicApi,
} from "@/src/features/public-api/server/traces";
import { env } from "@/src/env.mjs";
+import { legacyPublicApiRateLimitUpgradePaths } from "@/src/features/public-api/server/rateLimitUpgradePaths";
export default withMiddlewares(
{
@@ -73,6 +74,7 @@ export default withMiddlewares(
rateLimitResource: "public-api-legacy",
querySchema: GetTracesV1Query,
responseSchema: GetTracesV1Response,
+ rateLimitUpgradePath: legacyPublicApiRateLimitUpgradePaths.tracesList,
rejectInEventsOnlyMode: true,
fn: async ({ query, auth }) => {
// Api-performance controls.