Skip to content

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

perf: add opt-in perf improvements for self-hosters on otel SDKs (#10059)

Steffen Schmitzfbe485dfa38d
diff --git a/web/src/env.mjs b/web/src/env.mjs
index f37dcf48b5..ab323bcf31 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -301,6 +301,19 @@ export const env = createEnv({
LANGFUSE_AI_FEATURES_SECRET_KEY: z.string().optional(),
LANGFUSE_AI_FEATURES_PROJECT_ID: z.string().optional(),
+ // API Performance Flags
+ // Whether to add a `FINAL` modifier to the observations CTE in GET /api/public/traces.
+ // Can be used to improve performance for self-hosters that are fully on the new OTel SDKs.
+ LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL: z
+ .enum(["true", "false"])
+ .default("false"),
+ // Whether to propagate the toTimestamp restriction (including a server-side offset)
+ // onto the observations CTE in GET /api/public/traces. Can be used to improve performance
+ // for self-hosters that have a trace known trace duration of less than multiple hours.
+ LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS: z
+ .enum(["true", "false"])
+ .default("false"),
+
// Events table migration
LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS: z
.enum(["true", "false"])
@@ -423,7 +436,8 @@ export const env = createEnv({
AUTH_ONELOGIN_ISSUER: process.env.AUTH_ONELOGIN_ISSUER,
AUTH_ONELOGIN_ALLOW_ACCOUNT_LINKING:
process.env.AUTH_ONELOGIN_ALLOW_ACCOUNT_LINKING,
- AUTH_ONELOGIN_CLIENT_AUTH_METHOD: process.env.AUTH_ONELOGIN_CLIENT_AUTH_METHOD,
+ AUTH_ONELOGIN_CLIENT_AUTH_METHOD:
+ process.env.AUTH_ONELOGIN_CLIENT_AUTH_METHOD,
AUTH_ONELOGIN_CHECKS: process.env.AUTH_ONELOGIN_CHECKS,
AUTH_AUTH0_CLIENT_ID: process.env.AUTH_AUTH0_CLIENT_ID,
AUTH_AUTH0_CLIENT_SECRET: process.env.AUTH_AUTH0_CLIENT_SECRET,
@@ -598,6 +612,12 @@ export const env = createEnv({
// Langfuse Tracing AI Features
LANGFUSE_AI_FEATURES_HOST: process.env.LANGFUSE_AI_FEATURES_HOST,
+ // Api Performance Flags
+ LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS:
+ process.env.LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS,
+ LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL:
+ process.env.LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL,
+
// Natural Language Filters
LANGFUSE_AI_FEATURES_PUBLIC_KEY:
process.env.LANGFUSE_AI_FEATURES_PUBLIC_KEY,
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index 6897adcba7..3d1be85246 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -17,6 +17,7 @@ import {
TRACE_FIELD_GROUPS,
type TraceFieldGroup,
} from "@/src/features/public-api/types/traces";
+import { env } from "@/src/env.mjs";
import type { FilterState } from "@langfuse/shared";
@@ -47,6 +48,12 @@ export const generateTracesForPublicApi = async ({
advancedFilters?: FilterState;
orderBy: OrderByState;
}) => {
+ // ClickHouse query optimizations for List Traces API
+ const disableObservationsFinal =
+ env.LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL === "true";
+ const propagateObservationsTimeBounds =
+ env.LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS === "true";
+
const requestedFields = props.fields ?? TRACE_FIELD_GROUPS;
const includeIO = requestedFields.includes("io");
const includeScores = requestedFields.includes("scores");
@@ -61,12 +68,18 @@ export const generateTracesForPublicApi = async ({
);
const appliedFilter = filter.apply();
- const timeFilter = filter.find(
+ const fromTimeFilter = filter.find(
(f) =>
f.clickhouseTable === "traces" &&
f.field.includes("timestamp") &&
(f.operator === ">=" || f.operator === ">"),
) as DateTimeFilter | undefined;
+ const toTimeFilter = filter.find(
+ (f) =>
+ f.clickhouseTable === "traces" &&
+ f.field.includes("timestamp") &&
+ (f.operator === "<=" || f.operator === "<"),
+ ) as DateTimeFilter | undefined;
// We need to drop the clickhousePrefix here to make the filter work for the observations and scores tables.
const environmentFilter = filter
@@ -91,6 +104,9 @@ export const generateTracesForPublicApi = async ({
const ctes = [];
if (includeObservations || includeMetrics) {
+ // Conditionally add FINAL based on env var and whether metrics are requested
+ const shouldUseFinal = includeMetrics && !disableObservationsFinal;
+
ctes.push(`
observation_stats AS (
SELECT
@@ -98,9 +114,11 @@ export const generateTracesForPublicApi = async ({
project_id,
${includeMetrics ? "sum(total_cost) as total_cost, date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds, " : ""}
groupUniqArray(id) as observation_ids
- FROM observations ${includeMetrics ? "FINAL" : ""}
+ FROM observations ${shouldUseFinal ? "FINAL" : ""}
WHERE project_id = {projectId: String}
- ${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ ${fromTimeFilter ? `AND start_time >= {cteFromTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ ${toTimeFilter && propagateObservationsTimeBounds ? `AND start_time <= {cteToTimeFilter: DateTime64(3)} + ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ ${toTimeFilter && propagateObservationsTimeBounds ? `AND end_time <= {cteToTimeFilter: DateTime64(3)} + ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
GROUP BY project_id, trace_id
)`);
@@ -117,7 +135,7 @@ export const generateTracesForPublicApi = async ({
WHERE project_id = {projectId: String}
AND session_id IS NULL
AND dataset_run_id IS NULL
- ${timeFilter ? `AND timestamp >= {cteTimeFilter: DateTime64(3)}` : ""}
+ ${fromTimeFilter ? `AND timestamp >= {cteFromTimeFilter: DateTime64(3)}` : ""}
${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
GROUP BY project_id, trace_id
)`);
@@ -137,9 +155,18 @@ export const generateTracesForPublicApi = async ({
...(props.page !== undefined
? { offset: (props.page - 1) * props.limit }
: {}),
- ...(timeFilter
+ ...(fromTimeFilter
+ ? {
+ cteFromTimeFilter: convertDateToClickhouseDateTime(
+ fromTimeFilter.value,
+ ),
+ }
+ : {}),
+ ...(toTimeFilter && propagateObservationsTimeBounds
? {
- cteTimeFilter: convertDateToClickhouseDateTime(timeFilter.value),
+ cteToTimeFilter: convertDateToClickhouseDateTime(
+ toTimeFilter.value,
+ ),
}
: {}),
},
@@ -150,7 +177,7 @@ export const generateTracesForPublicApi = async ({
projectId: props.projectId,
operation_name: "getTracesForPublicApi",
},
- fromTimestamp: timeFilter?.value ?? undefined,
+ fromTimestamp: fromTimeFilter?.value ?? undefined,
preferredClickhouseService: "ReadOnly",
},
fn: (input) => {