Skip to main content
← CONCEPTS / ALGORITHMS & DATA STRUCTURES
An end-to-end domain learning journey

HyperLogLog & Count-Min
Sketch (Streaming Sketches).

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.
Start the journey7 sections· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Full walkthrough · 7 stages
01
Stage 1 • Foundationfoundation

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.
Memory Scaling

Exact O(N) HashSet vs O(1) Streaming Sketches

Exact HashSet ProducerHLL + Count-MinStateStore

1.:

2.:

Caption: Probabilistic sketches replace gigabyte-scale exact hash tables with fixed kilobyte arrays that merge cleanly across distributed shards.

02
Stage 2 • Distinct Countfoundation

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 p bits (m = 2^p buckets): Selects register M[idx].
  • Remaining 64 - p bits: Counts leading zeros + 1 (rho), updating M[idx] = max(M[idx], rho).
  • Harmonic Mean: Combines 2^M[i] using the harmonic mean alpha_m * m^2 / sum(2^-M[i]) so one lucky rho=30 outlier doesn't ruin the estimate.
HLL Pipeline

64-Bit Hash -> Bucket Index + Leading Zeros -> Harmonic Mean

64-bit HashRegister M[idx]Harmonic MeanStorealpha * m^2 / sum(2^-M[i])

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.

03
Stage 3 • Frequency Estimationintermediate

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): Increment matrix[i][h_i(x)] += c for all i = 0..d-1.
  • Query(x): Return min_i(matrix[i][h_i(x)]). Collisions only add positive noise, so the minimum across d independent rows is closest to true count.
  • Sizing Formulas: Set w = ceil(e / epsilon) and d = ceil(ln(1 / delta)). For epsilon = 0.001 (0.1% of total stream) and delta = 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%.
CMS Matrix

d Independent Hashes -> Increment -> Minimum Estimate

Item x5 x 2719 Matrixmin(row_i[h_i(x)])StorePrunes collision noise

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.

04
Stage 4 • Distributed Aggregationintermediate

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]) across i = 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.

Shard Merge

HLL Element-Wise Max vs CMS Element-Wise Sum

HLL MergeCMS MergeStateStore

1.:

2.:

Caption: Shards merge HyperLogLog registers via element-wise max and Count-Min matrices via element-wise addition in constant network bandwidth.

05
Stage 5 • Implementationintermediate

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)
Reference Code

64-bit Blake2b -> Bytearray Registers -> Linear/Harmonic Estimate

blake2b(8B)bytearray(2^p)Small-Range CheckStoreMerge-validated count()

1.:

2.:

Caption: A bytearray-backed HyperLogLog with blake2b hashing, merge precision checks, and Linear Counting small-range correction.

06
Stage 6 • Top-K Heavy Hittersadvanced

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):

  1. On each incoming (key, 1): update CMS and query est = cms.query(key).
  2. If key is in the heap, update its frequency and sift down.
  3. Else if len(heap) < K or est > heap[0].freq: push key (and pop the smallest if len > K).

Memory stays O(d*w + K) regardless of whether 100M distinct keys flow past.

Top-K Pipeline

Stream -> Count-Min Sketch -> Bounded Size-K Min-Heap

Stream KeyProducerCount-Min SketchSize-K Min-HeapStore

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.

07
Stage 7 • Pitfalls & Alternativesadvanced

Sketch Pitfalls: Poor Hash Functions, Deletions, and Theta Sketches.

Avoid three common production mistakes:

  • Correlated Hashes: Never derive d hashes via h(x) + i—use independent seeds (xxhash/MurmurHash3) or Kirsch-Mitzenmacher h1(x) + i * h2(x).
  • Set Intersections (A ∩ B): HLL estimates |A ∪ B| accurately via merge(), 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.
Sketch Selection

HLL (Unions) vs Theta Sketch (Intersections)

HyperLogLogTheta SketchStateStore

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

When querying a Count-Min Sketch for key `x`, why do we take the MINIMUM across the `d` hash rows instead of the average?

Recommended Learning Flow