-
Notifications
You must be signed in to change notification settings - Fork 392
feat(shared): Add in-memory telemetry throttling for non-browsers #6842
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(shared): Add in-memory telemetry throttling for non-browsers #6842
Conversation
🦋 Changeset detectedLatest commit: 6f585b6 The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
WalkthroughAdds an in-memory throttling path to TelemetryEventThrottler for environments without Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant T as TelemetryEventThrottler
participant LS as localStorage (browser)
participant MC as In-Memory Cache (non-browser)
Client->>T: isEventThrottled(payload)
alt Browser (localStorage available)
T->>LS: get(key)
LS-->>T: timestamp or null
T->>T: compare timestamp to TTL
T-->>Client: true / false
note right of LS #eef2ff: Browser/localStorage path unchanged
else Non-browser (no localStorage)
T->>MC: get(key)
MC-->>T: timestamp or null
T->>T: compare timestamp to TTL
T->>MC: evict if size > 10000
T-->>Client: true / false
note right of MC #eef9ee: New in-memory throttling path
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests
Comment |
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (4)
packages/shared/src/telemetry/throttler.ts (2)
15-15
: Initialize memory cache eagerly and make it readonly.Removes null checks and prevents accidental reassignment.
Apply this diff:
- #memoryCache: Map<string, TtlInMilliseconds> | null = null; + readonly #memoryCache: Map<string, TtlInMilliseconds> = new Map();And remove the lazy init in the in‑memory method (see below).
47-72
: Unify TTL semantics and extract a named limit; tighten max-size check.
- Align TTL behavior with the localStorage path (or update the localStorage path to match this one). Currently, in-memory allows immediately after TTL; localStorage deletes then returns throttled for that call. Prefer consistent “allow and refresh” on expiry.
- Replace the magic number 10000 with a named constant.
- Use a “>=” check so the cache never grows beyond the limit, and clear before inserting.
- Remove lazy init if adopting the readonly initialization.
Apply this diff to the in‑memory method:
- #isEventThrottledInMemory(payload: TelemetryEvent): boolean { - if (!this.#memoryCache) { - this.#memoryCache = new Map(); - } - - const now = Date.now(); - const key = this.#generateKey(payload); - - // Defensive: clear cache if it gets too large to prevent memory issues - if (this.#memoryCache.size > 10000) { - this.#memoryCache.clear(); - } - - const lastSeen = this.#memoryCache.get(key); - if (!lastSeen || now - lastSeen > this.#cacheTtl) { - this.#memoryCache.set(key, now); - return false; // Not throttled - allow the event - } - - return true; // Event is throttled - } + #isEventThrottledInMemory(payload: TelemetryEvent): boolean { + const now = Date.now(); + const key = this.#generateKey(payload); + + // Defensive: clear cache if it reaches the max size to prevent memory issues + if (this.#memoryCache.size >= MEMORY_CACHE_MAX_SIZE) { + this.#memoryCache.clear(); + } + + const lastSeen = this.#memoryCache.get(key); + if (!lastSeen || now - lastSeen > this.#cacheTtl) { + this.#memoryCache.set(key, now); + return false; // Not throttled - allow the event + } + + return true; // Event is throttled + }Add the named constant near the TTL:
// just below DEFAULT_CACHE_TTL_MS const MEMORY_CACHE_MAX_SIZE = 10_000;For consistency, consider updating the localStorage path to “allow and refresh” on expiry:
// Replace the invalidate+return branch in isEventThrottled() with: const isExpired = typeof entry === 'number' && now - entry > this.#cacheTtl; if (isExpired) { const updatedCache = { ...this.#cache, [key]: now, }; localStorage.setItem(this.#storageKey, JSON.stringify(updatedCache)); return false; // allow after TTL and refresh timestamp }packages/shared/src/__tests__/telemetry.test.ts (2)
396-401
: Strengthen environment mocking for non‑browser.Spying on window’s getter often works in jsdom, but it’s brittle. Prefer explicitly unsetting globalThis.window within the test scope (and restoring it) to avoid false positives in env detection.
Example:
const realWindow = globalThis.window; Object.defineProperty(globalThis, 'window', { value: undefined, configurable: true }); try { // run test } finally { Object.defineProperty(globalThis, 'window', { value: realWindow, configurable: true }); }Also consider asserting that Storage methods aren’t touched (e.g., spy on Storage.prototype.getItem).
457-475
: Make the cache‑limit test more deterministic.
- Set maxBufferSize: 1 to avoid depending on timers for flush.
- Assert that a sentinel event after exceeding the limit is delivered (e.g., inspect the last fetch payload) to prove the clear‑then‑allow behavior, instead of a generic “toHaveBeenCalled”.
Example pattern:
const collector = new TelemetryCollector({ publishableKey: TEST_PK, maxBufferSize: 1 }); // ... fill > 10_000 unique keys ... collector.record({ event: 'TEST_EVENT', payload: { id: 'SENTINEL' } }); jest.runAllTimers(); const lastCall = fetchSpy.mock.calls.at(-1); expect(JSON.parse(lastCall[1].body).events).toEqual( expect.arrayContaining([expect.objectContaining({ payload: { id: 'SENTINEL' } })]), );
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/shared/src/__tests__/telemetry.test.ts
(1 hunks)packages/shared/src/telemetry/throttler.ts
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/shared/src/telemetry/throttler.ts
packages/shared/src/__tests__/telemetry.test.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/shared/src/telemetry/throttler.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/telemetry/throttler.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/shared/src/telemetry/throttler.ts
packages/shared/src/__tests__/telemetry.test.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertions
for literal types:as const
Usesatisfies
operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/shared/src/telemetry/throttler.ts
packages/shared/src/__tests__/telemetry.test.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/shared/src/telemetry/throttler.ts
packages/shared/src/__tests__/telemetry.test.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/shared/src/__tests__/telemetry.test.ts
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}
: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/shared/src/__tests__/telemetry.test.ts
🧬 Code graph analysis (2)
packages/shared/src/telemetry/throttler.ts (1)
packages/types/src/telemetry.ts (1)
TelemetryEvent
(8-35)
packages/shared/src/__tests__/telemetry.test.ts (2)
packages/shared/src/telemetry/collector.ts (3)
TelemetryCollector
(102-450)event
(364-376)event
(414-427)packages/shared/src/telemetry/throttler.ts (2)
event
(77-93)payload
(51-71)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/shared/src/telemetry/throttler.ts (2)
9-11
: Good clarification in docs for non-browser fallback.Accurately documents the React Native/non‑browser path.
19-21
: Fallback routing LGTM.Gracefully switches to in‑memory throttling when not a valid browser.
packages/shared/src/__tests__/telemetry.test.ts (2)
402-424
: LGTM: baseline in‑memory throttling behavior is covered.Validates allow→throttle→allow(different event).
426-455
: LGTM: TTL advancement covered.Confirms eligibility after TTL with memory cache.
The latest updates on your projects. Learn more about Vercel for GitHub.
|
f105a00
to
6f585b6
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
.changeset/wet-mails-yawn.md (1)
5-5
: Make the summary more explicit (RN context, TTL, cap) — optional.Current line is fine, but a slightly richer note will produce clearer release notes.
Apply one of the following diffs:
-Update telemetry throttling to work in native environments +Fix telemetry throttling in native environments (e.g., React Native) by adding an in‑memory fallback with a 24h TTL and a 10k‑entry cap; browser behavior unchanged.Optional style tweak to align with common repo conventions (no behavior change):
-'@clerk/shared': patch +"@clerk/shared": patch
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
.changeset/wet-mails-yawn.md
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/wet-mails-yawn.md
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
.changeset/wet-mails-yawn.md (2)
1-3
: Changeset format and version bump look good for a bugfix.Frontmatter parses correctly and a patch bump for
@clerk/shared
matches the scope of the change.
1-5
: No action required: @clerk/shared package entry verified
Description
Problem
React Native SDKs were bypassing client-side throttling because
localStorage
doesn't exist, causing massive event volumes (335K+ METHOD_CALLED events per instance per day vs 5-25 for web).Solution
Added in-memory fallback throttling for non-browser environments:
TelemetryEventThrottler
: Added#memoryCache
Map as fallback whenwindow
is undefinedTesting
Expected Impact
Reduces React Native telemetry events by 99%+ during app sessions, bringing them in line with web SDK volumes while maintaining dev-only telemetry
functionality.
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Tests