Design a Search Autocomplete System: Trie Top-K Caching, Sharding & Analytics
The 100-Millisecond Rule for Typeahead Search
GET /v1/search?q=sys). To feel instantaneous without jitter, responses must arrive in under 100ms across ~24,000+ peak QPS (assuming 10M DAU × 10 searches × 20 keystrokes $\approx 2\text{B queries/day}$).SELECT ... WHERE query LIKE 'sys%' ORDER BY frequency DESC LIMIT 5 destroys databases under that load. Instead, production typeahead runs on in-memory Trie Caches built asynchronously.Search Autocomplete Trie Architecture
1. The Core Data Structure: Trie with Cached Top-K
"s" to sort millions of suffixes on every keystroke is still $O(n)$ too slow.Root
└── "s" [top 5: "system design", "spotify", "stripe", "sql", "swift"]
└── "sy" [top 5: "system design", "system design interview", "symfony", ...]
└── "sys" [top 5: "system design", "system design interview", ...]
max_length = 50), lookup time drops to $O(1)$ constant time!2. Two Separate Pipelines: Gathering vs. Serving
Path 1: Data Gathering Service (Asynchronous Offline Pipeline)
- Analytics Logs: Append search queries + timestamps to Kafka / S3 logs (
"system design",ts). - Aggregators: MapReduce / Spark / Flink jobs compute weekly (or hourly for trending news) query frequencies.
- Trie Builder & DB: Constructs the serialized Trie snapshot and stores it in a Trie DB (e.g., Cassandra/Document Store key-value snapshot per prefix).
Path 2: Query Serving Service (Read-Only Speed)
- Browser Cache + CDN: Cache static high-frequency prefixes like
"a","p","py"right in browser memory (Cache-Control: max-age=3600) and CDN edge. - Debouncing: Clients debounce keystrokes by ~100–150ms to cut redundant network calls in half.
- Trie Cache: Fleet of in-memory servers load the latest read-only Trie snapshot and swap pointers atomically when updated.
3. Scaling Beyond Single-Machine RAM: Prefix Sharding
- Naive Range Sharding (
a-mon Shard 1,n-zon Shard 2) causes massive imbalance ("s"and"c"receive vastly more traffic than"x"or"z"). - Shard Map Manager: Analyze historical prefix distribution and pack balanced prefix buckets onto shards (e.g., Shard 1 handles
"s", Shard 2 handles"u-z"), routing requests cleanly at the API gateway. - Safety Filter Layer: Maintain a fast profanity/blocklist filter at the serving gateway so blocked suggestions disappear instantly without waiting for weekly Trie rebuilds.