Design a Prefix Autocomplete Service with Live Trend Signals
System DesignModel answerLast updated
Design a distributed autocomplete backend that returns the top 10 popularity-ranked query completions for any typed prefix in under 30ms at global scale.
Context
A large social content platform lets users search for topics, ideas, and creators. As a user types in the search bar, the product fires a request on nearly every keystroke and renders a dropdown of up to 10 suggested completions. The team wants you to design the backend service powering those suggestions.
The system must feel instant, stay accurate during viral moments (a trending topic should surface within a few minutes), and never become a single point of failure for the broader search experience.
Functional Requirements
- Given a typed prefix string, return the top 10 query completions ranked by a popularity score.
- Scoring must reflect both long-term historical popularity and short-term trending activity (spikes visible within 2–5 minutes).
- The system must be able to suppress or filter completions that violate content policy (banned, adult, or abusive terms).
Non-Functional Requirements
- Latency: p99 end-to-end read latency under 30ms globally.
- Availability: 99.99% uptime; autocomplete degrading must not break core search.
- Scale: 1 billion registered users, ~500 million daily active searchers.
- Freshness: A newly viral query should appear in completions within 2–5 minutes.
Traffic and Scale Estimates
- Daily active users: 500M, averaging 4 searches per day.
- Autocomplete QPS: Each search generates roughly 5 autocomplete requests after client-side debouncing (~15 keystrokes, grouped). That's ~10 billion autocomplete requests per day — about 115,000 QPS on average and 300,000 QPS at peak.
- Vocabulary size: ~100 million unique query strings tracked globally.
What to Cover
Your answer should address all four of the following areas:
-
Data model and serving engine — Compare serving from a live trie versus a precomputed prefix-to-top-list key-value store. Reason through memory footprint, read/write trade-offs, and why one is more practical at this scale.
-
Freshness pipeline — Describe how you would blend a stable batch-computed baseline (e.g., a daily job) with a real-time streaming signal (e.g., a 5-minute sliding window) to produce a single score per query. Include the data flow from raw search events to updated completions.
-
Sharding and hot-prefix handling — Single-letter and two-letter prefixes ("h", "ho", "s") receive a wildly disproportionate share of traffic. How do you prevent those keys from overloading individual nodes?
-
Replication and update propagation — How do you push batch snapshots and streaming delta updates to all replicas without causing latency spikes or serving stale or inconsistent lists?
Include rough numbers where they help justify design choices.
Hints
Hint 1
Start with a back-of-envelope calculation: how large is the full prefix keyspace, how many bytes per entry, and does the whole table fit in RAM? That number drives the rest of the architecture.
Hint 2
Serving a trie dynamically on every read sounds appealing but falls apart for short prefixes — think about what the subtree under 'd' looks like. A precomputed flat key-value table swaps write amplification (one query update touches many prefix keys) for predictable O(1) reads. At 5K writes/s that trade is very favorable.
Hint 3
Short prefixes (length ≤ 3) are maybe 1% of the key space but carry 40–50% of traffic. Treating them as a special tier — fully replicated into every node's local memory plus cached at the CDN edge — removes most of the hot-key problem before it reaches your origin shards.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scope and Estimate Scale
Before diving in, nail down a few assumptions: matching is exact prefix on normalized text (lowercase, Unicode NFKC, collapsed whitespace); fuzzy/typo correction is out of scope; suggestions are scoped per locale.
Back-of-envelope
| Quantity | Estimate |
|---|---|
| Read QPS | 115K avg, 300K peak — design for ~1.2M to absorb a 4× spike |
| Vocabulary | 100M queries × ~30 bytes ≈ 3 GB dictionary |
| Prefix keyspace (raw) | Every prefix up to 20 chars ≈ 1B keys |
| Prefix keyspace (pruned) | ~300M keys after dropping prefixes below a volume floor |
| Bytes per entry | ~200B: 20B key + 10 × (8B query ID + 4B score) + overhead |
| Total serving table | ~60 GB — fits in RAM across a small shard set, replicated |
| Write rate | ~100K score changes per 5-min window × 15 prefixes each ≈ 5K writes/s |
The system is roughly 60:1 reads to writes. Every choice should favor read performance.
2. API Design
GET /v1/autocomplete?q=home%20d&locale=en-US&limit=10
200 OK
{
"prefix": "home d",
"version": 18342,
"suggestions": [
{"text": "home decor", "id": 7821},
...
]
}
- Responses carry
Cache-Control: max-age=60, stale-while-revalidate=300. - The client debounces keystrokes ~50–100ms and cancels in-flight requests when the user types further.
- The
versionfield lets clients discard out-of-order responses.
3. Data Model: Precomputed KV vs. Live Trie
Live trie traversal: walk to the prefix node, then scan its subtree for the top 10. The problem is that short prefixes have enormous subtrees — the subtree under "d" may span millions of completions. Even if you cache top-K at each node, a pointer-heavy trie carries 2–5× memory overhead, is hard to snapshot and replicate atomically, and produces GC and cache-miss tail latency.
Precomputed prefix → top_10_list: reads become a single O(1) hash lookup with no traversal. The table is flat, immutable, and trivially sharded. The cost is write amplification — updating one query's score touches up to 20 prefix keys — but at 5K writes/s that is negligible.
The practical architecture: run a trie offline in the batch job to propagate top-K scores upward, then emit the flat KV table. Serving nodes store query IDs rather than full strings and resolve them through a local in-memory dictionary, keeping entries small and allowing content suppressions to be applied in one place.
Storage engine: an in-process memory table (custom memory-mapped files or RocksDB-on-RAM with an LRU in front) inside the autocomplete service. Avoiding a network hop to a remote cache is what gets you under 1ms for the lookup itself.
4. Hybrid Freshness Pipeline
A two-term score separates stable signal from trending signal:
score(q) = log(1 + H(q)) + β · max(0, z(q))
H(q) = exponentially decayed historical count (daily job, ~14-day half-life)
z(q) = (count_5min(q) − expected_5min(q)) / sqrt(expected_5min(q) + 1)
z is a normalized deviation from the expected 5-minute rate. Viral spikes lift a query additively without overwriting historical rank. When the spike fades, z returns to 0.
Batch path (daily)
- Spark reads search logs, computes H(q) with decay, applies offline blocklists and classifiers.
- Builds the full prefix table as a versioned immutable snapshot
vN. - Also publishes
expected_5min(q)for each query for use by the streaming path.
Streaming path (every 1–5 minutes)
- Search events enter Kafka, partitioned by normalized query string.
- Flink maintains a sliding 5-minute window (1-minute slide) and computes
z(q). - For queries whose total score changed materially, Flink emits a delta.
- A Prefix Updater fans each delta out across the query's prefix keys — but only rewrites a prefix's top-10 list when the query's new score exceeds the current 10th-place score or the query is already in the list. This pruning eliminates most fanout.
- Each write replaces the entire list for a key atomically; no partial patches.
End-to-end freshness: roughly 2–3 minutes.
5. Sharding and Hot-Prefix Handling
Partitioning: hash (locale:prefix) across shards with 3+ replicas per shard per region. Never range-partition by first character — that puts all of "s" on one node.
Short prefixes (length ≤ 3) are the real problem. There are only ~1M such keys across all locales (~250 MB), yet they carry an estimated 40–50% of total traffic.
- Fully replicate them into every serving node's local memory. No shard routing needed; the lookup is always local.
- Cache at the CDN edge with a 30–60s TTL. A hit rate above 90% on these keys removes most load from origin entirely.
- Coalesce requests at both the edge and the service layer: one origin fetch per key per TTL window, regardless of how many clients asked simultaneously.
Long prefixes follow a long-tail distribution and route normally to sharded origin. A regional in-memory cache in front of origin handles medium-hot keys like "home decor" cheaply.
Latency budget check
| Path | Latency |
|---|---|
| CDN edge hit | ~5–10ms |
| Edge miss → regional service + lookup | ~15–20ms |
Both paths fit within the 30ms p99 target.
6. Replication and Update Propagation
Batch snapshots use a blue/green flip
- Each replica downloads snapshot
vN+1alongside the livevN. - It warms the new snapshot by paging through its data.
- It atomically swaps a pointer. No in-place mass mutation, so no latency spike.
- Rollout staggers across replicas; an automatic rollback fires if quality metrics regress.
Streaming deltas
- Deltas publish to a Kafka topic consumed by every replica.
- Each delta carries
(prefix, full_top_10, base_version, seq)— always the full list, never a diff. - A replica applies a delta only if
seqis newer than what it holds for that key. This makes application idempotent and order-safe. - On a snapshot flip, the replica replays deltas from the snapshot's recorded watermark forward.
Consistency model: brief cross-replica divergence of a few seconds is acceptable. Within a single replica every list is internally consistent because writes are whole-list replacements.
Content suppression: offline classifiers run at batch build time. Online, a small replicated suppression set is checked at serve time and propagates within seconds. Suppressed slots are backfilled from positions 11–15, so store top-15 per prefix. An async job then rewrites affected prefix keys.
7. Key Trade-offs
- Precompute vs. compute on read: spending write amplification upfront buys predictable O(1) tail latency on the read path.
- Freshness vs. stability: the additive scoring model lets trending signals surface quickly without destabilizing the historical baseline when spikes fade.
- Short-prefix replication vs. sharding: full replication of a small hot tier trades a little memory for a massive reduction in cross-shard hot-key traffic.
- Whole-list writes vs. partial updates: more bytes per write, but eliminates partial-read inconsistency and simplifies replica convergence significantly.
Common mistakes to avoid: range-partitioning by prefix character (creates instant hot shards), patching individual items within a stored list (opens a window for inconsistent reads), and skipping the pruning step in the Prefix Updater fanout (causes write amplification to blow up during viral spikes).