bigonotes
System DesignDesign Problems

Top K Videos (like YouTube Trending)

A top K videos service run through the Interview Approach: ingest view events, count them per window, and serve the most-viewed list fast.

10 min readLast updated

A top K service answers one question: which videos got the most views in the last hour, day or week? It's what sits behind a trending page. The query is simple, but the input is huge. Every play of every video is an event, and you have to count them all, keep the counts fresh within a minute, and still answer in a few milliseconds. This page runs it through the Interview Approach, one step at a time.

1. Functional requirements#

Three things the system has to do:

  1. Ingest view events. Every time a video is watched, the system records a view.
  2. Return the list of the top K most-viewed videos, where K is at most 1,000.
  3. Answer for three time windows: the last 1 hour, the last 1 day and the last 1 week.

The windows are sliding. "Last hour" at 14:37 means 13:37 to 14:37, so old views have to drop out as time moves on.

Out of scope: personalized trending, filtering by country or category, de-duplicating fake views, and arbitrary time ranges.

2. Non-functional requirements#

Quality Requirement
Scalable Billions of videos and 100 billion views a day, which is about 1 million view events per second
Availability over consistency The top K list must always load. It's fine if it's a little behind or slightly off
Freshness A view shows up in the counts within 1 minute
Low latency A top K query returns in under 50 ms

A quick estimate shows where the pressure is:

  • Writes: 100 billion ÷ 86,400 ≈ 1.2 million view events per second on average, and more at peak. This is the hard part.
  • Raw storage: at about 100 bytes per event, 100 billion events is about 10 TB a day. You can't store every event as a row and count them at query time.
  • Reads: top K queries are far fewer than views, and every user asking for the same window gets the same answer. That makes the read side easy to cache.

The two numbers that drive the design are the write rate and the 50 ms read target. Writes push you toward counting in a stream. The read target pushes you toward precomputing the answer.

3. Actors#

Actor What they do Access
Viewer Watches videos. Each play makes the video backend send a view event Indirect: the backend worker sends the event, not the viewer's device
Trending reader Opens the trending page and asks for the top K videos for a window Public, read-only
Aggregation job Turns raw view events into counts and top K lists Internal

The viewer and the trending reader are often the same person, but they use opposite halves of the system. Viewers drive the write path at a million events a second. Readers hit the read path, which only needs a precomputed list.

4. API routing#

Actor Endpoint Response
Backend worker (on behalf of a viewer) POST /v1/views 202 Accepted once the event is in the stream
Trending reader GET /v1/views/top-k?window={window}&k={k} 200 with the ranked list

window is one of 1h, 1d or 1w, and k is between 1 and 1,000.

A view event is small:

{ "videoId": string, "viewedAt": timestamp }

And the top K response is a ranked list:

{
  "window": "1h" | "1d" | "1w",
  "asOf": timestamp,
  "videos": [ { "videoId": string, "name": string, "views": number } ]
}

POST returns 202, not 201, because the view is accepted into the stream and counted later. The asOf field tells the client how fresh the list is.

User requests go through an API gateway, which handles rate limiting and routes GET requests to the API service.

5. High-level design#

Build it one functional requirement at a time.

Ingest view events (requirement 1). When a video is played, a backend worker publishes a view event to a Kafka stream. Kafka absorbs the firehose: producers write fast, and consumers read at their own pace (see queues). A server consumes the stream, aggregates the views, and writes the counts to the database.

Storing counts instead of raw events is the first key choice. Keep the aggregated count in the database itself:

Column Type Meaning
video_id string Which video
name string Video title, for display
timestamp timestamp Start of the minute bucket
view_count integer Views in that bucket

Add an index on timestamp, so a query for "the last hour" reads only the rows inside that range.

The trade-off: precomputing counts as the views arrive makes every read faster, because the work is already done. Pushing raw events now and computing the counts later makes writes simpler, but every read has to scan millions of events, which is far too slow. With 1.2 million writes a second and a 50 ms read target, precompute.

Return the top K for a window (requirements 2 and 3). A user sends GET /v1/views/top-k?window={window}&k={k} through the API gateway to the API service. The API service fetches the counts for that window from the aggregated database, ranks them, and returns the top K.

There are two ways to find the top K:

Approach How it works Trade-off
Hash map and heap Sum the counts per video ID into a hash map. Walk the map and keep a min-heap of size K. Push each video, and when the heap holds more than K, pop the smallest. What's left is the top K Touches every video in the window, so it's O(n log K). Memory stays small because the heap never holds more than K items
Let the database sort SUM(view_count) GROUP BY video_id ORDER BY total DESC LIMIT k in Postgres, and read the rows in decreasing order Simple to write, but the database still aggregates every row in the window on every query

Use a min-heap, not a max-heap. The smallest of the current top K sits at the root, so each new video is compared with it in O(1) and swapped in only if it beats it. Videos that fall out of the top K are evicted along the way, so the heap is always exactly the answer.

Both approaches work for a small system. Neither meets 50 ms when the window holds hundreds of millions of rows, which is what step 6 fixes.

6. Address the non-functional requirements#

The basic design is correct. Now take each quality and find where it breaks.

Low latency#

Computing the top K on every request means summing a week of counts for millions of videos. That takes seconds, not 50 ms. And every reader asks for one of only three windows, so the same work is repeated for everyone.

The fix is to precompute the answer. A job runs every minute as part of the stream processing, computes the top K for each window, and pushes the results into Redis under keys like top-k:{window}:{k}. The API service reads straight from Redis, which keeps latency in the low milliseconds and shields the database from traffic spikes. See caching.

Since K is at most 1,000, you don't need a key for every possible K. Store the top 1,000 for each window under top-k:{window}, and return the first K entries of that list. That's three keys in total. A Redis sorted set works well here: ZREVRANGE top-k:1h 0 99 returns the top 100 in order.

