Skip to content

fix: use singleton PostHog client instead of per-request instantiation#186

Open
jakebromberg wants to merge 2 commits intomainfrom
fix/30-posthog-singleton
Open

fix: use singleton PostHog client instead of per-request instantiation#186
jakebromberg wants to merge 2 commits intomainfrom
fix/30-posthog-singleton

Conversation

@jakebromberg
Copy link
Member

Summary

  • Bug: createBackendMirrorMiddleware instantiated a new PostHog client (with its own connection pool and flush interval) inside the res.once('finish', ...) callback on every request, then called shutdown() on each one.
  • Fix: Replaced with a module-level lazy singleton via getPostHogClient(). The client is created once on first use and reused for all subsequent requests. Removed the per-request shutdown() call since the singleton persists for the process lifetime.
  • Test: Added mirror.posthog.test.ts that mocks posthog-node, fires two request finish events, and asserts the PostHog constructor is called exactly once.

Test plan

  • New unit test fails before fix (constructor called 2x)
  • New unit test passes after fix (constructor called 1x)
  • All existing legacy mirror tests still pass (57/57)

Made with Cursor

@jakebromberg jakebromberg force-pushed the fix/30-posthog-singleton branch from 87012a5 to c31eb85 Compare February 26, 2026 04:39
@jakebromberg jakebromberg requested a review from AyBruno February 26, 2026 04:55
@AyBruno AyBruno force-pushed the fix/30-posthog-singleton branch from c31eb85 to 603b026 Compare March 8, 2026 23:15

import { PostHog } from 'posthog-node';

let postHogClient: PostHog | null = null;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than keep the posHogClient in this mirror.middleware.ts file, I think it would be good future proofing to move it into its own file in the utils directory as a common module level singleton. This way, in the future as we implement features we have a dedicated place to reach out to posthog for feature flags.

Jake Bromberg and others added 2 commits March 9, 2026 22:57
A new PostHog client (with its own connection pool and flush interval)
was created for every request. Moved to a module-level lazy singleton.

Co-authored-by: Cursor <cursoragent@cursor.com>
Extracts getPostHogClient() into a dedicated module so it can be reused for feature flags and other PostHog features beyond the mirror middleware.
@jakebromberg jakebromberg force-pushed the fix/30-posthog-singleton branch from 603b026 to 5c50bec Compare March 10, 2026 06:29
@jakebromberg jakebromberg requested a review from AyBruno March 10, 2026 06:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants