Design Top K / Trending Hashtags
Understanding the Problem
🔥 What is a Top K / trending system? A Top K system watches a stream of events (hashtags used, posts liked, products sold) and keeps a short, ranked list of the items with the most activity in a recent time window. "Trending in Brazil," "top posts in the last hour" and "bestsellers in Electronics" are all Top K lists. The challenge is that there are tens of millions of distinct items, the windows keep sliding, and everyone wants the list to be fresh.
This shows up under many names: "top K hashtags by location and category," "trending posts in the last 10 minutes, hour and day," "a 'most hyped' chart for videos," "top products by sales per category," or plain "Top K heavy hitters." They're the same problem with different events and weights. A hashtag use counts as one, a like on a post counts as one engagement, a sale counts as its quantity or revenue. We'll design around hashtags and cover the variants as we go.
Functional Requirements
We'll agree with our interviewer that posts, likes and orders are produced by other systems, and we're building the counting and ranking on top of them.
Core Requirements
- Users should be able to see the top K hashtags (say K = 10 to 50) for the last 10 minutes, 1 hour and 24 hours.
- Users should be able to filter the list by location (country) and by category (sports, politics, music...).
- Users should be able to see past trends: the top K for a window in the past, such as "trending in Brazil at 9pm last Tuesday."
Below the line (out of scope)
- Personalized trends ("trending for you"). That's a recommendation system that reads our output.
- Classifying posts into categories and locations. We assume each event arrives already tagged.
- Detailed spam and manipulation detection, beyond the basic defenses we'll build in.
Non-Functional Requirements
Ask about volume, freshness and how exact the list has to be. For our design: 500M posts a day, producing around 1B hashtag events a day, with spikes during big live events.
Core Requirements
- The system should reflect new activity in the lists within about one minute.
- The system should serve trending lists with low latency (under 50ms) at tens of thousands of reads/sec.
- The system should handle ~12k events/sec on average and ~100k/sec at peak, and much more if we count likes and views for trending posts.
- The top of the list should be accurate. Small errors far down the long tail don't matter.
- Past trends should be queryable for at least a year.
Below the line (out of scope)
- Exact counts shown to users. We'll show ranks and rounded numbers ("125K posts").
- Global strong consistency. Two users in different regions can see slightly different lists for a few seconds.
The math: 1B events / 86,400 ≈ 11.6k events/sec, and a World Cup final or an election night can push that up 5-10x. Each event is small (a hashtag, a post ID, a country, a category, a user ID, a timestamp: about 100 bytes), so even the peak is around 10 MB/sec. Throughput is not the hard part.
The hard parts are the number of distinct keys and the number of lists. There are on the order of tens of millions of distinct hashtags in a day, most of them used once. And the lists multiply: (1 global + ~200 countries) × (1 all-categories + ~20 categories) × 3 windows ≈ 12,700 top-K lists. Each list is tiny (50 entries), so storing them is trivial. Maintaining them continuously is the problem.
Reads are the easy side of this problem. Every user in Brazil asking for "trending in Brazil, last hour" gets the same list. So we precompute every list and serve it from a cache. The whole design is about the write path: turning a billion events into twelve thousand short lists, every few seconds.
The Set Up
Planning the Approach
We'll start with the obvious database query and see why it doesn't hold up, then build a streaming pipeline that maintains windowed counts and top-K lists. The deep dives cover sliding windows, finding the top K among millions of keys, hot hashtags, what "trending" actually means, and the variants (posts, hype, product sales).
Defining the Core Entities
- Event: one use of a hashtag (or a like, a view, a sale), with a timestamp, a location, a category and the user who caused it.
- Item: the thing being ranked: a hashtag, a post or a product.
- Window: a time range we rank over: the last 10 minutes, 1 hour or 24 hours, ending now (or ending at some time in the past).
- Dimension: the slice we rank within: global, a country, a category, or a country and category together.
- Top-K List: the output: the K highest-scoring items for one dimension and one window, with their counts and the time it was computed.
API or System Interface
GET /trending?window=1h&country=BR&category=sports&k=20
-> { items: [{ rank, hashtag, count }], window, computedAt }
GET /trending/history?window=1h&country=BR&at=2026-03-10T21:00:00Z&k=20
-> { items: [...], window, at }
That's the whole public interface. Events come in from internal producers over Kafka, not through a public API.
High-Level Design
1) Users should be able to see the top K hashtags for a time window
The simplest approach writes every hashtag event to a table and answers queries with SQL:
SELECT hashtag, COUNT(*) AS uses
FROM hashtag_events
WHERE created_at > now() - interval '1 hour'
GROUP BY hashtag
ORDER BY uses DESC
LIMIT 10;
It's correct and it's fine for a small app. At our scale, the last hour alone is about 40M rows, and the last 24 hours is 1B. Every request scans and groups all of them. Even if we ran the query once a minute and cached the result, we'd need 12,700 of these queries every minute, each scanning millions of rows.
The fix is to count as events arrive instead of when someone asks. Events flow through Kafka into a stream processor (Flink is the usual choice; Kafka Streams or Spark Structured Streaming also work). For each hashtag it keeps a count per one-minute bucket in memory. Every 10 seconds, it computes the top K for each window from those buckets and writes the lists to Redis. The Trending Service just reads a precomputed list:
GET trending:1h:global:all -> [ {"tag":"#WorldCup","count":1840221}, ... ]
Reads are now a single key lookup, and the expensive work happens once per update cycle, not once per request. Because Kafka keeps the events, a crashed counting job restarts from its last checkpoint and replays what it missed.
2) Users should be able to filter by location and category
Each event belongs to several dimensions at once. A post in Brazil about football contributes to four lists:
global / all
global / sports
BR / all
BR / sports
So the counting job emits each event under each of its dimension keys: (dimension, hashtag). That's 4x the counting work, which at our volumes is fine. The output is one top-K list per (dimension, window), written to Redis under keys like trending:1h:BR:sports.
We don't precompute every possible combination. If the product later wants cities, add them as another dimension level and accept the extra lists. If it wants arbitrary filters ("trending among women aged 25-34 in São Paulo"), that's no longer a precomputed list but an OLAP query, and it's worth saying so to your interviewer.
3) Users should be able to see past trends
The live lists in Redis only cover "now." For history, we keep two things:
- Snapshots of the lists. Once an hour (or every 10 minutes), we copy every live top-K list into a durable table keyed by
(dimension, window, timestamp). "Trending in Brazil at 9pm last Tuesday" is then a primary key lookup. 12,700 lists × 50 entries × 24 snapshots a day is about 15M small rows a day, which any database or a columnar store handles easily. - Aggregated counts. The counting job also writes hourly counts per
(dimension, hashtag)to an OLAP store like ClickHouse, which is built for exactly this kind of time-bucketed aggregate. That lets analysts ask questions we didn't precompute ("how did #Election trend over the past month?").
To keep the OLAP table from storing a row for every one-off hashtag, we only write hashtags above a minimum count per hour. The long tail is never going to trend anyway.
Potential Deep Dives
1) How do we maintain sliding windows efficiently?
"The last hour" moves every second. The question is how to keep counts for a window that keeps sliding without recounting everything.
Bad Solution: Recompute from Raw Events
Approach
Store raw events (in memory or a fast store) and recompute counts for each window on every update cycle.
Challenges
The 24-hour window holds 1B events. Rescanning it every 10 seconds is wasteful, and memory for raw events is enormous. This is the naive SQL design moved into a different engine.
Good Solution: Tumbling Buckets, Summed on Each Cycle
Approach
Keep a count per hashtag per one-minute bucket. Each update cycle, the 10-minute window is the sum of the last 10 buckets, the hour is the sum of the last 60, and the day is the sum of the last 1,440. Old buckets are dropped after 24 hours.
Challenges
Summing 1,440 buckets for every hashtag every cycle is a lot of repeated work, and storing 1,440 buckets for every one of tens of millions of hashtags is a lot of memory. The window is also a little jumpy: it moves a minute at a time, not continuously, though that's invisible to users.
Great Solution: Running Totals with Hierarchical Buckets
Approach
Keep a running total per hashtag per window, and update it incrementally. When a new minute bucket closes, add it to each window's total; when a bucket falls out of the window, subtract it:
total_1h[tag] += bucket[now]
total_1h[tag] -= bucket[now - 60 min]
Each update is O(1) per hashtag per window, no matter how long the window is.
To save memory on the long windows, use coarser buckets for longer windows: one-minute buckets for the 10-minute and 1-hour windows, and five-minute (or hourly) buckets for the 24-hour window. 288 five-minute buckets instead of 1,440 one-minute buckets is 5x less memory, and nobody notices that "the last 24 hours" moves in five-minute steps.
Only hashtags that actually appeared in a bucket have an entry, so the long tail of hashtags used once costs one entry for 24 hours and then disappears. In Flink, this is keyed state per hashtag with timers that fire when buckets expire.
Challenges
Events arrive late and out of order (a phone posts after reconnecting). We use event time with a watermark: a bucket stays open for, say, 30 seconds past its end before it's closed, and events later than that are dropped or counted into the current bucket. For trends, being off by a few late events is fine, and saying that explicitly is better than pretending they don't exist.
2) How do we find the top K among tens of millions of hashtags?
Once we have counts, we need the top 50 per list. Sorting tens of millions of totals every 10 seconds per list is the expensive way.
Bad Solution: Sort Everything on One Machine
Approach
Send all (dimension, hashtag, count) totals to a single process every cycle and sort them.
Challenges
It's a single bottleneck that has to receive and sort tens of millions of entries per cycle, and it gets slower every time a new dimension is added. It also can't grow past one machine's memory.
Good Solution: Count-Min Sketch Plus a Heap
Approach
A Count-Min Sketch is a small 2D array of counters (a few MB) with several hash functions. To add an item, increment one counter per row; to estimate its count, take the minimum across rows. It never undercounts and overcounts by a bounded amount. Alongside it, keep a min-heap of the K items with the highest estimates: when an item's estimate beats the smallest in the heap, swap it in.
This handles any number of distinct items in fixed memory, and sketches can be merged by adding their arrays, so you can count on many machines and combine.
Challenges
Estimates are approximate, and the errors are worst exactly where hashtags are close together, which is near the bottom of the top K. Sliding windows are awkward: you need a sketch per bucket and have to merge them for each window. And you lose exact counts entirely. It's a good answer when memory is the hard constraint, and interviewers often ask about it, but at our scale we can afford exact counts.
Great Solution: Partition by Hashtag, Local Top K, Then Merge
Approach
Partition the stream by hash(hashtag), so every event for a given hashtag goes to the same counter task. Each task owns the full count for its hashtags. It keeps a local top-K list per (dimension, window) (a small heap updated whenever a total changes) and, every cycle, sends only those local lists to a merger.
The merger receives K × P candidates per list (P = number of tasks: with 64 tasks and K = 50, that's 3,200 entries) and picks the top K.
This is exact. Because each hashtag's full count lives in exactly one task, a hashtag that's in the global top K must be in the top K of its own task. Merging local top-Ks loses nothing.
Challenges
That exactness depends on partitioning by item. If you partition by something else (by user, by time, round robin), each task only sees part of each hashtag's count, and a hashtag that's 40th everywhere but adds up to 1st globally gets missed. This is a classic trap, so say it out loud. The cost of partitioning by hashtag is skew, which is the next deep dive.
"Merge the local top Ks" is only correct when each item lives in exactly one partition. If an interviewer asks you to merge top-K lists from servers that each saw a random slice of traffic, the right answer is that it's approximate, and to either repartition by key or keep extra candidates (top 10K instead of top K) per server.
3) What happens when one hashtag gets a huge share of the traffic?
During a World Cup final, a single hashtag can get a large fraction of all events. Since we partition by hashtag, all of that lands on one counter task, which falls behind while the other 63 sit idle.
The fix is pre-aggregation before the shuffle. Put a first stage in front of the partitioned counters that consumes events in any order (round robin across tasks) and sums them by (dimension, hashtag, minute) for a couple of seconds before forwarding. 200,000 uses of #WorldCup in two seconds on 64 tasks become 64 messages, each carrying a partial count of about 3,000. The partitioned counter task now handles a few dozen messages a second for that hashtag instead of 100,000.
This is the same idea as a combiner in MapReduce, and Flink can do it with a local aggregation step. It keeps exactness, because the counters still own each hashtag's total; they just receive pre-summed partial counts instead of raw events.
For the rare case where even pre-aggregated traffic is too much for one key, you can salt it: split #WorldCup into #WorldCup#0 to #WorldCup#7 across eight tasks, and have the merger add the pieces back together before ranking. We'll go deeper on salting in /system-design/ad-click-aggregator, where skew hits harder.
4) What does "trending" actually mean?
If we rank by raw count, #GoodMorning and #love are at the top of every list every day. That's "popular," not "trending." Trending means unusually active right now compared to normal. Ask your interviewer which one they want; most products want trending.
A simple trending score compares the current window to a baseline:
expected = average count for this tag in the same window over the past 7 days
score = (current - expected) / sqrt(expected + 1)
The sqrt is a rough noise term: for counts that behave roughly like random arrivals, the expected fluctuation grows with the square root of the mean. So a tag that usually gets 100 uses an hour and now has 400 scores (400 - 100) / ~10 = 30, while #GoodMorning going from 1,000,000 to 1,010,000 scores about 10. The new tag wins, which is what we want.
This changes the pipeline a little. The counting job still produces raw window counts, and a scoring step in the merger joins them with baselines (precomputed daily from the ClickHouse rollups and loaded as a lookup table) before picking the top K.
Two more defenses matter in practice:
- Count unique users, not uses. A bot posting
#BuyMyCoin10,000 times should count once. Keep a HyperLogLog per(hashtag, window)to estimate distinct users, and rank by that (or use it to cap each user's contribution). HLLs merge, so they work with the partitioned design. - Require a minimum. A tag with 5 uses that usually gets 0 has a huge relative jump. Require a minimum count before anything can trend.
5) How do the variants work: trending posts, "most hyped" and top products by sales?
The pipeline is generic: events in, a weight per event, windowed sums per item per dimension, top K out. The variants change the events, the weights and how exact the answer has to be.
Trending posts in the last 10 minutes, hour and day. Items are post IDs, and events are engagements: a like counts 1, a repost 3, a reply 2, whatever the product decides. There are far more events (likes alone are tens of thousands per second, and views far more) and far more distinct items, since every post is a candidate. Pre-aggregation is essential, and so is a candidate threshold: a post only gets a counter once it has, say, 20 engagements in the window, which prunes the vast majority of posts. Trending posts also need a decay so yesterday's mega-post doesn't sit on top forever; the trending score above does that naturally, because the baseline catches up.
A "most hyped" chart. Some video platforms let fans spend a limited number of "hype" points on videos, and rank the videos with the most hype in the past week. Two differences from hashtags: each user has a budget (so events are already limited per user, and the system that grants hype points enforces it), and scores are often normalized by channel size so a small creator with 1,000 hypes can outrank a huge creator with 10,000. That's a per-item weight applied in the scoring step: score = hype_points × boost(channel_subscribers). The window is a week, so hourly buckets are plenty.
Top products by sales per category. Items are product IDs, events are order lines, and the weight is units sold (or revenue). Two differences matter:
- Categories are a hierarchy. A phone case is in Accessories, which is in Electronics. Emit each sale to every ancestor category, the same way we emit hashtags to several dimensions.
- Exactness matters more. A "bestsellers" widget can be approximate and live, but a sales report for merchandising has to match the orders database. Use the streaming pipeline for the live list, and a daily batch job over the orders warehouse for exact, reportable rankings. If the two disagree, the batch job wins. Having a fast approximate path and a slower exact path for the same numbers is a common pattern, and it's a good thing to bring up when an interviewer asks about accuracy.
6) How do we serve reads cheaply?
Every list is precomputed and the same for everyone who asks, so reads are easy:
- The Trending Service reads the list from Redis by key. 12,700 small lists fit in a few MB.
- Responses carry
Cache-Control: max-age=10, and a CDN serves them. The origin sees roughly one request per list per edge location every 10 seconds, no matter how many users are looking. - Clients refresh the trending module every 30-60 seconds. There's no need for push; a trend that's 30 seconds old is fine.
Final Design
The full flow:
- Post, like and order services publish events to Kafka, each tagged with location, category and user.
- A pre-aggregation stage sums events by
(dimension, item, minute)for a couple of seconds and tracks distinct users with HyperLogLogs, which flattens hot items. - Partial counts are partitioned by item to window counters, which maintain running totals for the 10-minute, 1-hour and 24-hour windows and a local top K per list.
- Every 10 seconds, the merger combines local top-K lists, applies the trending score against baselines, and writes the final lists to Redis.
- Clients read lists through a CDN and the Trending Service. Hourly snapshots of every list and hourly rollups in ClickHouse serve past trends and analysis.
What is Expected at Each Level?
Mid-level
You should see that counting on every read doesn't scale and move to precomputed lists fed by a stream (Kafka plus a counting job), with Redis serving the results. You should handle multiple windows with time buckets and multiple dimensions by emitting each event under several keys. If asked about memory, you should know that a Count-Min Sketch exists and roughly what it does.
Senior
You should design the sliding windows deliberately (running totals, coarser buckets for long windows, late events with watermarks) and explain why partitioning by item makes merging local top-K lists exact. Expect to handle a hot hashtag with pre-aggregation, and to distinguish trending from popular with a baseline-relative score and unique-user counting.
Staff+
You should treat the pipeline as a reusable platform and show how hashtags, trending posts, hype charts and product sales differ in weights, candidate pruning and exactness requirements. Expect to discuss the live-approximate vs. batch-exact split, how history is stored for both replay and analysis, and the operational side: lag monitoring, backfills when the scoring formula changes, and abuse resistance. Pushing back on precomputing arbitrary filter combinations, and saying when a question has become an OLAP query instead, is a strong signal.