Back to Streaming Sketching

Heavy Hitters & Frequent Items

September 25, 2026 Wasil Zafar 14 min read

Recover frequent items without storing the universe.

Table of Contents

  1. Finding the Few Keys That Dominate
  2. Thresholds, Tails and Candidate Sets
  3. Why Frequent-Item Guarantees Differ
  4. Hot Shards, Trending Terms and Attack Traffic
  5. Build a Heavy-Hitter Decision Rule

Finding the Few Keys That Dominate

Imagine counting votes on a board with room for only a few names. If Alice appears repeatedly, her name should survive even while thousands of one-off names arrive. A heavy hitter is a key whose frequency exceeds a specified share of the stream; a candidate is a key retained for later checking. For the stream A, B, A, C, A, B, D, A, the frequency of A is 4 of 8, B is 2 of 8, and C and D occur once. At a threshold strictly above 1/4, A qualifies; B is exactly on the boundary and does not. Which names can we guarantee to keep with limited counters? What happens when an attacker spreads traffic across many keys? These questions connect point-frequency estimates from the previous chapter to a harder task: discovering which keys to query at all. A point query answers a supplied key; it does not enumerate the unknown keys. In telemetry and search logs, the universe of possible keys can dwarf the memory budget.

From repeated names to heavy hitter candidates Click log one key per event Frequency A occurs 4 of 8 Threshold more than 2 of 8 Candidate report A
TermMeaning and exact exampleNon-example or assumptionQuestion answered
Frequency $f_x$A occurs 4 times in 8 updatesA probability without a time window is not a countHow many updates had key $x$?
$\ell_1$ heavy hitterA has $4>8/4$ at $\phi=1/4$B has $2=8/4$ and fails a strict thresholdWho exceeds a fraction of all events?
CandidateA remains in a compact summaryRetention alone does not prove $f_A=4$Whose counts should be checked?
Top-$k$For $k=2$, A and B are largestA fixed threshold need not return exactly twoWhich keys rank highest?
Warm-up

Finding the Few Keys That Dominate

Write down A, B, A, C, A, B, D, A. Checkpoint 1: $N=8$ and $(f_A,f_B,f_C,f_D)=(4,2,1,1)$. Checkpoint 2: at strict threshold $\phi=1/4$, compare each count with 2. Expected output: only A; B lies on the boundary. Reflection: if one A becomes a new key E, does A still clear the threshold? Yes, $3>2$.

Thresholds, Tails and Candidate Sets

Let an insertion-only stream contain $N$ unit updates over universe $U$, with nonnegative frequencies $f_x$ and $\lVert f\rVert_1=N$. For $0<\phi<1$, an $\ell_1$ heavy hitter satisfies $f_x>\phi N$. There are fewer than $1/\phi$ such keys, but identifying them requires a candidate mechanism. An $\ell_2$ heavy hitter instead satisfies $f_x>\phi\lVert f\rVert_2$, where $\lVert f\rVert_2=(\sum_x f_x^2)^{1/2}$; the two threshold scales differ. A useful approximate reporting contract has an inclusion threshold $\phi N$ and an exclusion threshold $(\phi-\varepsilon)N$: include every key strictly above the first, exclude every key strictly below the second, and permit either decision inside the gap. This gap is necessary when frequencies have additive error $\varepsilon N$. A top-$k$ query asks for the $k$ largest frequencies, which does not imply a particular absolute threshold; ties require an explicit policy. With $m=\lceil1/\varepsilon\rceil-1$ counters, Misra–Gries retains every key with $f_x>\varepsilon N$ under unit insertions. This is a recall statement, not an exact-frequency statement. Space-Saving retains keys using a different replacement rule and upper estimates; its bounds also assume nonnegative unit arrivals.

Heavy Hitters & Frequent Items: Thresholds, Tails and Candidate Sets
flowchart TD
  A["Unit insertions; nonnegative counts"] --> B["N equals total updates"]
  B --> C["MG: at most N/(m+1) cancellations"]
  C --> D["All keys above N/(m+1) retained"]
  D --> E["Verify candidates for reporting"]
  A --> F["L2 norm defines another threshold"]
  classDef navy fill:#17365D,color:#fff
  classDef teal fill:#147D84,color:#fff
  classDef crimson fill:#C6284D,color:#fff
  classDef purple fill:#6C3BAA,color:#fff
  class A,B navy
  class C,D teal
  class E crimson
  class F purple
