Trending Queries Service: Ranking the Most Frequent Searches
System DesignModel answerLast 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and set assumptions
State defaults and confirm them:
- Item: the full normalized query ("iphone 16"), since a trending widget shows queries. Offer a "word mode" that tokenizes and counts each token; it multiplies write volume by roughly 3x (about 3 tokens per query).
- Normalization: Unicode NFKC, lowercase, trim and collapse whitespace, strip leading/trailing punctuation. Remove stop words only in word mode, because dropping "the" from "the office" changes the meaning. Spell correction belongs to the search team.
- Dedup: count every event, but suppress repeats of the same (user, query) within about 60 seconds so refreshes and pagination do not inflate counts. Bots are filtered upstream.
- Accuracy: trending is a UI feature, so approximate counts are fine as long as ranking is stable and counts are close. Exact all-time numbers come from a batch job.
- Freshness: 30-60 seconds of lag is acceptable. Multi-region views are eventually consistent.
Scale (state aloud): about 100K events/s average, 300K/s peak, roughly 10B/day. About 500M distinct queries per day with a long tail. Around 100 B per event gives about 1 TB/day raw. Reads: about 10K QPS with K up to 100 (cap at 1000). Windows: all-time, 5 min, 1 h, 24 h.
2. API
POST /v1/search-events { user_id, query, region, timestamp } -> 202 Accepted
GET /v1/topk?window=1h&k=10&mode=query®ion=global
-> { window, generated_at, items: [{ term, count }] }
In practice the search service publishes to Kafka directly. Reads return a precomputed snapshot; nothing is computed on the request path.
3. Architecture
Search service -> Kafka (partition = hash(normalized query))
-> Stream aggregators (e.g. Flink): dedup -> per-minute counts -> local Top-M
-> Merger every 5-10 s -> Redis snapshots
Raw events -> object store -> daily Spark job -> exact all-time counts
- Ingest: normalize at the producer; partition by hash of the normalized query.
- Aggregate: each worker owns a disjoint set of queries, maintains per-minute counts, and emits a local Top-M with M much larger than K (say 1000).
- Merge: a small service merges the shards' Top-M lists with a heap and writes
topk:{window}:{mode}:{region}to Redis. - Serve: a Redis GET (under 5 ms), optionally cached for a few seconds at the edge.
4. Data model
- Aggregator state (checkpointed):
(minute_bucket, query) -> count. - All-time store (wide-column DB):
query -> total_count, plus a materialized all-time Top-K table. - Redis snapshot:
topk:1h:query:global -> [(term, count)...]withgenerated_at.
5. Why partition by query
If events are spread randomly, merging local Top-Ks is wrong: a query ranked #11 on each of 50 shards can be #1 globally yet appear in no local list. Partitioning by hash(query) puts a query's entire count on one shard, so every global Top-K member is in its owner's local Top-K and the merge is exact for the counted values.
Hot keys: a viral query would overload one partition. First pre-aggregate: producers or a combiner stage send (query, count) batches every second. If still too hot, salt the key (query#0..#7), sum the salted counts in a second stage, then rank.
6. Sliding windows
Heaps cannot cope with counts that shrink. Use bucketing:
- Keep 1-minute buckets. "Last N minutes" is the sum of N buckets.
- Maintain a running total per query: when the minute rolls, add the newest bucket and subtract the one that expired.
- Use hierarchy to bound memory: minute buckets for the last hour, hour buckets for the last 7 days.
- Every 5-10 s each shard rebuilds its local Top-M from the totals using a size-M min-heap, O(n log M).
Memory: a shard may see 10M+ distinct tail queries per hour. Options:
- Prune keys whose window count is below a threshold.
- Approximate: per bucket keep a Count-Min Sketch plus a Space-Saving/Misra-Gries list (about 10K candidates). For a window, union candidates and estimate each by summing sketches (sketches merge by element-wise addition). With epsilon = 1e-4 and delta = 1%, width is about 27K and depth 5, roughly 136K counters or 0.5 MB per bucket. Error is at most epsilon times total volume with probability 1 - delta. The trade-off: a query that is never a heavy hitter in any single bucket but is large in sum can be missed. That is rare for a top-100 list and acceptable for trending.
All-time: do not hold it in streaming memory forever. Use a lambda-style split: a daily batch job computes exact counts from raw logs, the stream adds deltas since the last batch, and the merger combines batch Top-M with streaming deltas. This also lets you reprocess after a normalization bug.
7. Dedup and abuse
- Keyed-state TTL set of
(user_id, query)with a 60 s TTL, co-partitioned with the query. - At larger scale, a time-rotated Bloom filter; false positives drop a few legitimate events, which is acceptable.
- Rate limiting and bot filtering upstream so one user cannot push a query into trending.
8. Multi-region
- Each region runs its own pipeline and serves regional Top-K, which users often want anyway.
- For a global view, regions ship per-minute partial aggregates (Top-M lists or sketches), not raw events, to a global merger. This cuts cross-region bandwidth dramatically.
- Results are eventually consistent; a region outage only delays its contribution to the global list.
9. Failure handling and operations
- Flink checkpoints plus Kafka offsets give at-least-once or effectively-once counting; small overcounts after replay are tolerable for trending.
- If the merger fails, Redis keeps serving the last snapshot; expose
generated_atso clients can see staleness. - Monitor consumer lag, snapshot age, and sketch error against the batch ground truth.
Trade-offs and common mistakes
- Exact vs. approximate: exact is simple but memory-heavy for long tails; sketches cut memory by orders of magnitude at a bounded error.
- Common mistakes: partitioning randomly then merging local Top-Ks; using a single heap for sliding windows; computing Top-K on each read; ignoring hot keys; stripping stop words in query mode; shipping raw events across regions; keeping all-time counts only in streaming state with no way to reprocess.