Sub topic 10
Tracking Heavy Hitters with a Sketch and a Heap
This chapter assumes you know the CountMinSketch class from the earlier chapters (add, estimate, and the one-sided error guarantee). It also assumes basic Python, heaps, and dictionaries.
The problem: which items are frequent?
A count-min sketch answers point queries. You give it an item and it returns a count estimate. It cannot list its items, because the table stores only sums of counters and never stores the items themselves.
Many real tasks need the list. Examples are the most requested URLs, the noisiest IP addresses, and the most common search queries. Items that account for a large share of a stream are called heavy hitters. There are two common definitions:
- Top-k: the k items with the highest counts.
- Threshold (φ-heavy hitters): every item whose true count is at least φ·N, where N is the stream length and φ is a fraction such as 0.01.
The usual solution is to keep the sketch for counting and add a small side structure that remembers candidate items. The sketch gives the counts. The side structure gives the names.
The design: sketch plus a bounded heap
For top-k, keep three things:
- The sketch, with fixed size
w × d. - A dictionary
trackedthat maps each candidate item to its latest estimate. It never holds more than k entries. - A min-heap of
(estimate, item)pairs, so the weakest candidate is always atheap[0].
For each arriving item, the algorithm does the following:
- Add the item to the sketch and read back its new estimate.
- If the item is already tracked, update its stored estimate.
- If it is new and there is room (fewer than k tracked), insert it.
- If it is new and the structure is full, compare its estimate with the smallest tracked estimate. If it is larger, evict the smallest and insert the newcomer. Otherwise ignore it.
Total memory is w·d counters plus about k items. It does not depend on the number of distinct items in the stream.
Implementation
This code assumes the CountMinSketch class from the earlier chapter is saved in cms.py.
import heapq
import random
from collections import Counter
from cms import CountMinSketch
def top_k(stream, k, epsilon=0.001, delta=0.01):
cms = CountMinSketch(epsilon, delta)
heap = [] # min-heap of (estimate, item)
tracked = {} # item -> latest estimate stored for it
for item in stream:
cms.add(item)
est = cms.estimate(item)
if item in tracked:
tracked[item] = est
heap = [(tracked[i], i) for i in tracked]
heapq.heapify(heap)
elif len(tracked) < k:
tracked[item] = est
heapq.heappush(heap, (est, item))
elif est > heap[0][0]:
_, evicted = heapq.heapreplace(heap, (est, item))
del tracked[evicted]
tracked[item] = est
return sorted(tracked.items(), key=lambda kv: -kv[1])
stream = ["a"] * 5000 + ["b"] * 3000 + ["c"] * 2000
stream += [f"tail{i}" for i in range(2000)] # 2000 distinct items, once each
random.Random(1).shuffle(stream)
truth = Counter(stream)
result = top_k(stream, k=3)
print(result)
assert [item for item, _ in result] == ["a", "b", "c"]
for item, est in result:
assert est >= truth[item] # one-sided error still holdsThe stream has 12,000 items. With epsilon=0.001 the table has 2,719 columns, so each counter receives about 4 collision counts from the tail items. The estimates for a, b, and c land a few counts above 5000, 3000, and 2000. The exact overshoot depends on the hash values, so the output varies slightly between runs. The ordering does not, because the gaps are large.
Why a repeat item rebuilds the heap
When a tracked item's count rises, its old (estimate, item) pair in the heap is stale. The simple version above rebuilds the heap, which costs O(k) for each repeat of a tracked item. That is clear and correct, but slow if k is large. Two common fixes:
- Lazy deletion: push a new pair every time and leave the old one in place. When you read
heap[0], pop it while its estimate no longer matchestracked[item]. The heap grows with stale entries, so rebuild it occasionally. - Indexed heap: keep each item's position in the heap and sift it down after increasing its key. This gives O(log k) updates.
Why the approach is sound
The sketch never undercounts, so estimate(x) >= f(x), where f(x) is the true count. This gives two properties.
Threshold queries have no false negatives. Suppose item x has f(x) >= φN. Then its estimate is at least φN, so at the end of the stream it passes the test estimate >= φN. Every true heavy hitter is therefore found (the guarantee is for a fixed item and holds with probability at least 1 − δ).
False positives are bounded. An item with a small true count can only pass the test if collisions inflate it. With probability at least 1 − δ, it has estimate <= f(x) + εN. So any reported item has f(x) >= (φ − ε)N. Choose ε well below φ. For example, with φ = 0.01 use ε = 0.001, so no reported item has a true frequency under 0.9%.
For a threshold query you also need N, the stream length so far. The sketch class from earlier already tracks it in self.total. Because N grows, the threshold φN grows too. An item that looked heavy early on may fall below the threshold later. So filter candidates against the current φN when you report, not only when you insert.
| Query type | Needs | Guarantee |
|---|---|---|
| Top-k | k, and heap of size k | The true top items are usually found if their counts clearly exceed the rest. No strict guarantee otherwise. |
| Threshold φ | φ, ε, and N | All items with `f >= φN` are reported. No reported item has `f < (φ − ε)N`, each with probability at least 1 − δ. |
Edge cases and failure modes
- Estimates stored in the heap go stale. A tracked item's stored estimate was correct when it was written. It is replaced when the item next arrives. Items that were evicted can return with a higher estimate and re-enter, which is expected.
- An item can enter late. If the heap is full of items with estimates above a heavy item's early estimate, the heavy item is skipped for now. Its estimate grows with every arrival, so it enters when it passes the minimum. This is why the comparison uses the sketch estimate and not a count since last seen.
- Evicted items lose nothing in the sketch. Eviction removes the name from the candidate list only. The counters still include its occurrences, so a later
estimatecall is still valid. - Wide tails inflate everything. The overcount is up to εN, where N counts every item, not only distinct ones. A very long stream with a small ε needs a larger table. Size the sketch for the N you expect.
- Insert-only assumption. The no-false-negative argument depends on counts only going up. With deletions the one-sided property fails, as a later chapter covers.
- Hash stability. Python's
hash()for strings is randomized per process. Within one run it is consistent, which is enough here. If you save or share sketches, use a stable hash.
Choosing parameters in practice
Pick ε relative to the frequency you care about. If you want items above 1% of traffic, ε of 0.001 to 0.0025 keeps the false-positive floor close to the target. The width is ⌈e/ε⌉, so ε = 0.001 gives 2,719 columns. Depth ⌈ln(1/δ)⌉ is 5 for δ = 0.01. That is 13,595 counters in total, plus k tracked entries.
Compare this with an exact Counter, which needs one entry per distinct item. For a stream with hundreds of millions of distinct items, the sketch's fixed few thousand counters are the difference between fitting in memory and not.
Exercise
A stream has N = 2,000,000 items. You want to report every item with true count at least 1% of N, and you want no reported item to have a true count below 0.8% of N, each with probability at least 0.99. (a) What ε and δ do you choose? (b) What are the sketch dimensions w and d? (c) Item "x" has a true count of 22,000. Can the threshold query miss it? Item "y" has a true count of 15,000. Could it be reported?
Show answer
(a) φ = 0.01 and the floor is φ − ε = 0.008, so ε = 0.002. A 0.99 success probability means δ = 0.01. (b) w = ⌈e/0.002⌉ = ⌈1359.1⌉ = 1360 and d = ⌈ln(100)⌉ = ⌈4.6⌉ = 5. (c) The threshold is φN = 20,000. Item "x" has 22,000, and estimates never undercount, so its estimate is at least 22,000 and it is not missed. Item "y" has 15,000, which is below the floor of (φ − ε)N = 16,000. With probability at least 0.99 its estimate is at most 15,000 + εN = 19,000, which is under 20,000, so it is not reported. It could be reported only in the failure case, which has probability at most δ = 0.01.
Exercise
In the top_k function, a heavy item "h" arrives for the first time when the heap is full and every tracked estimate is at least 1. Its estimate right after the add is 1. Is "h" inserted? Will it ever be inserted if it is truly heavy?
Show answer
Not on that arrival, because the test is est > heap[0][0] and 1 is not greater than a minimum of 1 or more. It is inserted later. Each arrival raises its estimate by at least 1 (the estimate never decreases), while the tail items that fill the heap stay small. Once its estimate exceeds the heap minimum, the test passes and it replaces the minimum.