Top-K Trending (YouTube Top Videos / Heavy Hitters)
Requirements: the top K most viewed videos for the last hour, day, month and all time; views arrive at very high rate; results can be a minute stale.
Estimates: 70 B views/day ≈ 800k views/s — far too many to update a database row per view.
view events -> Kafka (partition by video_id) -> stream counters (Flink): count per video per 1-minute bucket
-> per-partition top-K (min-heap) -> merge -> global top-K
-> window rollups: last hour = 60 minute-buckets, day = 24 hour-buckets
precomputed lists (per window) -> cache -> API "top 100 today"
Deep dives
- Exact counting works because the stream is partitioned by video id: each partition owns its videos' counts, keeps a local top-K, and a final stage merges the per-partition lists (the global top K must appear in some partition's top K).
- Sliding windows: keep per-minute counts and add the newest bucket / subtract the expiring one; long windows use coarser buckets (hours, days).
- Approximate alternative when memory is tight: Count-Min Sketch + heap per window — bounded memory, small overestimates.
- Hot keys: a viral video concentrates load on one partition → pre-aggregate in the producers (count locally for a second, then send) or salt the key and merge.
- All-time counts are updated in batches to the video database (e.g. every minute), never per view.