Quick revision
The short answer
The batch layer counts queries from the logs with time decay, drops rare and unsafe queries, builds the prefix table offline and publishes it as a versioned snapshot that servers swap atomically. A fresh layer next to it is a stream job that counts queries over sliding windows of a few minutes, using exact counts for heavy hitters or a Count-Min Sketch, and keeps a small trending top-k per prefix. At query time we merge the two lists, boosting queries whose recent rate far exceeds their usual rate with a cap on trending entries, guard the fast path with minimum distinct users, safety filters and manual removal, and measure the gain with click-through and keystrokes saved.
What to remember
In this answer, we combined a batch layer and a fresh layer. The batch layer counts logged queries with time decay, filters rare and unsafe queries, and publishes a versioned prefix snapshot that servers swap atomically. The fresh layer counts queries in sliding windows of a few minutes with heavy-hitter counts or a Count-Min Sketch and keeps a trending top-k per prefix. At query time the server merges both, boosting queries far above their usual rate with a cap on trending entries, guards the fast path with distinct-user thresholds, safety filters and manual removal, and we measure the gain with click-through and keystrokes saved in an A/B test.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The batch layer counts queries from the logs with time decay, drops rare and unsafe queries, builds the prefix table offline and publishes it as a versioned snapshot that servers swap atomically. A fresh layer next to it is a stream job that counts queries over sliding windows of a few minutes, using exact counts for heavy hitters or a Count-Min Sketch, and keeps a small trending top-k per prefix. At query time we merge the two lists, boosting queries whose recent rate far exceeds their usual rate with a cap on trending entries, guard the fast path with minimum distinct users, safety filters and manual removal, and measure the gain with click-through and keystrokes saved.
Why this question is asked
A daily rebuild from 30 days of logs is a sound start, but it means a breaking news story cannot appear in suggestions until tomorrow, and even then 29 older days outweigh it. Interviewers like this question because the fix is a classic pattern: a slow, complete batch layer combined with a fast, approximate streaming layer. In this answer, we will improve the batch build with time decay and safe publishing, add a streaming layer with sliding windows and sketches, merge the two at query time, protect the fast path from abuse, and decide how to measure whether it helps.
1Why the Daily Rebuild Misses the News
There are two separate delays. The first is the schedule: a once-a-day build can be up to 24 hours late. The second is the weighting: if counts are simple sums over 30 days, a query searched 2 million times today still loses to one searched 100,000 times a day for a month, which totals 3 million. Even a faster rebuild would not help unless recent searches weigh more. So we fix the weighting in the batch layer and add a separate fast layer for the schedule.
2The Batch Layer: Decayed Counts and Safe Publishing
A batch job, for example in Spark over the logs in object storage, normalises every logged query and computes a decayed score: each day's count is multiplied by a weight that halves every few days. With a 7-day half-life, a search from today counts 1.0, from a week ago 0.5 and from a month ago about 0.05. It then drops queries searched by fewer than a minimum number of distinct users, which removes typos, private information typed into the box and noise, applies the safety filters, and builds the prefix to top-k table.
The output is a versioned snapshot. Servers download it in the background, check it, then switch a single pointer, so every request sees either the old version or the new one, never a mix. Keeping the previous version means a bad build is rolled back in seconds.
3The Fresh Layer: Counting in Sliding Windows
The fresh layer reads the stream of search events, for example from a Kafka topic, in a stream processor such as Apache Flink or Kafka Streams. It counts queries over sliding windows of a few minutes, say the last 10 minutes updated every minute, and compares each query's recent rate with its usual rate from the batch layer.
Counting every distinct query exactly in memory would be expensive, because most queries are rare. Two techniques help. Heavy-hitter algorithms keep exact counts only for the most frequent items. A Count-Min Sketch is a small fixed-size table of counters with several hash functions; each query increments one counter per row, and its estimated count is the minimum across its counters. It can only overestimate, and with a few MB of counters the error for frequent queries is tiny. From these counts, the job keeps a small trending top-k per prefix, perhaps 3 to 5 entries, and publishes it every minute to a store the suggest servers read, such as Redis.
- Suggest servermerges both lists per request
- Fresh layer storetrending top-k per prefix, updated every minute
- Stream jobsliding 10-minute windows, Count-Min Sketch
- Search event streamKafka topic of normalised queries
- Batch snapshotdecayed 30-day counts, rebuilt daily
5 layers, from the top down. Step through them one at a time.
4Merging Both Lists at Query Time
The suggest server reads the batch list for the prefix from memory and the trending list from the fresh store, then merges them. The ranking boosts queries whose recent rate is far above their usual rate. A simple trend score is the ratio of the last 10 minutes' rate to the baseline rate from the batch layer, with a floor so new queries do not divide by zero. A query normally searched 50 times an hour and now searched 20,000 times an hour has a ratio of 400 and clearly belongs near the top.
We cap how many trending entries can appear, for example two of the ten, so a burst of news never pushes out everything people normally need.
| Suggestion | Batch score | Trend ratio | Shown at |
|---|---|---|---|
| earthquake today | low | 400 | 1 (trending, capped at 2) |
| earth | high | 1 | 2 |
| earthquake near me | medium | 35 | 3 (trending) |
| earth day | medium | 1 | 4 |
5Guarding the Fast Path
The fresh layer is exactly where abuse slips in. A batch build has a day of data and human review; a trending layer reacts in minutes, so a few hundred bots or a coordinated group can push an offensive or defamatory phrase into suggestions before anyone looks. So a query must be searched by a minimum number of distinct users, counted by user or device, not by requests, before it can trend. It passes through the same safety filters as the batch layer. And operators get a manual removal tool that takes effect within minutes across all servers, with an audit log. These guards cost a little freshness and buy a lot of safety.
6Measuring Whether It Helps
Finally, we prove the fresh layer is worth running. Two metrics matter: suggestion click-through, the share of searches where the person picked a suggestion, and keystrokes saved, how many characters the suggestion spared them. We run an A/B test with and without the fresh layer, and look especially at searches during trending events, where the gain should be largest, and at complaint and removal rates, where the risk shows up.
7Follow-up questions
Why not just rebuild the batch layer every five minutes?
Rebuilding the whole prefix table from billions of logged queries takes significant compute and time, and most of the table does not change minute to minute. A small streaming layer for the part that does change is cheaper and faster than repeating the full build.
What happens when the fresh store is unavailable?
The suggest server times out quickly, in a few milliseconds, and serves the batch list alone. Suggestions are a little less fresh but still correct, so the fresh layer can fail without users noticing an outage.
How long does a trending query stay boosted?
Only while its recent rate stays high. As the sliding window moves on, the ratio falls, and if interest persists the next batch build, with its time decay, gives the query a permanent place on its own merits.
8Conclusion
In this answer, we combined a batch layer and a fresh layer. The batch layer counts logged queries with time decay, filters rare and unsafe queries, and publishes a versioned prefix snapshot that servers swap atomically. The fresh layer counts queries in sliding windows of a few minutes with heavy-hitter counts or a Count-Min Sketch and keeps a trending top-k per prefix. At query time the server merges both, boosting queries far above their usual rate with a cap on trending entries, guards the fast path with distinct-user thresholds, safety filters and manual removal, and we measure the gain with click-through and keystrokes saved in an A/B test.
Open with
I would keep a batch layer and add a fresh layer. In the batch layer, a job over the logs counts queries with time decay, say a 7-day half-life, so recent days weigh more, drops rare queries below a distinct-user threshold and unsafe ones, builds the prefix to top-k table offline, and publishes it as a versioned snapshot that servers load in the background and swap atomically, keeping the previous version for rollback.
Then, if they want more
The fresh layer is a stream job, Flink or Kafka Streams on the search event topic, that counts queries over sliding windows of a few minutes. It uses exact counts for heavy hitters or a Count-Min Sketch to keep memory small, and maintains a small trending top-k per prefix in a store like Redis.
At query time the server merges both lists with a score that boosts queries whose recent rate is far above their usual rate, and caps trending entries at maybe two of ten.
The fast path needs guards: a minimum number of distinct users before anything can trend, the same safety filters, and manual removal within minutes, because that is where abusive suggestions slip in. And I would measure suggestion click-through and keystrokes saved in an A/B test with and without the fresh layer.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How do you build top-k suggestions per prefix from billions of logged queries, and add a...": https://scrivio-interview-library.netlify.app/architecture/system-design-problems/003fc2f74d/