The trade-off: the list can be up to a minute old. That matches the freshness requirement, and the asOf field makes it visible.

Freshness#

Views must show up within 1 minute, and old views must drop out of each window. Counting in time buckets handles both:

  • The stream server keeps a hash map of counts per video in memory and flushes it once a minute as one row per video per minute. A new view is counted within the minute.
  • The 1-hour window is the sum of the last 60 minute buckets. Each minute, add the newest bucket and subtract the one that just left the window. You never rescan the whole hour.
  • For the day and week windows, minute buckets are too many: a week is 10,080 of them per video. Roll minutes up into hour buckets, so a day is 24 buckets and a week is 168.

The trade-off: the day and week windows move in steps of one hour instead of one minute. For trending, nobody notices.

Scalable#

One server can't consume 1.2 million events a second. Partition the Kafka topic by video_id and run one consumer per partition. Each partition sees every view for its videos, so each consumer holds complete counts for its share.

That makes the global top K easy: each consumer computes the top K of its own videos, and the job merges those lists. Because no video is split across partitions, the true top K is always inside the union of the partition lists. Merging 50 lists of 1,000 is trivial.

Pre-aggregating in memory also shrinks the writes. Instead of a million database writes a second, each consumer writes one row per active video per minute. Old minute buckets can be deleted once they're rolled up into hours, and hour buckets once they're older than a week.

The weak spot is a hot video. A viral video sends all its views to one partition. If that partition falls behind, add a small random suffix to the key for the hottest videos so their events spread over a few partitions, then sum those partial counts before ranking. See scaling writes.

Availability over consistency#

If the job fails or a consumer lags, the API service keeps serving the last list in Redis. A trending list a few minutes old is much better than an error page, which is the "availability over consistency" choice from step 2. Run Redis with replicas, and keep Kafka's replication on so a broker failure doesn't lose events.

You can relax accuracy further at very large scale. A count-min sketch estimates counts for billions of videos in a fixed, small amount of memory, at the cost of slightly over-counting some videos. For a trending page, approximate counts are fine. For anything paid per view, they aren't.

Whiteboard sketch#

The sketch shows both paths: a backend worker sends views through a Kafka stream to a server that aggregates them into the database, and a job precomputes the top K into a cache that the API service reads for users.

Whiteboard sketch: on the write path, a backend worker sends view events through a Kafka stream to a server, which aggregates the result and writes it to the database (video id, name, timestamp, with an index on timestamp). A job reads from the database and writes the top K into the cache. On the read path, users send a GET through the API gateway to the API service, which reads the top K from the cache. A note says the job precomputes the top K per window every minute and pushes the results into Redis under keys like top-k:{window}:{k}, so API servers read straight from Redis, keeping latency in the low milliseconds and insulating the database from traffic spikes

Key takeaways#

  • Three functional requirements: ingest view events, return the top K (K ≤ 1,000), for the last hour, day and week.
  • 100 billion views a day is about 1.2 million events per second, so ingest through Kafka and count in a stream, not at query time.
  • Store counts per video per time bucket, not raw events. Sum buckets to get a window.
  • To find the top K, keep a hash map of counts and a min-heap of size K, which runs in O(n log K).
  • Precompute the top 1,000 per window every minute into Redis. Queries become a read of one key, well under 50 ms.
  • Partition Kafka by video_id, so each consumer's counts are complete and the global top K is a merge of partition top Ks.
  • Favor availability: serve the last precomputed list if the pipeline lags.
Revision notes · 2 min

Core idea#

A top K service counts every video view and returns the most-viewed videos for the last hour, day or week. Writes are a firehose of about 1.2 million events a second, so count in a stream and precompute the answer.

Requirements#

  • Functional: ingest view events, return the top K videos (K ≤ 1,000), for 1-hour, 1-day and 1-week sliding windows.
  • Non-functional: scalable (billions of videos, 100 billion views a day), availability over consistency, views counted within 1 minute, queries under 50 ms.
  • Estimate: about 1.2 million events/s and about 10 TB of raw events a day, so you can't count raw rows at query time.

Key points#

  • Actors: viewer (backend worker sends the event), trending reader (public, read-only), aggregation job (internal).
  • API: POST /v1/views returns 202. GET /v1/views/top-k?window={window}&k={k} returns the ranked list with asOf.
  • Basic design: backend worker → Kafka stream → server aggregates counts → database (video_id, name, timestamp, view_count, index on timestamp).
  • Precompute counts on write. Computing from raw events on read is far too slow.
  • Top K: hash map of counts plus a min-heap of size K, O(n log K). Letting Postgres sort still scans the whole window.

Step 6 changes#

Requirement Change
Low latency A job precomputes the top 1,000 per window every minute into Redis. The API reads one key and slices K
Freshness Minute buckets for 1 hour, rolled up into hour buckets for day and week. Add the new bucket, subtract the expired one
Scale Partition Kafka by video_id. Merge per-partition top Ks. Salt the keys of hot videos
Availability Serve the last list in Redis if the pipeline lags. Replicate Redis and Kafka
Huge scale Count-min sketch for approximate counts in fixed memory

Pitfalls#

  • Storing raw events and counting at query time.
  • Using a max-heap of every video instead of a min-heap of size K.
  • A Redis key for every possible K, instead of storing 1,000 and slicing.
  • Splitting one video's counts across partitions, which breaks the top K merge.
  • Forgetting that old views must leave the window.

Short line#

Stream views through Kafka partitioned by video, count them in time buckets, precompute the top 1,000 per window every minute into Redis, and serve each query from one key.

Found a mistake? Email ask@bigonotes.com