Real-Time Hourly Popularity Ranking at 100K Events per Second
System DesignModel answerLast updated
Design a scalable service that ingests a massive stream of view events and serves the most popular items over a rolling 60-minute window, allowing slightly approximate results.
Hourly Popularity Ranking Service
You are asked to design a backend that surfaces the items (product IDs, hashtags, articles) that received the most views during the last 60 minutes. Traffic is global and heavy: the service must sustain about 100,000 events per second, with bursts well above that.
Operations
record_click(item_id): register one view of an item. Item IDs are 64-bit integers.get_top_k(k): return thekitems with the most views inside the rolling 60-minute window, ordered by count.
Quality requirements
- Low latency on both reads and writes.
- High availability and tolerance of node failures.
- Horizontal scalability to the traffic level above.
- Slightly approximate rankings are acceptable if that buys a substantial gain in performance.
Small example
With k = 3 and the click sequence [A, B, C, A, D, B, A], the counts are A=3, B=2, C=1, D=1. A valid answer is [A, B, C] or [A, B, D], since the tie for third place is not specified.
What to cover in your answer
- A high-level architecture.
- The API design.
- Data model and storage choices.
- How you maintain the rolling window.
- The trade-offs between accuracy/consistency and performance.
State your assumptions about scale (distinct items, maximum k, acceptable staleness) and let them drive your decisions.
Hints
Hint 1
Do the arithmetic first: 100K events/s at roughly 50 bytes each is only about 5 MB/s. Decide where the real difficulty lies (bandwidth, or counting and ranking), and whether reads need to touch the raw events at all.
Hint 2
If every event for a given item is routed to the same shard, that shard knows the item's full count. What does that imply about how local top lists can be combined into a global top list?
Hint 3
Split the hour into small time buckets (for example, one per minute) and keep a running total. Think about what must happen when the oldest bucket falls out of the window, and how late-arriving events should be assigned.
Hint 4
If memory for exact counts of a very long tail is too large, consider bounded-memory structures such as Count-Min Sketch with a candidate heap, or Space-Saving. Be ready to state their error behavior.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
- Writes: 100K events/s average, plan for roughly 3x peaks (~300K/s).
- Event size: about 50 B (8 B ID, 8 B timestamp, small metadata), so ~5 MB/s and ~360M events per hour. Transport is cheap; aggregation and ranking are the hard parts.
- Cardinality: assume up to ~100M distinct items per hour with a heavy-tailed distribution; a few thousand items hold most of the traffic.
- K: bounded, say K ≤ 1000. This lets us precompute the answer.
- Freshness: a few seconds of staleness is fine. This is the main relaxation that makes reads cheap.
- Ties: unspecified in the example, so I would break them deterministically (for instance by lower item ID) to make testing easy.
2. API
POST /v1/clicks { "item_id": 123, "ts": 1718000000123 } -> 202 Accepted
GET /v1/trending?k=10 -> { as_of, items: [{item_id, count}, ...] }
Writes are fire-and-forget (202) and can be batched by the client. Reads return a precomputed list plus an as_of timestamp so staleness is explicit.
3. Architecture
Clients -> LB -> stateless ingestion API
-> Kafka "clicks" (partitioned by hash(item_id), e.g. 64 partitions)
-> Stream aggregators (Flink or custom), one per partition group
- minute buckets, rolling hour totals, local top-M
-> Merger: combine local lists into global top-K
-> Redis: "trending:1h" (refreshed every ~5 s)
Readers -> Read API -> Redis (+ in-process cache / CDN)
- Kafka absorbs bursts, decouples ingestion from counting, and provides replay after failures.
- Partition by item_id. All clicks for one item land on one shard, so that shard has its exact count. Therefore the global top-K is contained in the union of each shard's local top-K, and merging small lists is correct. With random partitioning you would need to merge full count maps.
- Precomputed reads make
get_top_kan O(K) cache lookup, independent of write volume.
4. Data model and storage
Per-shard in-memory state:
- A ring of 60 minute-buckets, each a map
item -> count(or a bounded summary). hour_total: map item -> count, updated incrementally.- An ordered structure holding the top M candidates (M ≫ K, e.g. 10K).
Output: Redis key trending:1h holding the top ~1000 (item_id, count) pairs and as_of.
Durability: periodic checkpoints of bucket state to object storage (Flink checkpoints), plus Kafka replay from the checkpointed offset. Optionally write minute aggregates to an OLAP store (ClickHouse/Druid) for analytics. No relational database on the hot path.
5. Rolling window
- Each click does
bucket[cur_min][item]++andhour_total[item]++: O(1). - At minute rollover, walk the bucket that is now 60 minutes old, subtract each count from
hour_total, clear and reuse it. Cost is amortized O(distinct items in that minute). - Every few seconds each shard emits its top-M; the merger does a k-way merge and writes the global top-1000 to Redis.
The window edge is accurate to one minute; use 10-second buckets (360 of them) for a smoother slide at higher memory cost.
Late events: use event time with a watermark (e.g. accept up to 30 s late) so mobile clients' delayed events land in the correct bucket; drop or side-output anything later.
6. Handling the long tail
- Exact counts first. With 64 shards, each holds ~1.5M items per hour; a hash map around 50 MB per shard is fine. Often this is the right answer, and I would say so before reaching for sketches.
- Count-Min Sketch + heap. If cardinality is far larger: width 2^20, depth 4 is ~16 MB per bucket, overcounting by at most εN with ε = e/w ≈ 2.6e-6. For ~6M events per shard-minute that is an overcount of roughly 16. A CMS cannot list keys, so pair it with a candidate heap. Sketches are linear, so add the new minute and subtract the expired one.
- Space-Saving / Misra-Gries. Keep only M counters per bucket with bounded error; good when only the head matters.
7. Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Precompute every ~5 s | O(1) reads, read/write isolation | Up to ~5 s staleness |
| Minute buckets | Cheap expiry | Window edge off by ~1 min |
| Sketches / Space-Saving | Bounded memory | Tail overcounts, possible misordering near rank K |
| At-least-once delivery | Simpler, faster | Duplicates inflate counts; use exactly-once checkpoints if it matters |
| Async Redis replication | Low latency | Failover may serve a slightly older list |
Trending is a ranking, and small count errors rarely change the head of the list, so trading exactness for throughput is justified. A nightly batch job computing exact counts from logs can audit the streaming error.
8. Failure handling
- Aggregator crash: restore from the last checkpoint and replay Kafka from that offset.
- Merger or Redis loss: the merger is stateless and rebuilds from shard output within seconds; run Redis with replicas.
- Hot items: a single viral item cannot overload one shard if the ingestion tier pre-aggregates (local combiner summing counts per item for a second before producing to Kafka).
9. Common mistakes
- Writing every click to a relational database or computing the top-K at read time by scanning the window.
- Partitioning randomly and then merging only local top-K lists, which gives wrong results.
- Using a single global sorted set as the hot write path (a bottleneck).
- Naming Count-Min Sketch without stating its error bound or noting that it cannot enumerate keys.
- Ignoring expiry, late events, and tie-breaking.
10. Complexity summary
Write: O(1) per click (plus batching). Expiry: amortized O(distinct items per minute). Merge: O(S · M log S) for S shards, run every few seconds. Read: O(K) from cache.