Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(dashboards): track dashboard render performance per view (#125706)

Matt Pua6fbc1fce4089
diff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsx
index 20c5e439bba0..99c0e24f6092 100644
--- a/frontend/src/scenes/dashboard/Dashboard.tsx
+++ b/frontend/src/scenes/dashboard/Dashboard.tsx
@@ -36,6 +36,7 @@ import { DashboardFlagCalledBanner } from './DashboardFlagCalledBanner'
import { DashboardHeader } from './DashboardHeader'
import { DashboardEmbeddedShareButton } from './DashboardHeaderActions'
import { DashboardModalLoading } from './DashboardModalLoading'
+import { dashboardPerformanceLogic } from './dashboardPerformanceLogic'
import { DashboardQueryScanBanner } from './DashboardQueryScanBanner'
import { DashboardRetentionBanner } from './DashboardRetentionBanner'
import { dashboardSubscribeNudgeLogic } from './dashboardSubscribeNudgeLogic'
@@ -152,6 +153,8 @@ function DashboardScene({
hasInvalidDashboardId,
} = useValues(dashboardLogic)
const { layoutZoom } = useValues(dashboardLogic)
+ const { id: dashboardId } = useMountedLogic(dashboardLogic).props
+ useMountedLogic(dashboardPerformanceLogic({ dashboardId, placement }))
const { currentTeamId } = useValues(teamLogic)
const { reportDashboardViewed, cancelDashboardRefresh, retryDashboardLoad, setLayoutZoom } =
useActions(dashboardLogic)
diff --git a/frontend/src/scenes/dashboard/dashboardPerformance.test.ts b/frontend/src/scenes/dashboard/dashboardPerformance.test.ts
new file mode 100644
index 000000000000..f475275807cf
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardPerformance.test.ts
@@ -0,0 +1,65 @@
+import posthog from 'posthog-js'
+
+import { DashboardPlacement } from '~/types'
+
+import { DashboardPerformanceMonitor } from './dashboardPerformance'
+
+describe('DashboardPerformanceMonitor', () => {
+ const context = { dashboardId: 1, placement: DashboardPlacement.Dashboard, getTileCount: () => 3 }
+ const heap = (mb: number): { usedJSHeapSize: number } => ({ usedJSHeapSize: mb * 1024 * 1024 })
+
+ it('reports once and leaves out time and jank from a hidden tab', () => {
+ const monitor = new DashboardPerformanceMonitor(context, 0, true)
+ monitor.recordHeapStart(heap(100))
+ monitor.recordLongFrame(120, 70)
+ monitor.setVisible(false, 30_000)
+ monitor.recordLongFrame(500, 450)
+ monitor.setVisible(true, 90_000)
+
+ expect(monitor.finish(120_000, heap(150))).toMatchObject({
+ duration_ms: 120_000,
+ visible_ms: 60_000,
+ long_frame_count: 1,
+ long_frame_max_ms: 120,
+ blocking_ms: 70,
+ blocking_ms_per_minute: 70,
+ heap_start_mb: 100,
+ heap_end_mb: 150,
+ tile_count: 3,
+ })
+ expect(monitor.finish(130_000, heap(150))).toBeNull()
+ })
+
+ it('skips views too short to measure', () => {
+ expect(new DashboardPerformanceMonitor(context, 0, true).finish(500, undefined)).toBeNull()
+ })
+
+ it('hands monitoring to the next dashboard when it mounts before the previous view cleans up', () => {
+ class FakePerformanceObserver {
+ static supportedEntryTypes = ['long-animation-frame']
+ observe(): void {}
+ disconnect(): void {}
+ takeRecords(): PerformanceEntry[] {
+ return []
+ }
+ }
+ const originalObserver = globalThis.PerformanceObserver
+ globalThis.PerformanceObserver = FakePerformanceObserver as unknown as typeof PerformanceObserver
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ jest.useFakeTimers()
+ try {
+ const reportFirst = new DashboardPerformanceMonitor({ ...context, dashboardId: 1 }).start()
+ jest.advanceTimersByTime(5_000)
+ const reportSecond = new DashboardPerformanceMonitor({ ...context, dashboardId: 2 }).start()
+ jest.advanceTimersByTime(5_000)
+ reportFirst()
+ reportSecond()
+
+ expect(capture.mock.calls.map(([, properties]) => properties?.dashboard_id)).toEqual([1, 2])
+ } finally {
+ jest.useRealTimers()
+ capture.mockRestore()
+ globalThis.PerformanceObserver = originalObserver
+ }
+ })
+})
diff --git a/frontend/src/scenes/dashboard/dashboardPerformance.ts b/frontend/src/scenes/dashboard/dashboardPerformance.ts
new file mode 100644
index 000000000000..501cb7bb2484
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardPerformance.ts
@@ -0,0 +1,185 @@
+import posthog from 'posthog-js'
+
+import { DashboardPlacement } from '~/types'
+
+// pinned: analytics event name, renaming it breaks insights built on it
+export const DASHBOARD_PERFORMANCE_EVENT = 'dashboard performance'
+export const DASHBOARD_PERFORMANCE_SAMPLE_RATE = 0.25
+
+const MIN_VISIBLE_MS = 2000
+
+// Not yet in lib.dom.d.ts.
+interface LongAnimationFrameEntry extends PerformanceEntry {
+ blockingDuration: number
+}
+
+interface ChromiumPerformanceMemory {
+ usedJSHeapSize: number
+}
+
+export interface DashboardPerformanceContext {
+ dashboardId: number
+ placement: DashboardPlacement
+ getTileCount: () => number
+}
+
+export interface DashboardPerformanceCaptureOptions {
+ transport?: 'sendBeacon'
+ send_instantly?: boolean
+}
+
+/**
+ * Collects main-thread jank and JS heap figures for one dashboard view, then sends them as one event.
+ */
+export class DashboardPerformanceMonitor {
+ // Everything observed is page-wide, so a second monitor would count the same jank twice.
+ private static endActiveView: (() => void) | null = null
+
+ private readonly startedAt: number
+ private finished = false
+
+ private visibleMs = 0
+ private visibleSince: number | null
+
+ private longFrameCount = 0
+ private longFrameMaxMs = 0
+ private blockingMs = 0
+
+ private heapStartBytes: number | null = null
+
+ constructor(
+ private readonly context: DashboardPerformanceContext,
+ now: number = performance.now(),
+ visible: boolean = document.visibilityState === 'visible'
+ ) {
+ this.startedAt = now
+ this.visibleSince = visible ? now : null
+ }
+
+ static shouldSample(random: number = Math.random()): boolean {
+ return random < DASHBOARD_PERFORMANCE_SAMPLE_RATE
+ }
+
+ recordLongFrame(durationMs: number, blockingMs: number): void {
+ if (this.finished || this.visibleSince === null) {
+ return
+ }
+ this.longFrameCount += 1
+ this.longFrameMaxMs = Math.max(this.longFrameMaxMs, durationMs)
+ this.blockingMs += blockingMs
+ }
+
+ recordHeapStart(memory: ChromiumPerformanceMemory | undefined): void {
+ this.heapStartBytes = memory?.usedJSHeapSize ?? null
+ }
+
+ setVisible(visible: boolean, now: number = performance.now()): void {
+ if (visible && this.visibleSince === null) {
+ this.visibleSince = now
+ } else if (!visible && this.visibleSince !== null) {
+ this.visibleMs += now - this.visibleSince
+ this.visibleSince = null
+ }
+ }
+
+ finish(
+ now: number = performance.now(),
+ memory: ChromiumPerformanceMemory | undefined = readHeap()
+ ): Record<string, unknown> | null {
+ if (this.finished) {
+ return null
+ }
+ this.finished = true
+ this.setVisible(false, now)
+ if (this.visibleMs < MIN_VISIBLE_MS) {
+ return null
+ }
+
+ return {
+ dashboard_id: this.context.dashboardId,
+ sample_rate: DASHBOARD_PERFORMANCE_SAMPLE_RATE,
+ placement: this.context.placement,
+ tile_count: this.context.getTileCount(),
+ duration_ms: Math.round(now - this.startedAt),
+ visible_ms: Math.round(this.visibleMs),
+ long_frame_count: this.longFrameCount,
+ long_frame_max_ms: Math.round(this.longFrameMaxMs),
+ blocking_ms: Math.round(this.blockingMs),
+ blocking_ms_per_minute: Math.round(this.blockingMs / (this.visibleMs / 60_000)),
+ heap_start_mb: toMegabytes(this.heapStartBytes),
+ heap_end_mb: toMegabytes(memory?.usedJSHeapSize ?? null),
+ viewport_width: window.innerWidth,
+ viewport_height: window.innerHeight,
+ device_memory_gb: (navigator as Navigator & { deviceMemory?: number }).deviceMemory ?? null,
+ hardware_concurrency: navigator.hardwareConcurrency ?? null,
+ }
+ }
+
+ start(): (options?: DashboardPerformanceCaptureOptions) => void {
+ // Without the long-animation-frame API the jank figures would read as zero, which looks like a perfect view.
+ if (!supportsLongAnimationFrames()) {
+ return () => {}
+ }
+ // The next dashboard mounts before the previous view cleans up, so the new view ends the old one.
+ DashboardPerformanceMonitor.endActiveView?.()
+
+ const stops: (() => void)[] = []
+ const stopAll = (): void => {
+ stops.splice(0).forEach((stop) => stop())
+ }
+ const report = (options?: DashboardPerformanceCaptureOptions): void => {
+ try {
+ stopAll()
+ const properties = this.finish()
+ if (properties) {
+ posthog.capture(DASHBOARD_PERFORMANCE_EVENT, properties, options)
+ }
+ } catch {}
+ }
+ DashboardPerformanceMonitor.endActiveView = report
+ stops.push(() => {
+ if (DashboardPerformanceMonitor.endActiveView === report) {
+ DashboardPerformanceMonitor.endActiveView = null
+ }
+ })
+
+ // Telemetry must never break the dashboard, so a failure here only drops this view's event.
+ try {
+ this.recordHeapStart(readHeap())
+
+ const onEntry = (entry: PerformanceEntry): void =>
+ this.recordLongFrame(entry.duration, (entry as LongAnimationFrameEntry).blockingDuration)
+ const observer = new PerformanceObserver((list) => list.getEntries().forEach(onEntry))
+ observer.observe({ type: 'long-animation-frame', buffered: false })
+ stops.push(() => {
+ observer.takeRecords().forEach(onEntry)
+ observer.disconnect()
+ })
+
+ const onVisibilityChange = (): void => this.setVisible(document.visibilityState === 'visible')
+ document.addEventListener('visibilitychange', onVisibilityChange)
+ stops.push(() => document.removeEventListener('visibilitychange', onVisibilityChange))
+ } catch {
+ stopAll()
+ this.finished = true
+ return () => {}
+ }
+
+ return report
+ }
+}
+
+function supportsLongAnimationFrames(): boolean {
+ return (
+ typeof PerformanceObserver !== 'undefined' &&
+ (PerformanceObserver.supportedEntryTypes ?? []).includes('long-animation-frame')
+ )
+}
+
+function readHeap(): ChromiumPerformanceMemory | undefined {
+ return (performance as Performance & { memory?: ChromiumPerformanceMemory }).memory
+}
+
+function toMegabytes(bytes: number | null): number | null {
+ return bytes === null ? null : Math.round((bytes / (1024 * 1024)) * 10) / 10
+}
diff --git a/frontend/src/scenes/dashboard/dashboardPerformanceLogic.ts b/frontend/src/scenes/dashboard/dashboardPerformanceLogic.ts
new file mode 100644
index 000000000000..1577bc13604e
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardPerformanceLogic.ts
@@ -0,0 +1,70 @@
+import { MakeLogicType, afterMount, kea, key, path, props } from 'kea'
+
+import { DashboardPlacement } from '~/types'
+
+import { dashboardLogic } from './dashboardLogic'
+import { DashboardPerformanceMonitor } from './dashboardPerformance'
+
+// Embedded, exported and public placements have their own layout and load paths, which would mix into the numbers.
+const MEASURED_PLACEMENTS = new Set([DashboardPlacement.Dashboard, DashboardPlacement.ProjectHomepage])
+
+export interface DashboardPerformanceLogicProps {
+ dashboardId: number
+ placement: DashboardPlacement
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface dashboardPerformanceLogicMeta {
+ key: number
+}
+
+export type dashboardPerformanceLogicType = MakeLogicType<
+ {},
+ {},
+ DashboardPerformanceLogicProps,
+ dashboardPerformanceLogicMeta
+>
+
+export const dashboardPerformanceLogic = kea<dashboardPerformanceLogicType>([
+ path(['scenes', 'dashboard', 'dashboardPerformanceLogic']),
+ props({} as DashboardPerformanceLogicProps),
+ key((props) => props.dashboardId),
+ afterMount(({ props, cache }) => {
+ if (
+ !Number.isFinite(props.dashboardId) ||
+ !MEASURED_PLACEMENTS.has(props.placement) ||
+ !DashboardPerformanceMonitor.shouldSample()
+ ) {
+ return
+ }
+ cache.disposables.add(
+ () => {
+ const start = (): ReturnType<DashboardPerformanceMonitor['start']> =>
+ new DashboardPerformanceMonitor({
+ dashboardId: props.dashboardId,
+ placement: props.placement,
+ getTileCount: () =>
+ dashboardLogic.findMounted({ id: props.dashboardId })?.values.tiles.length ?? 0,
+ }).start()
+ let report = start()
+ const onPageHide = (): void => report({ transport: 'sendBeacon', send_instantly: true })
+ // A page restored from the back-forward cache does not mount again, so it needs a new monitor.
+ const onPageShow = (event: PageTransitionEvent): void => {
+ if (event.persisted) {
+ report = start()
+ }
+ }
+ window.addEventListener('pagehide', onPageHide)
+ window.addEventListener('pageshow', onPageShow)
+ return () => {
+ window.removeEventListener('pagehide', onPageHide)
+ window.removeEventListener('pageshow', onPageShow)
+ report()
+ }
+ },
+ 'performanceMonitor',
+ // The monitor excludes hidden time itself, and a pause would split one view into two events.
+ { pauseOnPageHidden: false }
+ )
+ }),
+])