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.

fix(web-analytics): stop duplicate live stream reconnects (#70650)

Paul D'Ambrae4853aebf3d9
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/createStreamConnection.test.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/createStreamConnection.test.ts
new file mode 100644
index 000000000000..ca7c00f57787
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/createStreamConnection.test.ts
@@ -0,0 +1,47 @@
+import api from 'lib/api'
+
+import { createStreamConnection } from './createStreamConnection'
+
+describe('createStreamConnection', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ jest.restoreAllMocks()
+ })
+
+ it('does not reconnect when abort triggers a delayed stream error', () => {
+ const streamSpy = jest.spyOn(api, 'stream').mockResolvedValue(undefined)
+ const connection = createStreamConnection({
+ url: new URL('https://example.com/events'),
+ token: 'token',
+ onMessage: jest.fn(),
+ })
+ const streamOptions = streamSpy.mock.calls[0][1]
+
+ connection.abort()
+ streamOptions.onError(new Error('aborted'))
+ jest.runAllTimers()
+
+ expect(streamSpy).toHaveBeenCalledTimes(1)
+ })
+
+ it('stops the underlying retry and clears the scheduled reconnect when aborted', () => {
+ const streamSpy = jest.spyOn(api, 'stream').mockResolvedValue(undefined)
+ const connection = createStreamConnection({
+ url: new URL('https://example.com/events'),
+ token: 'token',
+ onMessage: jest.fn(),
+ })
+ const streamOptions = streamSpy.mock.calls[0][1]
+ const error = new Error('connection lost')
+
+ expect(() => streamOptions.onError(error)).toThrow(error)
+
+ connection.abort()
+ jest.advanceTimersByTime(1000)
+ expect(streamSpy).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/createStreamConnection.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/createStreamConnection.ts
index c609fc4d36d6..602494ba8aba 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/createStreamConnection.ts
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/createStreamConnection.ts
@@ -20,32 +20,62 @@ export const createStreamConnection = (config: StreamConnectionConfig): StreamCo
let abortController = new AbortController()
let retryTimeout: ReturnType<typeof setTimeout> | null = null
let retryDelay = INITIAL_RETRY_DELAY_MS
+ let aborted = false
- const connect = async (): Promise<void> => {
- await api.stream(url.toString(), {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- signal: abortController.signal,
- onMessage: (event) => {
- retryDelay = INITIAL_RETRY_DELAY_MS
- onMessage(event.data)
- },
- onError: (error) => {
- onError?.(error)
- retryTimeout = setTimeout(() => {
- abortController = new AbortController()
- void connect()
- }, retryDelay)
- retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS)
- },
- })
+ function scheduleReconnect(): void {
+ if (aborted || retryTimeout) {
+ return
+ }
+ retryTimeout = setTimeout(() => {
+ retryTimeout = null
+ if (aborted) {
+ return
+ }
+ abortController = new AbortController()
+ void connect()
+ }, retryDelay)
+ retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS)
+ }
+
+ async function connect(): Promise<void> {
+ if (aborted) {
+ return
+ }
+ try {
+ await api.stream(url.toString(), {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ signal: abortController.signal,
+ onMessage: (event) => {
+ if (aborted) {
+ return
+ }
+ retryDelay = INITIAL_RETRY_DELAY_MS
+ onMessage(event.data)
+ },
+ onError: (error) => {
+ if (aborted) {
+ return
+ }
+ scheduleReconnect()
+ onError?.(error)
+ throw error
+ },
+ })
+ } catch (error) {
+ if (!aborted && !retryTimeout) {
+ onError?.(error instanceof Error ? error : new Error(String(error)))
+ scheduleReconnect()
+ }
+ }
}
void connect()
return {
abort: () => {
+ aborted = true
abortController.abort()
if (retryTimeout) {
clearTimeout(retryTimeout)