Back to Streaming Sketching

Approximate Counting & Stream Sampling

September 25, 2026 Wasil Zafar 18 min read

Count and sample streams with sublinear state.

Table of Contents

  1. Counting Giants with Tiny State
  2. Counters, Samples and Inclusion Probabilities
  3. Unbiased Estimates, Variance and Merge Rules
  4. Traffic Sampling, Reservoirs and Rare Events
  5. Design a Memory-Bounded Measurement Plan

Counting Giants with Tiny State

Imagine a concert entrance with millions of arrivals but room for only a tiny notebook. One question is “roughly how many arrived?” Another is “which arrivals should we inspect later?” A compact counter addresses the first; a sample of records addresses the second. Both give up information, but in different ways. A count cannot reconstruct visitor attributes, and a few saved visitors cannot automatically give an accurate answer about a very rare group.

If four people arrive, an exact tally ends at $4$. A deliberately small randomized counter might instead finish with a value whose decoded estimate is $3$ or $7$; a guarantee describes its behavior over the counter's random choices, not that one run equals four. For sampling, suppose we keep one uniformly selected arrival from a four-person stream. Each person must have final selection probability $1/4$, even though the first person was once certain to be held. This is why an update rule needs a proof.

The preceding chapters introduced stream models, probability bounds, and controlled randomness. Here those tools answer three questions: What statistic is estimated? Which individual records can enter the sample, and with what probability? Which operations, such as merging workers or deleting events, preserve the stated guarantee? We start with insert-only streams of individually identified arrivals unless a different model is stated.

Two compact views of an arrival stream ArrivalsA B C D … Tiny counter → approximate totalquestion: how many? Small reservoir → selected recordsquestion: which examples? Neither output stores the entire stream.
TermConcrete meaning and exampleBoundary or non-exampleQuestion answered
Exact totalFour arrivals give $N=4$Does not retain their recordsHow many events occurred?
Approximate counterA randomized state $C$ decodes to an estimate of $N$Unbiasedness does not mean exact every runHow can state grow slowly with $N$?
Bernoulli sampleRetain each arrival independently with probability $p$Sample size is randomWhich records survive independent coin flips?
Reservoir of size $k$Hold a uniform subset of $k$ of the first $t$ arrivals when $t\ge k$“First $k$” is biased toward early arrivalsHow can sample size stay fixed?
Inclusion probability$\pi_i=\Pr(i\text{ is retained})$May differ between weighted itemsHow should an observed record be weighted?
Sampling unitA request, user, or distinct key, specified in advanceTen requests from one user are not ten distinct usersWhat population is represented?
Warm-up

Counting Giants with Tiny State

Write arrivals $A,B,C,D$ on paper. For a one-slot reservoir, keep A first; at step $t=2,3,4$, replace the held item with the new arrival with probability $1/t$. Checkpoint: A survives steps 2–4 with probability $(1/2)(2/3)(3/4)=1/4$. D enters at the last step with probability $1/4$. Expected: all four arrivals have final probability $1/4$. Reflection: if arrivals were users but one user generated three of these events, would this be a uniform user sample?

Counters, Samples and Inclusion Probabilities

Morris counting. Start an integer state $C=0$. On each insert-only arrival, increment $C$ with probability $2^{-C}$; otherwise leave it unchanged. Decode with $\widehat N=2^C-1$. The state increases rarely when it is large, using roughly $\log_2 N$ possible state values, or about $\log_2\log_2 N$ bits to represent the state at scale $N$ (ignoring fixed machine ranges and random-bit costs). The decoded answer is random and may be far from the true count in one run. It is an estimate of the number of processed insertions, not of distinct keys or the current total after arbitrary deletions.

Bernoulli sampling. For a fixed stream of $N$ records, independently retain record $i$ with probability $p_i$ known in advance or recorded when chosen. If all probabilities equal $p$, the retained count $S$ has expectation $Np$ and $S/p$ is unbiased for $N$. The sample size varies. For a property $y_i$, the inverse-probability estimator $\widehat T=\sum_{i\text{ retained}}y_i/p_i$ has expectation $T=\sum_i y_i$ when each $p_i>0$ and the decisions have those marginals. Independence is not needed for that expectation, but it affects variance. A changed or unknown selection probability invalidates the weighting argument.

