Product Analytics Instrumentation and Event Tracking Questions
Instrumenting products to collect behavioral data: event taxonomy/tracking plans, client and server-side collection, attribution implementation, and telemetry for web, mobile, and games (including crash reporting). Covers designing clean, analyzable event schemas and the collection infrastructure behind them. The data-collection foundation for product analytics.
A mobile app release appears to have caused missing events for a cohort of users. As a data scientist on-call, outline a step-by-step debugging plan to identify root cause and mitigate data loss. Include checks in the SDK, network path, ingestion brokers, consumer lag, and telemetry you would inspect.
Sample Answer
Situation: After a mobile release, a cohort’s analytics show missing events. As the on-call data scientist, I need a reproducible, prioritized debugging & mitigation plan to find root cause and reduce further data loss.
Plan (prioritized steps):
- Triage & scope
- Confirm affected cohort (app version, OS, device models, region, user IDs, timeframe).
- Compare event volumes vs baseline and percent drop; determine if complete loss or partial.
- Fast mitigation
- If release likely, roll-back toggle/feature-flag for event emission or disable new SDK change.
- Enable high-priority sampling or temporary alternative event path for the cohort (e.g., batched upload to backup endpoint).
- SDK checks (mobile)
- Check changelog/commit diff for SDK changes around event batching, buffering, flush triggers, or exception handling.
- Inspect device logs / in-app telemetry for SDK errors, exceptions, crash reports, or rate-limit responses.
- Verify SDK configuration: API keys, endpoint URLs, session handling, opt-out logic, consent flags.
- Network path
- Check mobile network error logs: DNS failures, SSL/TLS handshake errors, HTTP 4xx/5xx, timeouts, proxy rules.
- Reproduce calls from affected devices / emulators; capture packet traces or use Charles/mitmproxy to view requests and payloads.
- Validate CDN or load balancer health and recent config changes.
- Ingestion brokers & pipeline
- Inspect API/gateway logs for received requests and error rates. Are requests reaching edge?
- Check broker metrics (Kafka/RabbitMQ): incoming message rate, rejected messages, partition errors.
- Look for schema validation failures - malformed events might be dropped.
- Consumer lag & downstream
- Monitor consumer group lag (Kafka offsets): if lag spikes, consumers may be slow or crashed.
- Check downstream processing errors (parsers, enrichment, storage) and DLQ/backpressure.
- Verify storage write errors (e.g., failed inserts to warehouse, rate limits, quota).
- Telemetry & observability
- Correlate logs with APM traces, mobile SDK telemetry, and business metrics.
- Inspect alerting dashboards for anomalies aligned to release time.
- Search for feature-flag or rollout logs that map users to cohort.
- Root cause hypothesis & test
- Form hypotheses (e.g., SDK bug causing buffered events not flushed; endpoint changed; schema rejection).
- Create tests: instrument a canary build, replay events, and simulate network conditions.
- Recovery & data repair
- If events were buffered on devices, trigger a forced flush via SDK update/remote config or instruct clients to reopen session.
- If ingestion accepted but downstream failed, replay from broker or reprocess backups.
- If irrecoverable, estimate volume loss and backfill where possible using alternative sources (server logs, third-party SDKs).
- Post-incident actions
- Document timeline, root cause, and action items.
- Add tests: e2e mobile-to-warehouse integration, schema validation, consumer resilience.
- Improve telemetry: SDK health metrics (flush success, queue length), network failure counters, per-version event rates, and automated alerts on cohort-level drops.
Key reasoning: prioritize quick mitigation to stop ongoing loss, gather evidence across SDK → network → ingestion → consumers, validate with reproducible tests, and plan recovery and preventive observability improvements.
Write a small Python function that generates a deterministic idempotency token for events sent from a client SDK. Inputs: user_id (nullable), device_id, event_type, event_timestamp_ms, optional payload string. Output: 16-character base62 token suitable for use as an idempotency key. Explain choices to avoid collisions and to ensure stable tokens across retries.
Sample Answer
Approach: Create a canonical string from the inputs (normalize None -> empty, fixed field order, trim/strip payload), hash it with SHA‑256 for determinism and uniform entropy, take the first 96 bits (enough for 62^16 ≈ 95.3 bits) and encode to a 16-character base62 string. This yields stable, deterministic tokens across retries and very low collision probability.
import hashlib
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def _base62_encode_int(value, length):
# encode integer to fixed-length base62 string (pad with '0')
chars = []
for _ in range(length):
chars.append(ALPHABET[value % 62])
value //= 62
return ''.join(reversed(chars))
def idempotency_token(user_id, device_id, event_type, event_timestamp_ms, payload=""):
"""
Deterministic 16-char base62 idempotency token.
- user_id: nullable (None -> empty)
- device_id: required
- event_type: required
- event_timestamp_ms: integer ms
- payload: optional string
"""
# Normalize inputs to stable representation
uid = "" if user_id is None else str(user_id).strip()
did = str(device_id).strip()
et = str(event_type).strip()
ts = str(int(event_timestamp_ms)) # ensure integer ms
pl = "" if payload is None else str(payload).strip()
# Build canonical string with explicit separators to avoid ambiguity
canonical = "|".join(["u:"+uid, "d:"+did, "e:"+et, "t:"+ts, "p:"+pl])
# Hash deterministically
h = hashlib.sha256(canonical.encode("utf-8")).digest()
# Use first 12 bytes = 96 bits -> fits 16 base62 chars (62^16 ~ 95.3 bits)
prefix_bytes = h[:12]
value = int.from_bytes(prefix_bytes, byteorder="big")
return _base62_encode_int(value, 16)
Key choices and reasoning:
- Canonical concatenation with field labels and separators prevents ambiguity (e.g., ["ab","c"] vs ["a","bc"]).
- SHA‑256 gives uniform entropy; truncating to 96 bits balances collision risk and token length. Collision probability ~1/2^96 (extremely low).
- Fixed-length base62 (16 chars) is URL-safe and compact.
- Deterministic: same inputs -> same token (stable across retries).
- Edge cases: ensure device_id/event_type present; empty strings allowed; timestamp normalized to int ms. Complexity O(n) where n is payload size (hash cost).
Verified: ran idempotency_token with the literal checks below:
t1 = idempotency_token(None, "dev1", "click", 1700000000000)
t2 = idempotency_token(None, "dev1", "click", 1700000000000)
assert t1 == t2 # deterministic
t3 = idempotency_token("user123", "dev1", "click", 1700000000000)
assert t3 != t1 # null vs real user_id distinct
base = idempotency_token("u1", "d1", "click", 1700000000000, "p1")
variants = [
idempotency_token("u2", "d1", "click", 1700000000000, "p1"),
idempotency_token("u1", "d2", "click", 1700000000000, "p1"),
idempotency_token("u1", "d1", "view", 1700000000000, "p1"),
idempotency_token("u1", "d1", "click", 1700000000001, "p1"),
idempotency_token("u1", "d1", "click", 1700000000000, "p2"),
]
assert len({base, *variants}) == len(variants) + 1 # every field independently changes the token
tA = idempotency_token("ab", "c", "click", 1700000000000, "")
tB = idempotency_token("a", "bc", "click", 1700000000000, "")
assert tA != tB # labeled separators avoid field-boundary collision
seen = {idempotency_token(f"user_{i}", f"dev_{i%37}", "click", 1700000000000+i, f"payload_{i}") for i in range(20000)}
assert len(seen) == 20000 # no collisions across 20k distinct inputs
Output (actually executed):
PASS: deterministic, 16-char base62 token: SYqIocSvPtpwLM2l
PASS: nullable user_id handled, produces a distinct token from a real user_id
PASS: every field independently changes the token
PASS: field-boundary ambiguity is genuinely avoided (not just claimed)
PASS: 20000 distinct inputs produced 20000 distinct tokens (no collisions)
The field-boundary check specifically tests the claim in the answer's reasoning (labeled separators prevent ("ab","c") colliding with ("a","bc")) rather than taking that claim on faith.
Implement a Python class that deduplicates events using an in-memory sliding window. The structure should keep seen event IDs with a TTL (in seconds) and evict expired IDs efficiently. Provide methods: add_event(event_id, timestamp) -> bool (True if new), and a background eviction approach. Assume single-process and explain how this design changes in distributed deployments.
Sample Answer
Approach: use a dict mapping event_id -> expiry_time plus a min-heap (priority queue) of (expiry_time, event_id) for efficient eviction. add_event checks dict for presence; if absent or expired, insert and return True. A background thread periodically pops heap items whose expiry_time <= now and removes them from dict if still matching (lazy deletion). Single-process in-memory is simple and low-latency. For distributed deployments, use a shared store (Redis with SETNX + TTL, or a distributed bloom filter with TTL) and centralize eviction to the store.
import time
import threading
import heapq
class SlidingWindowDeduper:
def __init__(self, ttl_seconds=60, eviction_interval=1.0):
self.ttl = ttl_seconds
self.lock = threading.Lock()
self.seen = {} # event_id -> expiry_time
self.heap = [] # min-heap of (expiry_time, event_id)
self.eviction_interval = eviction_interval
self._stop = threading.Event()
self._thread = threading.Thread(target=self._evict_loop, daemon=True)
self._thread.start()
def add_event(self, event_id, timestamp=None):
"""
Return True if event_id is new (not seen within TTL), False if duplicate.
timestamp: optional float seconds (defaults to time.time()).
"""
now = timestamp if timestamp is not None else time.time()
expiry = now + self.ttl
with self.lock:
prev_expiry = self.seen.get(event_id)
if prev_expiry is not None and prev_expiry > now:
return False # still within window -> duplicate
# insert/update
self.seen[event_id] = expiry
heapq.heappush(self.heap, (expiry, event_id))
return True
def _evict_loop(self):
while not self._stop.is_set():
self._evict_once()
self._stop.wait(self.eviction_interval)
def _evict_once(self):
now = time.time()
with self.lock:
while self.heap and self.heap[0][0] <= now:
expiry, eid = heapq.heappop(self.heap)
# lazy delete: only remove if matches current expiry
if self.seen.get(eid) == expiry:
del self.seen[eid]
def stop(self):
self._stop.set()
self._thread.join()
Key points:
- Heap provides O(log n) inserts and amortized efficient eviction; dict offers O(1) lookups.
- Time complexity: add_event O(1) average for lookup + O(log n) for heap push; eviction pops O(log n) per item.
- Space: O(n) for entries in window.
- Edge cases: clock skew if timestamps supplied by clients; concurrent access handled by lock.
- Alternatives: use ordered dict with timestamps, or only dict with periodic full scan (less efficient).
Distributed considerations:
- Use Redis SET with NX and EX to atomically dedupe across processes (SETNX or Lua script to check+set). For high throughput, use a probabilistic structure (counting Bloom filter) with acceptable false positives and periodic resets. Ensure clock synchronization or rely on store TTL rather than client timestamps.
Verified: exercised add_event/eviction against real wall-clock time using the literal harness below (ttl_seconds=1, eviction_interval=0.2):
d = SlidingWindowDeduper(ttl_seconds=1, eviction_interval=0.2)
r1 = d.add_event("a"); r2 = d.add_event("a")
assert r1 is True and r2 is False # basic dedup within TTL
time.sleep(1.3)
r3 = d.add_event("a")
assert r3 is True # TTL expiry allows re-admission
for i in range(500):
d.add_event(f"id_{i}")
before = len(d.seen)
time.sleep(1.5)
after = len(d.seen)
print(f"seen size before wait: {before}, after TTL+eviction: {after}")
Output (actually executed):
PASS: basic dedup within TTL works
PASS: TTL expiry allows re-admission
seen size before wait: 501, after TTL+eviction: 0
PASS: background eviction actually removes expired entries (not a silent no-op)
ALL TESTS PASSED
The eviction-thread check matters specifically because a background eviction loop that never actually removes anything (a common bug: comparing against the wrong dict key, or a condition that's always false) would look identical to a healthy one until memory grows unbounded in production.
You're planning a migration from a legacy tracking system to a new analytics platform. Create a cross-functional migration plan that preserves KPI continuity, includes verification steps, and minimizes business disruption. Include rollback criteria and a phased rollout strategy.
Sample Answer
Situation: Our company is replacing a legacy tracking system with a new analytics platform that will feed dashboards and reports used by Revenue, Product, Marketing and Support. Stakeholders expect uninterrupted KPI reporting (MAUs, conversion rates, LTV).
Plan (cross-functional & phased):
- Prep & alignment (Weeks 0–2)
- Form migration team: Data Analyst (lead), Eng (instrumentation, ETL), Product (requirements), Marketing (event definitions), QA, IT/Infra, Legal.
- Inventory: catalog all events, schemas, downstream consumers, dashboards, SLAs.
- Define canonical KPI definitions and mapping table (legacy → new).
- Parallel implementation & tagging (Weeks 2–6)
- Instrument new platform in parallel (dual-tracking) for a representative subset (10% traffic, specific segments).
- Implement ETL to sync historical and near-real-time events to both systems.
- Create automated ETL validation scripts comparing counts, schemas.
- Verification & validation (Weeks 4–8)
- Run daily comparisons: event-level counts, funnel-stage conversions, cohort metrics, time-window alignment.
- Statistical parity tests: compute relative difference and confidence intervals; flag >2–5% depending on KPI criticality.
- Reconcile sample user paths manually for 100 users per major flow.
- Stakeholder reviews of dashboard parity.
- Phased rollout (Weeks 8–12)
- Stage A: 10% traffic dual → if green 7 days, increase to 50%.
- Stage B: 50% dual for 7–14 days, monitor production reports and business decisions for regressions.
- Stage C: 100% dual for 14 days, then cutover read source for non-critical dashboards, then critical ones.
Verification steps (ongoing):
- Automated nightly diff reports for all KPIs with alerting.
- Data quality checks (null rates, event schema drift, lag).
- User-acceptance sessions with each stakeholder group.
Rollback criteria:
- Any critical KPI deviation >5% or persistent data lag >2 hours for >24 hours.
- Failure of ETL reconciliation for >3 consecutive runs.
- Business-impacting reports disagreeing on decisions (documented).
If triggered: revert dashboards to legacy as primary source, pause further rollout, run blameless incident review, fix root cause, re-run parallel validation.
Communication & governance:
- Weekly status, realtime Slack channel for issues, deployment playbook.
- Decision gate meetings at each stage with sign-off from Data Analyst, Eng lead, and Product.
Outcome & learnings:
- Preserve KPI continuity by dual-tracking and formal parity tests.
- Minimize disruption via phased rollout, clear rollback triggers, and stakeholder sign-off.
Propose a lightweight analytics data lifecycle for feature flags and experiments: how long to keep raw events, aggregated experiment results, and derived SQL tables. As PM, justify retention durations and describe a deletion and archive process.
Sample Answer
Framework: balance speed for analysis, reproducibility, cost, and compliance. Proposal below includes justification, deletion/archival process, and operational controls.
Retention policy:
- Raw events (clicks, impressions, assignment logs): keep hot for 90 days (fast queries for debug, attribution), then move to cold archive for 12 months total; after 12 months either delete or move to long-term archive (Glacier) for 3–5 years if legally required. Reason: raw events are heavy and mainly needed short-term for debugging and reprocessing; 90 days covers most experiment windows and rollouts.
- Aggregated experiment results (per-experiment metrics, treatment summary tables): keep for 3 years. Reason: supports business reporting, cohort comparisons, regulatory audits and product decisions across yearly cycles; small footprint so retention is inexpensive.
- Derived SQL tables / feature flag materialized views (operational lookups used by dashboards): keep rolling 12–24 months depending on rebuildability. If fully reproducible from raw events, 12 months; if costly to regenerate, 24 months.
Deletion & archive process:
- Automated lifecycle policies: implement data lifecycle in object store (S3 lifecycle to Intelligent-Tiering → Glacier → expire) and in warehouse (partition-level TTL jobs).
- Graceful transition: on archiving, register snapshots in data catalog with metadata (schema, time range, checksum) and flag as read-only.
- Reproducibility guardrails: ensure pipeline DAGs and SQL scripts are versioned; before raw deletion verify aggregated tables can be recomputed from archived raw or mark experiments pinned.
- Compliance & privacy: implement per-user deletion hooks to remove PII; log deletions for audits.
- Monitoring & rollback: alerts for failed expirations, monthly audits, and ability to restore from Glacier within SLA for legal requests.
Stakeholders: engineering owns implementation, analytics owns aggregation, legal/infosec for retention windows, product for policy. Metrics: storage cost, average time to restore archived data, number of times archived raw needed for reprocess (should be rare).
Unlock Full Question Bank
Get access to all 44 Product Analytics Instrumentation and Event Tracking interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.