HyperLogLog tracks max leading-zero runs across m registers to estimate distinct counts in ~1.5–12 KB, while Count-Min Sketch uses d hash rows x w counters to bound item frequencies in sub-megabyte RAM.
TL;DR30-second simplified summary▾
Tracking exact COUNT(DISTINCT user_id) or per-key frequencies across 100M+ daily events with HashSet or HashMap requires O(N) memory—tens of gigabytes per metric—and cannot be merged across distributed shards without shuffling raw IDs.
HyperLogLog (HLL) solves distinct cardinality in O(1) fixed space. It hashes each element to 64 bits, uses p bits to index one of m = 2^p registers (e.g., p=14 -> 16,384 6-bit registers = 12 KB), and records the maximum leading-zero run rho seen in that bucket. Taking the bias-corrected harmonic mean across registers estimates billions of unique items within 1.04 / sqrt(m) (~0.81% error at 12 KB), and distributed shards merge via element-wise max(M_A[i], M_B[i]).
Count-Min Sketch (CMS) solves frequency estimation in O(d * w) space using a d x w 2D counter matrix with d pairwise-independent hashes. Inserts increment matrix[row][h_row(x)], and queries return min_row(matrix[row][h_row(x)]). Because counters only experience hash collisions upward, the minimum across rows strictly upper-bounds true frequency and bounds over-estimation to epsilon * TotalCount with probability 1 - delta.
Key trade-offs: neither sketch supports arbitrary element deletion cleanly (standard HLL has no delete; CMS needs signed counters or conservative updates), both trade exactness for 1000x–10,000x RAM savings, and CMS requires pairing with a small min-heap to list the actual Top-K keys.
From patterns to decisions.
Explain the bit-level mechanics, error bounds, and distributed mergeability of HyperLogLog and Count-Min Sketch.
Why Exact HashSets & HashMaps Fail at Streaming Scale.
Storing 50M 36-byte UUIDs in a Java/Python/Redis HashSet or HashMap consumes 4–12 GB per metric once hash-table load factors and object headers are included.
- Multi-Window Multiplication: Computing 5-minute, 1-hour, and 24-hour rollups across 100 tenants multiplies RAM by
300x. - Distributed Merge Cost: Merging exact sets across 32 Kafka/Flink partitions requires shipping gigabytes of raw keys over the network.
Exact O(N) HashSet vs O(1) Streaming Sketches
1.:
2.:
Caption: Probabilistic sketches replace gigabyte-scale exact hash tables with fixed kilobyte arrays that merge cleanly across distributed shards.
HyperLogLog: Leading Zeros, Buckets, and Harmonic Mean.
If a uniform 64-bit hash starts with k zero bits before the first 1, that event occurs with probability 2^-(k+1), implying roughly 2^k distinct items were hashed.
A single coin-flip estimator has huge variance, so HyperLogLog splits the hash into:
- First
pbits (m = 2^pbuckets): Selects registerM[idx]. - Remaining
64 - pbits: Counts leading zeros + 1 (rho), updatingM[idx] = max(M[idx], rho). - Harmonic Mean: Combines
2^M[i]using the harmonic meanalpha_m * m^2 / sum(2^-M[i])so one luckyrho=30outlier doesn't ruin the estimate.
64-Bit Hash -> Bucket Index + Leading Zeros -> Harmonic Mean
1.:
2.:
Caption: HyperLogLog hashes items into m=2^p registers tracking max leading-zero runs, then averages via harmonic mean for <1% error in kilobytes.
Count-Min Sketch: 2D Hash Matrix & Conservative Updates.
A Count-Min Sketch is a d x w integer matrix where each row i uses an independent hash h_i(x) in [0, w-1]:
- Insert(
x,c): Incrementmatrix[i][h_i(x)] += cfor alli = 0..d-1. - Query(
x): Returnmin_i(matrix[i][h_i(x)]). Collisions only add positive noise, so the minimum acrossdindependent rows is closest to true count. - Sizing Formulas: Set
w = ceil(e / epsilon)andd = ceil(ln(1 / delta)). Forepsilon = 0.001(0.1% of total stream) anddelta = 0.01(99% confidence):w = 2,719, d = 5(~54 KB at 32-bit ints). - Conservative Update: Only increment cells equal to the current minimum estimate, slashing collision noise by ~50%.
d Independent Hashes -> Increment -> Minimum Estimate
1.:
2.:
Caption: Count-Min Sketch hashes each key across d independent rows and takes the minimum counter to bound collision over-estimation within epsilon * N.
Merging HLL & Count-Min Sketches Across Shards.
Both sketches are monoids under simple element-wise operations (when initialized with identical p / (d, w) and hash seeds):
- HyperLogLog Merge:
M_merged[i] = max(M_A[i], M_B[i])acrossi = 0..m-1. Order-independent and idempotent! - Count-Min Merge:
CMS_merged[r][c] = CMS_A[r][c] + CMS_B[r][c].
Workers aggregate 1M events/sec locally and ship a 12–64 KB sketch once per minute to a central aggregator.
HLL Element-Wise Max vs CMS Element-Wise Sum
1.:
2.:
Caption: Shards merge HyperLogLog registers via element-wise max and Count-Min matrices via element-wise addition in constant network bandwidth.
Safe Python HyperLogLog & Count-Min Sketch with Seed Validation.
Always validate matching dimensions (p, d, w) before merging sketches from remote shards:
import hashlib, math
class HyperLogLog:
def __init__(self, p: int = 12):
if not (4 <= p <= 18):
raise ValueError('p must be between 4 and 18')
self.p = p
self.m = 1 << p
self.regs = bytearray(self.m)
self.alpha = 0.7213 / (1.0 + 1.079 / self.m)
def add(self, item: str) -> None:
h = int.from_bytes(hashlib.blake2b(item.encode(), digest_size=8).digest(), 'big')
idx = h >> (64 - self.p)
tail = ((h << self.p) & ((1 << 64) - 1)) | (1 << (self.p - 1))
rho = (64 - self.p) - tail.bit_length() + 1
if rho > self.regs[idx]:
self.regs[idx] = rho
def merge(self, other: 'HyperLogLog') -> None:
if self.p != other.p:
raise ValueError('Cannot merge HLLs with different precision p')
for i in range(self.m):
if other.regs[i] > self.regs[i]:
self.regs[i] = other.regs[i]
def count(self) -> int:
z = sum(2.0 ** (-r) for r in self.regs)
est = self.alpha * (self.m ** 2) / z
zeros = self.regs.count(0)
if est <= 2.5 * self.m and zeros > 0:
return int(self.m * math.log(self.m / zeros))
return int(est)64-bit Blake2b -> Bytearray Registers -> Linear/Harmonic Estimate
1.:
2.:
Caption: A bytearray-backed HyperLogLog with blake2b hashing, merge precision checks, and Linear Counting small-range correction.
Pairing Count-Min Sketch with a Min-Heap for Top-K.
Because Count-Min Sketch does not store keys, pair it with a size-K Min-Heap (plus a small dict of heap members):
- On each incoming
(key, 1): update CMS and queryest = cms.query(key). - If
keyis in the heap, update its frequency and sift down. - Else if
len(heap) < Korest > heap[0].freq: pushkey(and pop the smallest iflen > K).
Memory stays O(d*w + K) regardless of whether 100M distinct keys flow past.
Stream -> Count-Min Sketch -> Bounded Size-K Min-Heap
1.:
2.:
Caption: Pairing Count-Min Sketch with a size-K min-heap tracks the top-K heavy hitters in O(d*w + K) fixed memory.
Sketch Pitfalls: Poor Hash Functions, Deletions, and Theta Sketches.
Avoid three common production mistakes:
- Correlated Hashes: Never derive
dhashes viah(x) + i—use independent seeds (xxhash/MurmurHash3) or Kirsch-Mitzenmacherh1(x) + i * h2(x). - Set Intersections (
A ∩ B): HLL estimates|A ∪ B|accurately viamerge(), but|A| + |B| - |A ∪ B|has high relative error when overlap is tiny. Use Theta Sketches (Apache DataSketches) when set intersections are required. - No Exact Deletion: If you must decrement counts or delete items from a distinct set, use a Counting Bloom Filter or Cuckoo Filter instead.
HLL (Unions) vs Theta Sketch (Intersections)
1.:
2.:
Caption: Use 64-bit hashes for HLL unions, switch to Theta Sketches for set intersections, and avoid conservative CMS updates when merging across shards.
Practice: Make the trade-off yourself.
When querying a Count-Min Sketch for key `x`, why do we take the MINIMUM across the `d` hash rows instead of the average?