Insertion stream, frequency vector, thresholds, and candidate output Stream positive unit events Vector f sum f = N Threshold phi times N Candidates verify estimates
Definition or claimExact scopeCounterexample or consequence
$\ell_1$ heavy$f_x>\phi\lVert f\rVert_1$ for nonnegative $f$A boundary equality is not heavy under $>$
$\ell_2$ heavy$f_x>\phi\lVert f\rVert_2$With counts $(4,1,1,1,1)$, norm $\sqrt{20}$, so threshold differs from $\phi\cdot8$
MG recallWith $m$ counters and unit insertions, $f_x>N/(m+1)$ implies retainedAn absent key can have frequency exactly $N/(m+1)$
Approximate reportInclude above $\phi N$; exclude below $(\phi-\varepsilon)N$No specified decision in the gap; this is intentional
Top-$k$Return keys with largest $k$ counts under a tie ruleIf all $k$th counts tie, there may be more than $k$ eligible keys

Every full decrement removes one unit from $m$ distinct counters while consuming a new, different key, so it accounts for $m+1$ arrivals. After at most $N/(m+1)$ such rounds, any key above that frequency must still have a counter; this requires insertion-only unit updates.

Why Frequent-Item Guarantees Differ

The key accounting idea is cancellation. Misra–Gries either increments an existing key, opens a free counter, or decrements all $m$ stored counters when a new key arrives and all counters are occupied. Each decrement can be charged to a group of $m+1$ distinct stream occurrences: the incoming occurrence plus one occurrence represented by each counter. If there are $D$ global decrement rounds, $(m+1)D\leq N$. For every key, its final stored counter (zero if absent) lies between $f_x-D$ and $f_x$. Hence an absent key has $f_x\leq D\leq N/(m+1)$, proving the candidate guarantee. The proof uses positive unit arrivals and distinct occupied keys. For weighted positive updates, a unit expansion or properly weighted variant is needed; for deletions, cancellation cannot simply reuse this invariant. Space-Saving replaces a minimum counter of value $c$ with the new key and value $c+1$, retaining an error field $c$: an existing key's true frequency lies between estimated count minus error and estimated count. The minimum counter and bounded error support candidate recall, but neither method certifies exact ranks from its counters alone. A second pass can count the survivors exactly; otherwise pair with a point-query sketch and account for its own error and probability.

Misra Gries cancellation of three distinct occurrences Before A:2 B:1 Arrival C is unseen Cancel A:1 B:0 Charge A, B, C group
Heavy Hitters & Frequent Items: Why Frequent-Item Guarantees Differ
flowchart TD
  A["Unit insertions"] --> B["Every decrement charges m+1 distinct occurrences"]
  B --> C["D at most N/(m+1)"]
  C --> D["Absent key count at most D"]
  D --> E["Above threshold implies retained"]
  A --> F["Deletion or incompatible weights"]
  F --> G["Cancellation proof fails"]
  classDef navy fill:#17365D,color:#fff
  classDef teal fill:#147D84,color:#fff
  classDef crimson fill:#C6284D,color:#fff
  classDef purple fill:#6C3BAA,color:#fff
  class A,B navy
  class C,D teal
  class E purple
  class F,G crimson
Worked Derivation

Why Frequent-Item Guarantees Differ

Trace Misra–Gries with $m=2$ on A, B, C, A, A, B, A. After A,B: $(A:1,B:1)$. Arrival C cancels both, yielding no counters and $D=1$. The remaining A,A,B,A yields $(A:3,B:1)$; exact counts are $(4,2,1)$, and each deficit is at most 1. Since $N=7$, any key with $f_x>7/3$ must survive; A does. Variation: interpret a later “delete A” as a negative update. The unit-insertion charge no longer justifies $N/3$ from a signed stream; state the update model before reusing the theorem.

ToolEstablishesAssumption and tight caseFailure or limit
MG group charge$D\leq N/(m+1)$ and recall above this boundDistinct occupied keys, positive unit events; cycle of $m+1$ keys reaches equalityDoes not give exact frequencies
MG residual counter$f_x-D\leq c_x\leq f_x$Every decrement removes at most one from each keySigned deletions break the accounting
Space-Saving error field$\widehat f_x-e_x\leq f_x\leq\widehat f_x$ for tracked keysInsertion-only events, replacement from a minimum counterA stored upper estimate does not certify top-$k$ ordering
Exact second passExact $f_x$ for supplied candidate namesReplayable stream, unchanged intervalCannot recover a missing name if candidate recall failed

For a small website, count product clicks in a rolling batch to locate popular products; one key per click and a fixed reporting interval make the insertion model credible. At production scale, a router might process $10^8$ requests per minute across millions of customer IDs with room for only a few hundred counters per shard. Define whether the objective is per-shard or global heavy hitters: a key spread across shards can be globally heavy without qualifying locally. Candidate sets from all shards may be unioned and verified against merged frequency summaries or exact logs, subject to their error budgets and merge rules. For attack traffic, a bot can rotate identities so no single ID exceeds the threshold even while one source controls substantial volume. The mathematical guarantee is still valid for the chosen key, but its operational interpretation fails; aggregate by an appropriate trusted identity or combine with other signals. Window expiry and deletions also invalidate insertion-only proofs unless the system rebuilds per window or uses a compatible turnstile/windowed method.

