You type dinner into Google and suggestions appear before you finish the word. Type d and you get results. Type di and the list changes again. The system answers every keystroke in under a tenth of a second.
Key points
Requirements for this lesson:
Scope limits: English only. Lowercase alphabetic characters only. No spell check or autocorrect.
Back of the envelope math:
dinner sends 6 requests: d, di, din, dinn, dinne, dinner. Average is 20 requests per search.Exhibit 1: QPS and growth calculator
Drive it: move the sliders. The math below tracks the draft formula exactly. Try 20 searches per day or 30 characters and watch average QPS cross the 48,000 peak line.
DAU x searches x chars / 86,400
average x 2
DAU x searches x 20 bytes x new %
dinner: 6 requests for 6 prefixes. Every keystroke is a backend query unless cached.High level design splits into two services:
The naive query path is one table with query and frequency columns:
SELECT * FROM frequency_table WHERE query LIKE 'prefix%' ORDER BY frequency DESC LIMIT 5
Type tw and you might get twitter, twitch, twilight, twin peak, twitchprime. This works for small data. It breaks (4) at large scale because the database becomes the bottleneck on every keystroke.
Picture a trie (pronounced try, from retrieval). It is a tree for strings.
Example paths: tree, try, true, toy, wish, win.
To rank results, each query node also stores frequency:
tree: 10, try: 29, true: 35toy: 14, win: 50, wish: 25The trick is this: every node also remembers the winners below it. The node for be stores [best: 35, bet: 29, bee: 20, be: 15, beer: 10]. The node for bu stores [buy: 14]. Reading suggestions is then just reading a short list already sitting on the prefix node.
Exhibit 2: trie explorer, one post end to end
Drive it: type a prefix or tap a chip. The explorer walks the same example trie from the draft and reads the cached top list sitting on that node. No subtree walk at read time.
be maps to [be: 15, bee: 20, beer: 10, best: 35] style entries in the draft table, ranked best first. Prefix bee maps to [bee: 20, beer: 10]. Prefix bu holds only [buy: 14].Define p as prefix length, n as total nodes, c as children of a node.
Basic lookup for top k, with k = 2 and prefix tr:
Step 1. Find the prefix node tr. Cost: O(p).
Step 2. Walk the subtree and collect valid children that form queries. Here: [tree: 10], [true: 35], [try: 29]. Cost: O(c).
Step 3. Sort and take top k. Here: [true: 35], [try: 29]. Cost: O(c log c).
Total: O(p) + O(c) + O(c log c). This breaks (1) in the worst case because it can walk the whole trie.
Two optimizations fix the path:
A. Limit max prefix length. Users rarely type long queries. Cap p at about 50. Find becomes a small constant, effectively O(1).
B. Cache top queries at each node. Since users need only 5 to 10 suggestions, store top 5 on every node at build time. Return becomes O(1).
Result after both: O(1) to find the node plus O(1) to return the cached list.
Exhibit 3: lookup stepper for prefix tr, k = 2
Drive it: press Next or Play. Each step lights the active stage and shows the Big-O cost from the draft.
tr. Walk 2 chars from root. Cost O(p).[tree: 10], [true: 35], [try: 29]. Cost O(c).k = 2: [true: 35], [try: 29]. Cost O(c log c). Total O(p) + O(c) + O(c log c).p at about 50 and cache top 5 per node. Find plus return is O(1) + O(1).Live path in production:
search?q=di through AJAX. AJAX avoids a full page refresh.Failure case to predict: Trie Cache loses a hot prefix shard. Latency jumps because API servers fall through to Trie DB for the same prefix at 48,000 peak QPS. The fix is replenishment plus browser caching. Google caches autocomplete in the browser for one hour with cache-control: private, max-age=3600. That absorbs repeat typing without touching the backend.
Exhibit 4: live path and hot shard failure
Drive it: toggle hit versus miss, then press Lose hot shard to replay the failure at 48,000 peak QPS. Watch latency and where repeat keystrokes are absorbed.
Hit path: Browser to LB to API to Trie Cache. Returns 5 cached queries in about 12 ms, inside the 100 ms budget.
max-age=3600 holds suggestions for one hour.Weakness 1: real time updates are too expensive.
Updating the trie on every query slows the query service and wastes work because top suggestions change little day to day. This breaks (1) and (4).
Fix: move writes offline. The pipeline is:
time for week start and frequency summed for that week.Price: suggestions go stale for a week. A breaking news query will not appear until the next build.
Exhibit 5: weekly offline pipeline
Drive it: step through the write path. Reads stay fast because all heavy work happens offline on a schedule.
time and summed frequency.Weakness 2: logging everything costs too much.
Fix: data sampling. Log only 1 out of every N requests. Price: frequencies are approximate. For top 5 ordering that error is usually acceptable.
Exhibit 6: sampling simulator
Drive it: raise N to log fewer requests. Each dot is a keystroke for one post. Lit dots are logged. Ordering of the top 5 usually survives even when counts are approximate.
Weakness 3: deletes cannot wait a week.
Hateful, violent, sexually explicit, or dangerous suggestions must vanish now.
Fix: add a filter layer in front of Trie Cache. It removes unwanted suggestions per filter rules. Physical removal from the database happens asynchronously so the next weekly build is clean. Price: one more hop and a rule set to maintain.
tr: imagine one entry flagged hateful. The filter layer drops it before the response leaves, even though Trie DB still holds it until the async cleanup and next weekly build.Weakness 4: one server cannot hold the trie.
Naive sharding splits by first character. Two servers: a to m and n to z. Three servers: a to i, j to r, s to z. Up to 26 servers for 26 letters. Beyond that, shard on second or third level. Queries starting with a split into aa to ag, ah to an, ao to au, av to az (illustrative ranges).
This breaks (4) because distribution is uneven. Far more words start with c than with x.
Fix: analyze history and shard by load. A shard map manager keeps a lookup of where rows live. If s alone has about as many queries as u through z combined, keep s on one shard and u to z on another. Price: routing depends on the map. The map must be maintained and consulted.
Exhibit 7: sharding by distribution, not alphabet
Drive it: switch schemes. Naive alphabet splits overload the c and s shards. Load based sharding balances by history via the shard map manager. Type a prefix to see its shard.
a: aa to ag, ah to an, ao to au, av to az. Beyond 26 servers, shard deeper.Trie storage has two options, each with a price:
| Option | How it works | Price |
|---|---|---|
| Document store | Serialize the weekly trie snapshot, store as a document. MongoDB is an example. | Simple snapshot and replace. Must load and deserialize to serve. |
| Key-value store | Map every prefix to a key. Map node data to a value. Prefix be maps to [be: 15, bee: 20, beer: 10, best: 35]. Prefix bee maps to [bee: 20, beer: 10]. | Fast key lookup per prefix. Many keys to write on each rebuild. |
Trie update has two options:
beer moves from 10 to 30, so bee, be, b, and root lists that contain beer must change. This is slow and only acceptable when the trie is small.This Python example follows the chapter mechanism. It builds a trie, stores frequency, and caches top 5 at each node. Values below are illustrative.
class Node:
def __init__(self):
self.children = {} # char -> Node, max 26 in English lowercase
self.is_query = False
self.freq = 0
self.top = [] # cached list of (freq, query), max 5
class Autocomplete:
def __init__(self, k=5):
self.root = Node()
self.k = k # line that matters: matches requirement (3), top 5
def insert(self, query, freq):
node = self.root
path = [node]
for ch in query: # line that matters: capped at ~50 chars in prod for O(1) find
node = node.children.setdefault(ch, Node())
path.append(node)
node.is_query = True
node.freq = freq
# line that matters: Option 2 update, fix ancestors up to root
for i, anc in enumerate(path):
prefix = query[:i]
self._refresh(anc, prefix, query, freq)
def _refresh(self, node, prefix, query, freq):
# keep every candidate under this prefix, then keep best k
candidates = {}
self._collect(node, prefix, candidates)
ranked = sorted(candidates.items(), key=lambda x: -x[1])
node.top = ranked[:self.k] # line that matters: space for time
def _collect(self, node, prefix, out):
if node.is_query:
out[prefix] = node.freq
for ch, child in node.children.items():
self._collect(child, prefix + ch, out)
def search(self, prefix):
node = self.root
for ch in prefix:
if ch not in node.children:
return []
node = node.children[ch]
return node.top # line that matters: O(1) return, no subtree walk
# illustrative frequencies from the chapter shape
ac = Autocomplete(k=5)
for q, f in [("best", 35), ("bet", 29), ("bee", 20), ("be", 15), ("beer", 10), ("buy", 14)]:
ac.insert(q, f)
print(ac.search("be")) # expect best, bet, bee, be, beer in order
Notes on lines that matter: k=5 encodes requirement (3). Capping prefix length makes find O(1). Caching top on insert trades space for time. Updating the full ancestor path shows why direct updates are slow. Returning node.top shows why reads stay fast and why weekly rebuilds are preferred.
Follow up: How do you support multiple languages?
Answer: store Unicode characters in trie nodes. Unicode covers writing systems modern and ancient. Sharding by first character no longer means 26 shards.
Follow up: What if top queries differ by country?
Answer: build different tries per country and store them in CDNs for response time. Why: ranking is local popularity, not global.
Follow up: How do you support trending real time queries?
Answer: the weekly design will miss them because workers have not rebuilt yet and a full build takes too long. Ideas only: shard to shrink the working set, weight recent queries higher in ranking, and move to stream processing since data arrives continuously.
Q1Predict: Trie Cache evicts prefix tr during peak 48,000 QPS. What happens to latency and to Trie DB load, and which two caches absorb the next identical keystrokes?
Latency jumps because every tr keystroke hits Trie DB at peak QPS. After replenish, Trie Cache serves again, and browser cache with max-age 3600 absorbs repeat typing for one hour without backend hits.
Q2Compare: weekly replace versus direct node update for beer 10 to 30. Which protects (1) at 24,000 QPS and which risks stale hateful suggestions unless paired with what layer?
Weekly replace keeps the query path O(1) and protects (1) at 24,000 QPS. Direct update must fix bee, be, b, and root, so it is slow. Weekly builds go stale for a week, so hateful suggestions need the filter layer in front of Trie Cache with async DB cleanup.
Q3Choose under tradeoff: logging budget is cut in half but (1) must hold. Do you sample 1 in N more aggressively, shorten the rebuild interval, or add shards? Argue cost to accuracy, freshness, and capacity.
Sampling 1 in N more aggressively cuts log volume while (1) holds because reads stay O(1) from cache. Price is approximate frequencies, acceptable for top 5. Shortening rebuilds hurts freshness cost and build load. Adding shards adds capacity for (4) but does not cut logging cost.