Video in progress
How do you design an autocomplete (typeahead) service for a search box?
Popular queries are computed offline and stored in memory as ready-made top-N lists by prefix (a trie or a prefix -> results map). Each keystroke is a single fast lookup, and the client reduces the number of requests with debounce and a cache.
📖 Answer
The requirement: 5–10 suggestions within 50–100 ms on every keystroke. When a user types "jav", "java stream", "java interview", "javascript" should show up.
Querying the DB with LIKE 'jav%' on every request doesn't work — traffic multiplies with every keystroke and sorting (by popularity) is expensive each time.
Two parts:
Offline aggregation. Query counts are computed from the search logs (the last 7–30 days), with newer ones weighted more heavily. For each prefix the top 10 results are prepared in advance: "j" -> [...], "ja" -> [...], "jav" -> [...]. The prefix length goes up to, say, 20 characters. This is an hourly or daily batch job.
The online service. The ready map sits in each instance's memory or in Redis. A request is a single lookup:
// prefix -> ready-made top 10, in memory
Map<String, List<String>> suggestions = loader.load();
List<String> suggest(String q) {
String key = normalize(q); // lowercase, whitespace
return suggestions.getOrDefault(key, List.of());
}
A trie works too, but unless every node stores a top-N, you have to walk the tree on every request — slow. So in practice prefix -> ready-made list is often simpler and faster.
On the client side:
- a 150–250 ms debounce;
- cache responses on the client (the response for "java" can be reused for "javas" with filtering);
- if an old request's response arrives after a newer one — ignore it.
Things people forget: filtering offensive and illegal queries, typo tolerance (that's a separate layer), mixed Latin/Cyrillic input. If you need personalization, the user's recent searches are added on top of the general list.
Sign up to mark studied questions and save your progress.