Reservoir sampling. Hold the first $k$ arrivals. For arrival $t>k$, accept it with probability $k/t$ and, if accepted, replace a uniformly chosen held item. At time $t\ge k$, each arrival has inclusion probability $k/t$, and the held set is a uniform size-$k$ subset of the first $t$ distinct arrival positions. This is without replacement over positions. It does not sample unique values uniformly when duplicates arrive.

Bottom-$k$ and weighted priority. Give each unique record ID an independently uniform continuous rank in $(0,1)$ and keep the $k$ smallest ranks; for a fixed population, this gives a uniform subset of size $k$ with probability $k/N$ per item. Deterministic seeded hash ranks approximate this ideal only to the extent their proven independence or min-wise properties justify it; ties need a stable rule. For positive item weights $w_i$, an ideal weighted priority can use an independent uniform $U_i$ and score $E_i=-\ln(U_i)/w_i$, retaining small scores. The first selected item has probability $w_i/\sum_jw_j$. For a multi-item weighted sample, inclusion probabilities depend on the procedure and other weights; they are not generally $kw_i/\sum_jw_j$. These are distinct sampling contracts, not interchangeable variants.

Approximate Counting & Stream Sampling: Counters, Samples and Inclusion Probabilities
flowchart TD
    A["Insert-only arrival positions"] --> Q{"Which output?"}
    Q -->|Volume| M["Morris state C"]
    M --> N["Estimate 2^C minus 1"]
    Q -->|Independent records| B["Bernoulli decisions"]
    B --> P["Known inclusion probabilities"]
    Q -->|Fixed number of records| R["Reservoir or bottom-k"]
    R --> U["Uniform subset if assumptions hold"]
    Q -->|Weight-biased selection| W["Exponential priorities"]
    W --> V["Weight-specific inclusion analysis"]
    classDef navy fill:#17365D,color:#fff,stroke:#17365D;
    classDef teal fill:#147D84,color:#fff,stroke:#147D84;
    classDef crimson fill:#C6284D,color:#fff,stroke:#C6284D;
    classDef purple fill:#6C3BAA,color:#fff,stroke:#6C3BAA;
    class A,Q navy; class M,N,B,P teal; class R,U purple; class W,V crimson;
Annotated reservoir update and inclusion probabilities New arrival tposition in stream Admit with k/treplace one of k slots Reservoir after teach position: chance k/t An earlier held record is evicted with probability (k/t) × (1/k) = 1/t.
Method or claimExact scope and formulaAssumptionCounterexample or consequence
Morris estimate$\widehat N=2^C-1$ with increment probability $2^{-C}$Individual insertions, fresh conditional random choiceA deletion has no inverse update in this basic rule
Bernoulli sample$\pi_i=p_i$; equal $p$ gives $\mathbb E[S/p]=N$Selection probabilities known and positiveUnknown ingestion drops cause bias
Reservoir size $k$Each position has $\pi_i=k/t$ after $t\ge k$One arrival order, uniform replacement choiceKeeping first $k$ overrepresents early events
Bottom-$k$Independent continuous ranks give uniform size-$k$ subsetStable IDs and suitable independent ranksReused rank for duplicate values changes the population
Weighted priorityFor one draw, $\Pr(i\text{ first})=w_i/\sum_jw_j$Positive fixed weights, independent exponential scoresMulti-item inclusion is not simply $kw_i/\sum_jw_j$
Without replacementA held arrival position appears at most onceSampling unit defined as an arrival positionA repeated user ID can appear in multiple sampled positions

The reservoir's invariant concerns arrival positions: after $t\ge k$ inserts, every size-$k$ subset of the first $t$ positions is equally likely. Thus each position's inclusion probability is $k/t$; this says nothing about uniformity over distinct users unless users themselves are the sampling units.

