Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

13. Data streams: reservoir sampling, Bloom filters and count–min sketches

School of Engineering, Nazarbayev University

Suppose firmware for a wind-turbine microcontroller with 4 KB of free memory (an assumed figure) has to monitor a CAN-bus telemetry stream of 50,00050{,}000 frames per second, 4.3×1094.3 \times 10^9 frames per day. The stream cannot be stored, a set or dict of all IDs would not fit, and the stream length NN is not known in advance. Streaming algorithms handle four such tasks with a fixed amount of memory and one pass (Mental Move #22: Summarize Infinite Streams with One-Sided Sketches): (1) Vitter’s Reservoir Sampling (information_streams.vitter_reservoir_sample) maintains an exact uniform sample of kk frames without knowing NN; (2) Bloom Filters (information_streams.bloom_filter_simulate) block duplicate packet IDs in ~10 bits/item with no false negatives; (3) Count-Min Sketches (information_streams.count_min_sketch_frequencies) isolate heavy-hitter vibration spikes with strict one-sided error f^≥f\hat{f} \ge f; and (4) HyperLogLog / trailing-zero sketches count millions of distinct IDs in 64 bytes.

Learning objectives

  1. Prove and verify the inductive uniformity invariant P(xi∈Rt)=k/(t+1)\mathbb{P}(x_i \in R_t) = k/(t+1) of Vitter’s Algorithm R (information_streams.vitter_reservoir_sample) across arbitrary unknown stream lengths.

  2. Derive the Bloom Filter false-positive curve (1−e−kn/m)k(1 - e^{-kn/m})^k, locate the optimal hash count k⋆=(m/n)ln⁡2k^\star = (m/n)\ln 2 (information_streams.bloom_filter_simulate), and verify exact zero false negatives.

  3. Track Zipfian heavy-hitter frequencies in fixed O(w⋅d)\mathcal{O}(w \cdot d) RAM via information_streams.count_min_sketch_frequencies and verify the one-sided Markov error bound 0≤f^i−fi≤ϵN0 \le \hat{f}_i - f_i \le \epsilon N.

  4. Implement deterministic Misra-Gries frequent-items summaries and compare HyperLogLog register RAM against linear set growth.

Time: about 60 min

1. Exact Uniform Sampling Without Knowing NN: Vitter’s Reservoir Algorithm R

How do you pick kk items uniformly at random from a stream x0,x1,…,xN−1x_0, x_1, \dots, x_{N-1} when NN is unknown until the stream ends? Vitter’s (1985) Algorithm R (information_streams.vitter_reservoir_sample) initializes reservoir Rk−1={x0,…,xk−1}R_{k-1} = \{x_0, \dots, x_{k-1}\}. Upon seeing item xtx_t (t≥kt \ge k, 0-indexed, so t+1t+1 items seen so far), draw integer j∼Uniform{0,1,…,t}j \sim \mathrm{Uniform}\{0, 1, \dots, t\}; if j<kj < k, overwrite reservoir[j] = x_t.

Inductive Invariant Proof (P(xi∈Rt)=kt+1\mathbb{P}(x_i \in R_t) = \frac{k}{t+1})

  • Base case (t=k−1t = k - 1): Every one of the first kk items is in Rk−1R_{k-1} with probability 1=k/k1 = k / k.

  • Inductive step (t−1→tt - 1 \to t): Newcomer xtx_t enters iff j∈{0,…,k−1}j \in \{0, \dots, k-1\}, which occurs with exact probability kt+1\frac{k}{t+1}. Any existing member y∈Rt−1y \in R_{t-1} (present with probability kt\frac{k}{t} by induction) is evicted iff jj lands on its specific slot (probability 1t+1\frac{1}{t+1}). Hence yy survives with probability:

P(y∈Rt)=kt(1−1t+1)=kt⋅tt+1=kt+1(1.1)\mathbb{P}(y \in R_t) = \frac{k}{t}\left(1 - \frac{1}{t+1}\right) = \frac{k}{t}\cdot\frac{t}{t+1} = \frac{k}{t+1} \tag{1.1}

Every telescoping denominator cancels cleanly.


Demonstration 1: Vitter's reservoir sampling empirical uniformity and O(k) memory
=================================================================================
Stream length N = 50, Reservoir k = 5, Monte Carlo runs = 5000
Theoretical inclusion probability k/N = 0.1000
Empirical min / mean / max inclusion  = 0.0900 / 0.1000 / 0.1118 (max |err| = 0.0118)
<Figure size 1254x451 with 2 Axes>

Figure 13.1. Reservoir sampling with k=5k = 5 from a stream of 50 items. (a) Inclusion frequency of each item over 5,000 runs; all lie close to k/N=0.1k/N = 0.1. (b) Exact inclusion probability of three items against the number of items seen; all reach k/Nk/N at the end.

What Demonstration 1 shows. In the right panel, item i=0i = 0 enters with probability 1 and survives many gentle (1−1/t)(1 - 1/t) attrition steps, while late item i=34i = 34 enters with small probability 5/355/35 and undergoes far fewer attrition steps—yet at every stopping time NN all curves lie on the same line k/Nk/N, with only k=5k = 5 items held in memory. The empirical inclusion frequencies over 5000 runs range from 0.090 to 0.112 around k/N=0.1k/N = 0.1.


2. Bloom Filters (bloom_filter_simulate) & The Optimal Hash Count k⋆=mnln⁡2k^\star = \frac{m}{n}\ln 2

Suppose an edge gateway must suppress duplicate distress-packet UUIDs (n=800n = 800 unique packets) using only 1 KB1\ \mathrm{KB} (m=8,000 bitsm = 8{,}000\ \mathrm{bits})—far too small to store 800×36-byte800 \times 36\text{-byte} UUID strings (28.8 KB28.8\ \mathrm{KB}). Burton Bloom’s (1970) Filter allocates an mm-bit array initialized to False and hashes each inserted key to kk bit positions h1(x),…,hk(x)∈{0,…,m−1}h_1(x), \dots, h_k(x) \in \{0, \dots, m-1\}, setting those bits to True.

  • Zero False Negatives (FN=0\mathrm{FN} = 0): If xx was inserted, all kk of its bits remain True forever.

  • False Positive Tradeoff: After nn insertions, the fraction of bits still False is (1−1/m)kn≈e−kn/m(1 - 1/m)^{kn} \approx e^{-kn/m}, so an unseen query finds all kk of its probed bits True by coincidence with probability:

FPR(k)≈(1−e−kn/m)k(2.1)\mathrm{FPR}(k) \approx \left(1 - e^{-kn/m}\right)^k \tag{2.1}

Too few hashes (k=1k = 1) suffer frequent single-bit collisions; too many hashes (k=16k = 16) clobber the bit array toward 100%100\% ones. Differentiating ln⁡FPR(k)\ln \mathrm{FPR}(k) shows the unique global minimum occurs when exactly 50%50\% of the bits are set (e−k⋆n/m=12e^{-k^\star n/m} = \frac{1}{2}):

k⋆=mnln⁡2≈0.693 mn,FPRmin⁡=(12)(m/n)ln⁡2≈(0.6185)m/n(2.2)k^\star = \frac{m}{n}\ln 2 \approx 0.693\,\frac{m}{n}, \qquad \mathrm{FPR}_{\min} = \left(\frac{1}{2}\right)^{(m/n)\ln 2} \approx (0.6185)^{m/n} \tag{2.2}

Demonstration 2: Bloom filter hash-count U-curve and guaranteed zero false negatives
====================================================================================
Bit budget m/n = 10.0 bits/item -> Analytical k* = (m/n) ln 2 = 6.93 (auto-selected k = 7)
At optimal k = 7: bit fill = 50.0% (~50%), empirical FPR = 0.70% (theory = 0.82%)
Total false negatives across all 16 hash settings (12,800 positive queries): 0
<Figure size 1254x451 with 2 Axes>

Figure 13.2. Bloom filter with 10 bits per item. (a) False-positive rate against the number of hash functions: theory (dashed) and 3,000 queries of unseen IDs (points); the minimum lies near k⋆=6.93k^\star = 6.93. (b) Fraction of bits set, which passes 50 % at k⋆k^\star.

What Demonstration 2 shows. At k⋆=7k^\star = 7 the bit array is 50.0 %50.0\,\% ones, and the measured false-positive rate is 0.70 %0.70\,\% against 0.82 %0.82\,\% from Eq. (2.1). Referring back to Lecture 12, an mm-bit array carries its maximum possible Shannon information (m×H2(0.5)=m bitsm \times H_2(0.5) = m\ \mathrm{bits}) only when half its bits are 1 and half are 0.


3. Count-Min Sketch (count_min_sketch_frequencies): Heavy Hitters in Fixed RAM

A Bloom filter answers membership (seen before?), but what if we need event frequencies fxf_x (e.g., spotting the top 5 chattering CAN-bus fault codes out of millions of IDs)? Cormode & Muthukrishnan’s (2005) Count-Min Sketch maintains a tiny d×wd \times w integer matrix C[0…d−1,0…w−1]C[0\dots d-1, 0\dots w-1]:

  • Update(xx): Increment C[r,hr(x)]+=1C[r, h_r(x)] \mathrel{+}= 1 in every row r=0,…,d−1r = 0, \dots, d-1.

  • Query(xx): Return f^x=min⁡0≤r<dC[r,hr(x)]\hat{f}_x = \min_{0 \le r < d} C[r, h_r(x)].

Because hash collisions only add non-negative counts from other items, f^x\hat{f}_x obeys a strict one-sided invariant (fx≤f^xf_x \le \hat{f}_x). Choosing width w=⌈e/ϵ⌉w = \lceil e / \epsilon \rceil guarantees by Markov’s inequality on each row (E[noiser]≤N/w\mathbb{E}[\text{noise}_r] \le N / w) and independence across d=⌈ln⁡(1/δ)⌉d = \lceil \ln(1/\delta) \rceil rows that:

fx≤f^x≤fx+ϵNwith probability ≥1−δ(ϵ=ew, δ=e−d)(3.1)f_x \le \hat{f}_x \le f_x + \epsilon N \quad \text{with probability } \ge 1 - \delta \quad \left(\epsilon = \frac{e}{w},\ \delta = e^{-d}\right) \tag{3.1}

Demonstration 3: Count-min sketch on Zipfian fault streams and one-sided error scaling
======================================================================================
Stream N = 12000 events across 487 active fault codes; CMS table = 4 x 128 = 512 counters
Min overestimate = 0 (must be >= 0), mean = 13.34, max = 157 (bound e*N/w = 254.8)
<Figure size 1254x451 with 2 Axes>

Figure 13.3. Count–min sketch on a synthetic Zipf stream of 12,000 events. (a) Exact and estimated counts of the twelve most frequent codes with 4 × 128 counters; no estimate is low. (b) Maximum and mean error per event against the table width ww, with the bound e/we/w (dashed), which holds with high probability, not for every item.

What Demonstration 3 shows. In this synthetic Zipf stream the additive bound ϵN=0.021N\epsilon N = 0.021 N (254.8 counts) is small compared with the most frequent code (f0=0.22Nf_0 = 0.22 N), and the largest measured overestimate is 157 counts. The heavy hitters therefore stand well above the collision noise, with 512 counters (2 KB at 4 bytes per counter).


4. Distinct-Element Cardinality in 64 Bytes: HyperLogLog Trailing-Zero Intuition

How can a router count 107 distinct sensor IDs with a few hundred bytes instead of megabytes of hash-set keys? Flajolet, Fusy, Gandouet & Meunier’s (2007) HyperLogLog (HLL) uses a simple fact: in uniformly hashed 64-bit integers, only 1 in 2ρ2^\rho distinct hashes begins with ρ−1\rho - 1 leading zeros followed by a 1.

  1. Use the top b=6b = 6 bits of the hash to route each item into one of m=26=64m = 2^6 = 64 independent sub-stream registers M[0…63]M[0 \dots 63] (just 64 bytes total).

  2. Store the maximum position ρ≥1\rho \ge 1 of the first 1-bit seen in the remaining 58 bits of each bucket.

  3. Combine the mm noisy exponential estimators 2M[j]2^{M[j]} via their harmonic mean (which suppresses outlier single-hash jackpots):

N^HLL=αm m2(∑j=0m−12−M[j])−1,SE(N^/ ⁣N)≈1.04m(4.1)\hat{N}_{\mathrm{HLL}} = \alpha_m \, m^2 \left(\sum_{j=0}^{m-1} 2^{-M[j]}\right)^{-1}, \qquad \mathrm{SE}(\hat{N}/\!N) \approx \frac{1.04}{\sqrt{m}} \tag{4.1}

Demonstration 4: 64-byte HyperLogLog cardinality sketch against exact set memory growth
=======================================================================================
64-Register HLL RAM = 64 bytes (constant) vs. Exact ID Set at N=20,000 = 1406.2 KB (22500x larger)
Mean relative cardinality error across [100, 300, 1000, 3000, 8000, 20000]: 6.23% (theoretical 1.04/sqrt(64) = 13.0%)
<Figure size 1254x451 with 2 Axes>

Figure 13.4. HyperLogLog with 64 one-byte registers. (a) Estimated against true number of distinct IDs. (b) Memory of an exact set against the constant 64 bytes of the sketch.

What Demonstration 4 shows.

  • With 64 one-byte registers, the mean relative error over the six stream lengths is 6.2 %6.2\,\%, within the standard error 1.04/64=13 %1.04/\sqrt{64} = 13\,\% expected for one estimate. An exact set of the 20,000 IDs takes about 1.4 MB.


Inside the algorithm

We inspect all three core streaming primitives in information_streams (vitter_reservoir_sample, bloom_filter_simulate, and count_min_sketch_frequencies) and replace the Monte Carlo check of Demonstration 1 with an exact propagation of the inclusion probabilities, exact_markov_reservoir_probabilities(N, k), that reproduces Vitter’s k/Nk/N to rounding error (7×10−177 \times 10^{-17}).

Check against the library


Inside the algorithm: Reservoir, Bloom and count-min source + exact Markov uniformity check
===========================================================================================
def vitter_reservoir_sample(stream: np.ndarray, k_sample: int, seed: int = 42) -> np.ndarray:
    """Draw an exact uniform subset of size k_sample in one O(N) pass and O(k) memory via Vitter's Algorithm R."""
    arr = np.asarray(stream).ravel()
    k = int(k_sample)
    if k < 1 or k > arr.size:
        raise ValueError("Require 1 <= k_sample <= len(stream).")
    rng = np.random.default_rng(seed)
    reservoir = arr[:k].copy()
    for t in range(k, arr.size):
        j = int(rng.integers(0, t + 1))
        if j < k:
            reservoir[j] = arr[t]
    return reservoir

def bloom_filter_simulate(
    items_insert: list[str],
    items_query: list[str],
    m_bits: int,
    k_hashes: int | None = None,
) -> dict:
    """Simulate a m_bits Bloom Filter with optimal or user-specified k_hashes; verifies zero false negatives."""
    n_ins = len(set(items_insert))
    if m_bits < 8 or n_ins < 1:
        raise ValueError("Require m_bits >= 8 and at least one inserted item.")
    k = max(1, round((m_bits / n_ins) * math.log(2.0))) if k_hashes is None else int(k_hashes)
    if k < 1:
        raise ValueError("k_hashes must be >= 1.")

    bits = np.zeros(int(m_bits), dtype=bool)
    inserted_truth = set(items_insert)
    for item in items_insert:
        for pos in _double_hash_positions(item, int(m_bits), k):
            bits[pos] = True

    fp = 0
    fn = 0
    neg_queries = 0
    for q in items_query:
        present_est = all(bool(bits[pos]) for pos in _double_hash_positions(q, int(m_bits), k))
        present_true = q in inserted_truth
        if present_true and not present_est:
            fn += 1
        elif (not present_true) and present_est:
            fp += 1
        if not present_true:
            neg_queries += 1

    emp_fpr = (fp / neg_queries) if neg_queries > 0 else 0.0
    theo_fpr = (1.0 - math.exp(-k * n_ins / float(m_bits))) ** k
    return {
        "k_hashes": k,
        "bits_set_fraction": float(np.mean(bits)),
        "false_positives": fp,
        "false_negatives": fn,
        "empirical_fpr": emp_fpr,
        "theoretical_fpr": theo_fpr,
    }

def count_min_sketch_frequencies(stream_items: list[str], width_w: int, depth_d: int) -> dict:
    """Estimate item frequencies in O(w*d) memory via Count-Min Sketch (guaranteed zero underestimation)."""
    w = int(width_w)
    d = int(depth_d)
    if w < 2 or d < 1 or not stream_items:
        raise ValueError("Require width_w >= 2, depth_d >= 1, and non-empty stream_items.")

    table = np.zeros((d, w), dtype=np.int64)
    for item in stream_items:
        digest = hashlib.sha256(item.encode("utf-8")).digest()
        h1 = int.from_bytes(digest[:8], "big")
        h2 = int.from_bytes(digest[8:16], "big") | 1
        for r in range(d):
            col = (h1 + (r + 1) * h2 + 0x9E3779B97F4A7C15 * r) % w
            table[r, col] += 1

    exact = dict(Counter(stream_items))
    estimates: dict[str, int] = {}
    errors: list[int] = []
    for item, true_c in exact.items():
        digest = hashlib.sha256(item.encode("utf-8")).digest()
        h1 = int.from_bytes(digest[:8], "big")
        h2 = int.from_bytes(digest[8:16], "big") | 1
        est = min(
            int(table[r, (h1 + (r + 1) * h2 + 0x9E3779B97F4A7C15 * r) % w])
            for r in range(d)
        )
        estimates[item] = est
        errors.append(est - true_c)

    return {
        "estimates": estimates,
        "exact_counts": exact,
        "min_overestimate": min(errors),
        "max_overestimate": max(errors),
        "mean_overestimate": float(np.mean(errors)),
        "epsilon_bound_per_N": math.e / w,
    }

Exact Markov chain propagation (N=128, k=11): target k/N = 0.0859375000000000
Max |p_i(N) - k/N| across all 128 stream positions       = 6.939e-17

Exercises

Worked solutions are in 13_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Verify the Distributed Merge (Semilattice Join) Property of Bloom Filters: given two overlapping edge-sensor packet sets AA (500 IDs) and BB (500 IDs, sharing 200 common IDs so ∣A∪B∣=800|A \cup B| = 800 and ∣A∩B∣=200|A \cap B| = 200), construct bit vectors bA\mathbf{b}_A, bB\mathbf{b}_B, and centralized bA∪B\mathbf{b}_{A \cup B} using identical SHA-256 double hashing (m_bits = 8192, k_hashes = 7). Prove np.array_equal(b_A | b_B, b_AuB) bit-for-bit, and verify that bA∧bB\mathbf{b}_A \land \mathbf{b}_B achieves 0 false negatives on A∩BA \cap B while bounding its false-positive rate relative to bA∩B\mathbf{b}_{A \cap B}.

  2. Find how it fails. Diagnose two destructive streaming anti-patterns: (a) Compare Vitter’s vitter_reservoir_sample (N=40N = 40, k=5k = 5) against a naive unscaled replacement loop (reservoir[rng.integers(0, k)] = stream[t] for every t≥kt \ge k) across 4,0004{,}000 runs and verify the exact exponential forgetting formula pibuggy=1k(1−1k)N−1−ip_i^{\mathrm{buggy}} = \frac{1}{k}\left(1 - \frac{1}{k}\right)^{N - 1 - i} for i≥ki \ge k; (b) Sweep Bloom filter bit size mm downward from 8,0008{,}000 to 256 bits (plus excessive k=18k = 18 hashes) for n=800n = 800 items to expose catastrophic 100% bit-array saturation.

  3. Implement it yourself. Implement misra_gries_heavy_hitters(stream, k_counters) in pure Python/NumPy maintaining at most k_counters (item -> count) entries: if item is tracked, increment its counter; else if fewer than k_counters items are tracked, insert item: 1; else decrement all k_counters counters by 1 and purge zeros. Prove and verify on both a 10,000-element Zipfian telemetry stream and a worst-case adversarial stream that every decrement step cancels k+1k + 1 distinct items, guaranteeing fx−Nk+1≤c^x≤fxf_x - \frac{N}{k + 1} \le \hat{c}_x \le f_x and 100% recall of all heavy hitters with fx>Nk+1f_x > \frac{N}{k + 1}.


Self-check for the exercises
============================
All checks passed.