CAPSTONE: TOP-K IN A STREAM

Everything in this path, in one trending-topics service

L320 MINALGORITHMS
PREDICT

A trending service estimates each topic's count with a count-min sketch, which never underestimates, and keeps the 5 highest estimates in a small heap. Can it still drop a true top-5 topic from the report?

You need two answers from the stream: the top K topics and how many distinct topics there are. Exact counting stores every key, so memory grows with the stream.

Three fixed-size structures replace it. A count-min sketch estimates any topic’s count; it can only overestimate. A min-heap of K entries holds the current leaders: after each event, the topic enters if its estimate beats the heap’s minimum. A HyperLogLog estimates distinct topics. Like a Bloom filter, each one hashes into a fixed array and accepts a known error.

▶ SIMULATION
REPORTED TOP-5
—
exact counts
SERVICE MEMORY
hash map: 0 keys × 2 cells
now 0 · peak 0 / 1024 cells
distinct topics: —
ORACLE TOP-5
—
grader only, not in the budget
events0 of 20000
✓ memory <= budget (1024 cells)✓ the final report includes every true top-5 topic
SCHEDULE
01[SERVICE]config: count every topic in a hash map
02[STREAM]ingest events 1–5000
03[STREAM]ingest events 5001–10000
04[STREAM]ingest events 10001–15000
05[STREAM]ingest events 15001–20000
06[SERVICE]report top-5 and distinct topics
Start of exact hash map scenario. 6 steps.
const counts = new Map();
for (const tag of stream) counts.set(tag, (counts.get(tag) || 0) + 1);
// memory = one entry per distinct tag, forever
const top = [...counts].sort((a, b) => b[1] - a[1]).slice(0, K);

Watch SERVICE MEMORY and the invariant strip. EXACT HASH MAP reports the right answer but needs 4,800 cells for 2,400 distinct topics, almost five times the budget. SKETCH + HEAP + HLL uses 586 cells from the first event to the last and reports the same five leaders. Mid-stream it briefly ranks #strike above #eclipse, which are 4 events apart. The distinct count is within about 12%.

BREAK IT NOT YET

The sketch stays inside the budget at any width up to 232. Shrink SKETCH WIDTH until collisions push a true top-5 topic out of the report.

GOAL: a true top-5 topic is missing from the report

FIX IT NOT YET

This topK keeps at most k candidates but never checks whether the arriving item is already one of them, so a hot topic takes several slots. Keep at most one entry per item: refresh its estimate if it is already in the heap, otherwise add it or replace the minimum. Return the k items, highest estimate first. Use only sketch.add(item) and sketch.estimate(item) for counts. stream is a one-pass iterator, and memory is the point: once it ends you may look up estimates for at most k items.

Mental model:

on a stream you choose your memory first and your error second. Every structure here hashes into a fixed array and accepts a known error. Count-min and Bloom filters err one way: count-min only overestimates, and a Bloom filter says “maybe” but never wrongly says “no”. HyperLogLog errs either way, by a known standard error. The heap turns approximate counts into a ranking. Size the sketch so its error is smaller than the gap you need to resolve.

IN PRODUCTION

Trending and heavy-hitter detection (hashtags, hot keys in a cache, top talkers in network flow monitoring), Redis's RedisBloom module (Count-Min Sketch and Top-K), Redis PFCOUNT for HyperLogLog, and stream processors that report approximate top-N per window.

IN INTERVIEWS

“Design trending hashtags” or “find the top K items in a stream that does not fit in memory.” Start with the exact answer and its memory cost, then count-min plus a size-K heap, say which way the error goes and how width and depth bound it, add HyperLogLog for distinct counts, and mention windowing (one sketch per time bucket) for “trending now”.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: FX ARBITRAGE →