Search Autocomplete / Typeahead
The suggestions that appear as you type — sub-50ms, popularity-ranked, at web scale — worked through the TOGAF ADM.
Typeahead, the ADM way, in 30 seconds
- A (Vision): instant, relevant suggestions as the user types; principles — read path must be blazing fast, suggestions reflect real popularity, cheap per keystroke.
- B (Business): two very different capabilities — serve suggestions fast (hot read) and learn what's popular (cold batch); they share almost nothing.
- C (Data/App): a prefix structure (trie) of precomputed top-k suggestions on the read side; raw query logs feeding an offline aggregation on the write side.
- D (Technology): build a trie whose nodes carry precomputed top-k suggestions, served from memory for sub-50ms; refresh it periodically from aggregated query logs.
- E–H: ship a static trie, add the log-driven refresh, then shard and cache; govern with latency SLOs and refresh cadence.
- Lesson: 'blazing-fast reads' (Phase A) is why Phase D precomputes everything offline instead of ranking at query time.
A waiter who finishes your sentence
A great waiter at your regular café starts suggesting your order before you've finished the first word — 'the usual flat white?' They're not thinking in that instant; they already know, from a thousand past visits, what people who start with 'fl...' usually want. A typeahead works the same way: the moment you type sys, it offers the most likely completions, and the only reason it can answer that fast is that it did the thinking earlier and is now just recalling the answer.
That split — think ahead of time, recall instantly at the moment of truth — is the whole design, and it's forced by a single brutal constraint: the suggestion has to appear in the gap between your keystrokes. There's no time to rank candidates when you type; the ranking must already be done. So the system is really two systems: a slow, offline one that figures out what's popular, and a fast, online one that just looks up the pre-figured answer.
What makes it hard — the problem before the solution
- The latency budget is savage. A suggestion must land in the tens of milliseconds between keystrokes, or it's useless — so no ranking can happen at request time.
- Volume is enormous. One call per keystroke per user means the read path is among the busiest in the whole product.
- Rankings must track reality. Suggestions should reflect what people actually search now, which is a big, slow, batch computation.
- The two halves share almost nothing. A hot latency-critical read and a cold throughput batch are opposite systems joined only by a periodic publish.
Why the ADM fits
Typeahead looks trivial — match a prefix, return some strings — until you realize it must respond within the gap between keystrokes, rank by real-world popularity, and do it for every user on every character. The trick is that the read path and the write path are almost entirely different systems. The ADM keeps that in order: the blazing-fast reads principle from Phase A is precisely why Phase D precomputes top-k suggestions offline and serves a trie from memory, instead of scoring candidates live. Each technology choice is a consequence of a principle or a capability, not a guess.
Phase A — Architecture Vision
Intent: agree what we're building, for whom, and the principles that constrain every later choice.
- Vision: show a short list of the most likely completions the instant a user types a prefix, so they find what they want faster.
- Stakeholders: end users (want instant, relevant suggestions), the search product (wants suggestions that drive good queries), operators (want it cheap despite enormous read volume).
- Principles (the constraints that cascade): read path must be blazing fast (a suggestion that arrives after the next keystroke is useless); suggestions reflect real popularity (rank by what people actually search); cheap per keystroke (millions of lookups must each cost almost nothing).
Phase B — Business Architecture
Intent: model the business capabilities and value streams before any technology talk.
- Value stream: user types a prefix → sees ranked suggestions → picks one → runs a search → that search feeds back into what's popular.
- Capability 1 — Serve suggestions: staggering read volume (one call per keystroke), latency-critical, tolerant of slightly stale rankings.
- Capability 2 — Learn popularity: aggregate raw query logs into counts and top-k lists — high throughput but offline, with no latency requirement at all.
- Capability 3 — Refresh the read structure: periodically publish the newly computed top-k lists into the serving layer.
Impact: the two main capabilities are opposites. Serve suggestions is a tiny, hot, latency-critical read; learn popularity is a big, cold, throughput-oriented batch. Recognizing in Phase B that they share almost nothing is what lets Phase D build two independent systems joined only by a periodic publish — the single most important design decision here.
Phase C — Information Systems Architecture (Data & Application)
Intent: define the data and application architecture, and the gap from today (greenfield).
Data architecture
- Read-side structure: a trie of prefixes where each node stores the precomputed top-k completions for that prefix — the entire answer is already assembled, no scoring needed at request time.
- Write-side data: raw query logs (what people searched, how often) — append-only, huge, and only ever read in bulk by the aggregation job.
- Aggregated counts: per-query popularity totals (often over a rolling window) that feed the top-k computation.
- Conclusion: the access pattern — look up completions by prefix — is a pure prefix traversal, which chose the trie; the write side is a different shape entirely (see Indexing for the broader idea of precomputed lookup structures).
Application architecture
- A stateless suggestion service that holds the trie in memory and answers prefix lookups — scales horizontally per the Phase A principle.
- An offline aggregation pipeline (batch job over query logs) that computes top-k per prefix, fully decoupled from the serving path.
- A publish/refresh mechanism that swaps the freshly built trie into the serving tier without taking it offline.
Phase D — Technology Architecture (the core)
Intent: choose the concrete technologies and the deployment design that realize Phase C — and justify each one against the principles and numbers. This is where a technical interviewer spends most of the time, so we'll cover every step.
D1 — Estimate the load (sizing drives technology)
# 10M searches/day, each ~20 keystrokes -> ~20 suggestion calls per search
suggest_calls_per_day = 10_000_000 * 20 # 200M lookups/day
suggest_per_sec = suggest_calls_per_day / 86_400 # ~2,300 lookups/sec avg
# Latency budget: must return within the gap between keystrokes
latency_budget_ms = 50 # sub-50ms, so NO ranking at request time
# Trie: say 100M distinct queries, top-5 each -> precompute offline, keep hot part in RAM
# Verdict: read path = in-memory trie lookup; write path = periodic batch over logsThe numbers confirm the Phase B split quantitatively: a high-volume read with a punishing per-call latency budget on one side, and a large but latency-free batch on the other. That is why the read path does lookups only and all the thinking happens offline.
D2 — The read path (trie + memory + cache)
- Serve from a trie held in memory: walking a prefix is a handful of pointer hops, and the node already holds its precomputed top-k list — so a request is a traversal and a copy, no sorting or scoring, comfortably under the 50ms budget.
- Cache the hottest prefixes (see Caching): a small set of short, popular prefixes accounts for most traffic, so an in-front cache (or just the resident trie) absorbs the load cheaply — realizing cheap per keystroke from Phase A.
- Shard the trie by prefix range when it outgrows one node (see Sharding); a request routes to exactly the shard owning its prefix, so reads still hit one place.
- Keep it stateless and replicated so the fleet scales horizontally and a node loss doesn't drop suggestions.
class Node:
def __init__(self):
self.children = {}
self.top_k = [] # precomputed completions for this prefix (D2)
def insert(root, phrase, score, k=5):
node = root
for ch in phrase: # walk/extend the prefix path
node = node.children.setdefault(ch, Node())
# Cache the top-k at every node along the way (done offline).
node.top_k = merge_top_k(node.top_k, (score, phrase), k)
def suggest(root, prefix):
node = root
for ch in prefix: # a handful of pointer hops
node = node.children.get(ch)
if node is None:
return [] # no completions for this prefix
return [phrase for _, phrase in node.top_k] # already ranked -> just copyWhy precompute offline, and why not rank at query time?
The straightforward design is to rank when asked: user types sys, you query all matching phrases, score them by popularity, sort, and return the top five. It's less machinery and always perfectly fresh. The gap it can't fill is the clock. Fetching candidates, scoring, and sorting — on every keystroke, for every user — simply can't finish inside the sub-50ms gap between keypresses at scale. Freshness you can't deliver in time is worthless.
Precomputing flips the cost to where there's no deadline. All the scoring and sorting happens in an offline batch, far from any user, and the result — a tiny top-k list per prefix — is stashed in the trie. The online request does zero ranking: walk, copy, done. The price is staleness: suggestions lag reality by one refresh interval. For 'what are people searching for,' being an hour behind is invisible to users, so it's a trade worth making every time.
| Approach | What it buys | The gap it can't fill |
|---|---|---|
| Rank at query time | Always perfectly fresh. | Can't score + sort within the keystroke budget at scale — too slow. |
| Precompute top-k offline (chosen) | Online request is a lookup; easily sub-50ms. | Suggestions lag by one refresh interval — invisible for popularity data. |
| Hybrid (precompute + live personalization) | Fast base list, lightly personalized. | Adds request-time work — keep it tiny or the budget breaks. |
D3 — The write path (aggregate offline, refresh periodically)
- Collect query logs via a stream (see Message queues) so logging never touches the latency-critical read path.
- Aggregate offline in batch: a periodic job counts query popularity (often over a rolling time window so trends surface and stale terms fade), then computes the top-k completion per prefix — all the ranking work lives here, far from any request.
- Rebuild and publish the trie periodically (e.g. hourly or daily): build the new structure, validate it, then atomically swap it into the serving tier so suggestions refresh without downtime.
- Accept staleness as a trade: suggestions can lag reality by one refresh interval — this eventual freshness is exactly the trade Phase A's latency principle asked for (see Consistency models).
def build_top_k(query_logs, k=5):
counts = defaultdict(int)
for q in query_logs.window(hours=24): # rolling window: trends rise, stale terms fade
counts[q.text] += q.weight # weight recent/clicked queries higher
top_k = defaultdict(list) # prefix -> best completions
for phrase, score in counts.items():
for i in range(1, len(phrase) + 1): # every prefix of the phrase
prefix = phrase[:i]
top_k[prefix] = merge_top_k(top_k[prefix], (score, phrase), k)
return top_k # becomes the next trie — built far from any requestlive_trie = load_initial_trie() # what the read path serves right now
def publish(new_top_k):
fresh = build_trie(new_top_k) # build the whole structure OFF to the side
if not validate(fresh): # sanity-check before going live
return
global live_trie
live_trie = fresh # one pointer flip = instant, atomic swap
# Readers were never blocked: they saw the old trie, then the new one, never a half-built one.Scaling & bottlenecks — what breaks first
Because the read and write paths are separate systems, they strain in separate ways — and naming which breaks first on each side shows you understand the split.
| Breaks first as you scale | The symptom | The fix |
|---|---|---|
| Trie outgrows one node's RAM | The in-memory structure no longer fits. | Shard the trie by prefix range; route each lookup to the shard owning its prefix. |
| A few short prefixes are white-hot | Short prefixes like 'a' or 'th' take most traffic. | Cache the hottest prefixes in front; replicate those shards for reads. |
| Refresh job can't keep up | Logs pile up faster than the batch rebuilds the trie. | Aggregate incrementally over a rolling window; parallelize the batch. |
| The atomic swap stalls reads | Publishing a fresh trie briefly blocks lookups. | Build the new trie aside, then hot-swap the pointer — never rebuild in place. |
The decisive design move is the atomic swap: you never edit the live trie, you build a fresh one off to the side and flip a pointer when it's ready. That keeps the read path a pure lookup even while the write path is churning out a new structure — the two systems stay independent right up to the instant they meet.
Phases E & F — Opportunities, Solutions & Migration Planning
- Greenfield, so sequence by risk: first ship a static trie built from a one-off query-log dump to prove the read path and latency budget.
- Add the log-driven refresh next, turning the static trie into a periodically rebuilt one so popularity stays current.
- Then shard and add a cache layer once the trie or traffic outgrows a single node — each step independently shippable, echoing the expand-contract spirit of the TOGAF commerce scenario.
Phases G & H — Governance & Change Management
- Governance (G): define latency SLOs (suggestion p99 < 50ms), a refresh cadence (how stale top-k lists may get), and content policies (filtering offensive or sensitive completions).
- Change management (H): adding personalization or a new ranking signal is a bounded change to the offline aggregation job — not a re-architecture of the read path — precisely because the write path was isolated behind the periodic publish.
Typeahead is the cleanest example of splitting a system into a precompute-heavy write path and a lookup-only read path — a pattern that recurs wherever reads must be instant.
Why it matters
- It makes the 'do the work offline, serve the answer online' pattern concrete and defensible.
- It forces a sub-50ms latency budget that rules out any ranking at request time.
- It shows why popularity-ranked suggestions are a batch problem wearing a real-time costume.
If ignored
- Rank candidates at query time and you blow the keystroke latency budget, so suggestions arrive too late to help.
- Skip the offline aggregation and suggestions never reflect what people actually search.
- Couple logging to the read path and a logging hiccup slows every keystroke for everyone.
Where it fits
- Phase D holds the in-memory trie, the precomputed top-k, and the offline aggregation that feeds it.
- Phase A's blazing-fast-reads principle drives the no-ranking-at-request-time design.
- Sits beside the interview framework as a second way to structure the answer.
Related topics
- Caching: keeps the hottest prefixes instant and cheap
- Message queues: carries query logs to the offline aggregation off the read path
- Sharding: splits the trie by prefix range as it grows
- Indexing: the broader idea of a precomputed structure that makes lookups fast
Interview lens
Questions it unlocks
- Design search autocomplete / typeahead.
- How do you return ranked suggestions within the gap between keystrokes?
- Walk me through the technology architecture (Phase D) for a precompute-heavy, read-fast service.
60-second answer
I frame it as an ADM walk so every choice is traceable. Phase A sets principles — blazing-fast reads, suggestions that reflect real popularity, cheap per keystroke. Phase B finds two opposite capabilities: serve suggestions, a tiny hot latency-critical read, and learn popularity, a big cold latency-free batch. Phase C makes the read side a trie of precomputed top-k lists and the write side raw query logs. Then Phase D builds two systems joined by a periodic publish: the read path serves the trie from memory so a request is just a prefix traversal and a copy, well under 50ms, with the hottest prefixes cached and the trie sharded by prefix range; the write path streams query logs into an offline batch job that counts popularity over a rolling window, computes top-k per prefix, and atomically swaps a freshly built trie into the serving tier. Staleness of one refresh interval is the accepted trade. E–H ship a static trie, then the refresh, then sharding and caching, governed by latency SLOs and a refresh cadence. The power is that precomputing offline is a direct consequence of the Phase A latency principle, not a guess.
Common traps
- Ranking candidates at request time and blowing the sub-50ms keystroke budget.
- Forgetting the offline aggregation, so suggestions don't track real query popularity.
- Letting the write path (logging, aggregation) leak onto the hot read path and slow every lookup.