Design a Top K / Trending Topics System
hard 45 minCount billions of mentions a day and show the ten topics that are rising right now, in each country and city.
Deep dives
Compare the options before you open them, then say which you would pick.
Deep dive 1
When is a merged top K correct?
Counts are on 20 machines. How do you get the true top 10?
BreaksSpread events at random, merge the top 10 lists
- How
- Each machine sends its ten best and the sums are ranked.
- Limit
- A topic that is eleventh on all twenty can be first overall and is sent by none.
- Choose when
- Only for a rough look.
WorksSpread at random, merge complete sketches
- How
- Each machine keeps a sketch of the same shape. Add them counter by counter, then rank all known candidates.
- Limit
- Sketches travel every 15 seconds, candidates must be collected, and errors add up. Adding is right: taking the larger counter would lose mentions.
- Choose when
- A few large places, or events that cannot be moved.
StrongDivide by topic, merge the top lists
- How
- All sums of one place and topic go to one counter. The true top 10 is inside the union of the counters' top 10 lists.
- Limit
- A shuffle between two stages, and a counter may be busier than another.
- Choose when
- Our choice.
Why it works
The same reasoning rejects building the world list from regional lists. Count the world as a place of its own.
Deep dive 2
Little memory, known error
A sketch by hand: two rows of four counters
| After | Row 1 | Row 2 |
|---|---|---|
| red, red, red | 3 0 0 0 | 0 3 0 0 |
| blue (shares red's counter in row 1) | 4 0 0 0 | 0 3 1 0 |
| Estimate for blue | 4 | 1, so the answer is 1 |
| Estimate for red | 4 | 3, so the answer is 3 |
How do you keep rare topics from filling memory?
BreaksA heap of ten, and forget the rest
- How
- Keep only current winners with counts.
- Limit
- A rising topic is forgotten each time and never reaches its real count.
- Choose when
- Never for counting.
WorksSpace-Saving
- How
- Keep m entries. A new topic replaces the smallest and starts from its count plus one.
- Limit
- With m entries an estimate can be too high by N/m at most. Removing old minutes is hard, so it needs one summary for each bucket.
- Choose when
- One window, one machine, no buckets. This is the story's small board.
StrongA sketch as a gate, exact after it
- How
- Everything goes through a Count-Min Sketch of the current hour. From 20 mentions on, a topic gets exact buckets.
- Limit
- The first 20 are an estimate. Width must match the events per hour, and the sketch starts again each hour.
- Choose when
- Our choice: exact where it is seen, approximate where it is not.
Choosing a structure
| Structure | Answers | Cannot |
|---|---|---|
| Count-Min Sketch | How often was x seen? At most this | List what it has seen |
| Space-Saving, Misra-Gries | Which items are frequent? | Remove old events easily |
| Lossy counting | Items above a share, with fixed error | Stay at fixed size for every input |
| HyperLogLog | How many different people? About 12 KB for under 1% typical error | Say who, or list them |
| t-digest, KLL | Percentiles, such as p90 watch time | Count items |
| Exponential histogram | Recent total in little memory | Exact recent totals |
Tuning. Width sets the error, depth sets the confidence: five rows give 99.3%. Raising only the smallest of an item's counters when adding, called conservative update, reduces overcounting and still never undercounts, but such sketches can no longer be merged by plain adding. Deleting is possible if an item is never removed more often than it was added.
The start of an hour. An empty gate would delay every topic by 20 mentions. Keep the previous hour's sketch and ask whether the sum of both estimates reaches 20. Existing entries stay until they have been quiet for an hour.
Deep dive 3
Windows that slide
How do you count the last hour, refreshed each minute?
BreaksKeep every event of the hour
- How
- Add new ones, remove old ones.
- Limit
- 167 million events. Each removal needs the event again.
- Choose when
- A small stream.
WorksTumbling hours
- How
- Start at zero on the hour and show partial results.
- Limit
- At 10:01 the list has one minute of data, and at 10:59 fifty-nine. Ranks jump on the hour.
- Choose when
- Daily reports.
StrongMinute buckets in a ring
- How
- Sixty buckets and a total. Add the new one and subtract the one that leaves.
- Limit
- 240 bytes for each entry, and edges move in one-minute steps.
- Choose when
- Our choice. Day and week use hour buckets.
Details of time
- 1
Event time
The minute comes from the post, not from when we saw it, so a slow hour in our system does not become a trend.
- 2
Late events
Ten seconds of waiting, then results are shown. Up to five minutes late, the mention is added to its own bucket. Later ones are kept for history only.
- 3
Bad clocks
Times in the future are replaced by arrival time.
- 4
Decay instead of windows
Score each mention by e to the power of minus age times a rate. One number for each topic and no edge, but no answer to "how many in the last hour".
- 5
Flink's own sliding windows
Its documentation warns that an element is copied for each window it belongs to. A one-hour window that slides each minute would mean sixty updates for each event. Our buckets mean one.
Deep dive 4
Trending, not popular
Two topics, one hour
| Famous singer | New word | |
|---|---|---|
| Now | 500,000 | 50,000 |
| Baseline | 480,000 | 1,000 |
| Relative growth v | 0.042 | 49 |
| count × (1 + 0.3 v) | 506,250 | 785,000 |
| (now − base) / √(base + 100) | 28.9 | 1,477 |
Which score?
BreaksGrowth alone
- How
- (now − base) / base.
- Limit
- From 1 to 50 is 4,900%. The list fills with tiny topics.
- Choose when
- Never without a minimum.
WorksCount times growth
- How
- now × (1 + weight × growth), with a smallest baseline of 100 and less weight for topics under a day old.
- Limit
- Two constants to tune, and large topics still get a head start.
- Choose when
- A clear first version.
StrongSurprise against expected noise
- How
- (now − base) / √(base + 100), at least 1,000 different people, baseline from the same hour on the last seven days.
- Limit
- Needs a week of hour buckets. Not a true probability.
- Choose when
- Our choice: large means unlikely by chance.
Baselines
| Baseline | Good | Weak |
|---|---|---|
| Average of the last 24 hours | Simple | Every breakfast word trends at breakfast |
| Exponential average | One number, adapts | Learns the spike itself, so a trend erases itself |
| Same hour, last seven days (median) | Knows day patterns | Needs a week. New topics use a floor |
Attackers may keep a topic quiet to lower its baseline and then push it. Very flat histories followed by a step are a signal for review.
Deep dive 5
Against fake crowds
Four layers
- 1
Account weight
From 0 to 1, from age, verification, history and recent human checks. Under 0.3 counts as zero. New accounts count half after their first day, and nothing before.
- 2
Repeats and caps
Once per account, topic and hour. At most 100 topics an hour for an account, and a cap on what one network address may add to one topic.
- 3
Shape
Even spacing in time, accounts made on one day, one circle of friends, one place for a world topic, mentions without replies. A step instead of a curve.
- 4
People
A newcomer in the top 20 within 30 minutes, a sensitive word or a machine flag goes to the review desk with samples, ages of accounts, a map and the curve. Answers: allow, hold, suppress.
Where do you put the filter?
BreaksDrop suspicious events at the API
- How
- Rejected before the log.
- Limit
- A wrong rule cannot be undone, and attackers learn from the answer.
- Choose when
- Only for broken formats and noisy callers.
WorksAfter ranking
- How
- Check only the top 50.
- Limit
- Fake topics push real ones out of each counter's 50 first.
- Choose when
- As a last check, together with another one.
StrongIn the stage divided by account, plus a check on candidates
- How
- All events of one account meet at one worker, so repeats and weights are local. Shape checks run on the few thousand candidates.
- Limit
- Rules are code in the stream, with releases and replays.
- Choose when
- Our choice.
Edge cases
What can go wrong
| Case | Answer |
|---|---|
| A hundred times the traffic | The log keeps it. Combining means counters see little more. Lists say how old they are |
| One topic is 30% | Divided by account first, so no hot partition |
| Collisions in the sketch | A rare topic is promoted too early. It then has exact counts |
| Minute edge | One sixtieth changes at a time, no jump |
| Late or future time | Own bucket within five minutes, clocks corrected |
| Topic spelled five ways | Normal form with display form |
| Harmful topic | Blocklist, classifier, hold until reviewed. Removing purges the edge |
| Trend of one place | Counted for its own place. The world has its own count |
| Filter or counter dies | Checkpoint and log position restored together |
| Kafka partition leader lost | A copy takes over. Producers retry with sequence numbers |
| Redis lost | The next cycle writes all 600 lists in 15 seconds. The edge serves old ones meanwhile |
| Edge copies expire together | One request each, stale while refreshing. See thundering herd |
| New place added | Replay a week from the log for its baseline |
| Region cut off | Serve the last lists, marked stale. Replay when back |
| Too many promoted topics | Raise the gate from 20 to 40 for that counter, and alert |
Failure drill: say it before you read it
- 1
A counter machine is lost
Its topics stop for about a minute. The ranker keeps its last best list. The new one loads a checkpoint and reads up to 30 seconds of log again. Counts and position were saved together, so nothing is doubled.
- 2
The stream falls ten minutes behind
Lists carry their time, so readers can be told. Filters drop phrases first and keep hashtags, then catch up.
- 3
A wrong trust rule removed real people
The log still has every event. Fix the rule, replay the last hour into a second set of counters, compare, then switch.
- 4
Are the numbers right?
Count one in a thousand topics exactly on the side, chosen by hash, and compare. Report the gap.