Unbiased Estimates, Variance and Merge Rules

The Morris estimator's unbiasedness follows from one conditional step. At state $C$, an increment changes $2^C$ by $2^C$; it occurs with probability $2^{-C}$. Hence the conditional expected change in $2^C-1$ is exactly $1$. Starting at zero, $\mathbb E[\widehat N]=N$ after $N$ insertions. The variance quantifies why this alone is a weak per-run promise. Let $A_N=\mathbb E[2^{C_N}]$ and $B_N=\mathbb E[4^{C_N}]$. The update gives $A_N=N+1$ and $B_{N+1}-B_N=3A_N$. Summing yields $B_N=1+3N(N+1)/2$ and therefore $\operatorname{Var}(\widehat N)=N(N-1)/2$. Relative standard deviation approaches $1/\sqrt2$, so achieving small relative error needs a modified counter design or independent replicas and a justified aggregation rule.

For equal-probability Bernoulli sampling, write $S=\sum_{i=1}^N I_i$ with independent indicators of mean $p$. Then $\mathbb E[S/p]=N$ and $\operatorname{Var}(S/p)=N(1-p)/p$. A property total $T$ can be estimated by weighting observed values by reciprocal inclusion probability; its variance depends on joint inclusion probabilities when sampling decisions are dependent. For a fixed-size reservoir, the naive sample fraction is unbiased for a population fraction, while an observed count without scaling is generally not an estimate of the full count.

To prove the reservoir invariant, the new position is included with probability $k/t$. Any older position held at step $t-1$ survives step $t$ with probability $1-(k/t)(1/k)=1-1/t$. By induction its final inclusion probability is $(k/(t-1))((t-1)/t)=k/t$. To prove the stronger uniform subset claim, consider a particular size-$k$ subset: if it excludes the new item, the previous same subset must survive; if it includes the new item, one of its $k$ possible predecessor subsets must replace the correct old position. Both cases give probability $1/\binom tk$.

Merging needs a separate theorem. Independently generated Morris states cannot simply be added: $C_A+C_B$ decodes to $(2^{C_A+C_B}-1)$, generally unrelated to $N_A+N_B$. Two one-slot uniform reservoirs from shards of sizes $n_A,n_B$ can be merged by choosing shard A's held item with probability $n_A/(n_A+n_B)$ and B's otherwise; the result is uniform over the union of arrival positions. For larger reservoirs, a merge needs a size-aware procedure. Bottom-$k$ can retain the $k$ smallest ranks from the union of local bottom-$k$ lists if every worker uses consistent ranks for the same unique IDs and the population/duplicate policy is explicit. Distinct worker seeds or mismatched key encodings break that identity.

One decisive step of the reservoir proof After t−1 arrivalsolder item: k/(t−1) Step t survival1 − 1/t After t arrivalsolder item: k/t Multiply prior inclusion by conditional survival; do not assume the record is always held.
Approximate Counting & Stream Sampling: Unbiased Estimates, Variance and Merge Rules
flowchart TD
    A["Choose target and sampling unit"] --> C{"Which estimator?"}
    C -->|Morris| M["Conditional mean increment = 1"]
    M --> V["Compute variance; unbiased is not precise"]
    C -->|Reservoir| R["New item k/t; old survives 1−1/t"]
    R --> U["Uniform subset by induction"]
    C -->|Bernoulli| B["Known inclusion probabilities"]
    B --> H["Inverse-probability total"]
    V --> G{"Need to merge shards?"}
    U --> G
    H --> G
    G --> D["Use a method-specific merge proof"]
    classDef navy fill:#17365D,color:#fff,stroke:#17365D;
    classDef teal fill:#147D84,color:#fff,stroke:#147D84;
    classDef crimson fill:#C6284D,color:#fff,stroke:#C6284D;
    classDef purple fill:#6C3BAA,color:#fff,stroke:#6C3BAA;
    class A,C navy; class M,R,B,U,H teal; class V,D crimson; class G purple;
Worked Derivation

Unbiased Estimates, Variance and Merge Rules

