Your company's product decisions depend on analytics, but nobody trusts the numbers. Each of 20 teams calls a
different mix of Google Analytics, Segment, Amplitude and a home-grown endpoint. Event names are inconsistent
(AddToCart, add_to_cart, cart-add), properties change without notice, and an audit found email addresses in
event properties.
Design an analytics event pipeline and client SDK used by all web apps (and, later, mobile):
Expected volume: 15 million daily active users, around 2 billion events per day.
The brief's real problem is trust, not collection. Sending events is easy; making 2 billion events a day mean the same thing to every analyst is hard. Untrustworthy analytics usually comes from four causes:
The design therefore centres on a governed tracking plan that compiles into a typed SDK, plus a pipeline that validates every event against it. The SDK itself is the second half: small, reliable, consent-aware and boringly predictable.
track, page, identify, group/account context, automatic context (app, version, page,
locale, campaign parameters), batching, persistence, retries.Principles:
name: product_added_to_cart
version: 3
status: active # draft | active | deprecated
owner: team-cart
description: User added a product to the cart from any surface.
trigger: Fired after the add-to-cart API call succeeds, once per product added.
consent: analytics
properties:
product_id: { type: string, required: true }
quantity: { type: integer, minimum: 1, required: true }
price: { type: number, required: true, description: "Unit price as a decimal in the given currency" }
currency: { type: string, pattern: "^[A-Z]{3}$", required: true }
source_surface:
type: string
enum: [product_page, search_results, recommendations, quick_view]
required: true
pii: false
destinations: [warehouse, amplitude]
Conventions enforced by review and linting of the plan itself: object_action snake_case names in past tense, no
free-text properties without a reason, enums over open strings, currency as ISO 4217 code, explicit trigger text
(the most common source of analyst confusion is when an event fires). Each definition compiles to a JSON Schema
used for validation.
{
"batchId": "b_01HZX3...",
"sentAt": "2025-06-02T10:15:05.120Z",
"events": [
{
"eventId": "01HZX3F8Q4...",
"name": "product_added_to_cart",
"schemaVersion": 3,
"timestamp": "2025-06-02T10:15:03.004Z",
"anonymousId": "a_5d1c...",
"userId": "u_8f2a",
"sessionId": "s_77ab",
"consent": { "analytics": true, "marketing": false },
"context": {
"app": { "name": "storefront-web", "version": "2025.06.02-a1b2c3" },
"page": { "path": "/product/:id", "referrerHost": "www.google.com" },
"locale": "en-GB",
"campaign": { "source": "newsletter", "medium": "email" },
"flags": { "checkout.new-payment-sheet": "treatment" }
},
"properties": { "product_id": "p_123", "quantity": 1, "price": 24.99, "currency": "GBP", "source_surface": "search_results" }
}
]
}
eventId is a client-generated ULID or UUID v7: the deduplication key for at-least-once delivery.timestamp is the device time; the collector adds receivedAt, and downstream corrects skew using
receivedAt - (sentAt - timestamp), the standard approach for untrusted clocks.interface AnalyticsConfig {
writeKey: string;
endpoint: string; // first-party, e.g. https://www.acme.com/_e
app: { name: string; version: string };
consent: ConsentAdapter; // bridges to the CMP
flushIntervalMs?: number; // default 5000
maxBatchSize?: number; // default 50
maxQueueSize?: number; // default 1000, drop oldest beyond
debug?: boolean;
}
interface ConsentAdapter {
get(): { analytics: boolean; marketing: boolean } | 'unknown';
onChange(cb: (c: { analytics: boolean; marketing: boolean }) => void): () => void;
}
interface Analytics {
track<E extends EventName>(name: E, properties: EventProperties<E>): void;
page(properties?: { name?: string; category?: string }): void;
identify(userId: string, traits?: SafeTraits): void;
reset(): void; // on logout: new anonymousId, clear userId
flush(): Promise<void>;
}
EventName and EventProperties<E> are generated from the tracking plan, so:
analytics.track('product_added_to_cart', {
product_id: 'p_123', quantity: 1, price: 24.99, currency: 'GBP', source_surface: 'search_results',
}); // compiles
analytics.track('add_to_cart', { id: 1 }); // type error: unknown event
Generated wrappers can be even more explicit (track.productAddedToCart({...})), which tools like Avo and Segment
Protocols' Typewriter popularised.
<TrackImpression event="recommendation_viewed" properties={{ slot: 'pdp-bottom', count: 8 }}>
<Recommendations />
</TrackImpression>
Uses IntersectionObserver (50% visible for at least 1 s) and fires once per mount, standardising "viewed" semantics
that teams otherwise implement differently.
acme-analytics plan validate # lint the plan YAML
acme-analytics codegen --out src/analytics.generated.ts
acme-analytics diff --base main # human-readable changes for review
Plan changes live in a git repo; PRs require review from the data team (CODEOWNERS). Merging publishes schemas to the validator's schema registry before apps can ship code that uses them (the generated package is versioned).
localStorage or IndexedDB,
so a crash or navigation does not lose them. On next load, the SDK resends persisted events (dedupe handles any
duplicates).visibilitychange to hidden. Do not rely on
unload or beforeunload: they are unreliable on mobile and disable the back/forward cache.navigator.sendBeacon or fetch(url, { keepalive: true }); both have a body size budget
(about 64 KB shared across in-flight keepalive requests), so split large batches and prioritise newest events.Retry-After; drop after a maximum age (say 7 days) so
the queue cannot grow forever.Business-critical facts (order placed, subscription started, payment failed) should be emitted server-side from the system of record, which is complete and tamper-resistant. The client tracks behaviour that only the client sees (clicks, views, UI states). Sharing the same tracking plan and identity across both lets analysts join them. A good lead answer pushes revenue events to the server.
anonymousId: random ID in a first-party cookie set by the server (longer-lived than script-set cookies under
Safari ITP rules) with localStorage as backup.identify(userId) on login links anonymous and user IDs; the stitching is done in the warehouse (identity graph
table), not in the SDK, so rules can change and be reprocessed.reset() on logout prevents a shared device from merging two people.userId; use an opaque internal ID.userId/anonymousId; the warehouse supports deletion by ID, and the
router forwards deletion requests to destinations' APIs.At about 120k events/s peak, a stateless collector fleet behind a CDN or load balancer writes to a partitioned stream
(Kafka, Kinesis or Pub/Sub). The collector does minimal work: authenticate the write key, check size, add
receivedAt, write. Validation and enrichment happen asynchronously in stream processors, which can be scaled and
replayed independently. Warehouse loading uses micro-batches (Snowpipe, BigQuery Storage Write API or similar).
Deduplication by eventId happens in the warehouse model within a time window.
| Option | Notes |
|---|---|
| Segment (Twilio) | Mature SDKs, many destinations, Protocols for tracking plans; costs scale with tracked users and get significant at 15M DAU |
| RudderStack | Segment-compatible API, warehouse-first, open-source core, self-hostable |
| Snowplow | Schema-first (Iglu schemas), strong validation, self-hosted or managed; excellent data quality, more engineering effort |
| Amplitude, Mixpanel, PostHog | Analytics products with their own SDKs; great UIs but put raw data in their system first (PostHog can self-host) |
| Avo | Tracking plan management and typed codegen; pairs with any of the above |
| Build | A thin SDK and collector are feasible; validation, routing, identity and destination integrations are where the cost lies |
Recommendation: at this scale and with a data-trust problem, a warehouse-first, schema-first pipeline: Snowplow or RudderStack (managed or self-hosted) or a lean in-house collector, with an in-house facade SDK that generates typed tracking from our plan. Product tools like Amplitude are fed from the warehouse or router rather than directly from the page. Segment remains a reasonable buy if cost is acceptable and the team is small.
checkout_started fails the build.version and run both for a deprecation window.AddToCart, cart-add), pick canonical names,
map legacy names in the pipeline for continuity.How do you know you are losing events?
Compare client events against server-side ground truth (orders, sign-ups), compare event sequences (every
checkout_completed should have a checkout_started), and track sequence numbers per session to detect gaps.
A team needs an event today, but review takes a day.
Allow draft events in non-production environments without review, and fast-track additive changes. Production
requires the plan entry, which is a small YAML PR.
Should the SDK auto-capture all clicks? Autocapture gives quick coverage but noisy, unstable data tied to DOM structure. Use it, if at all, for exploratory analysis, and keep key metrics on explicit, planned events.
What about single-page app page views?
The SDK integrates with the router to emit page on route changes with templated paths and the previous route as
referrer, deduplicating replaceState updates that do not change the route template.
How do you handle bots?
Filter at the collector using known bot user agents and behavioural signals, and keep a is_suspected_bot flag
rather than dropping, so the rules can be tuned later.
Spotted a mistake or a rights concern? Report an issue