: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(frontend): mark and capture app boot phases (#117801)
Paul D'Ambraa100f6e01ecf
diff --git a/frontend/src/index.tsx b/frontend/src/index.tsxindex 1046f7f54e47..554761d364cc 100644--- a/frontend/src/index.tsx+++ b/frontend/src/index.tsx@@ -5,11 +5,14 @@ import './buffer-polyfill'import { Suspense, lazy } from 'react'import { createRoot, type Root } from 'react-dom/client'+import { markBootPhase } from 'lib/utils/bootTiming'import { retryBootImport } from 'lib/utils/retryImport'import { RootErrorBoundary } from './RootErrorBoundary'import { ChunkLoadErrorBoundary } from './scenes/ChunkLoadErrorBoundary'+markBootPhase('entry')+type AppModules = [typeof import('scenes/App'), typeof import('scenes/bootApp')]let appModulesPromise: Promise<AppModules> | undefined@@ -18,7 +21,11 @@ function loadAppModules(): Promise<AppModules> {return (appModulesPromise ??= Promise.all([retryBootImport(() => import('scenes/App')),retryBootImport(() => import('scenes/bootApp')),- ]))+ ]).then((modules) => {+ // Marked here, not in the lazy() factory: React calls the factory only after the CSS gate in boot().+ markBootPhase('app_modules_loaded')+ return modules+ }))}// Lazy-load App so the entry chunk stays minimal: the entire transitive dependencydiff --git a/frontend/src/lib/utils/bootTiming.test.ts b/frontend/src/lib/utils/bootTiming.test.tsnew file mode 100644index 000000000000..d46340d24581--- /dev/null+++ b/frontend/src/lib/utils/bootTiming.test.ts@@ -0,0 +1,119 @@+import type posthogType from 'posthog-js'++import type { markBootPhase as markBootPhaseType } from './bootTiming'++describe('bootTiming', () => {+ // Hash buckets 0 and 26 of 100, so one sits inside the 5% sample and one sits outside it.+ const IN_SAMPLE_ID = 'user-93'+ const OUT_OF_SAMPLE_ID = 'user-0'++ let markBootPhase: typeof markBootPhaseType+ let capture: jest.SpyInstance+ let getDistinctId: jest.SpyInstance+ let now: number+ let nowSpy: jest.SpyInstance++ beforeEach(() => {+ // The module keeps once-per-page-load state, so each test loads a fresh copy.+ jest.resetModules()+ now = 0+ nowSpy = jest.spyOn(performance, 'now').mockImplementation(() => now)+ markBootPhase = require('./bootTiming').markBootPhase+ const posthog: typeof posthogType = require('posthog-js').default+ capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)+ getDistinctId = jest.spyOn(posthog, 'get_distinct_id').mockReturnValue(IN_SAMPLE_ID)+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ const markAt = (time: number, ...args: Parameters<typeof markBootPhaseType>): void => {+ now = time+ markBootPhase(...args)+ }++ const flushSend = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))++ it('sends one event on the first scene render, with times since navigation start', async () => {+ markAt(50.4, 'entry')+ markAt(400, 'app_modules_loaded')+ markAt(620, 'scene_loaded', { scene: 'Insight' })+ // App and scene can commit together, and then the parent's `app_ready` effect runs after the scene's.+ markAt(910.6, 'scene_rendered')+ markAt(911, 'app_ready', { logged_in: true })+ await flushSend()++ markAt(5000, 'scene_loaded', { scene: 'Dashboard' })+ markAt(5100, 'scene_rendered')+ await flushSend()++ expect(capture).toHaveBeenCalledTimes(1)+ expect(capture).toHaveBeenCalledWith(+ 'app boot timing',+ expect.objectContaining({+ entry_ms: 50,+ app_modules_loaded_ms: 400,+ scene_loaded_ms: 620,+ app_ready_ms: 911,+ scene_rendered_ms: 911,+ scene: 'Insight',+ logged_in: true,+ page_was_hidden: false,+ sample_rate: 0.05,+ })+ )+ })++ it.each([+ { distinctId: IN_SAMPLE_ID, sends: true },+ { distinctId: OUT_OF_SAMPLE_ID, sends: false },+ // An empty ID hashes to bucket 0, so without a guard every such page load would land in the sample.+ { distinctId: '', sends: false },+ { distinctId: undefined, sends: false },+ ])('samples on distinct ID $distinctId (sends: $sends)', async ({ distinctId, sends }) => {+ getDistinctId.mockReturnValue(distinctId)+ markAt(50, 'entry')+ markAt(900, 'scene_rendered')+ await flushSend()++ expect(capture).toHaveBeenCalledTimes(sends ? 1 : 0)+ })++ it('reports a page hidden only between two marks', async () => {+ let visibilityState: DocumentVisibilityState = 'visible'+ jest.spyOn(document, 'visibilityState', 'get').mockImplementation(() => visibilityState)+ const setVisibility = (state: DocumentVisibilityState): void => {+ visibilityState = state+ document.dispatchEvent(new Event('visibilitychange'))+ }++ markAt(50, 'entry')+ setVisibility('hidden')+ setVisibility('visible')+ markAt(900, 'scene_rendered')+ await flushSend()++ expect(capture).toHaveBeenCalledWith('app boot timing', expect.objectContaining({ page_was_hidden: true }))+ })++ it.each([+ { reason: 'the entry script did not run, as in tests, storybook and the exporter', runEntry: false },+ { reason: 'performance.now is unavailable', runEntry: true, nowThrows: true },+ ])('sends nothing when $reason', async ({ runEntry, nowThrows }) => {+ if (nowThrows) {+ nowSpy.mockImplementation(() => {+ throw new TypeError('performance.now is not a function')+ })+ }+ if (runEntry) {+ markAt(50, 'entry')+ }+ markAt(400, 'app_modules_loaded')+ markAt(700, 'app_ready', { logged_in: true })+ markAt(900, 'scene_rendered')+ await flushSend()++ expect(capture).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/lib/utils/bootTiming.ts b/frontend/src/lib/utils/bootTiming.tsnew file mode 100644index 000000000000..23b88f6d8096--- /dev/null+++ b/frontend/src/lib/utils/bootTiming.ts@@ -0,0 +1,81 @@+// pinned: analytics event and property names. Boot performance insights read them.+const BOOT_TIMING_EVENT = 'app boot timing'+const SAMPLE_RATE = 0.05++export type BootPhase = 'entry' | 'app_modules_loaded' | 'app_ready' | 'scene_loaded' | 'scene_rendered'++export interface BootContext {+ scene?: string+ logged_in?: boolean+}++const phaseTimes: Partial<Record<BootPhase, number>> = {}+const context: BootContext = {}+let pageWasHidden = false+let sent = false++function getNavigationType(): string | null {+ const navigation = performance.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined+ return navigation?.type ?? null+}++// A background tab throttles timers and skips rendering, so its boot times are not comparable.+function recordHidden(): void {+ pageWasHidden ||= document.visibilityState === 'hidden'+}++async function sendBootTiming(): Promise<void> {+ // The entry chunk imports this module, and static imports would pull these modules into it.+ // import() also resolves after the current React commit. A parent's layout effect runs after+ // its children's, so an `app_ready` mark from the same commit still gets into the event.+ const [{ default: posthog }, { hashCodeForString }] = await Promise.all([+ import('posthog-js'),+ import('lib/utils/strings'),+ ])+ sent = true+ document.removeEventListener('visibilitychange', recordHidden)++ // Not `$device_id`: posthog-js gives it a new value on each page load of a user bootstrapped with+ // `identity_distinct_id`. The distinct ID changes only at login, so a user stays in or out across page loads.+ const distinctId = posthog.get_distinct_id()+ // hashCodeForString returns 0 for an empty string, which would put every such page load in the sample.+ if (!distinctId?.trim() || hashCodeForString(distinctId) % 100 >= SAMPLE_RATE * 100) {+ return+ }+ const durations = Object.fromEntries(+ Object.entries(phaseTimes).map(([phase, time]) => [`${phase}_ms`, Math.round(time)])+ )+ posthog.capture(BOOT_TIMING_EVENT, {+ ...durations,+ ...context,+ navigation_type: getNavigationType(),+ page_was_hidden: pageWasHidden,+ sample_rate: SAMPLE_RATE,+ })+}++/**+ * Records the first time a full page load reaches a boot phase, as a `performance.mark` and as ms since+ * navigation start. The first scene render sends all phases as one event, for a 5% sample of users. Later SPA+ * navigations change nothing.+ */+export function markBootPhase(phase: BootPhase, phaseContext?: BootContext): void {+ // Only the app entry script marks `entry`. Without it, this code runs in tests, storybook or the exporter.+ if (sent || phaseTimes[phase] !== undefined || (phase !== 'entry' && phaseTimes.entry === undefined)) {+ return+ }+ try {+ phaseTimes[phase] = performance.now()+ performance.mark?.(`posthog:boot:${phase}`)+ recordHidden()+ if (phase === 'entry') {+ document.addEventListener('visibilitychange', recordHidden)+ }+ } catch {+ return+ }+ Object.assign(context, phaseContext)+ if (phase === 'scene_rendered') {+ void sendBootTiming().catch(() => {})+ }+}diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsxindex 792c3650f295..b2a249a8642f 100644--- a/frontend/src/scenes/App.tsx+++ b/frontend/src/scenes/App.tsx@@ -1,7 +1,7 @@import { Tooltip as BaseTooltip } from '@base-ui/react/tooltip'import { BindLogic, useMountedLogic, useValues } from 'kea'import posthog from 'posthog-js'-import React, { Suspense, useEffect } from 'react'+import React, { Suspense, useEffect, useLayoutEffect } from 'react'import { Slide, ToastContainer } from 'react-toastify'import { PostHogProvider } from '@posthog/react'@@ -14,6 +14,7 @@ import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'import { autofillReleaseLogic } from 'lib/memory/autofillReleaseLogic'import { OAuthCallback } from 'lib/oauth/OAuthCallback'import { oauthLogic } from 'lib/oauth/oauthLogic'+import { markBootPhase } from 'lib/utils/bootTiming'import { lazyWithRetry, retryImport } from 'lib/utils/retryImport'import { appLogic } from 'scenes/appLogic'import { appScenes } from 'scenes/appScenes'@@ -53,6 +54,10 @@ window.process = MOCK_NODE_PROCESS*/function SceneAnimationRoot({ children }: { children: React.ReactNode }): JSX.Element {const ref = useCancelAnimationsOnUnmount<HTMLDivElement>()+ // For a logged-in user this sits inside the AuthenticatedShell Suspense boundary, so it runs when the scene+ // commits, not when the shell fallback does. A scene behind ProductEmptyStateGate can still commit the+ // gate's fallback first.+ useLayoutEffect(() => markBootPhase('scene_rendered'), [])return (// `className="contents"` is load-bearing: the wrapper must take a DOM// node so the ref has something to attach to (we need an element to@@ -130,6 +135,9 @@ function AppScene(): JSX.Element | null {const { showingDelayedSpinner } = useValues(appLogic)const { isDarkModeOn } = useValues(themeLogic)+ // App mounts this component on the first commit where appLogic's `showApp` is true.+ useLayoutEffect(() => markBootPhase('app_ready', { logged_in: !!user }), [user])+// Once we know the user is authenticated, kick off an idle prefetch of the// AuthenticatedShell chunk so the Suspense fallback rarely actually fires// when the shell mounts. No-op on prefetch failure — Suspense still works.diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex 7061d15b0dad..276cbd4c99ea 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -23,6 +23,7 @@ import { trackFileSystemLogView } from 'lib/hooks/useFileSystemLogView'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { Spinner } from 'lib/lemon-ui/Spinner'import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { markBootPhase } from 'lib/utils/bootTiming'import { getAppContext } from 'lib/utils/getAppContext'import { isChunkLoadError } from 'lib/utils/isChunkLoadError'import { addProjectIdIfMissing, getProjectIdentifierInPath, removeProjectIdIfPresent } from 'lib/utils/kea-router'@@ -804,6 +805,10 @@ export const sceneLogic = kea<sceneLogicType>([await cache.homepageSave},setScene: ({ sceneKey, sceneId, exportedScene, params, scrollToTop }, _, __, previousState) => {+ if (exportedScene) {+ markBootPhase('scene_loaded', { scene: sceneId })+ }+const {sceneId: lastSceneId,sceneKey: lastSceneKey,