Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Backend Development
9 min read

E-commerce Tracking System at 100k QPS: Zero Loss, No Duplicates, Sub-second PV/UV

This article details the end-to-end design of a high-throughput e-commerce tracking system handling 100k QPS, covering Vue3 SDK batching, Java backend with Kafka buffering, ClickHouse storage, HyperLogLog for UV, and Lambda architecture for real-time and offline PV/UV accuracy, with 15 production pitfalls and solutions.

Overview

The article presents a production-grade tracking (埋点) system for e-commerce product pages that must handle 100,000+ QPS during flash sales while guaranteeing no data loss, no duplication, non-blocking reporting, and accurate PV/UV metrics. The core contradiction: frontend events are "fast and fragmented" while network send and database writes have cost and limits. The system is defined as a "high-throughput, log-type pipeline tolerating minimal loss but zero duplication, with strict metric definitions" — not a transactional system.

Architecture

The pipeline consists of five layers: Collection → Reporting → Receive Buffer → Computation → Storage/Application , decoupled by Kafka to absorb traffic spikes. Data flow: frontend batches 10 events or flushes every 3 seconds → backend receives, validates, deduplicates via Redis SETNX, writes to Kafka immediately → consumers batch 1,000 events for ClickHouse bulk insert and update Redis HyperLogLog for real-time PV/UV.

Event Model Design

A standardized event schema is defined upfront to avoid dirty data. Core fields include eventId (UUID, global idempotency key), appKey, eventType (page_view/click/exposure/custom), eventName, pageCode, userId, deviceId, sessionId, clientTs, serverTs, and props (JSON extensions). Two critical fields: eventId for end-to-end idempotency across retries, Kafka redelivery, and offline补发; serverTs as the sole time authority because client clocks are unreliable.

Frontend SDK (Vue3)

Key Decisions

Binding : Avoid per-element addEventListener; adopt single global event delegation + data-track-* attributes → zero cost for virtual scroll, dynamic elements.

Exposure detection : Avoid scroll + getBoundingClientRect; adopt IntersectionObserver → no main-thread blocking.

Report timing : Avoid fire per click; adopt batch 10 events / 3s dual threshold → 90% request reduction.

Page unload : Avoid unload + fetch; adopt sendBeacon + visibilitychange → weak network, page close no loss.

Collection: Declarative + Programmatic

Declarative via v-track directive (covers 90% cases) and programmatic tracker.track() for complex interactions. Click capture uses global delegation on the capture phase to avoid @click.stop interference. Exposure requires ≥50% visibility for ≥800ms to prevent scroll-through inflation.

// Global capture listener
document.addEventListener('click', (e) => {
  const el = e.target.closest('[data-track-event]');
  if (!el) return;
  tracker.track(el.dataset.trackEvent, {
    eventType: 'click',
    itemId: el.dataset.trackItem,
    props: { x: e.clientX, y: e.clientY, text: el.innerText.slice(0,50) }
  });
}, { capture: true, passive: true });

Batching & Consistent Sampling

In-memory queue with dual thresholds (count ≥10 or time ≥3s). Sampling uses consistent hashing on deviceId (not per-event Math.random) to keep UV stable and A/B experiment data clean.

private sampled(): boolean {
  if ((this.opts.sampleRate ?? 1) >= 1) return true;
  return this.hash(this.deviceId) < (this.opts.sampleRate ?? 1);
}
private hash(str: string): number {
  let h = 0;
  for (let i = 0; i < str.length; i++) h = (h * 31 + str.charCodeAt(i)) | 0;
  return Math.abs(h % 10000) / 10000;
}

Reporting Channel: Fallback Chain

Not just sendBeacon. Regular batches use fetch(keepalive:true) (has Promise, can detect failure); page unload uses sendBeacon (browser guarantees dispatch). Two pitfalls: sendBeacon defaults to text/plain (must wrap with Blob + explicit type); cross-origin application/json triggers CORS preflight (use text/plain and parse on backend). fetch keepalive has ~64KB size limit.

Reliability: Page Close & Weak Network

Listen to visibilitychange → hidden (most reliable on mobile), pagehide (better than unload), beforeunload as fallback. Failed batches persist to localStorage (or IndexedDB), retry with exponential backoff + jitter (1s, 2s, 4s… + random offset) to avoid thundering herd. Queue capacity capped at 500 events; overflow drops oldest.

Complete SDK Core (TypeScript)

