KatInterview

Trending Pages Leaderboard: Top K URLs in a Rolling Window

System DesignModel answer
MediumModel answerSystem Designsystem-designstreamingtop-k

Last 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.