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 and estimate), basic Python, and how a min-heap works.
The problem: a sketch cannot list its items
A heavy hitter is an item whose count is at least a fraction φ of the stream length N. Examples are the most-searched queries, the busiest IP addresses, and the most-played songs.
A count-min sketch answers "how often did X appear?" It cannot answer "which items appeared most often?" The table holds only mixed counters, so no item names are stored. To find the top items, you must keep a short list of candidates next to the sketch.
The idea: sketch for counts, heap for candidates
Keep two structures:
- The sketch, which gives a count estimate for any item in fixed memory.
- A min-heap of at most k candidates, ordered by estimated count. The root is the weakest candidate.
For each arriving item, update the sketch and read its new estimate. Then decide whether the item belongs in the candidate set.
The code
import heapq
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])The tracked dictionary lets you check membership in constant time. The heap gives you the weakest candidate in constant time and replaces it in O(log k). When a tracked item repeats, this version rebuilds the heap, which costs O(k) per repeat. That keeps the code short. A production version would use lazy deletion or an indexed heap instead.
Trying it
import random
stream = ["a"] * 500 + ["b"] * 300 + ["c"] * 200
stream += [f"noise{i}" for i in range(1000)]
random.Random(1).shuffle(stream)
for item, est in top_k(stream, k=3):
print(item, est)The output should list a, b, and c with estimates close to 500, 300, and 200. Each estimate is at least the true count. With ε = 0.001 and N = 2000, an estimate is too high by more than 2 with probability at most δ = 0.01.
Why the one-sided error helps
Estimates never fall below the true count. So a genuinely heavy item always looks at least as heavy as it is, and it cannot be hidden by undercounting. The risk runs the other way. A light item can look heavy because collisions inflated its counters, and it can then take a place in the candidate set.
Two practical rules follow:
- To report items above a threshold φN, return candidates whose estimate is at least φN. Every true heavy hitter that entered the candidate set passes this test.
- Treat each reported count as an upper bound, within about εN of the truth.
Failure modes
- Late entry. An item that is rare early and heavy later enters the set only when its estimate exceeds the current minimum. With k above the number of true heavy hitters, this is rarely a problem.
- Stale estimates. A tracked item's stored estimate can lag behind its sketch value if collisions raise its counters while it is not arriving. Call
cms.estimate(item)again when you report. - Memory. Total memory is the sketch plus O(k) for the candidates. It does not grow with the number of distinct items.
Exercise
A stream has N = 1,000,000 items. You want every item with at least 1% of the stream (φ = 0.01), and you choose ε = 0.001. By how much can a reported estimate exceed the true count, and why should you set k above 100?
Show answer
With probability at least 1 - δ, an estimate exceeds the true count by at most εN = 0.001 × 1,000,000 = 1,000. At most 1/φ = 100 items can each have a count of at least 1% of the stream, so k must be at least 100. A larger k leaves room for light items that collisions have inflated, so true heavy hitters are not pushed out.