When concurrent writes contend on shared state, counting 1 billion unique UUIDs drops from ~64 GB in a HashSet to 1.5 KB in HyperLogLog, while cross-shard unions shrink from O(N) to O(m) element-wise max.
TL;DR30-second simplified summary▾
With p = 11 (2,048 registers = 1.5 KB) or Redis's p = 14 (16,384 registers = 12 KB), HLL estimates 1B+ distinct items within 2.3% or 0.81% error and merges across distributed shards via element-wise MAX.
The O(N) Memory Wall of Exact Distinct Counting.
Why this matters: Quantify why storing raw user IDs in a HashSet or Redis SET causes OOM crashes at billion-event scale.
An exact set[str] or Redis SET must retain every unique identifier seen so far to deduplicate future arrivals. At 1,000,000,000 UUIDs (~64 bytes per entry including hash-table pointers), a single metric consumes 64 GB of RAM—and tracking 100 segmented metrics (by country, campaign, or device) requires 6.4 TB.
def exact_distinct_memory_gb(unique_items: int, bytes_per_entry: int = 64) -> float:
if unique_items < 0:
raise ValueError("unique_items must be non-negative")
return (unique_items * bytes_per_entry) / (1024 ** 3)Exact HashSet / Redis SET O(N) Explosion
1.Cross-Shard Bottleneck: Unioning exact sets across Flink/Spark workers ships gigabytes over the network.
2.Fixed Window Trap: Sliding 24h windows multiply memory overhead by window granularity.
Caption: Exact deduplication stores every unique key in RAM, scaling linearly to 64 GB per billion-user metric.
Leading-Zero Intuition: Rare Bit Patterns Reveal Cardinality.
Why this matters: Understand how the longest run of leading zeros in a uniform hash estimates log2(N) without storing any keys.
Suppose you hash every unique user_id into a uniform 64-bit binary string.
Half of all hashes start with 1... (rho = 1), one quarter start with 01... (rho = 2), and only 1 in 2^k hashes starts with k - 1 zeros followed by a 1.
Mapping Uniform Hash Bits to Log2 Cardinality
1.Single-Bucket Variance: A single lucky hash (e.g., 25 leading zeros early) would wildly overestimate N.
2.Idempotent Repeats: Duplicate user_ids produce the exact same hash, leaving max(rho) unchanged.
Caption: Leading-zero counts in uniform hashes estimate cardinality logarithmically while naturally ignoring duplicates.
- Problem
- How to implement HyperLogLog & Probabilistic Cardinality Estimation 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 concurrent writes contend on shared state, counting 1 billion unique UUIDs drops from ~64 GB in a HashSet to 1.5 KB in HyperLogLog, while cross-shard unions shrink from O(N) to O(m) element-wise max.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When HyperLogLog & Probabilistic Cardinality Estimation experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Stochastic Averaging Across m = 2^p 6-Bit Registers.
Why this matters: Split the 64-bit hash into p bucket-index bits and (64 - p) tail bits to tame variance in 1.5 KB of RAM.
To eliminate single-bucket luck, HyperLogLog partitions the stream into m = 2^p independent sub-streams using the top p bits of the 64-bit hash (e.g., p = 11 -> m = 2,048 buckets). Each bucket stores only a 6-bit integer regs[idx] (max value 63, sufficient for 2^63 distinct items), totaling 2048 * 6 bits = 1,536 bytes (1.5 KB)!
import hashlib
class HyperLogLog:
def __init__(self, p: int = 11) -> None:
if not (4 <= p <= 16):
raise ValueError("p must be between 4 and 16")
self.p = p
self.m = 1 << p
self.regs = [0] * self.m
self.alpha = 0.7213 / (1.0 + 1.079 / self.m)p = 11 Bucket Bits + 53 Tail Bits -> 1.5 KB Array
1.6-Bit Register Width: 53 tail bits + 1 = 54 max rho, which fits inside 6 bits (0..63).
2.Redis Standard: Redis uses p = 14 (16,384 registers = 12 KB) for 0.81% standard error.
Caption: Splitting the 64-bit hash across 2,048 6-bit registers caps memory at 1.5 KB regardless of stream size.
Harmonic Mean Aggregation & Small-Range LinearCounting.
Why this matters: Combine all m registers without outlier distortion and correct small-cardinality bias when registers are mostly empty.
An arithmetic mean over 2^regs[j] would be skewed by a single lucky bucket. HyperLogLog uses the harmonic mean E = alpha_m * m^2 / sum(2^-regs[j]), which suppresses large outliers. When cardinality N is small (E <= 2.5 * m) and V registers are still 0, HLL switches to LinearCounting: m * ln(m / V) for accurate small-set counts.
import mathHarmonic Mean + LinearCounting Small-Range Correction
1.Standard Error Formula: sigma = 1.04 / sqrt(m): ~2.3% for m=2,048 (1.5 KB) and ~0.81% for m=16,384 (12 KB).
2.HyperLogLog++: Google's HLL++ adds sparse representation for tiny sets and 64-bit bias tables.
Caption: Harmonic averaging suppresses outlier registers while LinearCounting keeps small-set estimates accurate.
Lossless Distributed Merging (PFMERGE) in O(m) Time.
Why this matters: Union distinct counts across Kafka/Flink partitions or hourly time rollups without losing accuracy.
Because each register stores a commutative, associative max over its bucket, merging two HLL sketches A and B (compiled with the same p and hash function) is simply C[i] = max(A[i], B[i]) for i in 0..m-1. The merged sketch has the exact same error bound as if all events had been fed into a single HLL—in O(m) = 2,048 operations!
def merge(self, other: "HyperLogLog") -> "HyperLogLog":
if self.p != other.p:
raise ValueError("Cannot merge HLLs with different precision p")
merged = HyperLogLog(self.p)
merged.regs = [max(a, b) for a, b in zip(self.regs, other.regs)]
return mergedCommutative Element-Wise MAX Merge (PFMERGE)
1.Pre-Aggregated Rollups: Merge 24 hourly HLL sketches into a daily unique count in microseconds.
2.Strict Precondition: Both sketches MUST share identical precision p and hash seed.
Caption: Element-wise max merges arbitrary distributed HLL sketches in O(m) time with zero accuracy loss.
Trade-Offs: HLL vs Exact Sets, Bloom Filters & Set Intersections.
Why this matters: Know when HyperLogLog is the wrong tool (membership tests, deletions, or tiny set intersections).
Think of Trade-Offs: HLL vs Exact Sets, Bloom Filters & Set Intersections as the intuition layer for HyperLogLog & Probabilistic Cardinality Estimation: Know when HyperLogLog is the wrong tool (membership tests, deletions, or tiny set intersections).
HyperLogLog answers COUNT(DISTINCT)—it CANNOT answer is user_id X in the set? (use a Bloom or Cuckoo filter) and it CANNOT support deletions (removing an item cannot lower max because older items may have also hit that register). Similarly, estimating set intersection |A ∩ B| via Inclusion-Exclusion (|A| + |B| - |A ∪ B|) suffers catastrophic relative error when |A ∩ B| is small compared to |A ∪ B| (use Theta Sketches instead).
Matching Sketch Primitives to Query Semantics
1.No Deletions: HLL is append-only per window; expire old windows via TTL or ring buffers.
2.Intersection Error: 2.3% error on 100M union is +/- 2.3M—which dwarfs a 500k intersection.
Caption: Use HLL for cardinality and unions, Bloom/Cuckoo filters for membership, and Theta sketches for intersections.
Production Hardening: Sparse Encoding & Hash Hygiene.
Why this matters: Avoid wasting 12 KB on millions of long-tail metrics with only 1–5 users, and prevent hash-seed drift.
Think of Production Hardening: Sparse Encoding & Hash Hygiene as the intuition layer for HyperLogLog & Probabilistic Cardinality Estimation: Avoid wasting 12 KB on millions of long-tail metrics with only 1–5 users, and prevent hash-seed drift.
When tracking 10 million segmented metrics (e.g., per-advertiser or per-URL unique visitors) where 90% of keys have fewer than 20 visitors, allocating a full 12 KB dense HLL per key wastes 120 GB of RAM! Production engines (Redis PFADD and Google HLL++) start in a sparse representation (storing only non-zero (bucket_idx, rho) pairs in ~64–512 bytes) and promote to the dense 2^p array only once sparse size crosses a threshold.
Sparse-to-Dense Promotion for Long-Tail Metrics
1.90% RAM Savings: Sparse encoding prevents 12 KB overhead on long-tail metrics with tiny traffic.
2.Hash Seed Pinning: Never change the HLL hash function or seed without versioning keys, or PFMERGE silently corrupts.
Caption: Sparse-to-dense promotion cuts long-tail RAM by 90% while keeping dense sketches bounded at 1.5–12 KB.
Practice: Make the trade-off yourself.
Why does HyperLogLog use the harmonic mean of 2^regs[j] across m buckets instead of the arithmetic mean?