: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
fix(web-analytics): manage live dashboard timers via kea disposables (#70215)
Paul D'Ambra4bf7bbfb20ab
diff --git a/frontend/src/kea-disposables.ts b/frontend/src/kea-disposables.tsindex 4b932b01263f..b8b7cc3e6064 100644--- a/frontend/src/kea-disposables.ts+++ b/frontend/src/kea-disposables.ts@@ -13,7 +13,7 @@ type DisposableEntry = {options: DisposableOptions}-type DisposablesManager = {+export type DisposablesManager = {add: (setup: SetupFunction, key?: string, options?: DisposableOptions) => voiddispose: (key: string) => booleanregistry: Map<string, DisposableEntry>diff --git a/frontend/src/scenes/activity/live/deduplicateEvents.test.ts b/frontend/src/scenes/activity/live/deduplicateEvents.test.tsnew file mode 100644index 000000000000..4c1a57179e27--- /dev/null+++ b/frontend/src/scenes/activity/live/deduplicateEvents.test.ts@@ -0,0 +1,34 @@+import { LiveEvent } from '~/types'++import { deduplicateEvents } from './deduplicateEvents'++function makeEvent(uuid: string): LiveEvent {+ return {+ uuid,+ event: '$pageview',+ properties: {},+ timestamp: '2026-01-01T00:00:00Z',+ team_id: 1,+ distinct_id: 'user-1',+ created_at: '2026-01-01T00:00:00Z',+ }+}++describe('deduplicateEvents', () => {+ it('prepends new events and drops duplicates by uuid', () => {+ const state = [makeEvent('a')]+ const result = deduplicateEvents(state, [makeEvent('b'), makeEvent('a')], 10)+ expect(result.map((e) => e.uuid)).toEqual(['b', 'a'])+ })++ it('caps the result at the limit', () => {+ const state = [makeEvent('a'), makeEvent('b')]+ const result = deduplicateEvents(state, [makeEvent('c')], 2)+ expect(result.map((e) => e.uuid)).toEqual(['c', 'a'])+ })++ it('returns the same array reference when the batch contains only duplicates', () => {+ const state = [makeEvent('a')]+ expect(deduplicateEvents(state, [makeEvent('a')], 10)).toBe(state)+ })+})diff --git a/frontend/src/scenes/activity/live/deduplicateEvents.ts b/frontend/src/scenes/activity/live/deduplicateEvents.tsindex 72e79932db79..7c110ffc480b 100644--- a/frontend/src/scenes/activity/live/deduplicateEvents.ts+++ b/frontend/src/scenes/activity/live/deduplicateEvents.ts@@ -12,5 +12,10 @@ export function deduplicateEvents(state: LiveEvent[], incoming: LiveEvent[], lim}}+ // duplicate-only batches keep the existing array identity so downstream memoization holds+ if (newEvents.length === 0) {+ return state.length > limit ? state.slice(0, limit) : state+ }+return [...newEvents, ...state].slice(0, limit)}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsxindex 7cfcb99755e0..8fc6dc2db870 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx@@ -16,6 +16,7 @@ import { ProductTab } from 'scenes/web-analytics/common'import { webAnalyticsFilterLogic } from 'scenes/web-analytics/webAnalyticsFilterLogic'import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'+import type { DisposablesManager } from '~/kea-disposables'import { performQuery } from '~/queries/query'import {HogQLQuery,@@ -393,10 +394,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypecache.batch = []cache.geoBatch = []stopFlushInterval(cache as FlushCache)- if (cache.liveUserCountInterval) {- clearInterval(cache.liveUserCountInterval)- cache.liveUserCountInterval = null- }+ cache.disposables.dispose('liveUserCountInterval')},resumeStream: () => {if (cache.hasInitialized) {@@ -406,12 +404,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType})}startFlushInterval(cache as FlushCache, actions as FlushActions)- if (!cache.liveUserCountInterval) {- // Drives the "Users online" count so users drop off within ~5s of leaving the 60s window- cache.liveUserCountInterval = setInterval(() => {- actions.tickLiveUserCount()- }, 5000)- }+ startLiveUserCountInterval(cache as FlushCache, actions as FlushActions)actions.loadInitialData()},loadInitialData: async () => {@@ -580,30 +573,24 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType// Ensures that our graph continues to update and old data "falls off"// even if new events aren't coming in- const scheduleNextTick = (): void => {- const now = Date.now()- const msUntilNextMinute = 60000 - (now % 60000)- cache.minuteTickTimeout = setTimeout(() => {- actions.tickCurrentMinute()- scheduleNextTick()- }, msUntilNextMinute)- }- scheduleNextTick()- cache.liveUserCountInterval = setInterval(() => {- actions.tickLiveUserCount()- }, 5000)+ cache.disposables.add(() => {+ let minuteTickTimeout: ReturnType<typeof setTimeout>+ const scheduleNextTick = (): void => {+ const now = Date.now()+ const msUntilNextMinute = 60000 - (now % 60000)+ minuteTickTimeout = setTimeout(() => {+ actions.tickCurrentMinute()+ scheduleNextTick()+ }, msUntilNextMinute)+ }+ scheduleNextTick()+ return () => clearTimeout(minuteTickTimeout)+ }, 'minuteTick')+ startLiveUserCountInterval(cache as FlushCache, actions as FlushActions)},beforeUnmount: () => {cache.eventsConnection?.abort()cache.geoConnection?.abort()- stopFlushInterval(cache as FlushCache)- if (cache.minuteTickTimeout) {- clearTimeout(cache.minuteTickTimeout)- }- if (cache.liveUserCountInterval) {- clearInterval(cache.liveUserCountInterval)- cache.liveUserCountInterval = null- }},})),])@@ -612,19 +599,25 @@ interface FlushCache {batch: LiveEvent[]geoBatch: LiveGeoEvent[]newerThan: Date- flushInterval: ReturnType<typeof setInterval> | null+ disposables: DisposablesManager}interface FlushActions {addEvents: (events: LiveEvent[], newerThan: Date) => voidaddGeoEvents: (events: LiveGeoEvent[]) => void+ tickLiveUserCount: () => void}const stopFlushInterval = (cache: FlushCache): void => {- if (cache.flushInterval) {- clearInterval(cache.flushInterval)- cache.flushInterval = null- }+ cache.disposables.dispose('flushInterval')+}++// Drives the "Users online" count so users drop off within ~5s of leaving the 60s window+const startLiveUserCountInterval = (cache: FlushCache, actions: FlushActions): void => {+ cache.disposables.add(() => {+ const intervalId = setInterval(() => actions.tickLiveUserCount(), 5000)+ return () => clearInterval(intervalId)+ }, 'liveUserCountInterval')}// Translates the canonical filter list into repeated `?property=key=value` query params@@ -648,19 +641,19 @@ export const appendFilterParams = (url: URL, filters: WebAnalyticsPropertyFilter// Flush both event and geo batches on a fixed interval// to cap kea dispatches at a predictable rate regardless of event volumeconst startFlushInterval = (cache: FlushCache, actions: FlushActions): void => {- if (cache.flushInterval) {- return- }- cache.flushInterval = setInterval(() => {- if (cache.batch.length > 0) {- actions.addEvents(cache.batch, cache.newerThan)- cache.batch = []- }- if (cache.geoBatch.length > 0) {- actions.addGeoEvents(cache.geoBatch)- cache.geoBatch = []- }- }, FLUSH_INTERVAL_MS)+ cache.disposables.add(() => {+ const intervalId = setInterval(() => {+ if (cache.batch.length > 0) {+ actions.addEvents(cache.batch, cache.newerThan)+ cache.batch = []+ }+ if (cache.geoBatch.length > 0) {+ actions.addGeoEvents(cache.geoBatch)+ cache.geoBatch = []+ }+ }, FLUSH_INTERVAL_MS)+ return () => clearInterval(intervalId)+ }, 'flushInterval')}const loadQueryData = async ({diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsxindex 244e73a7e017..51fc7f71c5e2 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWorldMapLogic.tsx@@ -3,6 +3,8 @@ import { actions, events, kea, listeners, path, reducers, selectors } from 'kea'import { getSeriesColor } from 'lib/colors'import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'+import type { DisposablesManager } from '~/kea-disposables'+import { CountryBreakdownItem } from './LiveWebAnalyticsMetricsTypes'import type { liveWorldMapLogicType } from './liveWorldMapLogicType'@@ -175,9 +177,6 @@ export const liveWorldMapLogic = kea<liveWorldMapLogicType>([cache.prevCounts = {}cache.lastActivity = {}},- beforeUnmount: () => {- stopHeatInterval(cache as HeatCache)- },})),])@@ -198,32 +197,34 @@ function computeHeat(lastActivity: Record<string, number>): Record<string, numbeinterface HeatCache {lastActivity: Record<string, number>- heatInterval: ReturnType<typeof setInterval> | null+ disposables: DisposablesManager}+const HEAT_INTERVAL_KEY = 'heatInterval'+// Only run the heat decay interval while there are active heat values.// Stops automatically when all heat has decayed to 0.function startHeatInterval(cache: HeatCache,actions: { setCountryHeat: (heat: Record<string, number>) => void }): void {- if (cache.heatInterval) {+ if (cache.disposables.registry.has(HEAT_INTERVAL_KEY)) {return}- cache.heatInterval = setInterval(() => {- const heat = computeHeat(cache.lastActivity || {})- if (Object.keys(heat).length === 0) {- stopHeatInterval(cache as HeatCache)- actions.setCountryHeat({})- return- }- actions.setCountryHeat(heat)- }, HEAT_UPDATE_INTERVAL_MS)+ cache.disposables.add(() => {+ const intervalId = setInterval(() => {+ const heat = computeHeat(cache.lastActivity || {})+ if (Object.keys(heat).length === 0) {+ stopHeatInterval(cache)+ actions.setCountryHeat({})+ return+ }+ actions.setCountryHeat(heat)+ }, HEAT_UPDATE_INTERVAL_MS)+ return () => clearInterval(intervalId)+ }, HEAT_INTERVAL_KEY)}function stopHeatInterval(cache: HeatCache): void {- if (cache.heatInterval) {- clearInterval(cache.heatInterval)- cache.heatInterval = null- }+ cache.disposables.dispose(HEAT_INTERVAL_KEY)}