Design Top-K Trending Videos (YouTube Top-K)
Ready to put this into practice?
Rehearse the design in a 1:1 mock interview, or build the core pieces yourself in our backend challenges.
Rehearse the design in a 1:1 mock interview, or build the core pieces yourself in our backend challenges.
Problem: "Design top K most viewed YouTube videos." The same design works for top songs, hashtags, search terms, products or error codes. All numbers are interview assumptions, not YouTube production numbers.
How to read this article
The one idea to say first:
"You can't add up top-K lists, but you can add up counts. So I store counts for every minute, hour and day, and I build the top-K list at the end. Flink gives fast numbers in about 90 seconds. A Spark job recounts every hour exactly from the raw events and replaces the fast numbers."
| Ask | Assume |
|---|---|
| What counts as a view? | The player sends one view event after 30 s of watching |
| Scale? | 1B views/day, 100M videos |
| K? | Up to 1000 |
| Time windows? | Last 60 min, 1 hour, 1 day, 1 month, 1 year, plus custom ranges |
| Breakdown? | Global and per country |
| Exact or approximate? | Real-time can be slightly off. Final numbers must be exact |
| How fresh? | "Trending now" updates every minute |
Functional
Non-functional
| Number | Math | Result | What it tells us |
|---|---|---|---|
| Average events/s | 1B ÷ 86,400 | ~12K/s | |
| Peak events/s | ~4× average | ~50K/s | Moderate. Kafka + Flink handle it easily |
| Data per day | 1B × 200 bytes | 200 GB/day (10 MB/s at peak) | Kafka is not a bottleneck |
| Distinct (video, country) per minute | ≤ events per minute | ~500K rows/minute | Storing exact counts is affordable. No need for approximation |
| Rows per hour | ~5M rows/hour | An analytics database scans this in well under a second | |
| Read requests | ~1K/s | Serve from a cache, not the database | |
| Viral video | 10% of traffic | 5K events/s for one video | One Flink worker counts 100K+/s, so no hot-key problem at this scale |
POST /v1/events body: [{event_id, video_id, event_time, watch_ms}] → 202 Accepted
GET /v1/topk?window=1h&start=2026-11-23T10:00Z&country=IN&k=10
GET /v1/topk/range?from=...&to=...&country=IN&k=50
response: { status: "provisional" | "final", as_of, items: [{rank, video_id, title, views}] }
| Data | Where | Shape |
|---|---|---|
| View event | Kafka | event_id, video_id, user_id, event_time, country |
| Raw events | S3 | Same as the event, one folder per hour |
| Counts | ClickHouse | (time bucket, video_id, country, views) for minute, hour, day, month, year |
| Ready-made top-K lists | Redis | key topk:{window}:{start}:{country} → top 1000 list |
Write path
event_id (UUID) for each view and sends it to the Ingestion API. If it retries, it reuses the same event_id.event_id, so events are spread evenly across partitions.Speed layer (fast, provisional)
event_ids, and counts views per (video, country) in 1-minute windows, using the time the view happened (event time).Batch layer (slow, exact)
Serving
This is the Lambda architecture: a fast path and an exact path over the same raw data.
| Time | What happens |
|---|---|
| 10:42:15 | User in India watches video v123 for 30 s. The player sends {event_id: E1, v123, 10:42:15} |
| 10:42:18 | The API writes E1 to Kafka and returns 202 |
| 10:42:19 | Flink reads E1. It is not a duplicate, so +1 for (v123, IN) in the 10:42 window |
| ~10:43:31 | Flink waits 30 s for late events, then closes the 10:42 window and writes (10:42, v123, IN, 1834) to ClickHouse. ClickHouse adds it to hour 10:00 and day 23 Nov |
| ~10:43:45 | The Top-K builder sums the last 60 minutes and saves the top 1000 in Redis (provisional) |
| 10:44 | A user asks for "top 10 last 60 min in India". The Query service reads Redis and returns the list marked provisional |
| ~10:47 | Kafka Connect has written E1 to S3 in folder hour=10:00 |
| 11:30 | Spark recounts hour 10:00 from S3, removes duplicates and bots, and replaces the hour's counts in ClickHouse |
| ~11:41 | The Top-K builder rebuilds the 10:00 list and saves it in Redis as final |
| 12:00 | A user asks for "top 10 for hour 10:00" and gets the final list |
| Next day 02:00 | A day job sums the 24 exact hours into the day count. Month and year rollups follow the same pattern |
| Traffic | What changes | Why |
|---|---|---|
| 10× (500K/s) | More Kafka partitions (256+); more Flink workers | Spread the load |
| 10× | Two-stage counting for hot videos: stage 1 counts per worker with a random "salt" (video, salt 0–7), stage 2 adds the salts together | A viral video is split across 8 workers instead of overloading one |
| 10× | ClickHouse cluster sharded by video_id | Each video's count lives on one shard, so "top K per shard, then merge" is still exact |
| 10× | CDN cache (30–60 s) in front of the Query service | Most readers ask for the same lists |
| 100× or many breakdowns (video × country × device × age) | Real-time path switches to Count-Min Sketch + heap (one sketch per Flink worker, merged per window) | Exact counters become too many to store. A sketch uses fixed memory |
| Any scale | Spark batch stays exact | Final numbers stay correct even when real-time is approximate |
Details: Part B, B6.
Top-K lists can't be added together correctly (example in B1). Counts can. So every layer stores counts, and the ranking is done at the end.
| Need | How Kafka helps |
|---|---|
| Absorb traffic spikes | Writes are fast appends to a log. Consumers catch up later |
| Two readers of the same data | Flink and Kafka Connect each read every event independently |
| Replay after a bug | Kafka keeps events for days. Restart a consumer from an older offset |
| Order and scale | Partitions let many workers read in parallel |
Not RabbitMQ / SQS: they delete a message once it's processed, so you can't replay it or have two independent readers.
event_id, not video_id?Keying by video_id sends all views of a viral video to one partition, so one partition gets hot. With event_id the load is even. Flink groups by video after counting locally.
| Option | Verdict |
|---|---|
| Flink | ✅ Windows based on when the view happened (event time), waiting for late events (watermarks), built-in state for dedup, recovers after a crash without losing or double counting (checkpoints), processes each event as it arrives |
| Spark Structured Streaming | OK alternative. Works in small batches, so a bit slower. Late-event handling is less flexible |
| Kafka Streams | OK for smaller jobs. It's a library inside your app. Scaling and state recovery are harder at this size |
Your own consumer service + Redis INCR | ❌ You would rebuild windows, dedup, late events and crash recovery yourself. Counters are lost if Redis fails |
| ClickHouse reading Kafka directly | Simplest. But no dedup and no event-time windows |
The main query is: "add up views per video over millions of rows, sort, take the top K." That's an analytics query, not a transaction.
| Postgres (row database) | ClickHouse (column database) | |
|---|---|---|
| How data is stored | Row by row. A query reads whole rows, even unused columns | Column by column. A query reads only the columns it needs |
| Compression | Low | 5–10× (similar values sit next to each other) |
Query speed for SUM … GROUP BY over 30M rows | Seconds to tens of seconds | Well under a second (uses all CPU cores, processes values in batches) |
| 720M new rows/day | Indexes, VACUUM and table bloat make this painful | Built for fast bulk inserts |
| Counting | You run UPDATE … SET views = views + n on hot rows, which causes locks | SummingMergeTree adds rows together in the background. No updates, no locks |
| Rollups | You write your own jobs | Materialized views add minutes into hours and days automatically |
| Old data | Manual partition drops | Built-in TTL deletes old minute data |
| Good for | Users, orders, payments, small metadata | Dashboards, counters, logs, top-K |
When Postgres is fine: a small product with ~1M views/day. A Postgres table with hourly counts and an index is enough. Switch when the GROUP BY queries get slow.
| Option | Why not (here) |
|---|---|
| BigQuery | Works, no servers to run. But each query takes 1–5 s, you pay per data scanned, and it isn't built for many users querying at once. Good if you're on GCP and keep Redis in front |
| Druid / Pinot | Good alternatives (real-time analytics). ClickHouse is simpler to run |
| Cassandra / DynamoDB | Fast key lookups and writes, but no GROUP BY / ORDER BY across keys. They can't compute a top K |
Redis sorted set (ZINCRBY) | Great for one "trending now" list. But you need one set per window × country, there are no rollups, no custom ranges, and 100M videos in RAM is expensive. Good as a cache, not as the store |
| Time-series DB (Prometheus, InfluxDB) | Built for few metrics with few labels. 100M video ids is too many labels |
Cheap, durable, and kept forever. It's the source of truth: the batch job recounts from it, and after a bug you can recompute anything.
It's built for large scans (8 GB per hour, terabytes per month), with shuffles and joins. Bot rules are easy to write in code. Alternatives: Flink in batch mode, or SQL in ClickHouse over S3 files.
1K reads/s for the same few lists. Redis answers in about 1 ms. ClickHouse would recompute the same answer again and again.
Smaller windows (1 s) mean 60× more rows for little benefit. Bigger windows (5 min) make "trending now" stale. One minute is a good balance.
Network delays and offline phones would put views in the wrong minute. Event time puts every view in the minute it really happened.
| Min | Section | What to say |
|---|---|---|
| 0–5 | Clarify | What counts as a view, K, windows, global/country, exact vs approximate, freshness |
| 5–8 | Estimates | 50K/s peak, 10 MB/s, ~500K counts/minute → exact counting is affordable |
| 8–12 | API + data | Two endpoints, count tables, Redis lists |
| 12–22 | Design (A5) | Draw the image. Say the one idea: counts, not lists |
| 22–25 | E2E flow (A6) | Walk one view from 10:42 to the final list |
| 25–35 | Deep dive (they pick) | Usually Flink windows + late events + dedup (B3, B4), or how top K is computed (B2) |
| 35–40 | Scale-up (A7, B6) | Hot videos (salting), sharding by video, Count-Min Sketch at 100× |
| 40–45 | Trade-offs (A8) | Why Flink, why ClickHouse not Postgres, Lambda vs Kappa, exact vs approximate |
Two-minute summary to say at the end:
"Players send a view event with a unique id. The API writes it to Kafka keyed by that id, so no partition gets hot. Flink drops duplicates and counts views per video and country in one-minute windows, then writes the counts to ClickHouse, which rolls them up into hours and days. I store counts, not top-K lists, because lists can't be added together. Kafka Connect also archives raw events to S3, and an hourly Spark job recounts each hour exactly, removes bots, and replaces the real-time numbers. A builder turns counts into top-1000 lists in Redis, and the API says whether a list is provisional or final. At 100× scale, the real-time path switches to a Count-Min Sketch, and batch stays exact."
K = 1, three minutes:
| Video | min 1 | min 2 | min 3 | Hour total |
|---|---|---|---|---|
| A | 100 | 0 | 0 | 100 |
| B | 0 | 100 | 0 | 100 |
| C | 0 | 0 | 100 | 100 |
| D | 90 | 90 | 90 | 270 |
The minute winners are A, B and C. The real hour winner is D (270), but D was never #1 in any minute, so a design that keeps only minute lists never sees it. In general: a video just below the cut-off in every window can be #1 overall.
When merging lists is correct: when each video's full count lives on exactly one node (data split by video_id). Then "top K per node, then merge" is exact. Spark's shuffle and a ClickHouse cluster sharded by video_id both work this way.
O(n log k), better than sorting everything (O(n log n)).ORDER BY views DESC LIMIT K.event_id for 10 minutes and drops repeats (player retries).| Where a duplicate can come from | Fix |
|---|---|
| Player retries | Same event_id → Flink drops it |
| API retries writing to Kafka | Kafka idempotent producer |
| Flink restarts after a crash | Flink restores its state and Kafka position from the last checkpoint; ClickHouse ignores a repeated insert with the same dedup token |
| Anything that slips through | The hourly batch dedups the whole hour by event_id and replaces the numbers |
event_id, removes bot views (for example: max 20 views per user per video per hour, known bot IPs), and counts per video and country.1. Hot video: two-stage counting
Each worker counts a part of the views, and one worker adds the 8 partial counts. One worker no longer has to handle all the traffic for one video.
2. ClickHouse cluster sharded by video_id
Each shard holds full counts for its videos. Each shard computes its top K, then the lists are merged. Exact (see B1).
3. Count-Min Sketch at 100× (real-time path only)
A Count-Min Sketch is a small grid of counters, d rows × w columns, with one hash function per row.
| Step | What happens |
|---|---|
| Add a view of video A | For each row, hash A to a column and add 1 |
| Estimate A's count | Read A's cell in every row and take the smallest value (other videos sharing a cell only add, never subtract) |
| Know which videos are top | Keep a min-heap of size K next to the sketch |
| Merge two sketches | Add them cell by cell (same hash functions) |
4. CDN in front of reads Lists change at most once a minute, so a 30–60 s CDN cache absorbs most of the read traffic.
5. Multi-region (mention only) Ingestion and Kafka run in each region; events are mirrored to one central region for counting.
| Failure | What happens | Handling |
|---|---|---|
| API server dies | Some requests fail | Load balancer; player retries with the same event_id |
| Kafka broker dies | Nothing visible | 3 copies of every partition |
| Flink crashes | "Trending now" pauses | Restarts from the last checkpoint and catches up. No loss, no double counting |
| Flink has a bug | Real-time numbers are wrong | Final numbers are safe (batch). Fix it and replay Kafka |
| Spark job fails | Hour stays provisional | Retry. Re-running is safe because it replaces the hour |
| Redis down | Slower reads | Read from ClickHouse with a limit on concurrent queries |
| ClickHouse replica down | Slightly slower | Use another replica |
His design: Kafka keyed by item id → Spark Streaming keeps the top K per hour → Flink merges lists (uses ZooKeeper to know when all lists arrived) → time-series DB. Fast path: a single Count-Min Sketch server with a second copy for failover. Exact path: an on-demand Spark job over raw Parquet files.
| Topic | Jordan | This design | Better |
|---|---|---|---|
| What is stored | Top-K list per hour | Counts per minute/hour/day | Ours: rollups stay exact. His admits multi-hour answers are approximate |
| Exact answer for any range | Spark job per query (minutes) | Sum ready-made counts (seconds) | Ours |
| Kafka key | Item id (viral = hot partition) | event_id (even load) | Ours |
| Knowing a window is done | ZooKeeper counts consumers | Flink watermarks | Ours (simpler, handles late events) |
| Very high scale | Count-Min Sketch as the main path | Sketch only at 100× | His is cheaper at Google-search scale |
| Duplicates, bots, late events, countries, provisional vs final | Not covered | Covered | Ours |
Worth borrowing from his design: heap O(n log k) + merge k sorted lists; one sketch per thread to avoid locks; say "restricting to whole hours makes reads faster."
Interview line: "Merging hourly top-K lists is approximate. I store counts so rollups stay exact, and I switch to a Count-Min Sketch only when there are too many distinct items to count exactly."
| ClickHouse | BigQuery | |
|---|---|---|
| What | A database you run (or ClickHouse Cloud) | Google-managed, no servers |
| Query time | Milliseconds to under a second | ~1–5 s minimum |
| Many users at once | Yes | Limited; queries can queue |
| Cost | Fixed (servers) | Per data scanned ($6.25/TiB) or reserved capacity |
| Best for | Real-time dashboards, counters, top-K | Reports, analysts, batch jobs |
Short version: ClickHouse is like owning a car; BigQuery is like a taxi. For this problem ClickHouse is the usual answer. BigQuery works if Redis serves reads and BigQuery only feeds the builder.
| Question | Short answer |
|---|---|
| Why not store top K per minute? | Lists can't be added (B1). Store counts |
| How do you avoid double counting? | event_id + Flink dedup + checkpoints + batch dedup (B4) |
| Viral video? | Kafka keyed by event_id; two-stage counting with salt (B6) |
| How fresh is "trending now"? | ~90 s: 60 s window + 30 s wait + write |
| Batch differs from real-time? | Batch wins once final. Usually lower because bots are removed |
| Top K across ClickHouse shards? | Shard by video_id, top K per shard, merge. Exact |
| "Last 7 days" sliding? | Sum the final days + today's hours/minutes; cache for 5–15 min |
| Add a "category" breakdown? | Add a column. If rows explode, use a sketch in real-time only |
| Lambda vs Kappa? | Batch handles late events, heavy bot rules and cheap recompute |
Flink writes only to real-time tables, Spark only to batch tables. If both wrote to the same table, a Flink replay could add counts on top of the exact batch numbers. Reads use the batch number when the hour is final, otherwise the real-time number.
Flink keeps the rows in its saved state and inserts them only after a checkpoint succeeds, with a fixed dedup token. If it crashes and retries, ClickHouse sees the same token and ignores the repeat.
Record Kafka's latest position at the cutoff, wait until Kafka Connect has written up to it in S3, then run Spark. Events that arrive after that are handled as corrections (C4).
Keep past event times up to 7 days old, so a late view lands in the right hour. A small job re-runs any hour that received new raw files, then rebuilds the day, month and year that contain it.
Minute counts 7 days, hour counts 90 days, day/month/year counts and raw S3 events forever. So custom ranges older than 7 days are rounded to hours, and older than 90 days to days.