Given: a basic Morris counter starts at $C=0$ and processes two insertions. The first always increments to $C=1$. The second increments with probability $1/2$, yielding final $C=2$ and estimate $3$; otherwise $C=1$ and estimate $1$. Checkpoint: $\mathbb E[\widehat N]=(3+1)/2=2$ and $\operatorname{Var}(\widehat N)=((3-2)^2+(1-2)^2)/2=1$, agreeing with $N(N-1)/2$ at $N=2$. Variation: if the same biased random bit is reused or the second increment probability is set to $1/4$, the conditional-increment proof no longer gives expectation $2$ (with $1/4$, the expectation is $1.5$). Merge challenge: do not add two stored Morris states and assume their decoded sum estimates the combined stream.

Reasoning toolWhat it establishesAssumptions and scopeFailure case
Conditional expectation$\mathbb E[\widehat N]=N$ for basic MorrisCorrect state-dependent coin on each insertIncrement probability changed without recalibration
Second moment$\operatorname{Var}(\widehat N)=N(N-1)/2$Basic base-two process and insert-only streamAssuming unbiasedness implies small relative error
Inclusion indicators$\mathbb E[\sum I_i y_i/p_i]=\sum y_i$Every $p_i>0$ is known for the target populationMissing events before sampling have no valid $p_i$
Reservoir inductionEvery arrival position has probability $k/t$Correct admission and uniform replacementFirst-$k$ retention biases early arrivals
One-slot shard mergeChoose shard with probability proportional to its sizeEach shard's held item uniform within that shardChoosing two shards equally when sizes differ
Bottom-$k$ mergeGlobal $k$ smallest lie in union of local $k$ smallestSame stable ranks, compatible populations, tie ruleDifferent seeds across shards

Traffic Sampling, Reservoirs and Rare Events

Approachable audit. A school receives six anonymous survey cards in arrival order and wants to inspect two. A two-slot reservoir gives each card probability $2/6=1/3$ of inclusion. If the first four cards happen to report a positive experience and the last two a negative one, keeping the first two would systematically conceal the negatives; a uniform reservoir does not. But after any single realization, two cards remain too few for a strong conclusion about a rare complaint rate. The formal population is cards, not students, if one student may submit several cards.

Production network telemetry. Suppose a gateway processes $100{,}000$ requests per second and retains each request independently with probability $p=0.001$. Expected retention is $100$ records per second, and each retained request can represent $1{,}000$ requests in an inverse-probability total. Over one second, the count estimator has variance $N(1-p)/p\approx99{,}900{,}000$, giving standard deviation about $9{,}995$ around $N=100{,}000$. These are stylized fixed-rate calculations; drops before the sampler, bursts, retention capacity, user-level correlations, and privacy rules require separate treatment. A fixed-size reservoir helps bound stored record count; Bernoulli sampling gives independent decisions and simpler scaling but variable output volume.

Rare and adversarial events. If an event type has true fraction $q=10^{-5}$ among requests, retaining each request with probability $p=0.001$ yields an expected $Np q$ rare retained events. Over $N=100{,}000$ requests, that is $0.001$; under independent selection and a fixed population with exactly one rare event, the chance of capturing it is only $0.001$. Weighting a retained rare event by $1/p$ does not make it likely to be retained. An attacker who changes event volume or chooses IDs after learning a seeded bottom-$k$ ranking may invalidate a fixed-stream guarantee. Rare-event monitoring needs stratification, targeted collection, or another explicit design, with new inclusion probabilities and threat assumptions.

Sampling boundaries in a telemetry pipeline Requests100,000 per second Ingest boundarydrops or duplicates? Sample decisionrecord probability p Outputsrecords + estimates Low inclusion probability can miss a rare event even with unbiased weighting.
Case Study

Traffic Sampling, Reservoirs and Rare Events: Approximate Counting & Stream Sampling

