Skip to content

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

Open
jakebromberg wants to merge 1 commit intomainfrom
fix/30-posthog-singleton
Open

fix: use singleton PostHog client instead of per-request instantiation#186
jakebromberg wants to merge 1 commit 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

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>
@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
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.

1 participant