Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a 1B-Event Real-Time Unique
User & Ad-Attribution Analytics Pipeline.

Replace 64 GB/metric exact HashSets with partitioned Flink/Kafka HyperLogLog sketches (1.5–12 KB each) merged via O(m) element-wise MAX into ClickHouse/Redis rollups.
Start the journey7 stages· Last modified Nov 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, 100 concurrent billion-scale metrics shrink from 6.4 TB of RAM to 150 KB–1.2 MB while supporting instant hourly-to-monthly rollups.

TL;DR30-second simplified summary
▾

Workers accumulate local HLLs per 1-minute window, flush to ClickHouse/Redis for hourly and daily PFMERGE rollups, and benefit from natural idempotency during Kafka replays.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
HyperLogLog & Probabilistic Cardinality Estimation
HyperLogLog hashes each element into 64 bits, routes it to one of m = 2^p registers, tracks the maximum leading-zero run rho(w), and averages registers via a bias-corrected harmonic mean in O(1) space.
Full walkthrough · 7 stages
01
Stage 1 · Foundationfoundation

Capacity Sizing: 6.4 TB Exact Sets vs 150 KB HLL Sketches.

Why this matters: Compare memory and network shuffle costs across 100 metrics at 1B+ events/day.

At 1B unique users/day (~11,500 new uniques/sec, 50k+ total events/sec), retaining raw 64-byte UUID entries costs 64 GB per metric. With HyperLogLog at p = 11 (1.5 KB) or p = 14 (12 KB), 100 metrics occupy only 150 KB to 1.2 MB total—fitting entirely inside L3 CPU cache.

def compare_footprint(metrics: int, uniques_per_metric: int) -> dict[str, str]:
    exact_tb = (metrics * uniques_per_metric * 64) / (1024 ** 4)
    hll_mb = (metrics * 1536) / (1024 ** 2)
    return {"exact_ram": f"{exact_tb:.2f} TB", "hll_ram": f"{hll_mb:.3f} MB"}
Capacity Sizing

100 Metrics x 1B Users: 6.4 TB Exact vs 150 KB HLL

1B+ Daily EventssourceExact HashSet: 6.4TBwarningHLL (p=11): 150 KBstoreStoreO(1) register array

1.40,000,000x Reduction: Memory drops from terabytes to kilobytes per node.

2.Network Savings: Flushing 100 metrics every 10s ships only 150 KB over the wire.

Caption: HyperLogLog reduces 100 billion-scale distinct metrics from 6.4 TB to 150 KB.

02
Stage 2 · Foundationfoundation

Stream Ingestion & Partition-Local Pre-Aggregation.

Why this matters: Avoid expensive key-by-user_id shuffles by aggregating HLL sketches locally on every Kafka/Flink partition.

Think of Stream Ingestion & Partition-Local Pre-Aggregation as the intuition layer for Design a 1B-Event Real-Time Unique User & Ad-Attribution Analytics Pipeline: Avoid expensive key-by-user_id shuffles by aggregating HLL sketches locally on every Kafka/Flink partition.

An exact COUNT(DISTINCT user_id) in Spark/Flink usually forces a global GROUP BY metric_id, user_id shuffle across the cluster. Because HyperLogLog is mergeable, each Flink worker updates a partition-local HLL sketch for (metric_id, 1-minute_bucket) with zero network shuffle per event, emitting only the 1.5 KB sketch at window close!

Shuffle-Free Ingestion

Partition-Local HLL Accumulation Before Window Flush

Kafka PartitionssourceFlink Worker ShardsprocessWindow Flush (60s)storeStoreO(m) sketch emit

1.Zero Hot-Key Skew: Even if one campaign gets 90% of traffic, each partition updates its own local 1.5 KB sketch independently.

2.Event-Time Watermarks: Late events update the corresponding historical minute sketch before compaction.

Caption: Partition-local HLL accumulation eliminates global user_id shuffles across the streaming cluster.

Engineering Decision Framework
Problem
How to implement Design a 1B-Event Real-Time Unique User & Ad-Attribution Analytics Pipeline without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When traffic spikes expose hidden coupling, 100 concurrent billion-scale metrics shrink from 6.4 TB of RAM to 150 KB–1.2 MB while supporting instant hourly-to-monthly rollups.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a 1B-Event Real-Time Unique User & Ad-Attribution Analytics Pipeline experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
Stage 3 · Intermediateintermediate

Hierarchical Time-Bucket Rollups (Minute -> Hour -> Day).

Why this matters: Enable sub-10ms arbitrary date-range unique counts (e.g., 7-day or 30-day uniques) via pre-merged HLL rollups.

You cannot sum daily unique counts to get weekly uniques (users repeat across days).

Instead, store 1-minute HLL sketches in ClickHouse (AggregateFunction(uniqHLL12)) or Redis, and run background PFMERGE rollups into hourly and daily HLL rows.

Time Rollups

Hierarchical O(m) PFMERGE Pyramids

1-Min Sketchessource1-Hour Rollupsprocess1-Day RollupsstoreStoreO(m) max-merge

