Skip to content

Conversation

mwickett
Copy link
Member

@mwickett mwickett commented Sep 23, 2025

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 when window is undefined
  • Memory safety: 10,000 entry limit with automatic cache clearing to prevent memory issues
  • Same behavior: Identical 24-hour TTL and throttling logic as localStorage version
  • Zero impact: Browser behavior completely unchanged

Testing

  • Added comprehensive test suite for React Native throttling scenarios
  • Verified TTL expiration works correctly in memory
  • Confirmed memory safety with cache size limits
  • All existing tests pass

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.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • In-memory telemetry throttling for non-browser environments (e.g., React Native) to maintain consistent rate-limiting when persistent storage isn’t available.
    • Cache-size safeguard to prevent unbounded memory growth by clearing the cache if it becomes very large.
  • Tests

    • Added tests covering in-memory throttling: first-pass vs repeat events, TTL expiry, distinct event handling, and cache-size limits.

Copy link

changeset-bot bot commented Sep 23, 2025

🦋 Changeset detected

Latest commit: 6f585b6

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 19 packages
Name Type
@clerk/shared Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/chrome-extension Patch
@clerk/clerk-js Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/clerk-expo Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/vue Patch

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

Copy link
Contributor

coderabbitai bot commented Sep 23, 2025

Walkthrough

Adds an in-memory throttling path to TelemetryEventThrottler for environments without localStorage (e.g., React Native) and expands tests to cover in-memory behavior: duplicate suppression, TTL expiry, and cache-size eviction. No public API changes; browser/localStorage logic remains unchanged.

Changes

Cohort / File(s) Summary
Throttling logic (non-browser fallback)
packages/shared/src/telemetry/throttler.ts
Adds private #memoryCache and #isEventThrottledInMemory(...); isEventThrottled delegates to memory when localStorage is unavailable. Implements TTL checks and a cache-size guard (~10,000 entries). No public signature changes.
Tests: in-memory throttling (React Native-like)
packages/shared/src/__tests__/telemetry.test.ts
Adds tests exercising the in-memory path: first event allowed, identical events throttled, different events allowed, TTL expiry via fake timers, and cache eviction when size limit exceeded. Duplicate suite appears to reinforce coverage.
Release metadata
.changeset/wet-mails-yawn.md
Adds a patch changeset for @clerk/shared describing the native-environment throttling update.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I thump my paws in tidy glee,
When browsers sleep, my cache runs free.
I hush repeats with TTL light,
Evict old crumbs to keep things tight.
Small hops, then signals take to flight. 🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly conveys the primary change, namely adding an in-memory telemetry throttling mechanism for non-browser environments, and uses a clear conventional commit format without extraneous details.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch mwickett/grow-774-fix-telemetry-throttling-for-mobile-sdks

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

pkg-pr-new bot commented Sep 23, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6842

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6842

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6842

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6842

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6842

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6842

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6842

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6842

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6842

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6842

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6842

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6842

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6842

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6842

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6842

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6842

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6842

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6842

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6842

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6842

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6842

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6842

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6842

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6842

commit: 6f585b6

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 98fe792 and 90e1043.

📒 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
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly 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
Use const assertions for literal types: as const
Use satisfies 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 ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly 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.

@mwickett mwickett changed the title feat: add in-memory telemetry throttling for non-browsers feat(shared): Add in-memory telemetry throttling for non-browsers Sep 23, 2025
Copy link

vercel bot commented Sep 23, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Sep 30, 2025 8:12am

@nikosdouvlis nikosdouvlis force-pushed the mwickett/grow-774-fix-telemetry-throttling-for-mobile-sdks branch from f105a00 to 6f585b6 Compare September 30, 2025 08:11
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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.

📥 Commits

Reviewing files that changed from the base of the PR and between f105a00 and 6f585b6.

📒 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

@mwickett mwickett requested review from nikosdouvlis and removed request for nikosdouvlis September 30, 2025 15:26
@mwickett mwickett merged commit 2c0128b into main Oct 1, 2025
43 checks passed
@mwickett mwickett deleted the mwickett/grow-774-fix-telemetry-throttling-for-mobile-sdks branch October 1, 2025 11:39
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.

3 participants