Trending Pages Leaderboard: Top K URLs in a Rolling Window
System DesignModel answerLast updated
Design a pipeline that ranks the K most-viewed URLs over a rolling time window, covering partitioned counting, correct merging, viral-URL skew, late events, and exact versus approximate counts.
You are asked to build a "trending pages" leaderboard. Page-serving backends already emit one event per page view, each carrying a URL and a timestamp. Consumers call an API to fetch the K most-viewed URLs over a recent period, and the leaderboard should keep up with changing traffic.
You are expected to start by clarifying requirements (or stating explicit assumptions), then present an end-to-end design, then go deeper on the follow-up areas below.
Assumptions to settle yourself. Event rate, number of distinct URLs, the value of K, the window length and the freshness target are not specified. Ask about them or pick numbers and justify them. Browser-side collection is out of scope.
Part 1: End-to-end design. Describe how events are ingested, how per-URL counts are maintained over the window (including how old views drop out), how a global top K is derived from per-worker results, and how clients read it. State when the merge of partial top-K lists is exact.
Part 2: Hot keys. One URL suddenly receives a large fraction of all traffic. What breaks, and how do you fix it without breaking ranking correctness?
Part 3: Late and out-of-order events. Events may arrive late (client reconnects, producer retries). How are they assigned to windows, when is a window considered complete, what happens to stragglers, and how do you handle duplicates?
Part 4: Exact vs. approximate counts. Exact counts need memory proportional to the number of distinct URLs. When would you accept approximation, what structure would you use, and how does error affect the ranking near position K? How could you combine a fast approximate path with an exact one?
Hints
Hint 1
Estimate first: for example 100k events/s and 100M distinct URLs per day. This tells you whether per-worker exact hash maps fit in memory and whether a single reader can serve the result.
Hint 2
A sliding window is easiest to maintain as many small time buckets (e.g., 1-minute) per URL or per worker. Adding a bucket and subtracting the oldest one keeps counts rising and expiring. Merging local top-K lists is exact only if each URL's full count lives on one worker.
Hint 3
For a viral URL, salt the key across several sub-partitions, pre-aggregate locally, and then combine the partial counts for that URL before the final ranking. For approximate counting, think of a Count-Min Sketch plus a small heap of candidates, with an exact recount for the candidates.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
I would confirm: window (say last 1 hour and last 24 hours, sliding), freshness (results at most ~10-60 seconds old), accuracy (exact preferred for a public leaderboard, approximate acceptable for internal trends), K (small and fixed, e.g., 10 to 100, with a cap such as 1,000), and whether bots or repeat views from one user count.
Assumed scale: 100k views/s peak, about 10 billion events/day, roughly 100M distinct URLs per day, and about 5k top-K reads/s. Reads are far lighter than writes and can be served from a cache.
2. End-to-end design
Ingestion. Page servers publish events to a durable partitioned log (Kafka or similar). Partition by hash(url), so all views of one URL land on one partition and one consumer.
Counting. Stream workers, one per partition group, keep counts in time buckets, for example 1-minute buckets. For a 1-hour window, a URL's count is the sum of its last 60 buckets. Maintain a running total per URL: on each new bucket, add its counts; when a bucket falls out of the window, subtract it and delete URLs that reach zero. This makes both rises and expiries cheap. Memory per worker is about (distinct URLs on that worker) times (bytes per entry), so 100M URLs at roughly 50 bytes is 5 GB total, sharded across workers.
Local top K. Each worker maintains a min-heap of size K, or recomputes it periodically (every few seconds) from its running totals.
Global merge. A merger collects each worker's local top K and takes the top K of the union. This is exact because each URL's total count lives on exactly one worker. If URL X is in the global top K, it must be in the top K of its own worker, since fewer than K URLs anywhere beat it. If the same URL were split across workers, the merge would be wrong: a URL might be small on every worker yet large in total.
Serving. The merger writes the result (a small list of K items plus a version and timestamp) to a cache such as Redis. The API only reads that key. Reads never touch the counting path, and the payload is tiny, so a CDN or in-process cache with a few seconds of TTL handles the read load.
Fault tolerance. Checkpoint worker state and consumer offsets together (periodic snapshots to durable storage). On restart, restore the snapshot and replay from the stored offset. Monitor consumer lag, merge latency, result age and heap/memory usage.
3. Hot keys
With hash partitioning, a viral URL sends all its traffic to one partition, which overloads one worker and raises lag, while others idle.
Fixes:
- Key salting. For a URL detected as hot, append a random salt
0..S-1to the key so its events spread over S sub-keys and workers. Each worker counts a partial value. - Local pre-aggregation. Producers or an upstream stage combine counts for a short interval (e.g., 1 second) before emitting
(url, count), cutting event volume dramatically for popular URLs. - Combine step. Partial counts for salted keys must be summed in a second stage keyed by the original URL before the global ranking. Without this step, the merge is no longer exact, because a hot URL's total is split across workers and each part may fall below the local top-K cutoff.
- Detection. Use a lightweight Count-Min Sketch or a Space-Saving counter on the ingestion side, or monitor per-partition lag, and keep a dynamic "hot set" in configuration. Only hot URLs pay the extra combine cost.
4. Late and out-of-order events
Use event time (timestamp on the event), not processing time, so retries and reconnects land in the right bucket. Track a watermark (roughly max event time seen minus an allowed lateness, say 1-2 minutes). Buckets older than the watermark are finalized.
- Events within allowed lateness update their bucket normally, so the served top K may be revised slightly; this is acceptable for a trending list.
- Events beyond the lateness limit are dropped from the live view, or sent to a side output and applied by a nightly batch job that recomputes exact counts.
- Duplicates. Retries and restarts can double-count. Give each event a unique ID and dedupe with a short-lived store (keyed by ID, TTL a bit longer than the lateness bound), or rely on the stream's exactly-once semantics with transactional offsets and state. At-least-once without dedupe overcounts, which matters most near the K-th boundary.
5. Exact versus approximate
Exact counts cost memory linear in distinct URLs (about 5 GB in my estimate, comfortably shardable). If cardinality is much higher or per-window state is too costly, use a Count-Min Sketch, a few rows by a few hundred thousand counters (megabytes), plus a heap of candidate heavy hitters. Alternatives include Space-Saving or Misra-Gries, which track only the top candidates with bounded error.
Trade-offs: Count-Min Sketch only overestimates, with error about epsilon times total events. URLs whose true counts are close to the K-th place may be swapped or mis-ranked, while clear leaders are stable. Sketches also do not support deletes easily, so a sliding window needs one sketch per bucket, merged (summed) when queried.
Hybrid. Use the approximate path for a fast, cheap candidate list (say the top 5K), then recount only those candidates exactly from bucketed counters or a batch store, or run a slower exact batch/stream job and reconcile. This gives low latency with exact final ranks.
Common mistakes
- Merging local top-K lists after splitting a URL across workers without a combine step.
- Using processing time, so late events land in the wrong window.
- Making clients query the counting workers rather than a precomputed cache.
- Forgetting to expire old buckets, so counts and memory grow forever.
- Ignoring duplicates from retries.