Designing Trending Topics
Difficulty: Advanced Topics: Count-Min Sketch, Heavy Hitters, Stream Processing, Sliding Windows Asked at: Twitter, Google, Meta, Amazon · Prerequisites: Message Queues, Batch vs Stream, and Bloom Filters
1. Understanding the Problem
Trending topics is the short list in the sidebar: the 50 terms that are spiking right now, scoped to where you are. Behind it is a firehose of events - tweets, searches, hashtags - and the job is to pick the 50 most interesting terms out of millions, refresh that pick every few seconds, and do it per region and per time window.
The thing to say out loud early, because it changes every decision that follows: this is not a leaderboard. A leaderboard tracks exact scores for a bounded, known set of players. You know every player ID up front, there are maybe 10 million of them, each has one authoritative number, and getting a rank wrong by one position is a bug. Trending is top-K over an unbounded, high-cardinality stream of strings you have never seen before. New terms appear continuously, 99.9% of them will never matter, and nobody can tell whether the term at rank 23 was counted as 41,200 or 41,350. One problem wants a Redis sorted set and exact arithmetic. The other wants approximate counting, and approximation is the correct answer rather than a shortcut.
💡 A Redis sorted set keeps a score next to every member and maintains the members in score order, so “who is at rank 23” is a direct lookup rather than a sort. That only works when you know the members in advance, which is exactly what trending does not.
Real examples: X/Twitter Trends, Google Trends and the Trending Searches carousel, YouTube Trending, Reddit’s r/popular, Spotify Viral 50.
2. Naive First Cut
flowchart LR
APP["Client<br/>tweets and searches"]
API["Ingest API"]
DB[("Counters DB<br/>term and count")]
UI["Trends UI"]
APP -->|"1. Send event"| API
API -->|"2. Increment per term"| DB
UI -->|"3. ORDER BY count DESC LIMIT 50"| DB
One row per term with a counter. Increment on every occurrence, sort the table when someone opens the page.
Why this breaks:
- The write volume is not what you think. 500K events/sec, and each event carries several countable terms (hashtags, tokens, bigrams). Call it 5 - that is 2.5M counter updates per second spread across 10M distinct keys.
💡 A bigram is a two-word phrase (“world cup”); an n-gram is the same idea at n words. Counting phrases as well as single words is what lets “world cup final” trend as a unit instead of three unremarkable words. - Almost all of that work is wasted. Of 10M distinct terms a day, a few thousand have any chance of reaching a top-50 list. You are spending 99.9% of your write budget on rows nobody will ever read.
ORDER BY count DESCover 10M rows is a full sort. Do it every 10 seconds, times 20 regions, times 3 window sizes, and the database does nothing else.- There is no window. A single lifetime counter per term means the list shows what has been popular since launch, not what is happening now. Adding windows multiplies the row count by the number of live buckets.
- Raw count is the wrong ranking anyway. Sort 10M counters by count and you get the platform’s permanent vocabulary - the same generic words every single day. Volume is not trend.
The rest of the doc evolves this into a streaming pipeline with bounded-memory sketches, two-tier top-K aggregation, and a ranking function that measures rate of change instead of volume.
3. Prior Art We’re Drawing From
- Count-Min Sketch (Cormode and Muthukrishnan, 2005) - “An Improved Data Stream Summary: The Count-Min Sketch and its Applications.” The frequency-estimation primitive this whole design rests on: a fixed-size 2D counter array that answers “how often have I seen this term” with a bounded one-sided error. Cited by name; it is in the Journal of Algorithms, 2005.
💡 A sketch is a fixed-size summary of a stream that answers a question approximately. You trade exactness for memory that never grows, which is the only way to count a key space you cannot enumerate. Learn more → - Space-Saving (Metwally, Agrawal and El Abbadi, 2005) - “Efficient Computation of Frequent and Top-k Elements in Data Streams,” ICDT 2005. Built for exactly this question rather than adapted to it: m counters, a guarantee that anything above
N/mof the stream is in the table, and an error bound tied to stream length.
💡 Space-Saving keeps a fixed number of slots; a new term evicts the smallest one and inherits its count as an error bound, which guarantees any genuinely frequent term is still in the table. - Twitter’s trends pipeline and the Storm/Heron lineage - Twitter ran trend detection on Storm, then rewrote the engine as Heron for backpressure and per-component resource isolation while keeping the Storm topology API. The shape we borrow is the topology itself: parallel counting bolts feeding a low-parallelism ranker. (Apache Heron repo)
💡 Storm and Heron are stream-processing engines; a “topology” is the graph of processing steps and a “bolt” is one step in it. Backpressure is the engine slowing its own intake when a downstream step falls behind, instead of piling up work until it dies. Learn more → - Apache Flink event time and watermarks - The clearest production treatment of out-of-order streams: watermarks, allowed lateness, and side outputs for events that miss their window. We use all three. (Flink docs on time)
💡 A watermark is the pipeline’s statement “I believe I have now seen everything up to time T”, which is what lets it close a window; allowed lateness is the grace period after that, and a side output is the separate channel stragglers are diverted to. - HyperLogLog++ (Heule, Nunkesser and Hall, 2013) - “HyperLogLog in Practice,” EDBT 2013. Google’s refinement of HyperLogLog (HLL) with much better accuracy at low cardinality, which matters here because most terms have few distinct users and that is precisely the range where plain HLL is worst. (Google Research publications)
💡 HyperLogLog estimates how many distinct values a stream contained using a few kilobytes no matter how many values it saw. Here it answers “how many different people posted this term”, which raw counts cannot.
4. Functional Requirements
Core (Top 3)
- Return the top K trending terms for a time window - K = 50, ordered, with a score you can explain
- Support several windows - 5 minutes, 1 hour, 24 hours, all live at the same time
- Scope trends by region - a user in Mumbai and a user in Berlin see different lists
Discussion
Newest first