FrontendPro

130Build a browser-side analytics delivery system with batching, sampling, offline queueing, and deduplication

hardAbout 75 minutesCodinganalyticsofflinesamplingbatching

Problem

At scale, analytics costs real money and real bandwidth. Build a delivery pipeline that sends fewer, better events:

createAnalyticsPipeline({ transport, storage, sampleRate = 1, random = Math.random, online = true, batchSize = 20, dedupeWindowMs = 1000, now = Date.now, retryDelay = 1000, createId = () => crypto.randomUUID() }) returns { ready, track(name, props, { id, critical }), flush(), setOnline(online), queueSize }.

  • Sampling per session: decide once whether this browser session is sampled (random() < sampleRate) and store the decision in storage under "analytics:sampled", so reloads keep it. Unsampled sessions drop ordinary events; events tracked with critical: true (errors, purchases) are always kept.
  • Deduplication: drop an event whose id was already tracked (id defaults to a new createId()), and drop an event with the same name and props as one tracked less than dedupeWindowMs ago (double clicks, re-renders).
  • Batching: events { id, name, props, ts } are queued; when online and the queue reaches batchSize, flush.
  • Offline queueing: the queue is saved in storage under "analytics:queue" after every change and loaded on start (ready resolves after loading), so nothing is lost across reloads or offline periods. setOnline(true) flushes.
  • Delivery: flush() sends batches of up to batchSize, oldest first, with await transport.send(batch). A successful batch is removed; a failure stops the flush, keeps the events and schedules a retry after retryDelay.

storage has getItem, setItem and removeItem.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

Deciding per event makes funnels meaningless (a sampled "add to cart" without its "checkout"). Decide once per session, store the decision, and always keep critical events so errors and revenue are never undercounted.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever