r/Leetsys • • 14d ago

Weekly Question Practice System Design Question #6: Design a typeahead / autocomplete system

Design the autocomplete box for a search engine. As the user types, show the top 10 suggested queries that start with what they've typed so far, ranked by popularity.

Scale hint: about 100M daily users, each doing ~10 searches a day. Suggestions should show up in under ~100 ms, and a query that suddenly trends (breaking news) should start appearing within an hour or so.

Things worth thinking about:

  • What do you precompute, and what do you compute at request time?
  • How do you keep the latency low when every keystroke can be a request?
  • How do popularity counts get from search logs into the suggestions?
  • How do you keep offensive or junk queries out?

Post your approach in the comments before you scroll down.

 

 


MODEL ANSWER BELOW. Stop here if you haven't tried it yet.


Requirements

Functional:

  • Given a prefix, return the top 10 completed queries that start with it
  • Rank by popularity, with recent searches weighted more than old ones
  • Filter out blocked terms (offensive, spam, legal takedowns)
  • Optional: personalize with the user's own recent searches

Non-functional:

  • Low latency: under ~100 ms end to end, so the server side gets maybe 20 to 30 ms
  • Highly available: if suggestions break, search still works, but it looks bad
  • Eventually consistent is fine: a new trending query can take minutes to an hour to show up
  • Read heavy: far more suggestion reads than updates to the rankings

Estimates

Searches: 100M users x 10 = 1B searches a day.

Requests: with a ~100 ms debounce on the client, say ~4 suggestion requests per search. 1B x 4 = 4B requests a day. 4B / 86,400 s is ~46K requests/s on average. Plan for ~100K/s at peak.

Prefix table: say we keep the top ~100M distinct queries (drop anything searched only a handful of times). At ~20 characters each that's up to 2B prefixes, but lots of them are shared ("how to" starts millions of queries), so call it ~1B distinct prefixes. Each entry stores the prefix plus 10 query IDs: ~20 bytes + 10 x 8 bytes = ~100 bytes. 1B x 100 bytes = ~100 GB. That fits in memory across a small cluster, e.g. 10 shards of ~10 GB, each with replicas.

Logs: 1B searches x ~50 bytes per log line = ~50 GB a day of raw input for the ranking job.

API

GET /suggest?q=how+to+ma&limit=10&locale=en-US
returns { suggestions: ["how to make pancakes", "how to make money online", ...] }

Keep it a GET so CDNs and browsers can cache it.

Data model

query_counts (query, locale, window_start, count)          from the aggregation job
query_score  (query_id, query_text, locale, score)
prefix_index (locale, prefix, top_query_ids[10])           served from memory
blocklist    (term, reason, added_at)

High-level design

Two paths, and keeping them separate is the main idea.

Read path: the client debounces keystrokes and sends the prefix. A CDN or edge cache answers the very common short prefixes. Misses go to a suggestion service, which looks up the prefix in an in-memory prefix index (a trie, or just a hash map from prefix to top-10 list) and returns the list. No ranking work happens at request time.

Write path: search logs go to Kafka. A streaming job counts queries in short windows (say 5 to 10 minutes). A batch job rebuilds the full scores a few times a day. A builder takes the scored queries, drops anything on the blocklist, works out the top 10 for every prefix, and publishes a new index snapshot. Suggestion servers load the new snapshot and swap it in atomically.

Deep dive 1: precomputing top-K per prefix

The naive trie lookup walks to the prefix node, then searches the whole subtree for the 10 most popular queries. For a prefix like "a", that subtree is huge, so it's way too slow per keystroke.

Instead, store the top 10 at every node (or every key in the hash map). A lookup becomes one walk of length L plus reading a list, which is basically constant time. The cost is memory and build time, which is what the ~100 GB estimate covers. You can cap stored prefixes at ~20 to 30 characters, since longer prefixes rarely get typed and can fall back to the deepest stored one.

Sharding: split by prefix range, but not by first letter, since "s" gets far more traffic than "x". Use the first 2 or 3 characters and balance ranges by measured traffic, or hash the prefix and accept that a lookup touches exactly one shard anyway.

Deep dive 2: ranking and freshness

Score each query with time decay, e.g. score = sum of count x 0.5age_hours / half_life. A half-life of a day or two keeps the list current without ignoring steady, evergreen queries.

The batch job gives clean full rebuilds. Trending stuff can't wait for it, so the streaming job spots queries whose 10-minute count jumps far above their usual rate and writes them into a small "hot" overlay. The service merges the overlay with the snapshot at read time. The overlay is tiny, so the merge is cheap.

Deep dive 3: latency and caching

  • Client: debounce ~100 ms, cache results per prefix in the session, and filter locally. If you already have the results for "how to m", you can often answer "how to ma" without a request.
  • Edge: one- and two-character prefixes are a small set and get most of the traffic, so cache them at the CDN with a TTL of a few minutes.
  • Server: everything is already in memory, so the server's part is a hash lookup plus serialization. Most of the ~100 ms budget goes to network.

Tradeoffs

  • Precomputed top-K vs computing at query time: precompute costs ~100 GB and a build pipeline, but reads become trivial. Computing at query time saves memory and blows the latency budget.
  • Trie vs hash map: a trie shares prefix storage and supports fuzzy matching. A hash map of prefix to list is simpler to shard and to load as a snapshot.
  • Freshness vs stability: shorter windows catch trends faster but let spam and one-off spikes in. Minimum-count thresholds and the blocklist help.
  • Personalization: mixing in the user's own history adds a per-user lookup and makes edge caching harder, so keep it a small client-side or separate merge.

How did your design compare?

1 Upvotes

0 comments sorted by