Inputs: six ordered cards $P,P,P,P,N,N$; hold exactly two cards. Model selection: uniform two-slot reservoir over arrival positions, not a fixed first-two inspection. Hand calculation: after all six arrivals, each card has inclusion probability $2/6=1/3$; the expected number of negative cards held is $2(1/3)=2/3$. The probability of seeing no negative card is $\binom42/\binom62=6/15=0.4$, so the chance of seeing at least one is $0.6$. Expected observation: fairness of inclusion does not guarantee a negative card in a particular sample. Success criterion: derive the per-card inclusion, list the 15 equally likely pairs, and identify the sampling unit. Changed assumption: duplicate cards from one student would require a user-level sampling plan if the target is students.

Production

Traffic Sampling, Reservoirs and Rare Events: Approximate Counting & Stream Sampling

Workload: $100{,}000$ requests/s at an edge gateway, $p=0.001$ Bernoulli retention, a strict storage ceiling, and a rare incident type. Decision record: estimate $100$ retained requests/s and explicitly size buffers for variability, not just the mean; record that $S/p$ estimates processed arrivals under independent decisions, with approximate standard deviation $9{,}995$ for a fixed one-second total of $100{,}000$. Evidence: measure events dropped before sampling, realized inclusion rates by region and traffic class, rare-event coverage, retries, and seed correlation. Design choice: use a bounded reservoir for record review when a hard item count matters, or Bernoulli sampling with backpressure handling and known $p_i$ for weighted totals; add an explicit targeted path for high-priority incidents. Acceptance: document the target population, selection probabilities, memory and throughput limits, confidence criterion, merge policy, and what invalidates the guarantee. Do not label a missing rare incident as evidence that none occurred.

Design a Memory-Bounded Measurement Plan

Begin with the unit and statistic, then select a mechanism whose probability statement answers that question. Check the representation cost of a counter or retained records, the randomness source, and how the result is updated and merged. The exercises below progress from a simple trace to a production decision with falsifiable criteria.

Practice

Practice: Design a Memory-Bounded Measurement Plan

Level 1 — Define (2 points). Distinguish an approximate arrival count, a fixed-size sample of arrival positions, and a distinct-user sample. Expected: three different targets, with duplicate-user events illustrating why the latter two differ. State which one a basic Morris counter estimates.

Level 2 — Derive (2 points). Trace a Morris counter for two inserts. Expected: after the first it is $C=1$; after the second its estimate is $1$ or $3$ with probability $1/2$ each, giving mean $2$ and variance $1$. Hint: condition the next increment on the current state.

Level 3 — Prove and test (2 points). For a reservoir of size $k=2$ after $t=5$ arrivals, give the new item's admission probability and an earlier item's survival probability at that step. Expected: $2/5$ and $1-1/5=4/5$ conditional on already being held; earlier item's final inclusion is $(2/4)(4/5)=2/5$. Counterexample: show why replacing a random slot on every arrival is not uniform.

Level 4 — Apply (2 points). With $N=1{,}000$, $p=0.1$, compute expected Bernoulli sample size, estimator mean, and count-estimator variance. Expected: $100$, $1{,}000$, and $N(1-p)/p=9{,}000$. If records were dropped upstream, state why this estimate may target only the observed stream.

Level 5 — Extend (2 points). Two regions have sizes $90$ and $10$, each with one uniform retained item. Choose a region with probabilities $0.9$ and $0.1$, then output its item; verify a given record in either region has probability $1/100$. Artifacts: a diagram of the sampling unit and merge rule, a table of inclusion probabilities, and a short threat analysis for duplicate IDs, unequal rates, and deletions. Stretch: specify consistent-rank bottom-$k$ merging and why mismatched hash seeds fail. Rubric: full credit states all conditional probabilities, memory costs, target population, and a measurable audit of realized retention.

Before deploying a small counter or sample, name the population and statistic, the inclusion or state-transition probabilities, the uncertainty measure, the insert/delete model, and the shard merge rule. Check rare-event coverage and upstream data loss separately; the next sketch topics build on these distinctions when estimating membership, cardinality, and frequencies.

Next in the Series

In Membership Filters & Duplicate Detection, we'll explore Trade bounded false positives for compact membership state..