Skip to content

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

perf(dashboards): cache in frontend (#12299)

Nimar38ba952ef940
diff --git a/web/src/features/widgets/components/DashboardWidget.tsx b/web/src/features/widgets/components/DashboardWidget.tsx
index d33cdf579c..fb244669a9 100644
--- a/web/src/features/widgets/components/DashboardWidget.tsx
+++ b/web/src/features/widgets/components/DashboardWidget.tsx
@@ -38,7 +38,6 @@ import {
isV2BreakdownChart,
buildWidgetOrderBy,
} from "@/src/features/query/validateQuery";
-import { hashKey } from "@tanstack/react-query";
export interface WidgetPlacement {
id: string;
@@ -178,19 +177,6 @@ export function DashboardWidget({
: ({ valid: true } as const),
[widgetQuery, metricsVersion, widget.data],
);
- const queryRunKey = useMemo(
- () =>
- hashKey([
- {
- projectId,
- version: metricsVersion,
- query: widgetQuery,
- },
- retryCount,
- ]),
- [metricsVersion, projectId, retryCount, widgetQuery],
- );
-
const queryResult = useScheduledDashboardExecuteQuery(
{
projectId,
@@ -207,7 +193,7 @@ export function DashboardWidget({
meta: {
silentHttpCodes: [422],
},
- runKey: queryRunKey,
+ refreshKey: retryCount,
useSSE: shouldUseWidgetSSE({
isV4BetaEnabled: isBetaEnabled,
version: metricsVersion,
diff --git a/web/src/hooks/useDashboardQueryScheduler.tsx b/web/src/hooks/useDashboardQueryScheduler.tsx
index 4335271ca7..4c1fe3f211 100644
--- a/web/src/hooks/useDashboardQueryScheduler.tsx
+++ b/web/src/hooks/useDashboardQueryScheduler.tsx
@@ -2,8 +2,8 @@ import {
type TimeRange,
toAbsoluteTimeRange,
} from "@/src/utils/date-range-utils";
-import { api, type RouterInputs } from "@/src/utils/api";
-import { hashKey } from "@tanstack/react-query";
+import { api, type RouterInputs, type RouterOutputs } from "@/src/utils/api";
+import { hashKey, useQuery, type UseQueryOptions } from "@tanstack/react-query";
import {
createContext,
type ReactNode,
@@ -42,6 +42,8 @@ export type DashboardQuerySchedulerApi = {
};
const DAY_MS = 24 * 60 * 60 * 1000;
+const SECOND_MS = 1000;
+const MINUTE_MS = 60 * SECOND_MS;
export const getDashboardQuerySchedulerMaxConcurrent = (
timeRange: TimeRange,
@@ -59,6 +61,15 @@ export const getDashboardQuerySchedulerMaxConcurrent = (
return 9;
};
+const parseIsoDateMs = (value: unknown): number | null => {
+ if (typeof value !== "string") return null;
+
+ const parsedMs = Date.parse(value);
+ if (Number.isNaN(parsedMs)) return null;
+
+ return parsedMs;
+};
+
export const useDashboardQueryScheduler = ({
maxConcurrent,
resetKey,
@@ -214,6 +225,7 @@ type DashboardQuerySchedulerContextValue = {
DashboardQuerySchedulerApi,
"register" | "unregister" | "canFetch" | "markDone"
>;
+ shouldBucketQueriesByTimeRange: boolean;
};
const DashboardQuerySchedulerContext =
@@ -221,9 +233,11 @@ const DashboardQuerySchedulerContext =
export const DashboardQuerySchedulerProvider = ({
scheduler,
+ shouldBucketQueriesByTimeRange = false,
children,
}: {
scheduler: DashboardQuerySchedulerContextValue["scheduler"];
+ shouldBucketQueriesByTimeRange?: boolean;
children: ReactNode;
}) => {
const contextValue = useMemo(
@@ -234,12 +248,14 @@ export const DashboardQuerySchedulerProvider = ({
canFetch: scheduler.canFetch,
markDone: scheduler.markDone,
},
+ shouldBucketQueriesByTimeRange,
}),
[
scheduler.register,
scheduler.unregister,
scheduler.canFetch,
scheduler.markDone,
+ shouldBucketQueriesByTimeRange,
],
);
@@ -255,11 +271,18 @@ const useDashboardQuerySchedulerContext = () => {
};
type DashboardExecuteQueryInput = RouterInputs["dashboard"]["executeQuery"];
-type DashboardExecuteQueryOptions = NonNullable<
- Parameters<
- typeof api.dashboard.executeQuery.useQuery<Record<string, unknown>[]>
- >[1]
->;
+type DashboardExecuteQueryOutput = RouterOutputs["dashboard"]["executeQuery"];
+type DashboardExecuteQueryOptions = Omit<
+ UseQueryOptions<DashboardExecuteQueryOutput, Error>,
+ "enabled" | "meta" | "queryFn" | "queryKey"
+> & {
+ meta?: Record<string, unknown>;
+ trpc?: {
+ context?: {
+ skipBatch?: boolean;
+ };
+ };
+};
type ScheduledDashboardExecuteQueryOptions = Omit<
DashboardExecuteQueryOptions,
"enabled" | "meta"
@@ -268,12 +291,106 @@ type ScheduledDashboardExecuteQueryOptions = Omit<
meta?: DashboardExecuteQueryOptions["meta"];
priority?: number;
queryId: string;
- runKey?: string;
+ refreshKey?: unknown;
useSSE?: boolean;
};
-const getDefaultRunKey = (input: DashboardExecuteQueryInput) =>
- hashKey([input]);
+const getDashboardExecuteQueryDurationMs = (
+ input: DashboardExecuteQueryInput,
+): number | null => {
+ const fromMs = parseIsoDateMs(input.query?.fromTimestamp);
+ const toMs = parseIsoDateMs(input.query?.toTimestamp);
+
+ if (fromMs === null || toMs === null) return null;
+ return Math.max(0, toMs - fromMs);
+};
+
+const getDashboardExecuteQueryCachePolicy = (
+ input: DashboardExecuteQueryInput,
+): {
+ staleTime: number;
+ gcTime: number;
+} => {
+ const durationMs = getDashboardExecuteQueryDurationMs(input);
+
+ if (durationMs === null) {
+ return {
+ staleTime: 30 * SECOND_MS,
+ gcTime: 10 * MINUTE_MS,
+ };
+ }
+
+ if (durationMs <= 30 * MINUTE_MS) {
+ return {
+ staleTime: 15 * SECOND_MS,
+ gcTime: 5 * MINUTE_MS,
+ };
+ }
+
+ if (durationMs <= DAY_MS) {
+ return {
+ staleTime: 30 * SECOND_MS,
+ gcTime: 10 * MINUTE_MS,
+ };
+ }
+
+ if (durationMs <= 7 * DAY_MS) {
+ return {
+ staleTime: 2 * MINUTE_MS,
+ gcTime: 20 * MINUTE_MS,
+ };
+ }
+
+ if (durationMs <= 30 * DAY_MS) {
+ return {
+ staleTime: 5 * MINUTE_MS,
+ gcTime: 30 * MINUTE_MS,
+ };
+ }
+
+ return {
+ staleTime: 10 * MINUTE_MS,
+ gcTime: 60 * MINUTE_MS,
+ };
+};
+
+const normalizeIsoTimestampByBucket = (
+ value: unknown,
+ bucketMs: number,
+): unknown => {
+ if (typeof value !== "string") return value;
+ const parsedMs = Date.parse(value);
+ if (Number.isNaN(parsedMs)) return value;
+
+ const effectiveBucketMs = Math.max(1, Math.floor(bucketMs));
+ const normalizedMs =
+ Math.floor(parsedMs / effectiveBucketMs) * effectiveBucketMs;
+ return new Date(normalizedMs).toISOString();
+};
+
+const normalizeDashboardExecuteQueryInputForCache = (
+ input: DashboardExecuteQueryInput,
+ bucketMs: number,
+): DashboardExecuteQueryInput => {
+ if (!input.query) return input;
+
+ // Intentionally bucket from/to timestamps only for derived cache/restart keys.
+ // The backend payload still uses the original timestamps.
+ return {
+ ...input,
+ query: {
+ ...input.query,
+ fromTimestamp: normalizeIsoTimestampByBucket(
+ input.query.fromTimestamp,
+ bucketMs,
+ ) as string,
+ toTimestamp: normalizeIsoTimestampByBucket(
+ input.query.toTimestamp,
+ bucketMs,
+ ) as string,
+ },
+ };
+};
export const useScheduledDashboardExecuteQuery = (
input: DashboardExecuteQueryInput,
@@ -282,7 +399,7 @@ export const useScheduledDashboardExecuteQuery = (
meta,
priority = 1000,
queryId,
- runKey,
+ refreshKey,
useSSE = false,
...queryOptions
}: ScheduledDashboardExecuteQueryOptions,
@@ -297,14 +414,36 @@ export const useScheduledDashboardExecuteQuery = (
error: string | null;
} => {
const context = useDashboardQuerySchedulerContext();
+ const utils = api.useUtils();
const scheduler = context?.scheduler;
const register = scheduler?.register;
const unregister = scheduler?.unregister;
const markDone = scheduler?.markDone;
+ const shouldBucketQueriesByTimeRange =
+ context?.shouldBucketQueriesByTimeRange ?? false;
+ const cachePolicy = useMemo(
+ () => getDashboardExecuteQueryCachePolicy(input),
+ [input],
+ );
+ const cacheKeyInput = useMemo(
+ () =>
+ shouldBucketQueriesByTimeRange
+ ? normalizeDashboardExecuteQueryInputForCache(
+ input,
+ cachePolicy.staleTime,
+ )
+ : input,
+ [cachePolicy.staleTime, input, shouldBucketQueriesByTimeRange],
+ );
+ const queryCacheKey = useMemo(
+ () => ["dashboard.executeQuery", cacheKeyInput, refreshKey ?? null],
+ [cacheKeyInput, refreshKey],
+ );
const effectiveRunKey = useMemo(
- () => runKey ?? getDefaultRunKey(input),
- [input, runKey],
+ () => hashKey(queryCacheKey),
+ [queryCacheKey],
);
+ const { trpc, ...reactQueryOptions } = queryOptions;
useEffect(() => {
if (!unregister) return;
@@ -321,10 +460,18 @@ export const useScheduledDashboardExecuteQuery = (
const canFetch = scheduler ? scheduler.canFetch(queryId) : true;
// tRPC path (default)
- const trpcResult = api.dashboard.executeQuery.useQuery<
- Record<string, unknown>[]
- >(input, {
- ...queryOptions,
+ const trpcResult = useQuery<DashboardExecuteQueryOutput, Error>({
+ ...reactQueryOptions,
+ queryKey: queryCacheKey,
+ queryFn: async () =>
+ utils.dashboard.executeQuery.fetch(input, {
+ trpc,
+ }),
+ staleTime: queryOptions.staleTime ?? cachePolicy.staleTime,
+ gcTime: queryOptions.gcTime ?? cachePolicy.gcTime,
+ refetchOnWindowFocus: queryOptions.refetchOnWindowFocus ?? false,
+ refetchOnReconnect: queryOptions.refetchOnReconnect ?? false,
+ refetchOnMount: queryOptions.refetchOnMount ?? false,
enabled: enabled && canFetch && !useSSE,
meta,
});
@@ -332,6 +479,7 @@ export const useScheduledDashboardExecuteQuery = (
// SSE path (opt-in)
const sseResult = useSSEDashboardQuery(input, {
enabled: enabled && canFetch && useSSE,
+ inputKey: effectiveRunKey,
queryId,
});
diff --git a/web/src/hooks/useSSEDashboardQuery.ts b/web/src/hooks/useSSEDashboardQuery.ts
index 2b826eea78..8acdecacc5 100644
--- a/web/src/hooks/useSSEDashboardQuery.ts
+++ b/web/src/hooks/useSSEDashboardQuery.ts
@@ -76,10 +76,11 @@ export function useSSEDashboardQuery(
input: DashboardExecuteQueryInput,
options: {
enabled?: boolean;
+ inputKey?: string;
queryId: string;
},
): SSEQueryResult {
- const { enabled = true } = options;
+ const { enabled = true, inputKey: inputKeyOverride } = options;
const [data, setData] = useState<Record<string, unknown>[] | undefined>(
undefined,
);
@@ -223,7 +224,7 @@ export function useSSEDashboardQuery(
);
// Derive a stable key from the input to detect changes
- const inputKey = JSON.stringify(input);
+ const inputKey = inputKeyOverride ?? JSON.stringify(input);
useEffect(() => {
if (!enabled) {
diff --git a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
index 2fa211958a..78da2aaecf 100644
--- a/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
+++ b/web/src/pages/project/[projectId]/dashboards/[dashboardId]/index.tsx
@@ -411,7 +411,10 @@ export default function DashboardDetail() {
});
return (
- <DashboardQuerySchedulerProvider scheduler={scheduler}>
+ <DashboardQuerySchedulerProvider
+ scheduler={scheduler}
+ shouldBucketQueriesByTimeRange={!("from" in timeRange)}
+ >
<Page
withPadding
scrollable
diff --git a/web/src/pages/project/[projectId]/index.tsx b/web/src/pages/project/[projectId]/index.tsx
index 53257dac81..926d91161f 100644
--- a/web/src/pages/project/[projectId]/index.tsx
+++ b/web/src/pages/project/[projectId]/index.tsx
@@ -196,7 +196,10 @@ export default function Dashboard() {
const homeSchedulerIdPrefix = `${projectId}:`;
return (
- <DashboardQuerySchedulerProvider scheduler={scheduler}>
+ <DashboardQuerySchedulerProvider
+ scheduler={scheduler}
+ shouldBucketQueriesByTimeRange={!("from" in timeRange)}
+ >
<Page
withPadding
scrollable