Skip to content

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

fix(tracing): send batchIO I/O queries as POST to avoid HTTP 431 (#14393)

Nikita Kabardin98eb8d3e47b2
diff --git a/web/src/components/trace/api/usePrefetchObservation.ts b/web/src/components/trace/api/usePrefetchObservation.ts
index b10597cdd4..412b9af4d5 100644
--- a/web/src/components/trace/api/usePrefetchObservation.ts
+++ b/web/src/components/trace/api/usePrefetchObservation.ts
@@ -1,4 +1,4 @@
-import { api } from "@/src/utils/api";
+import { api, sendAsPostOption } from "@/src/utils/api";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
export type UsePrefetchObservationParams = {
@@ -32,6 +32,7 @@ export function usePrefetchObservation({
truncated: false, // Must match useLogViewObservationIO for cache hit
},
{
+ ...sendAsPostOption,
staleTime: 5 * 60 * 1000, // 5 minutes
},
);
diff --git a/web/src/components/trace/components/TraceLogView/useLogViewObservationIO.ts b/web/src/components/trace/components/TraceLogView/useLogViewObservationIO.ts
index 4eea300b05..a78f812225 100644
--- a/web/src/components/trace/components/TraceLogView/useLogViewObservationIO.ts
+++ b/web/src/components/trace/components/TraceLogView/useLogViewObservationIO.ts
@@ -7,7 +7,7 @@
import { useMemo } from "react";
import { useQueryClient } from "@tanstack/react-query";
-import { api } from "@/src/utils/api";
+import { api, sendAsPostOption } from "@/src/utils/api";
import { type FlatLogItem } from "./log-view-types";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
@@ -60,6 +60,7 @@ export function useLogViewObservationIO({
truncated: false,
},
{
+ ...sendAsPostOption,
enabled: enabled && isBetaEnabled,
staleTime: Infinity,
refetchOnWindowFocus: false,
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
index 71799b3f44..6e31af0f11 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
@@ -6,7 +6,7 @@ import {
BatchEvalSourceTable as SourceTable,
getEvalTargetObjectFromSourceTable,
} from "@langfuse/shared";
-import { api } from "@/src/utils/api";
+import { api, sendAsPostOption } from "@/src/utils/api";
import {
Dialog,
DialogBody,
@@ -119,6 +119,7 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
truncated: false,
},
{
+ ...sendAsPostOption,
enabled:
isBetaEnabled &&
Boolean(
diff --git a/web/src/features/evals/hooks/usePreviewData.ts b/web/src/features/evals/hooks/usePreviewData.ts
index 45a3e7454c..d48e121650 100644
--- a/web/src/features/evals/hooks/usePreviewData.ts
+++ b/web/src/features/evals/hooks/usePreviewData.ts
@@ -3,7 +3,7 @@ import {
isExperimentTarget,
} from "@/src/features/evals/utils/typeHelpers";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
-import { api, type RouterOutputs } from "@/src/utils/api";
+import { api, sendAsPostOption, type RouterOutputs } from "@/src/utils/api";
import {
EvalTargetObject,
extractValueFromObject,
@@ -200,6 +200,7 @@ function useEventPreview({
truncated: false,
},
{
+ ...sendAsPostOption,
enabled: enabled && !!observationId && !!traceId && !!timestamp,
},
);
@@ -247,6 +248,7 @@ function useExperimentPreview({
truncated: false,
},
{
+ ...sendAsPostOption,
enabled: enabled && !!observationId && !!traceId && !!timestamp,
},
);
diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.ts
index 3818a3d9cd..313621f96b 100644
--- a/web/src/features/events/hooks/useEventsTableData.ts
+++ b/web/src/features/events/hooks/useEventsTableData.ts
@@ -1,4 +1,4 @@
-import { api } from "@/src/utils/api";
+import { api, sendAsPostOption } from "@/src/utils/api";
import { useMemo } from "react";
import {
type FilterState,
@@ -111,6 +111,7 @@ export function useEventsTableData({
// Fetch I/O data
const ioDataQuery = api.events.batchIO.useQuery(batchIOPayload!, {
+ ...sendAsPostOption,
enabled: observations.isSuccess && batchIOPayload !== null,
refetchOnWindowFocus: false,
staleTime: 0,
diff --git a/web/src/features/events/hooks/useEventsTraceData.ts b/web/src/features/events/hooks/useEventsTraceData.ts
index a82e6f8afd..55a98e6faf 100644
--- a/web/src/features/events/hooks/useEventsTraceData.ts
+++ b/web/src/features/events/hooks/useEventsTraceData.ts
@@ -1,5 +1,5 @@
import { useMemo } from "react";
-import { api } from "@/src/utils/api";
+import { api, sendAsPostOption } from "@/src/utils/api";
import {
adaptEventsToTraceFormat,
type AdaptedTraceData,
@@ -113,6 +113,7 @@ export function useEventsTraceData(
truncated: false,
},
{
+ ...sendAsPostOption,
enabled:
enabled && !!primaryObservation && !!timeRange && !!eventsQuery.data,
staleTime: 60 * 1000,
diff --git a/web/src/features/experiments/hooks/useExperimentItemsTableData.ts b/web/src/features/experiments/hooks/useExperimentItemsTableData.ts
index 487076d85d..862d72168b 100644
--- a/web/src/features/experiments/hooks/useExperimentItemsTableData.ts
+++ b/web/src/features/experiments/hooks/useExperimentItemsTableData.ts
@@ -1,6 +1,6 @@
import { useMemo } from "react";
import { type FilterState } from "@langfuse/shared";
-import { api } from "@/src/utils/api";
+import { api, sendAsPostOption } from "@/src/utils/api";
import {
type ExperimentItemsTableRow,
type ExperimentOutputData,
@@ -118,6 +118,7 @@ export function useExperimentItemsTableData({
// Fetch IO data for visible items
const batchIOQuery = api.experiments.batchIO.useQuery(batchIOPayload!, {
+ ...sendAsPostOption,
enabled: hasSelectedRuns && itemsQuery.isSuccess && batchIOPayload !== null,
refetchOnWindowFocus: false,
staleTime: 0,
diff --git a/web/src/hooks/useParsedObservation.ts b/web/src/hooks/useParsedObservation.ts
index 6ea54f1730..27440e9eff 100644
--- a/web/src/hooks/useParsedObservation.ts
+++ b/web/src/hooks/useParsedObservation.ts
@@ -13,7 +13,7 @@
import { useQuery } from "@tanstack/react-query";
import { useMemo, useEffect } from "react";
-import { api } from "@/src/utils/api";
+import { api, sendAsPostOption } from "@/src/utils/api";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import { type EventBatchIOOutput } from "@/src/features/events/server/eventsRouter";
import {
@@ -231,6 +231,7 @@ export function useParsedObservation({
truncated: false,
},
{
+ ...sendAsPostOption,
enabled: isBetaEnabled,
staleTime: 5 * 60 * 1000, // 5 minutes
select: (data) => data[0], // Extract single result from batch
diff --git a/web/src/pages/api/trpc/[trpc].ts b/web/src/pages/api/trpc/[trpc].ts
index db69ac3524..b790a08385 100644
--- a/web/src/pages/api/trpc/[trpc].ts
+++ b/web/src/pages/api/trpc/[trpc].ts
@@ -18,6 +18,14 @@ export const config = {
export default createNextApiHandler({
router: appRouter,
createContext: createTRPCContext,
+ // Allow queries to be sent as POST. The client only does this for the
+ // `*.batchIO` I/O queries, whose per-row payload would otherwise inflate the
+ // GET URL and trip HTTP 431 (queries opt in via the `sendAsPost` context flag;
+ // see `sendAsPostOption` in src/utils/api.ts). This flag is handler-wide (tRPC
+ // has no per-procedure option), but it only widens the accepted method for
+ // queries (read-only); mutations remain POST-only, so the GET-mutation
+ // protection is unchanged.
+ allowMethodOverride: true,
onError: ({ path, error }) => {
const { logLevel, shouldTrace } = getTRPCErrorReporting(error);
const message = `tRPC route failed on ${path ?? "<no-path>"}: ${error.message}`;
diff --git a/web/src/utils/api.ts b/web/src/utils/api.ts
index 90c1e8d073..0166ded499 100644
--- a/web/src/utils/api.ts
+++ b/web/src/utils/api.ts
@@ -13,6 +13,7 @@ import {
loggerLink,
splitLink,
TRPCClientError,
+ type Operation,
type TRPCLink,
} from "@trpc/client";
import { QueryCache } from "@tanstack/react-query";
@@ -153,6 +154,28 @@ if (vitest && typeof vitest === "object") {
}
/* eslint-enable @repo/no-in-source-vitest */
+/**
+ * tRPC serializes query input into the GET URL. For reads whose input scales with
+ * the number of rows (the `*.batchIO` I/O fetches), that URL grows large (~6KB at
+ * 50 rows, ~12KB at 100) and — together with per-user cookies (NextAuth session
+ * JWT, PostHog, ...) — can exceed the request line/header budget enforced by
+ * browsers and reverse proxies, failing with HTTP 431 (Request Header Fields Too
+ * Large). Because cookie size varies per user, it reproduces for some and not
+ * others.
+ *
+ * A query opts into being sent as POST (payload in the body, URL stays small) by
+ * setting the `sendAsPost` context flag at the call site: merge `sendAsPostOption`
+ * into its query options, e.g. `useQuery(input, { ...sendAsPostOption, enabled })`.
+ * The server accepts query-over-POST via `allowMethodOverride` (see
+ * src/pages/api/trpc/[trpc].ts); mutations stay POST-only.
+ */
+export const sendAsPostOption = {
+ trpc: { context: { sendAsPost: true } },
+} as const;
+
+const shouldSendQueryAsPost = (op: Operation): boolean =>
+ op.context.sendAsPost === true;
+
/**
* Creates a unique hash for an error to track it for debouncing; implementation hashes based on the tRPC path and http status
*/
@@ -251,6 +274,70 @@ const buildIdLink = (): TRPCLink<AppRouter> => () => {
};
};
+// HTTP statuses returned when a request's URL/headers are too large for the
+// browser or an upstream proxy. The response body is usually not a tRPC
+// envelope, so these are otherwise hard to diagnose.
+const REQUEST_TOO_LARGE_STATUSES = [414, 431];
+
+// Logs request-size context to the console when a GET-routed query fails because
+// its URL was too large. tRPC serializes query input into the GET URL, so an
+// oversized input (a long list, a wide filter selection, ...) can trip HTTP 414
+// (URI Too Long) or 431 (Request Header Fields Too Large). Surfacing the path and
+// approximate URL size makes such failures diagnosable from a console screenshot
+// and points at the fix (send the query as POST). `*.batchIO` and mutations are
+// already POST, so the URL is not the culprit for them and they are skipped.
+const requestTooLargeDiagnosticsLink = (): TRPCLink<AppRouter> => () => {
+ return ({ next, op }) => {
+ return observable((observer) => {
+ const unsubscribe = next(op).subscribe({
+ next(value) {
+ observer.next(value);
+ },
+ error(err) {
+ const sentAsGet =
+ op.type === "query" && op.context.sendAsPost !== true;
+ const status =
+ err.meta?.response instanceof Response
+ ? err.meta.response.status
+ : undefined;
+
+ if (
+ sentAsGet &&
+ status !== undefined &&
+ REQUEST_TOO_LARGE_STATUSES.includes(status)
+ ) {
+ try {
+ const encodedInput = encodeURIComponent(
+ JSON.stringify(superjson.serialize(op.input)),
+ );
+ const approxUrlBytes =
+ `${getBaseUrl()}/api/trpc/${op.path}?input=`.length +
+ encodedInput.length;
+ // Keep the format string constant (no interpolation) and pass the
+ // dynamic values as a structured argument — they remain visible and
+ // expandable in the console without risking format-string injection.
+ console.error(
+ "[tRPC] a query sent as GET failed because the request URL was " +
+ "too large (HTTP 414/431). Large query inputs should be sent as " +
+ "POST — add { ...sendAsPostOption } to the query's options (see " +
+ "sendAsPostOption in src/utils/api.ts).",
+ { path: op.path, status, approxUrlBytes },
+ );
+ } catch {
+ // diagnostics only — never throw from the logging path
+ }
+ }
+ observer.error(err);
+ },
+ complete() {
+ observer.complete();
+ },
+ });
+ return unsubscribe;
+ });
+ };
+};
+
const shouldSilenceError = (
meta: Record<string, unknown>,
error: Error,
@@ -281,6 +368,7 @@ export const api = createTRPCNext<AppRouter>({
*/
links: [
buildIdLink(),
+ requestTooLargeDiagnosticsLink(),
loggerLink({
// Only enable in development - production logs would be captured by Sentry
// in an unreadable format. We handle 5xx errors via captureException() in
@@ -297,10 +385,20 @@ export const api = createTRPCNext<AppRouter>({
return skipBatch || alwaysSkipBatch;
},
- // when condition is true, use normal request
- true: httpLink({
- url: `${getBaseUrl()}/api/trpc`,
- transformer: superjson,
+ // when condition is true, use normal request. Route the oversized
+ // `*.batchIO` queries through POST so their per-row payload does not
+ // inflate the GET URL and trip HTTP 431. See `shouldSendQueryAsPost`.
+ true: splitLink({
+ condition: shouldSendQueryAsPost,
+ true: httpLink({
+ url: `${getBaseUrl()}/api/trpc`,
+ transformer: superjson,
+ methodOverride: "POST",
+ }),
+ false: httpLink({
+ url: `${getBaseUrl()}/api/trpc`,
+ transformer: superjson,
+ }),
}),
// when condition is false, use batching
false: httpBatchLink({