Skip to content

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

perf: persist hasAnyTrace to PostgreSQL, propagate via session to eliminate polling (#11921)

Copilote5144dc401a1
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 3398a439fb..672ec3095e 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -776,6 +776,7 @@ export type Project = {
deleted_at: Timestamp | null;
name: string;
retention_days: number | null;
+ has_traces: Generated<boolean>;
metadata: unknown | null;
};
export type ProjectMembership = {
diff --git a/packages/shared/prisma/migrations/20260209000000_add_project_has_traces/migration.sql b/packages/shared/prisma/migrations/20260209000000_add_project_has_traces/migration.sql
new file mode 100644
index 0000000000..f95fdc37c1
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260209000000_add_project_has_traces/migration.sql
@@ -0,0 +1 @@
+ALTER TABLE "projects" ADD COLUMN "has_traces" BOOLEAN NOT NULL DEFAULT false;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index aa07eec322..a269c2fc22 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -128,6 +128,7 @@ model Project {
deletedAt DateTime? @map("deleted_at")
name String
retentionDays Int? @map("retention_days")
+ hasTraces Boolean @default(false) @map("has_traces")
metadata Json?
projectMembers ProjectMembership[]
organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 2ac82f0b8c..2964249075 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -35,6 +35,8 @@ import type { AnalyticsTraceEvent } from "../analytics-integrations/types";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { DEFAULT_RENDERING_PROPS, RenderingProps } from "../utils/rendering";
import { logger } from "../logger";
+import { traceException } from "../instrumentation";
+import { prisma } from "../../db";
/**
* Checks if trace exists in clickhouse.
@@ -311,7 +313,24 @@ export const getTracesBySessionId = async (
};
export const hasAnyTrace = async (projectId: string) => {
- return measureAndReturn({
+ // Check PostgreSQL flag first — once set, it's never reverted
+ try {
+ const project = await prisma.project.findUnique({
+ where: { id: projectId },
+ select: { hasTraces: true },
+ });
+ if (project?.hasTraces) {
+ return true;
+ }
+ } catch (error) {
+ traceException(error);
+ logger.error("Failed to read hasTraces flag from PostgreSQL", {
+ projectId,
+ error,
+ });
+ }
+
+ const result = await measureAndReturn({
operationName: "hasAnyTrace",
projectId,
input: {
@@ -338,11 +357,33 @@ export const hasAnyTrace = async (projectId: string) => {
projectId: input.projectId,
},
tags: input.tags,
+ clickhouseSettings: {
+ max_threads: 1,
+ },
});
return rows.length > 0;
},
});
+
+ // Persist positive result in PostgreSQL — once a project has traces, it stays true
+ // Only update if not already set to avoid unnecessary writes
+ if (result) {
+ try {
+ await prisma.project.updateMany({
+ where: { id: projectId, hasTraces: false },
+ data: { hasTraces: true },
+ });
+ } catch (error) {
+ traceException(error);
+ logger.error("Failed to persist hasTraces flag to PostgreSQL", {
+ projectId,
+ error,
+ });
+ }
+ }
+
+ return result;
};
export const getTraceCountsByProjectInCreationInterval = async ({
diff --git a/web/src/__tests__/async/repositories/hasAnyTrace.servertest.ts b/web/src/__tests__/async/repositories/hasAnyTrace.servertest.ts
new file mode 100644
index 0000000000..ec13fe0966
--- /dev/null
+++ b/web/src/__tests__/async/repositories/hasAnyTrace.servertest.ts
@@ -0,0 +1,66 @@
+import { prisma } from "@langfuse/shared/src/db";
+import { hasAnyTrace, createTracesCh } from "@langfuse/shared/src/server";
+import { createTrace } from "@langfuse/shared/src/server";
+import { v4 } from "uuid";
+
+const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+describe("hasAnyTrace", () => {
+ afterEach(async () => {
+ // Reset the hasTraces flag to false after each test
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { hasTraces: false },
+ });
+ });
+
+ it("should return true immediately when PG hasTraces flag is set", async () => {
+ // Set the PG flag directly — no ClickHouse data needed
+ await prisma.project.update({
+ where: { id: projectId },
+ data: { hasTraces: true },
+ });
+
+ const result = await hasAnyTrace(projectId);
+ expect(result).toBe(true);
+ });
+
+ it("should return true and persist PG flag when ClickHouse has traces", async () => {
+ // Ensure PG flag is false
+ const projectBefore = await prisma.project.findUniqueOrThrow({
+ where: { id: projectId },
+ select: { hasTraces: true },
+ });
+ expect(projectBefore.hasTraces).toBe(false);
+
+ // Insert a trace into ClickHouse
+ const trace = createTrace({
+ id: v4(),
+ project_id: projectId,
+ timestamp: Date.now(),
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ is_deleted: 0,
+ });
+ await createTracesCh([trace]);
+
+ // hasAnyTrace should find the trace via ClickHouse and persist to PG
+ const result = await hasAnyTrace(projectId);
+ expect(result).toBe(true);
+
+ // Verify PG flag was persisted
+ const projectAfter = await prisma.project.findUniqueOrThrow({
+ where: { id: projectId },
+ select: { hasTraces: true },
+ });
+ expect(projectAfter.hasTraces).toBe(true);
+ });
+
+ it("should return false when no traces exist", async () => {
+ // Use a random projectId that has no traces in either PG or ClickHouse
+ const emptyProjectId = v4();
+ const result = await hasAnyTrace(emptyProjectId);
+ expect(result).toBe(false);
+ });
+});
diff --git a/web/src/pages/project/[projectId]/observations.tsx b/web/src/pages/project/[projectId]/observations.tsx
index b09edf9d59..02ebf801ef 100644
--- a/web/src/pages/project/[projectId]/observations.tsx
+++ b/web/src/pages/project/[projectId]/observations.tsx
@@ -10,13 +10,16 @@ import {
} from "@/src/features/navigation/utils/tracing-tabs";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import ObservationsEventsTable from "@/src/features/events/components/EventsTable";
+import { useQueryProject } from "@/src/features/projects/hooks";
export default function Generations() {
const router = useRouter();
const projectId = router.query.projectId as string;
const { isBetaEnabled } = useV4Beta();
+ const { project } = useQueryProject();
// Check if the user has tracing configured
+ // Skip polling entirely if the project flag is already set in the session
const { data: hasTracingConfigured, isLoading } =
api.traces.hasTracingConfigured.useQuery(
{ projectId },
@@ -27,7 +30,9 @@ export default function Generations() {
skipBatch: true,
},
},
- refetchInterval: 10_000,
+ refetchInterval: project?.hasTraces ? false : 10_000,
+ initialData: project?.hasTraces ? true : undefined,
+ staleTime: project?.hasTraces ? Infinity : 0,
},
);
diff --git a/web/src/pages/project/[projectId]/observations/new.tsx b/web/src/pages/project/[projectId]/observations/new.tsx
index 395626ba5d..11eae998f9 100644
--- a/web/src/pages/project/[projectId]/observations/new.tsx
+++ b/web/src/pages/project/[projectId]/observations/new.tsx
@@ -8,12 +8,15 @@ import {
getTracingTabs,
TRACING_TABS,
} from "@/src/features/navigation/utils/tracing-tabs";
+import { useQueryProject } from "@/src/features/projects/hooks";
export default function Events() {
const router = useRouter();
const projectId = router.query.projectId as string;
+ const { project } = useQueryProject();
// Check if the user has tracing configured
+ // Skip polling entirely if the project flag is already set in the session
const { data: hasTracingConfigured, isLoading } =
api.traces.hasTracingConfigured.useQuery(
{ projectId },
@@ -24,7 +27,9 @@ export default function Events() {
skipBatch: true,
},
},
- refetchInterval: 10_000,
+ refetchInterval: project?.hasTraces ? false : 10_000,
+ initialData: project?.hasTraces ? true : undefined,
+ staleTime: project?.hasTraces ? Infinity : 0,
},
);
diff --git a/web/src/pages/project/[projectId]/traces.tsx b/web/src/pages/project/[projectId]/traces.tsx
index ca2c412058..71d15e6df9 100644
--- a/web/src/pages/project/[projectId]/traces.tsx
+++ b/web/src/pages/project/[projectId]/traces.tsx
@@ -11,12 +11,14 @@ import {
} from "@/src/features/navigation/utils/tracing-tabs";
import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import ObservationsEventsTable from "@/src/features/events/components/EventsTable";
+import { useQueryProject } from "@/src/features/projects/hooks";
export default function Traces() {
const router = useRouter();
const projectId = router.query.projectId as string;
const { isBetaEnabled } = useV4Beta();
const [, setQueryParams] = useQueryParams({ viewMode: StringParam });
+ const { project } = useQueryProject();
// Clear viewMode query when beta is turned off (e.g. from sidebar)
useEffect(() => {
@@ -26,6 +28,7 @@ export default function Traces() {
}, [isBetaEnabled, setQueryParams]);
// Check if the user has tracing configured
+ // Skip polling entirely if the project flag is already set in the session
const { data: hasTracingConfigured, isLoading } =
api.traces.hasTracingConfigured.useQuery(
{ projectId },
@@ -36,7 +39,9 @@ export default function Traces() {
skipBatch: true,
},
},
- refetchInterval: 10_000,
+ refetchInterval: project?.hasTraces ? false : 10_000,
+ initialData: project?.hasTraces ? true : undefined,
+ staleTime: project?.hasTraces ? Infinity : 0,
},
);
diff --git a/web/src/pages/project/[projectId]/traces/setup.tsx b/web/src/pages/project/[projectId]/traces/setup.tsx
index 5568e9fb14..e589748075 100644
--- a/web/src/pages/project/[projectId]/traces/setup.tsx
+++ b/web/src/pages/project/[projectId]/traces/setup.tsx
@@ -9,6 +9,7 @@ import { Button } from "@/src/components/ui/button";
import { ApiKeyRender } from "@/src/features/public-api/components/CreateApiKeyButton";
import { type RouterOutput } from "@/src/utils/types";
import { useState } from "react";
+import { useQueryProject } from "@/src/features/projects/hooks";
export const TracingSetup = ({
projectId,
@@ -93,14 +94,18 @@ export const TracingSetup = ({
export default function TracesSetupPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
+ const { project } = useQueryProject();
// Check if the user has tracing configured
+ // Skip polling entirely if the project flag is already set in the session
const { data: hasTracingConfigured } =
api.traces.hasTracingConfigured.useQuery(
{ projectId },
{
enabled: !!projectId,
- refetchInterval: 5000,
+ refetchInterval: project?.hasTraces ? false : 5000,
+ initialData: project?.hasTraces ? true : undefined,
+ staleTime: project?.hasTraces ? Infinity : 0,
trpc: {
context: {
skipBatch: true,
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 7fcae576c2..ed3e704b2c 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -706,6 +706,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
name: project.name,
role: projectRole,
retentionDays: project.retentionDays,
+ hasTraces: project.hasTraces,
deletedAt: project.deletedAt,
metadata:
(project.metadata as Record<
diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.ts
index 245394abab..b4d45d3c2a 100644
--- a/web/types/next-auth.d.ts
+++ b/web/types/next-auth.d.ts
@@ -49,6 +49,7 @@ declare module "next-auth" {
name: PrismaProject["name"];
deletedAt: PrismaProject["deletedAt"];
retentionDays: PrismaProject["retentionDays"];
+ hasTraces: PrismaProject["hasTraces"];
metadata: Record<string, unknown>;
role: Role; // include only projects where user has a role
}[];