Real-Time Leaderboard for a High-Traffic Content Platform
System DesignModel answerLast updated
Design a distributed service that tracks the most-viewed content items over a rolling one-hour window at 100K events/sec, serving ranked results with low latency.
Scenario
A video streaming platform wants to surface a "Trending Now" rail on its homepage. The rail shows the top-K most-watched videos over the past hour and refreshes every minute. Product analytics says the platform receives roughly 100,000 play-start events per second across tens of millions of distinct video IDs.
What You Need to Design
Build the backend service that powers this feature end to end.
Functional requirement
Expose an API that returns the current top-K trending videos. Callers should be able to request any K up to 1,000 and optionally filter by region or content category.
Scale and performance targets
- 100K write events per second on average; plan for 3× spikes.
- Millions of distinct video IDs active within any given hour.
- Dashboard read latency: p99 under 50 ms, high availability.
- Rankings may lag reality by a few seconds to one minute — eventual consistency is fine.
What your answer should cover
- Ingestion — how you get 100K events/s reliably into the processing pipeline without losing data during spikes.
- Aggregation — how you count efficiently across distributed nodes over a sliding one-hour window, and why you prefer streaming over re-scanning the full window each minute.
- Memory and accuracy trade-offs — exact counters versus a probabilistic sketch; when each is appropriate and what the error bounds look like.
- Storage and serving — where precomputed rankings live, how reads stay fast and isolated from the write path, and how you avoid serving a partially-written result.
- Reliability — what happens when a processing node crashes, traffic spikes far above average, or the pipeline stalls entirely.
Describe your architecture as a labeled data-flow (text is fine, no diagram tool required), then walk through each component and the key trade-offs you made.
Hints
Hint 1
Think about where the heaviest computation should happen — the write path or the read path. Precomputing rankings before a request arrives is almost always the right call at this scale.
Hint 2
A sliding window does not require re-reading all 360M events every minute. Each node can maintain per-minute delta buckets: add the new minute's counts, subtract the minute that just expired, and the running total stays current in O(active items) work.
Hint 3
Exact hash maps work fine when cardinality is in the tens of millions (roughly 640 MB cluster-wide at 64 B per entry). A Count-Min Sketch only becomes necessary if cardinality or the number of dimension combinations explodes — know the error formula (εN overcount with probability 1 − δ) so you can justify the switch.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and size the system
Before sketching anything, nail down the numbers interviewers expect you to reason through:
- Write throughput: 100K events/s average, ~300K/s at peak (3× multiplier is a safe assumption).
- Event payload: ~150 B per event (
video_id, timestamp, user/session ID, region, category). That is ~15 MB/s average and ~45 MB/s peak into the pipeline. - Window contents: 100K × 3,600 s = 360M events per one-hour window.
- Cardinality: assume ~10M distinct video IDs active per hour.
- K: up to 1,000; compute top-1,000 once and slice per request.
- Read QPS: low (dashboard, not a public API), but latency must be under 50 ms p99.
The central insight: writes are hard, reads are cheap. Design the write path to precompute rankings so that reads are just a cache lookup.
2. API contract
GET /v1/trending?k=100&window=1h[®ion=us][&category=comedy]
200 OK
{
"generated_at": "2024-06-15T09:04:00Z",
"window": "1h",
"items": [
{"rank": 1, "video_id": "abc123", "plays": 51840},
...
]
}
Return generated_at so clients can surface staleness if needed. View events are written fire-and-forget by app servers via POST /ingest/play.
3. Architecture overview
App servers
└─► Collector fleet (stateless, batches ~500 events or 50 ms)
└─► Kafka topic "plays" (RF=3, 64 partitions)
├─► Flink stream processor
│ Stage 1: local pre-aggregation (1–5 s combiner)
│ Stage 2: keyBy(video_id), sliding 1-hour window
│ per-minute delta buckets + running count
│ local top-K min-heap per node
│ Stage 3: global merge → top-1000 list
│ └─► Redis (versioned atomic write)
│ └─► Trending API
│ └─► CDN / in-process cache (TTL 30 s)
└─► S3 raw sink
└─► Hourly Spark job (exact counts, audit, backfill)
4. Deep dives
Ingestion
Collectors batch events client-side before writing to Kafka with acks=all. This absorbs bursty traffic without losing events — if Flink falls behind, Kafka lag grows but nothing is dropped (set retention to 24 h to allow replay). Apply basic bot filtering and session-level deduplication here; raw trending is trivially gameable otherwise.
Aggregation: streaming, not batch re-scan
Re-scanning 360M events every minute is both wasteful and slow. Streaming computes incrementally.
Stage 1 (combiner): each Kafka consumer counts video_id → count locally for 1–5 s, then emits (video_id, minute_bucket, partial_count). This collapses ~100K events/s into far fewer keyed messages and is the primary defense against hot-key skew.
Stage 2 (keyed sliding window): shuffle by video_id so each item's count is fully owned by one node. Each node maintains:
- 60 per-minute delta maps (only items active that minute), and
- a running hourly total
count[video_id].
Each minute: add the new bucket's deltas, subtract the bucket that just aged out. Cost is O(active items per minute), not O(window size). After updating, build a size-K min-heap over the node's running counts: O(n log K). With 10M items spread across 32 nodes, this scan takes single-digit milliseconds.
Stage 3 (global merge): because partitioning is by video_id, every item's total is complete on exactly one node. The global top-K must appear in the union of the per-node top-Ks. One lightweight task merges 32 lists of K items (32K comparisons) and writes the result to Redis.
Exact counters vs. Count-Min Sketch
Exact hash map: 10M items × 64 B ≈ 640 MB cluster-wide. Feasible — use exact counts by default.
Switch to a Count-Min Sketch (CMS) only if cardinality explodes (billions of keys, or many dimension slices). Size it with ε = 10⁻⁵ and δ = 0.01: width w = ⌈e/ε⌉ ≈ 272K, depth d = ⌈ln(1/δ)⌉ = 5, so ~1.36M counters × 4 B = 5.4 MB. The worst-case overcount is εN ≈ 3,600 plays over a 360M-event window, with 99% probability.
Two things to know about CMS: it only overestimates (collisions add counts, never remove them), and it is linear so you can maintain per-minute sketches and subtract them for a sliding window. Because CMS cannot enumerate keys, pair it with a candidate min-heap: promote an item into the heap whenever its CMS estimate exceeds the current heap minimum.
Storage and serving
Stage 3 writes the full top-1,000 as a single serialized value under a versioned key (e.g., trending:1h:v{n}), then atomically flips a pointer key. Readers never observe a half-written ranking. A Redis sorted set is an equally valid option.
The Trending API reads from Redis, slices to the requested K, and caches the result in-process and at the CDN with a 30-second TTL. Read latency is O(1) and fully isolated from the aggregation pipeline.
Reliability and scaling
| Failure mode | Mitigation |
|---|---|
| Kafka broker loss | RF=3 survives one broker failure; partitions rebalance automatically |
| Flink node crash | Periodic checkpoints (every 30–60 s) to S3; restart replays Kafka from checkpointed offset |
| Traffic spike | Kafka absorbs the burst; Flink applies backpressure; autoscale on consumer lag; sample 1-in-N with weight N under extreme overload |
| Pipeline stall | API keeps serving the last written ranking with its generated_at; a stale leaderboard beats an error page |
| Redis primary failure | Replica promotion via automatic failover; data is fully recomputable so durability is not critical |
5. Trade-offs to state explicitly
Stream vs. batch: streaming avoids re-reading 360M events every minute and delivers results within seconds, but it introduces stateful jobs and operational complexity. The batch layer on S3 provides exact audit counts and a reconciliation path.
Exact vs. approximate: exact counters are simpler and correct; CMS trades a bounded overcount for orders-of-magnitude less memory. Knowing when to cross that line (and the error formula) is what separates a strong answer from a surface-level one.
Precompute vs. on-demand: computing top-K at read time would push the heaviest work onto the latency-sensitive path and serialize all readers behind one computation. Precomputing into Redis makes reads trivially fast at the cost of up to ~1 minute of staleness — well within the stated requirement.
Delivery semantics: at-least-once is acceptable here. Occasional duplicate counts cause minor overestimates that don't materially change rankings of genuine heavy hitters.
Common mistakes to avoid
- Proposing a MapReduce batch job on the full window every minute — it re-reads 360M records unnecessarily and misses the streaming alternative.
- Forgetting that CMS cannot enumerate keys — you still need a candidate heap.
- Computing top-K at read time in Redis using
ZRANGEBYSCOREacross millions of keys — this doesn't scale and blows latency. - Skipping bot filtering — without it, a single script can trivially dominate the leaderboard.