1.Exact Union Semantics: Users active on both Monday and Tuesday are counted once in the merged weekly HLL.

2.Bounded Query Latency: 30-day query touches 30 rows (45 KB) instead of scanning 30 billion raw events.

Caption: Hierarchical PFMERGE rollups turn 30-day distinct queries into 30-row O(m) merges.

04
Stage 4 · Intermediateintermediate

Precision Tuning: 1.5 KB (2.3% err) vs 12 KB (0.81% err).

Why this matters: Choose register precision p based on billing-grade vs operational-dashboard accuracy requirements.

Standard error scales as 1.04 / sqrt(2^p).

For real-time anomaly dashboards, p = 11 (2,048 registers, 1.5 KB, 2.3% error) is ideal.

Precision Trade-Off

Choosing p: Memory Footprint vs Standard Error

p=11 (2,048 regs)sourcep=14 (16,384 regs)processp=16 (65,536 regs)storeStore4x RAM -> 2x tighter error

1.Fixed p Per Pipeline: Pick p upfront; merging sketches with different p requires down-folding or fails.

2.3-Sigma Bound: At p=14 (0.81% sigma), 99.7% of estimates fall within +/- 2.43% of exact truth.

Caption: Increasing precision p by 2 bits quadruples register memory while halving standard error.

05
Stage 5 · Intermediateintermediate

Handling Long-Tail Segmented Metrics with Sparse Encoding.

Why this matters: Prevent OOM when users slice dashboards by high-cardinality dimensions (e.g., 5M distinct URLs or ads).

If analysts group by ad_id (5 million ads), 90% of ads receive fewer than 50 clicks/day.

Allocating 12 KB dense HLLs for 5M keys would take 60 GB!

Long-Tail Compression

Sparse-to-Dense HLL Promotion Across 5M Ad IDs

4.5M Long-Tail AdssourcePromotion Thresholdprocess500K Viral AdsstoreStoreHigh-traffic keys

1.60 GB -> 6.5 GB: Sparse encoding shrinks 5M-key footprint by nearly an order of magnitude.

2.Transparent Merge: Sparse-with-dense merge unpacks only the sparse entries in O(k) time.

Caption: Sparse encoding keeps long-tail segmented metrics compact before promoting hot keys to dense HLL.

06
Stage 6 · Advancedadvanced

Idempotent Checkpointing & Exact-Once Sketch Durability.

Why this matters: Ensure worker restarts or Kafka replays do not corrupt sketches or lose window state.

Think of Idempotent Checkpointing & Exact-Once Sketch Durability as the intuition layer for Design a 1B-Event Real-Time Unique User & Ad-Attribution Analytics Pipeline: Ensure worker restarts or Kafka replays do not corrupt sketches or lose window state.

Because PFADD / max(regs[idx], rho) is idempotent, replaying a duplicate Kafka message for the same user_id leaves the HLL sketch completely unchanged! Pairing Flink incremental RocksDB checkpoints with idempotent MERGE upserts into ClickHouse/Redis guarantees at-least-once replays produce exact HLL convergence.

Fault Tolerance

Idempotent Replays & Checkpoint Recovery

Kafka Replay /RetrysourceIdempotent max()processConsistent HLLStatestoreStoreNo inflation

1.Natural Idempotency: Unlike SUM/COUNT(+), HLL MAX-updates are immune to duplicate event delivery.

2.Versioned Hash Seed: Store a 1-byte schema/seed version header on every serialized HLL blob.

Caption: HLL's idempotent max-register update makes distinct counting naturally immune to duplicate event replays.

07
Stage 7 · Advancedadvanced

Observability, Hash-Drift Guards & Billing Reconciliation.

Why this matters: Detect silent hash-seed mismatches and reconcile probabilistic estimates against nightly exact batch audits.

Think of Observability, Hash-Drift Guards & Billing Reconciliation as the intuition layer for Design a 1B-Event Real-Time Unique User & Ad-Attribution Analytics Pipeline: Detect silent hash-seed mismatches and reconcile probabilistic estimates against nightly exact batch audits.

Because HLL errors are bounded and predictable (~1.04 / sqrt(m)), run a nightly Spark/SQL exact COUNT(DISTINCT) audit on a 1% sampled metric set. Alert if observed drift exceeds 3 * sigma (which immediately catches hash-seed mismatches, truncated 32-bit hashes, or corrupted sparse-to-dense merges).

SRE Verification

Nightly 1% Exact Audit & 3-Sigma Drift Alerting

Live HLL Estimatesource1% Nightly BatchAuditprocess|est - exact| >3*sigmastoreStoreVerify error bound

1.32-Bit Hash Trap: Using a 32-bit hash saturates above ~4B items via collisions; always use 64-bit hashes.

2.Audit Confidence: Automated 3-sigma checks prove ongoing SLA compliance for ad-tech billing.

Caption: Nightly sampled exact audits catch 32-bit hash collisions or seed mismatches if error exceeds 3-sigma.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

In a Flink + Kafka pipeline computing COUNT(DISTINCT user_id) for 100 campaign metrics, why does HyperLogLog eliminate the need to shuffle raw events by user_id?

Recommended Learning Flow