A deep dive into designing a production-grade analytics and error tracking SDK — from script injection and event batching to multi-tenant ingestion pipelines and GDPR compliance.
FrontendX EngineeringSystem Design Series #10
0. What Are We Building?
We are building an analytics and error tracking SDK that any company can embed into their product with a single npm install. Think Amplitude meets Sentry — a library that tracks custom events (button clicks, page views, conversions) and automatically captures JavaScript errors with full stack traces and breadcrumbs.
This sounds straightforward until you realize the SDK runs inside someone else's application. It must never crash the host, never block the main thread, and never lose data — even when the user is on a subway with spotty connectivity. On the server side, we need to ingest events from millions of concurrent clients while keeping each customer's data isolated. Questions like these show up in senior and staff-level interviews at Amplitude, Sentry, Datadog, and Stripe exactly because they touch SDK design, distributed systems, security, and developer experience all at once.
Key Insight
The hard part is not the event schema. It is authorization across thousands of tenants, making the SDK invisible to the host app's performance, defending against abuse, and handling the massive ingestion throughput when millions of end users fire events simultaneously.
1. Requirements & Scoping
An analytics SDK is not a REST API client wrapped in fancy packaging. It is a long-running background process that lives inside the host application, manages its own state, persists data to disk, and silently handles failures. Before we design, we scope what the SDK must do and what we explicitly leave out.
Cross-browser: Chrome, Firefox, Safari, Edge, mobile browsers
Privacy: opt-out, data masking, GDPR deletion API
Nice-to-Have (Out of Scope for Core Design)
Session replay — recording DOM mutations via rrweb for debugging.
Source map upload — translating minified stack traces back to readable code.
Sampling — sending a percentage of events in high-traffic environments.
Analytics query engine and dashboard UI — entirely separate system.
Tip
In an interview, scope by asking: "Is this a thin REST wrapper or a full telemetry SDK?" The answer determines the entire architecture — a thin wrapper just calls fetch(), an SDK needs a queue, retry, offline storage, error hooks, and a plugin pipeline.
2. Singleton vs Factory — SDK Instance Design
This is the design decision that trips up most engineers, because the right answer for an SDK is different from the right answer for a web app. The wrong choice causes problems that are invisible during development but painful in production.
Why the Singleton Breaks in Real Apps
A singleton guarantees one global instance. That is convenient for the developer — import it anywhere, call getInstance() — but it creates three problems that only surface at scale.
You cannot run two projects at once. A company with a main product and a white-label version needs two API keys. With a singleton, the second init() overwrites the first. You cannot write meaningful unit tests. Test A initializes the singleton, test B still sees that state — tests are not isolated. SSR leaks user identity. In a Node.js server, one singleton is shared across all HTTP requests. Calling identify() in one request leaks that identity into the next.
A factory creates a new instance every time. Each caller gets an independent object with its own queue, its own config, and its own timer. Two projects? Two instances. Testing? Local instance per test, no cleanup needed. SSR? Each HTTP request creates its own instance scoped to that request's lifetime.
The Module-Level Instance — What Most SDKs Actually Ship
In practice, most SDKs (Amplitude Browser SDK 2, Sentry, Mixpanel) export a pre-created instance that works like a singleton for 95% of users, alongside a createInstance() factory for power users. JavaScript modules are singletons by definition — the module is evaluated once per environment. A pre-init queue buffers events that arrive before init() is called, so code-split components that load early do not lose data.
The practical compromise: export a default module-level instance for convenience and a createAnalytics() factory for power users. This is exactly what Sentry does — Sentry.init() configures a default client, but you can also create isolated Hub instances for advanced use cases.
3. Architecture & Client-Side Design
An analytics SDK is not a REST API client. It is more like a long-running background process that lives inside the host application. It maintains in-memory state, persists data to disk, manages timers, and silently handles retries — all without the host app knowing any of this is happening.
The Three-Layer SDK Architecture
The SDK is built in three layers. Layer 1 is the public API surface — track(), identify(), flush(). These calls are synchronous and return immediately; the developer should never have to await an analytics call. Layer 2 is the event pipeline — a chain of plugins that enrich, filter, and transform events before they leave the device. Layer 3 is the transport layer — batching, serialization, compression, and the actual HTTP delivery.
The Event Pipeline
Developer calls track()
Synchronous call, returns immediately. No await, no .then().
Plugin Pipeline
Enrichment, filtering, transformation. Each plugin can modify or drop the event.
In-Memory Queue
Max 30 events or 1s timer. Flushes whichever comes first.
Persistent Storage
IndexedDB / localStorage for offline durability. Capped at 1000 events.
Transport
HTTP POST with JSON body. sendBeacon on page exit.
Ingestion Endpoint
Edge proxy → Kafka → ClickHouse for analytics queries.
Why the Queue Matters
Without a queue, every track() fires an individual HTTP request. For a product with 20 tracked interactions per minute per user and 500,000 DAU, that is an enormous number of tiny requests. Batching them into groups of 30 cuts the server-side request count by 30×. The SDK also switches to navigator.sendBeacon() when it detects visibilitychange — the browser's preferred mechanism for sending data at page exit.
Storage
localStorage
IndexedDB
API
Simple synchronous get/set
Async, promise-based API
Storage limit
~5MB per origin
Large — 50% of disk up to several GB
Thread blocking
Synchronous — blocks main thread
Asynchronous — does not block
Complexity
Low — just JSON stringify
Higher — need to manage DB lifecycle
SDK usage
Amplitude JS SDK (default)
Preferred for >5MB offline queues
Error Capture Design
Error tracking hooks into three browser mechanisms on initialization: window.onerror for uncaught JS errors, unhandledrejection for unhandled promise rejections, and optionally console.error for manual error logs. When an error fires, the SDK collects a full stack trace, a rolling log of up to 100 breadcrumbs (navigation, network requests, console calls from the last 30 seconds), user context, and the SDK release tag. This payload can be 30–50KB — much larger than a typical analytics event at ~200B.
Warning
The SDK must catch all its own exceptions internally. An uncaught error from the analytics SDK crashing the host app's checkout flow is one of the worst failures imaginable. Every try/catch in the SDK is an insurance policy against your own bugs.
4. Data Model & Event Schema
Every event that the SDK sends needs a consistent schema. We define two types: analytics events (small, high-volume) and error events (larger, lower-volume). Both share a common base but carry different payloads.
The Analytics Event Schema
Notice sentAt and time are separate. The time is when the event happened on device. sentAt is when it was transmitted. In offline scenarios these can be hours apart. The backend uses time for analysis and sentAt to detect data that is unreasonably old.
Error events extend the analytics base with exception details, breadcrumbs, and grouping hints. The release field and inApp flag on stack frames are critical for production debugging — they tell you whether an error is a regression in the latest deploy and which frames are your code versus third-party libraries.
The in-memory queue uses a two-phase structure: pending for events waiting to flush, and inFlight for the batch currently being sent. If the HTTP request fails, events move back from inFlight to the front of pending for retry. Only a successful 200 discards them.
The two-phase queue design guarantees that a network blip never silently swallows data. Events are never discarded until the server confirms receipt.
5. Interface Definition (API)
The SDK has two API surfaces: the public SDK API that developers call in their application code, and the ingestion HTTP API that the SDK uses to send events to the server. Both must be minimal — every method we add is a method that companies have to understand and test.
The Public SDK API
Seven methods. That is the entire surface area. Developers initialize once, then call track() and identify(). Everything else — batching, retries, offline queue, transport — is internal.
A single endpoint accepts batched events. The API key is sent as a header — not in the URL or body — and the Origin header is validated against the project's allowed domains list. The response includes a nextFlushRecommendedAt field for server-side backpressure: the server can tell the SDK to slow down without rejecting requests.
Plugins make the SDK flexible without bloating the core. An enrichment plugin adds context (device fingerprint, user agent). A filter plugin drops events (consent enforcement, sampling). A destination plugin routes events to a custom endpoint. Theexecute method returning null drops the event entirely.
Use the plugin system for consent management. Register a plugin that checks the user's opt-in status and returns null for all events until consent is given. This keeps the core SDK agnostic about privacy regulations while giving customers full control.
6. Authorization & Ingestion Pipeline
This is the section most engineers underestimate. Authorization for a multi-tenant SDK is qualitatively different from authorization for a user-facing API.
The DSN Model — Public Keys Are Not Secrets
In a user-facing API, the credential is a session token or JWT that lives in a cookie. In an SDK embedded in a web page, the credential is included in JavaScript that ships to every end user's browser. It can be viewed by anyone who opens DevTools. This means the credential cannot be a secret — it is a routing key that tells the ingestion server which project the event belongs to.
Sentry calls this a DSN (Data Source Name). Amplitude calls it an API key. Mixpanel calls it a project token. They all have the same property: visible in the page source, functionally write-only. The server validates that the key exists, maps it to a project, and routes the event to the right storage partition. No secret is needed because knowing the key lets you submit events but not read anyone else's data.
The allowedDomains field is a critical security feature. Because the DSN is visible in client-side JS, anyone can copy it and submit fake events. Allowed domains restrict which Origin header values the ingestion server will accept. The revokedAt field supports key rotation: if a key leaks, you revoke it without needing a new deployment.
End-to-End Authorization Flow
Developer initializes — analytics.init({ apiKey: 'pk_live_abc' }). The SDK parses the DSN and stores the public key and ingest host.
Event fires — the SDK serializes the event and sends it to the ingest endpoint with the API key in the X-API-Key header.
Edge proxy validates — a lightweight Rust proxy (like Sentry's Relay) checks the key against a Redis cache, validates the origin, and applies per-key rate limits.
Kafka decouples — valid events are written to Kafka topics. Kafka absorbs bursts and applies backpressure naturally.
Stream processors — Kafka consumers symbolicate stack traces, group similar errors, and stitch user identities.
ClickHouse stores — processed events land in ClickHouse, partitioned by (projectId, time) for fast analytical queries.
Key Insight
Once an event makes it into Kafka, recovery is straightforward. The critical path is getting it there. Sentry's September 2024 incident — where 62.4% of events were dropped in Asia during a Relay crash — proves that the edge proxy is the most brittle point in the pipeline.
7. Scaling, Rate Limiting & DDoS Protection
The hardest engineering challenge on the server side is not writing events fast enough — it is handling the case where one customer's viral moment threatens to degrade the platform for everyone else.
Noisy Neighbor Defense at Three Levels
At the edge proxy: Per-project key rate limits using a sliding window algorithm in Redis. If a key has a limit of 10,000 events per minute and exceeds it, the proxy returns HTTP 429. The sliding window prevents cliff-edge spikes at the top of each minute.
At the Kafka layer: High-traffic projects move to a dedicated Kafka cluster with more partitions. A monitoring system watches partition lag — the number of unconsumed messages — and auto-promotes noisy projects when lag exceeds 100,000.
At the ClickHouse layer: Per-tenant query quotas. Enterprise customers running complex funnel queries do not compete with free-tier customers for query resources.
DDoS Protection Layers
Layer
Mechanism
What it stops
CDN / IP reputation
Block known-malicious IPs, Tor exit nodes, cloud provider ranges
Distributed attacks that use many keys from one IP
Retry and Backoff in the SDK
The SDK's retry logic is as important as server-side rate limiting. A poorly designed retry can turn a brief server hiccup into a sustained load spike — every SDK retrying at the same time magnifies rather than spreads the load.
retry.tsTypeScript
function calculateRetryDelay(retryCount: number): number { const base = 1000; const maxDelay = 30000; const exponential = base * Math.pow(2, retryCount); const capped = Math.min(exponential, maxDelay); const jitter = capped * 0.2 * Math.random(); return capped + jitter;}// Retry sequence: ~1s, ~2s, ~4s, ~8s, ~16s, max 30s// With jitter: each SDK instance retries at a slightly different time
Warning
Never retry without jitter. If 10,000 SDKs all get a 429 at T=0 and retry at exactly T=2000ms, the second wave is just as bad as the original spike. Jitter spreads retries across a window the server can absorb.
Performance is the key consideration for an SDK that runs inside someone else's product. Every byte of bundle size and every millisecond of main thread work we add is a regression in someone else's application.
Bundle Size
Amplitude Browser SDK 2 is about 20KB gzipped. Sentry's full bundle (with session replay) is around 50KB. For comparison, React itself is about 42KB gzipped. You are asking customers to add roughly the equivalent of a React install for error tracking — every KB needs to justify itself. We reduce bundle size through tree-shakable ES module exports: a company that only uses track() should not pay the bundle cost of session replay.
Source Maps
Without source maps, production errors are nearly unreadable:at a.n (main.abc123.js:1:4892). With source maps: at handleFormSubmit (src/components/CheckoutForm.tsx:47:12). Maps are uploaded at deploy time through a CI pipeline, never served publicly. They are versioned by release tag so the symbolication service can translate errors from any deployed version.
Sampling
For analytics events, a 100% sample rate is usually desired. For performance tracing, 100% is prohibitively expensive. Sentry supports tracesSampleRate: 0.1 for 10% sampling. Error sampling is more nuanced: capture 100% of TypeErrors but only 5% of rate limit errors. The beforeSend hook handles this — returnnull to drop the event client-side, saving network cost and ingestion quota.
Session Replay
Session replay uses rrweb to record DOM mutations via MutationObserver. The initial snapshot captures the full DOM once; subsequent records are incremental mutations only. The CPU cost varies with DOM churn — negligible on simple pages, 3–5% on data-heavy dashboards. Enable it with sampling (replaysSessionSampleRate: 0.01) and optionally only on error (replaysOnErrorSampleRate: 1.0).
Deduplication
Network conditions mean the same batch may be sent twice. Each event carries an eventId (UUID generated client-side). The server stores these IDs in Redis with a 24-hour expiry. Duplicates are accepted (return 200) but dropped — a pattern Amplitude calls insertId deduplication.
Key Insight
The three biggest performance wins for an analytics SDK: (1) tree-shakable modular exports to minimize bundle size, (2) client-side sampling via beforeSend to control ingestion costs, and (3) eventId-based deduplication to handle at-least-once delivery without data inflation.
9. Privacy, Consent & Identity Resolution
GDPR in Europe, CCPA in California, and LGPD in Brazil all impose requirements on data collection. For a multi-tenant SDK, we are the data processor and our customers are the data controllers — they handle consent, but we must provide the tools that make compliance possible.
Opt-Out, Data Masking, and Residency
The SDK supports a global opt-out flag persisted in localStorage. When opted out, track() silently no-ops. An excludedProperties config drops sensitive fields like password before events leave the device. For EU data residency, the DSN encodes the region: https://pk_live_abc@eu.ingest.ourplatform.com routes to the EU cluster.
privacy.tsTypeScript
// Opt-out persists in localStorage across page reloadsanalytics.init({ apiKey: '...', defaultOptOut: true, excludedProperties: ['password', 'creditCard', 'ssn'],});// When user accepts cookie banneranalytics.optIn();// When user revokes consentanalytics.optOut();// Unsent events in the queue are discarded silently
Identity Resolution
A user visits your product anonymously, browses for 10 minutes, then creates an account. You want the pre-login behavior associated with the same user as the post-login behavior. Without identity resolution, you have two user records and funnel analyses break.
The SDK uses a two-phase identity model. During anonymous browsing, an auto-generated anonymousId is persisted in localStorage. When the user logs in and the app calls identify(), the SDK sends both IDs to the backend, which creates an alias entry. The analytics backend uses this alias table to retrospectively associate the anonymous session with the identified user at query time.
Rate-limit identify() calls per user per session. If a developer calls identify() on every page load, the backend receives thousands of redundant identity events. Memoize the last known user properties and skip the call if nothing changed.
10. Developer Experience
The best SDK is the one developers never think about after the initial setup. This means thoughtful defaults, a useful debug mode, type safety, and a clear testing story.
Debug Mode
During development, verbose logging is invaluable. The SDK should print every event, every flush, and every server response to the console when logLevel: 'verbose' is set. This turns a frustrating "why isn't my event showing up" debugging session into a 10-second check.
Type-Safe Tracking with Code Generation
Schema drift is the biggest long-term quality problem in analytics. An engineer renames product_id to productId, and six months of historical data become unqueryable. The solution is code generation — take a tracking plan and produce a type-safe SDK wrapper that enforces event schemas at compile time. This is what Amplitude's Ampli does, and it is dramatically more effective than documentation.
Testing Pattern
Because the factory pattern gives each test its own isolated instance, testing is straightforward. Inject a mock instance, call the method, assert it was called with the right arguments. No network, no global state, no module-level teardown.
CheckoutButton.test.tsxTypeScript
// Production codefunction CheckoutButton({ analytics }: { analytics: AnalyticsSDK }) { return ( <button onClick={() => { analytics.track('Checkout Started', { cartTotal: 99.99 }); navigate('/checkout'); }}> Proceed to Checkout </button> );}// Test — inject a mock, no globals, no networkconst mockAnalytics = { track: vi.fn() };render(<CheckoutButton analytics={mockAnalytics} />);fireEvent.click(screen.getByText('Proceed to Checkout'));expect(mockAnalytics.track) .toHaveBeenCalledWith('Checkout Started', { cartTotal: 99.99 });
Note
Bundle size regression tests deserve special emphasis. Sentry's CI pipeline fails if a code change increases the gzipped bundle size by more than 1KB. This is what keeps SDK bundles from silently doubling over two years of feature development.
11. Key Takeaways
If you remember only a few things from this article, make them these:
Use the factory pattern, not singleton
Singletons break SSR, testing, and multi-project setups. Factory gives isolation. Export a default instance for convenience, createInstance() for power users.
Batch events in a two-phase queue
pending → inFlight. Only discard on 200. Switch to sendBeacon on page exit. Persist to IndexedDB for offline durability.
Public keys are routing keys, not secrets
DSN/API keys are visible in DevTools. Use allowedDomains and per-key rate limits for security. Revoke leaked keys without redeploying.
Kafka decouples ingestion from processing
Edge proxy → Kafka → ClickHouse. Partition by projectId for ordering. Move noisy projects to dedicated clusters.
Export tree-shakable modules for bundle control
Separate entry points for analytics, error tracking, performance, session replay. Customers pay for only what they use.
Sampling and deduplication control cost
beforeSend to drop events client-side. tracesSampleRate for performance. eventId deduplication in Redis handles at-least-once delivery.