Design Top-K Trending
How to compute the most viewed videos over sliding windows, when to use exact counts or a count-min sketch, and what interviewers ask about it.
On this page
A top-K trending system shows the most viewed items in a recent time window, for example the 100 most viewed videos of the last hour, the last day and the last month. It has to count a very large stream of view events, keep each window moving as time passes, and serve the result to a page that millions of people load.
Interviewers ask this question because the obvious answer, a database query that groups by video and sorts by count, does not survive the numbers. The question tests whether you work out the memory that exact counting needs and know what to do when it does not fit. The steps follow A Framework for Any Design.
Clarify the problem
Design a system that shows the top K most viewed videos.
Over which time ranges, and how large is K?
The last hour, the last day and the last month. K is at most 100.
Do the windows slide ("the 60 minutes up to now") or are they calendar windows ("since 10:00")? And how fresh must they be?
They slide. The hour list should move every minute, and the month list can be an hour old.
Does the order have to be exact, or is a very close answer acceptable?
Close is fine if a clearly top video never goes missing.
Then I will choose exact or approximate counting for each window by its memory cost, and precompute every list.
The system returns the top K videos (K up to 100) with their view counts for the last hour, day or month. The hour and day lists refresh every minute and the month list every hour. A read takes under 50 ms at any load. A video clearly above 100th place is never missing, and month counts are accurate to about 5%. Fraud filtering, personalised lists and arbitrary time ranges are out of scope.
Estimate the scale
Assume 5 billion views a day, with 30 million distinct videos viewed in an hour, 150 million in a day, 500 million in a month, and 50 bytes per counter entry.
- Write rate. 5 × 109 views ÷ 86,400 seconds is about 58,000 views a second. At 3 times the average, the peak is about 175,000 views a second.
- Memory for the hour window with exact counts. The design keeps one count map per minute plus running totals for the hour. Assuming 2 million distinct videos a minute, the 60 maps take 60 × 2 × 106 × 50 B = 6 GB, and the running totals take 30 × 106 × 50 B = 1.5 GB, so the hour needs 7.5 GB.
- Memory for the day window with exact counts. The design keeps one map per hour plus running totals, which take 24 × 30 × 106 × 50 B = 36 GB for the hourly maps and 150 × 106 × 50 B = 7.5 GB for the totals, so the day needs 43.5 GB.
- Read rate. Assume 20,000 page loads a second at peak.
The hour and day fit in memory when split across machines. Estimate the month yourself.
How much memory do exact counts for a sliding 30-day window take?
- One count map per day, so the oldest day can be subtracted: 150 million distinct videos a day
- Running totals for the month: 500 million distinct videos
- About 50 bytes per entry
Show the working
- Daily maps: 30 × 150 × 106 × 50 B = 225 GB
- Running totals: 500 × 106 × 50 B = 25 GB
- Total: 250 GB
Estimate 250 GB (anything from 80 GB to 800 GB is a good answer)
Most of the 250 GB is videos with very few views, so the month needs a different technique.
Write the read endpoint. Which parameters does it take, and which requests does it refuse?
Compare with a model answer
It is a single GET request that takes a window name (hour, day or month) and a limit of at most 100. It refuses anything that is not precomputed, such as a limit of 1,000 or an arbitrary time range.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
GET /v1/trending?window=hour&limit=50
200 { "window": "hour", "as_of": "2026-11-14T10:06:00Z",
"items": [ { "video_id": "V7", "title": "...", "views": 48210 }, ... ] }
400 Bad Request window is not hour, day or month, or limit > 100
Cache-Control: max-age=30
View events (internal, from the video service to the log):
{ "video_id": "V7", "count": 3, "second": "10:05:12" } -- pre-summed per server per secondThe API decision worth discussing is what it refuses. "The top 50 between 14:00 and 15:30 last Tuesday" would force a scan over billions of events, so arbitrary ranges belong in a warehouse.
Each server sums its views per video for one second and sends one event, so a viral video watched 20,000 times a second on 500 servers becomes at most 500 events a second.
What state does counting keep for the hour window, and what does the read side store?
Compare with a model answer
The counters keep one map per minute and running totals in memory, partitioned by video id. The read side stores one finished, sorted list per window in a key-value store.
Model the data
Counter task state (one task per log partition, 32 partitions)
minute_buckets : ring of 60 maps video_id -> views in that minute
hour_totals : map video_id -> sum of the 60 buckets
hour_buckets : ring of 24 maps video_id -> views in that hour (the day window)
day_totals : map video_id -> sum of the 24 hour buckets
day_sketches : 31 daily count-min sketches + 1 running month sketch
candidates : video ids whose month estimate passed a floor
checkpoint : state + log offsets, written to object storage every minute
Results (key-value store, about 10 KB per value)
key "trending:hour" | "trending:day" | "trending:month"
value { as_of, version, items: [ {video_id, title, thumbnail, views} x 100 ] }The results are three keys that are read constantly and written once a minute, which suits a key-value store. Titles are added when the list is built.
Sketch the path from a view to the trending page. Where are the counts kept, and where do the answers from different partitions come together?
Compare with a model answer
Views go into a log partitioned by video id. Each counter task sends its local top 100 to a merger every minute, and the merger combines the 32 lists into the global top 100. The page reads one key through a CDN.
High-level design
The tracer follows one minute of the hour list, then a crash and a stale write.
- V7 this minute
- 0
1At 10:05:12 a video server sends an event saying V7 had 3 views in the last second, and it lands in V7's log partition, number 12.
- V7 this minute
- 3
- V7 hour total
- 48,820
2Counter task 12 adds 3 to V7 in the 10:05 minute bucket and in the hour total.
- V7 hour total
- 48,210
3At 10:06:00 the window slides. The task subtracts the 09:06 bucket, where V7 had 610 views, and reuses its slot for 10:06.
- V7 hour total
- 48,210
4The task scans its roughly 1 million hour totals with a min-heap of size 100 and sends its top 100 to the merger.
- V7 global rank
- 4
5The merger keeps the best 100 of the 3,200 entries. This is exact because each video is counted in one partition.
- V7 global rank
- 4
6The merger adds titles and writes
trending:houras version 10:06, which the store accepts only if its version is older.- V7 global rank
- 4
7Counter task 12 crashes at 10:06:40. At 10:07 the merger gets 31 lists and reuses task 12's 10:06 list, so V7 stays on the page.
- V7 hour total
- 48,610
8A replacement loads the 10:06 checkpoint, which holds state and log offsets together, and replays about 40 seconds of partition 12.
- stale writes applied
- 0
9A merger paused by garbage collection wakes up and tries to write its old 10:05 list, but the store holds 10:06 and refuses it.
Deep dives
Tumbling and sliding windows
A tumbling window is a fixed block of time such as 10:00 to 11:00. At 10:01 its list rests on one minute of data, and a video that peaked at 9:55 vanishes at 10:00.
A sliding window covers the 60 minutes up to now and changes smoothly, but done literally it must forget each view exactly 60 minutes after it arrived.
The practical solution is to build the sliding window from 60 one-minute tumbling buckets and keep a running total for each video. Every minute the task adds the newest bucket to the totals and subtracts the oldest one. The day window uses 24 hourly buckets plus the current partial hour and refreshes every minute. The oldest hour is subtracted only at the hour boundary, so the day window covers 23 to 24 hours.
Partitioning by video and merging local top lists
Each counter task sees part of the stream, so the system merges their local top-100 lists. Whether that is correct depends on how events were partitioned.
If events are partitioned by video id, every view of a video reaches the same task, so that task holds the video's true total. Suppose V7 is in the global top 100. At most 99 videos in the whole system have a higher count than V7, so at most 99 videos in V7's partition do, and V7 must be in that partition's top 100. The merge of the 32 lists is therefore exact.
If events are partitioned by server or at random, the views of V7 are spread across all 32 partitions. V7 could be 101st in every partition and still be first overall, because its counts add up across partitions. Merging local lists is then wrong.
The cost of partitioning by video is skew. A viral video loads one partition, though pre-summing limits it to a few hundred events a second. The ad click aggregator shows how to split a hot key across tasks if that is not enough.
Exact counts or a count-min sketch for the month
Exact counts for the month need 250 GB. There are three ways to handle that window.
The first is exact counting in the same stream job, which makes recovery slow because the job must restore 250 GB of state. The third is an hourly warehouse job that sums the last 30 daily counts, which is exact but adds a second system.
The second is a count-min sketch. A sketch is a grid of counters with d rows and w columns, and each row has its own hash function. To record a view, the task hashes the video id with each row's function and adds the count to one cell in every row. To estimate a video's count, it reads those same cells and takes the smallest value. Other videos can collide with the video in a cell and add to it, but nothing ever subtracts, so every cell is at least the true count and the minimum is never too low. The tracer shows this on a small grid.
- sketch
0 1 2 3 4 5 6 7 h1 0 3 0 0 0 0 0 0 h2 0 0 0 0 0 3 0 0 h3 0 0 3 0 0 0 0 0 - total views
- 3
1The sketch has 3 rows of 8 counters, one hash per row. V7 gets 3 views and hashes to columns 1, 5 and 2, so 3 is added to one cell in each row.
- sketch
0 1 2 3 4 5 6 7 h1 0 3 0 0 2 0 0 0 h2 0 0 0 0 0 5 0 0 h3 0 0 3 0 0 0 0 2 - total views
- 5
2V2 gets 2 views and hashes to columns 4, 5 and 7. In row h2 it shares column 5 with V7, so that cell becomes 5.
- sketch
0 1 2 3 4 5 6 7 h1 0 3 0 0 2 0 0 0 h2 0 0 0 0 0 5 0 0 h3 0 0 3 0 0 0 0 2 - V7 estimate
- 3
- V7 true
- 3
3To estimate V7, the sketch reads its three cells, which hold 3, 5 and 3. The minimum is 3, which is exactly right.
- sketch
0 1 2 3 4 5 6 7 h1 0 3 0 0 2 0 0 0 h2 0 0 0 0 0 5 0 0 h3 0 0 3 0 0 0 0 2 - V4 estimate
- 2
- V4 true
- 0
4To estimate V4, which was never viewed, the sketch reads columns 1, 5 and 7, which hold 3, 5 and 2. Every cell collided with another video, so the estimate is 2 although the true count is 0.
The error is bounded. With width w and depth d, an estimate is at most the true count plus (e ÷ w) × N, where N is the total of all counts in the sketch and e is about 2.718. This holds with probability at least 1 − e−d for any one video. A month is 1.5 × 1011 views, so each of the 32 tasks, which sketches only its partition, has N of about 4.7 × 109.
Choose w = 218 = 262,144 columns and d = 5 rows. Then an estimate is too high by at most 2.718 ÷ 262,144 × 4.7 × 109 ≈ 48,600 views, with probability 1 − e−5 ≈ 99.3%. If the video in 100th place has at least a million views, that is under 5%. With 8-byte counters each sketch takes 5 × 218 × 8 B ≈ 10.5 MB.
A sketch estimates the count of a given video but cannot list the top videos, so it is paired with a candidate set and a heap. The task works as follows.
- Each view is added to today's sketch and to a running month sketch. If the month estimate of the video is above a floor, here 500,000 (half of the assumed count at 100th place), the video joins the candidate set. Estimates are never low, so no video joins late.
- At midnight the task subtracts the sketch of the expired day from the month sketch, cell by cell. All sketches share hash functions and width.
- Every hour the task re-estimates each candidate, drops those that are below the floor, picks the best 100 with a min-heap and sends them to the merger.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Exact counts in the stream | The counts are exact and the code is the same as for the hour and day windows. | The job has to checkpoint and restore 250 GB of state. | Use it when there are few distinct items or exact counts are required. |
| Count-min sketches with a candidate heap Usual default | About 11 GB in all, 23 times less, however many videos exist. | Counts can be too high by about 48,600 views. | Use it when close counts are acceptable and the key space is huge. This is the choice for the month. |
| Hourly batch over daily counts | The counts are exact and the job is simple to write. | It adds a second system and a large scan every hour. | Use it when a warehouse already exists and an hour of lag is acceptable. |
Precomputing the lists so that a read is one lookup
At 20,000 page loads a second, computing a list per request would redo one minute's answer 1.2 million times. Instead the merger writes each list under one key, and the API serves that key through a CDN with a lifetime of 30 seconds.
Bottlenecks and failures
What breaks first at 10 times the load
At 10 times the load, the system records 1.75 million views a second and sees 10 times as many distinct videos. Exact state for the hour grows to 75 GB, so you raise the partitions from 32 to 320, about 234 MB per task. Exact state for the day reaches 435 GB, so the day moves to sketches as well.
What happens when each component fails
| Component that fails | What happens | What you do |
|---|---|---|
| A counter task | Counts for its partition stop updating. | The merger reuses its last list, and a replacement restores the checkpoint and replays the log. |
| The merger | The lists stop refreshing. | Readers keep the last version. Run a standby merger, and the conditional write blocks stale lists. |
| The results store | The API cannot fetch lists. | The CDN and API serve the last copy. Replicate the store. |
| The view log | The video servers cannot send their counts. | The servers buffer their sums locally, the lists freeze and then catch up, and playback is unaffected. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Runs GROUP BY video ORDER BY count LIMIT 100 over a views table and adds a cache when prompted. |
| Mid | Counts in a windowed stream processor, keeps a heap for the top K and precomputes the results. |
| Senior | Asks about sliding windows and exactness, works out memory per window, partitions by item for an exact merge, and uses a sketch only where needed, with its error bound. |
Why not use a count-min sketch for every window?
Exact counts are affordable for the hour and day, at 7.5 GB and 43.5 GB over 32 tasks. The month needs 250 GB exactly, and sketches cut that to about 11 GB, with each estimate too high by at most about 48,600 views at 99.3% probability, under 5% for a video near 100th place.
What does that error look like on the page?
Counts are shown rounded, and videos near 100th place might swap. A clearly top video cannot disappear, because its estimate is never lower than its true count.
Follow-up questions
What changes if the system ranks the most searched terms instead of videos?
You first normalise the queries, for example by lowercasing and trimming them, so that equivalent searches count together. Most search terms appear only once or twice, so exact maps spend most of their memory on terms that will never rank. The day window should therefore use sketches as well, and the rest of the design stays the same.
Trending should mean rising fast, not just large. How do you rank for that?
Rank videos by this hour's views divided by their usual hourly views, where the usual rate comes from the day or week counters you already keep. Also require a minimum count, or a video that went from 2 views to 20 would beat one that went from 50,000 to 200,000.
What happens to a view event that arrives late?
The event carries the second at which the view happened, and the counter task assigns it to the bucket for that time, not to the bucket for the current minute. If that bucket is still inside the window, the task adds the count to the bucket and to the running total, and the next refresh includes it. Events older than a few minutes are dropped.
How do you avoid counting a view twice after a crash?
The checkpoint stores the counter state together with the log offsets it covers. A replacement task restores both and replays the log from that offset, so every event is applied to the restored state exactly once. Writes of the finished lists are safe to repeat, because each carries a version and the store ignores any version that is not newer.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".