KatInterview

Trending Queries Service: Ranking the Most Frequent Searches

System DesignModel answer
MediumModel answerSystem Designsystem-designtop-kstreaming

Last updated

Design a scalable pipeline that ingests a high volume of search events and serves low-latency Top-K rankings, both all-time and over recent sliding windows, across multiple regions.

Problem

You are asked to design a backend service that watches what users type into a search box and reports which queries are most popular right now and over all time.

Functional requirements

  • An interface to record a search event, for example a user searching for "iphone 16".
  • An interface to retrieve the Top-K most frequent entries.
  • Two ranking scopes:
    • All-time Top-K.
    • Recent-window Top-K, covering the last N minutes or hours (a "trending" view).

Non-functional requirements

  • Very high write throughput from search events.
  • Low-latency reads for the Top-K result.
  • Horizontal scalability.
  • Sensible correctness. You decide, and justify, whether exact or approximate counts are acceptable.

Points your design should settle

  • What counts as an item: a single word or the whole query string?
  • Normalization rules: case, punctuation, whitespace, stop words.
  • Whether repeated searches by the same user count once or every time.
  • Behavior across multiple regions, including what consistency users can expect.

What to deliver

Walk through the requirements and assumptions, rough capacity numbers, the API, the architecture, the data model, how sliding windows and all-time ranking are computed, and how you handle hot keys, memory pressure, deduplication, and multi-region operation. Call out trade-offs.

Hints

Hint 1

Pick sensible defaults first (full normalized query vs. token, approximate vs. exact, freshness target) and give rough numbers for events per second, distinct queries and read QPS before drawing boxes.

Hint 2

Think about how events are partitioned across workers. If one query's counts are spread over many shards, merging each shard's local Top-K can give wrong answers. What partition key makes the merge correct, and what do you do when one key gets extremely hot?

Hint 3

A heap does not handle counts that go down when events expire. Consider fixed-size time buckets with a running total (add the new bucket, subtract the expired one), and consider Count-Min Sketch plus a heavy-hitter structure if memory becomes a problem.

Hint 4

Keep the read path trivial: precompute snapshots and serve them from a cache. Use a batch job for exact all-time counts and a streaming layer for recent deltas.