Design Search Autocomplete (Typeahead)
Return the top suggestions for a typed prefix within tens of milliseconds, using tries or precomputed prefix tables built from query logs.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Event Streaming with Kafka, Caching Fundamentals and Cache Layers
As a user types "biry" on Swiggy or "iph" on Flipkart, suggestions must appear in under about 100 ms, updated with every keystroke. That latency budget drives the whole design.
Requirements
- Given a prefix, return the top 5 to 10 suggestions ranked by popularity (and maybe personalisation, location, trends).
- Very high read QPS (every keystroke is a request), low latency.
- Suggestions can lag reality by minutes or hours; strict freshness is not needed.
Data structure
A trie keyed by characters. To make lookups O(prefix length), store the top K completions at every node, so a query just walks the prefix and returns the cached list. Without that, you would traverse the whole subtree per keystroke. An alternative is a prefix table: precompute prefix to top K list in a key-value store (Redis or similar), which is simple to shard and cache.
Two pipelines
- Data collection: log search queries to Kafka; aggregate counts per query in batch (hourly or daily) or in a streaming job for trending terms, with time decay so old popularity fades.
- Build and serve: periodically build a new trie or prefix table from the aggregates and swap it in atomically. The serving layer is read-only and heavily replicated.
Scaling and latency
- Shard by prefix (careful: "s" is far hotter than "x"; shard by hashed prefix or by prefix ranges sized by traffic).
- Cache popular prefixes at the edge or in the client; debounce keystrokes (wait 50 to 100 ms) and cancel stale requests on the client.
- For product search, engines like Elasticsearch offer completion suggesters with fuzzy matching for typos.
Pitfalls
- Updating the trie on every search in real time and locking the read path.
- Ignoring offensive or unsafe suggestions; keep a blocklist filter.
- Forgetting multi-language and transliterated queries common in India ("paneer" vs Hindi script).
You are ready to move on when you can explain why storing top K at each trie node matters, and draw the offline and online pipelines.
Key concepts
- Trie with top K per node
- Prefix table in key-value store
- Query log aggregation
- Time decay and trending
- Atomic index swap
- Client debouncing and caching
- Typo tolerance
Mini project
Build an autocomplete service: generate a fake query log, aggregate counts, build a trie with top 5 per node, serve it over HTTP, and add a front end with 80 ms debounce. Measure p99 latency for 10,000 random prefixes.
Check yourself
Why is it better to rebuild the suggestion index periodically and swap it in than to update it on every search query?
Free resources
- Trie (Wikipedia)
- Elasticsearch guide (Elastic)
- ByteByteGo System Design 101 (ByteByteGo)