The article provides a full Tracker class with queue management, lifecycle binding, persistence, sampling, hashing, and flush logic. It also shows Vue3 plugin registration ( createTrackPlugin) and usage in components via v-track directive and injected tracker instance.

Backend (Java/Spring Boot)

Receiver Layer: Return Immediately, Never Block

Endpoint /api/track/collect accepts text/plain and application/json. Steps: appKey validation → IP rate limit (200 req/s) → parse batch (max 100 events) → validate eventType whitelist & required fields → discard if clientTs deviates >10min from serverTs → ensure eventId (generate UUID if missing) → idempotency via Redis SETNX with 36h TTL → enrich with serverTs, IP, User-Agent → async send to Kafka → return 200/204 immediately (RT <10ms).

Boolean first = redis.opsForValue().setIfAbsent("dup:" + e.getEventId(), "1", Duration.ofHours(36));
if (!Boolean.TRUE.equals(first)) continue; // duplicate dropped
kafka.send(TOPIC, e.getEventId(), JsonUtils.toJson(e));

Buffer Layer: Bounded Queue + Backpressure

Uses ArrayBlockingQueue(50000); on offer() failure, increment dropped counter and alert. Principle: "Drop new rather than crash DB". For higher throughput, replace with Disruptor ring buffer. Processing runs on isolated thread pool ( trackExecutor).

Why Kafka?