Boundaries in a frequent item monitoring pipeline Events identity trust Window clock boundary Summary approximate set Verify decision audit
Case Study

Hot Shards, Trending Terms and Attack Traffic: Heavy Hitters & Frequent Items

A shop records twelve clicks: P, Q, P, R, P, Q, S, P, T, Q, P, R. Select the insertion-only $\ell_1$ model with one key per click. Exact counts are $f_P=5$, $f_Q=3$, $f_R=2$, $f_S=f_T=1$. For strict $\phi=1/4$, the cutoff is 3, so only P qualifies; Q equals the cutoff. With $m=3$ MG counters, every key above $12/4=3$ is guaranteed retained. Hand trace or replay, then check whether P survives. Success criterion: candidate list contains P and final verified report contains only P; explain why Q is excluded.

Production

Hot Shards, Trending Terms and Attack Traffic: Heavy Hitters & Frequent Items

A service logs $10^8$ requests each minute from roughly $10^7$ tenant IDs across 40 shards, with 256 counters available per shard. Set the reporting goal to global tenants above 1% of the minute's total, with no tenant below 0.8% reported. A per-shard threshold based on local volume may miss a globally large tenant whose activity is evenly distributed; collect candidates using a global-compatible threshold and union names, then verify from replayable logs or a merged point-query summary with error at most 0.2% of global $N$. Check counter and merge semantics before claiming full recall. Evidence: exact sampled minutes, missing-candidate rate, false-positive rate, peak memory, processing latency, skew across shards, and clock-boundary tests. Written decision: use candidate generation plus verification only if the measured coverage and specified guarantees hold for the actual shard and window model; escalate rotating-ID abuse to identity aggregation and a different threat model.

Build a Heavy-Hitter Decision Rule

Choose a signal, key, time horizon, threshold and allowable uncertainty before selecting a summary. Start from a desired guarantee: full recall above $\phi N$, no reports below $(\phi-\varepsilon)N$, or a ranked top-$k$ with an explicit tie rule. Compute the memory implied by candidate generation, then budget verification error separately. Compare exact counts on a small trace, stress boundary cases, and document whether updates can be negative or adversarial. The exercises below turn those decisions into reproducible artifacts. The frequency-estimation prerequisite explains why a sketch can verify nominated keys but cannot by itself discover arbitrary names; the next useful bridge is frequency moments and norms, whose $\ell_2$ scale changes what “heavy” means.

Practice

Practice: Build a Heavy-Hitter Decision Rule

Tier 1 (definitions): on $(5,3,2,1,1)$ and $\phi=1/4$, compute $N=12$, $\lVert f\rVert_2=\sqrt{40}$ and list strict $\ell_1$ heavy hitters (only the key with 5); explain the equality case for 3. Tier 2 (trace): run $m=2$ MG on A,B,C,A,A,B,A; record counters after every update and $D=1$, and compare $c_A=3$ with $f_A=4$. Tier 3 (proof): explain why one decrement charges three distinct occurrences, then derive $D\leq7/3$ and why any absent key has count at most $D$. Tier 4 (counterexample): apply the same claim to a stream with a deletion and point out exactly which charging step lacks justification. Tier 5 (decision): for $10^6$ events and desired recall above 1%, choose $m=99$ (threshold $N/100$), specify whether the strict boundary is included, and propose an exact second pass or a point-query error budget. Deliver a definition sheet, seven-row trace, four-line proof, counterexample, and a one-paragraph system choice. Rubric: 2 points each for correct boundary, trace, proof, model critique, and verification plan; pass at least 8/10 with no missed heavy hitter. Debugging prompt: if a retained count exceeds the true count in your MG trace, revisit the update rule. Stretch: compare Space-Saving upper estimates and an $\ell_2$ threshold on the same counts. Reflection: which part would change if only a sliding window were relevant?

Decision checklist: define key and window; specify insertion-only or signed updates; choose $\ell_1$, $\ell_2$, or top-$k$ and a strict boundary; size the candidate summary; verify counts and error before acting. A candidate is not an exact frequency, and a point-query sketch does not discover unknown keys: revisit frequency estimation for verification and frequency moments for the $\ell_2$ scale.

Next in the Series

In Frequency Moments, Norms & Entropy, we'll explore Estimate global norms and distribution statistics..