Three roles: peak shaving (buffer spikes), decoupling (downstream jitter doesn't backpressure receiver), multi-consumer (real-time UV, offline archive, risk control). Partition key trade-offs: deviceId (session order), userId (user sequence), eventId (downstream keyBy dedup), or no key (max throughput, no order). Author recommends deviceId with two-phase aggregation to mitigate hot partitions. Producer config: acks=1, batch.size=65536, linger.ms=20, compression=lz4, enable.idempotence=true.

Consumer Layer: Batch Consume + Idempotent Write

@KafkaListener

with batchFactory, max.poll.records=500, fetch.min.bytes=1MB, fetch.max.wait.ms=500. Manual offset commit. Processing: parse → filter bots (UA keywords) → filter events older than 7 days → bulk insert to ClickHouse (batch ≥1000) → update real-time PV/UV in Redis (PV: INCR; UV: HyperLogLog add). Deduplication in consumer uses Redis Lua script for atomic SETNX+EXPIRE.

private static final DefaultRedisScript<Long> DEDUP = new DefaultRedisScript<(
  "if redis.call('SETNX', KEYS[1], '1') == 1 then " +
  "  redis.call('EXPIRE', KEYS[1], 86400) return 1 " +
  "else return 0 end", Long.class);

Minimal Viable: Spring Boot + MySQL

For small teams: bounded queue → background thread batches → MySQL INSERT IGNORE on event_id primary key. Requires JDBC rewriteBatchedStatements=true. Not suitable for large scale; migrate to ClickHouse/Doris/StarRocks when volume grows.

ClickHouse Schema & Optimization

Table track_events uses ReplacingMergeTree(ingest_time) partitioned by month ( toYYYYMM(event_date)), ordered by (page_code, event_type, event_time, event_id). Key techniques: LowCardinality for page_code/event_name (dictionary encoding), Enum8 for event_type, props as JSON string (or Map), TTL 90 days. Materialized view pre-aggregates PV/UV per minute using countState() and uniqState() (HyperLogLog state) enabling millisecond queries via sumMerge/uniqMerge.

CREATE MATERIALIZED VIEW mv_pv_uv_1m
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(dt)
ORDER BY (dt, page_code, minute)
AS SELECT
  toStartOfMinute(event_time) AS minute,
  toDate(event_time) AS dt,
  page_code,
  countState() AS pv_state,
  uniqState(if(user_id != '', concat('u:', user_id), concat('d:', device_id))) AS uv_state
FROM mall_track.track_events
GROUP BY minute, dt, page_code;

PV/UV Calculation

PV: Simple Counter

Real-time: Redis INCR per (page, time window). Offline: ClickHouse count() after eventId deduplication.

UV: HyperLogLog Standard

Redis Set for 30M UV ≈ 720MB; HyperLogLog fixed ~12KB with 0.81% error. Code uses PFADD / PFCOUNT / PFMERGE. Comparison of trade-offs: Set (exact, high mem), HLL (approx, tiny mem), RoaringBitmap (exact, compressed), ClickHouse uniqExact (exact, heavy), uniq (approx, fast). Rule: dashboards use HLL; financial reconciliation uses Bitmap/ uniqExact.

Lambda Architecture: Real-time + Offline

Real-time: Flink + Redis HLL (approx, second-level). Offline: ClickHouse/Hive T+1 (exact). Flink uses event-time, 10s watermark, 5min allowed lateness, tumbling 1-min windows, HyperLogLogPlus(14) for constant memory. Two-phase aggregation (local then global) mitigates hot product skew. Offline recalculates with uniqExact and FINAL to trigger ReplacingMergeTree merge.

Metric Definition Pitfalls

Identity resolution: userId priority > deviceId fallback; prefix u: / d: to avoid collision.

Login before/after ID break: maintain deviceId↔userId mapping table, offline merge; cross-end via OneID.

Cleared localStorage resets deviceId → UV inflation; document as known limitation.

Funnel & CTR

SessionId chains page_view → expose → click → add_cart → order_submit. CTR = click/expose (same window, same item). Session timeout 30min/cross-day breaks chain.

15 Production Pitfalls & Solutions

Page close loses data : User clicks then closes tab, request aborted → sendBeacon + pagehide / visibilitychange triple fallback.

Weak/offline network loses events : Request fails, queue dies with page → Local persistence + exponential backoff retry + capacity limit drop oldest + cold-start replay.

Duplicate reporting : Retries, refresh, multi-tab, Kafka redelivery inflate PV → eventId end-to-end idempotency: SDK gen → Redis SETNX → Flink keyBy → ReplacingMergeTree → offline FINAL.

Tracking blocks main business : Sync reporting blocks click/render → Fully async: single delegation + non-blocking IO + batching + passive listeners + requestIdleCallback + separate reporting domain.

Flash sale traffic spike : Midnight QPS 50x blows services → Batching + dynamic sampling + gateway rate limit + bounded queue backpressure + Kafka shaving; extreme: drop extensions keep core fields.

UV memory explosion : Set storing 30M UV = 720MB → HyperLogLog: 12KB, 0.81% error; exact scenarios use Set/Bitmap.

UV definition chaos : Pre/post login, multi-end inconsistent → userId first, deviceId fallback + u:/d: prefixes + ID-Mapping offline + explicit timezone/window.

Client clock skew : Events land in wrong partition, out-of-order → Stats use serverTs; >10min drift discard or route to exception table; Flink watermark + allowedLateness.

Bot/fraud pollution : Scripted clicks, competitor data stuffing → UA filtering + IP/device frequency cap + signature anti-replay + <100ms dwell invalid exposure + offline risk cleanup.

Data skew : Hot product/user overloads single partition → Kafka partition hash spread or no key; compute two-phase aggregation (local then global).

ClickHouse write slow : High-frequency single inserts create too many parts → Memory batch: flush per 1000 rows or 1s, 100x perf boost.

Real-time vs offline mismatch : Dashboard 1M, report 980k → Lambda: real-time approx for trends, T+1 exact for reports; label data status on dashboard.

Tracking governance mess : Same button instrumented differently by 3 people → Schema registry + event whitelist/enum validation + versioning + visual point-and-click + pre-release reconciliation.

Privacy compliance : Accidental PII/geolocation collection → Minimal collection, client-side masking, consent switches, TTL auto-delete, export/delete APIs (PIPL).

No end-to-end observability : Post-launch nobody trusts numbers → Three-layer reconciliation: SDK local count ↔ Kafka offset ↔ ClickHouse detail; diff alerts + gray dual-write comparison.

Key observability metrics: SDK success rate, receiver queue length/drops, Kafka lag, ClickHouse write latency, PV/UV YoY/MoM, schema error rate.

Evolution Roadmap

Scale progressively: start with Spring Boot + MySQL → add Kafka + ClickHouse → replace receiver with OpenResty/Netty for higher throughput → cold data to object storage. Extensions: gradual sampling (10% non-core events), traceId integration for full-chain tracing, A/B test group auto-tagging, error monitoring correlation, data compliance (export/delete + audit).

Closing Principles

Frontend handles "unreliability", backend blocks "duplication", compute aligns "definitions". Kafka, Flink, ClickHouse serve these three goals.

Define contracts before code : eventId idempotency key, serverTs time baseline, userId -first deduplication — freeze day one.

Async everything, batch everything, compute in memory not DB — these three rules prevent most performance issues.

Degradation plans first : sampling switches, bounded queues, rate limits — rehearse before big promotions; tracking system never outranks core business.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion