Design typeahead suggestions for a search box - show the 10 most popular searches that start with the typed letters within 100 ms, at 60,000 lookups a second, with rankings that follow what people searched in the last half hour. Nothing is ranked at query time. The senior-level signal is sorting when the index is built, replacing the index as a whole instead of editing it, and keeping fast-changing rules beside it.
Written by a Staff+ Engineer and an Engineering Manager
12+ years of experience in distributed systems and real-time messaging. Tech lead for large-scale chat applications serving billions of users. Over 12 years of industry experience with 6 years in engineering leadership, building and scaling tech infrastructure teams that deliver end-to-end large-scale distributed systems.
Finished this lesson?
Sign in to save your progress across devices.
Tip: use ← and → to move between lessons.
Was this lesson helpful?
Rehearse this exact question with the author
45-minute mock with a Staff+ engineer who interviews at your target company. Premium members save $20.
What to Design?
Could you answer these today? Tick what you already know.
The data structure is quick to name: a prefix tree. The interview is decided by four questions about what surrounds it: how a lookup stays cheap, how the tree is refreshed, how the load is spread, and how a phrase is removed. Each one is a deep dive later on this page, with three designs side by side: the one that sounds right, a better one, and the one that holds.
Swipe to see all columns
| The four questions, and the answer that sounds right | |||
|---|---|---|---|
| # | The interviewer asks | The answer that sounds right | What it misses |
| DD1 | 400,000 phrases start with "be". How do you return the best 10 in a few milliseconds? | An index on the phrase column | The index finds the 400,000 rows. Sorting them is the cost. Sort once, when the index is built: every node of the tree stores its own top 10 |
| DD2 | Rankings change every 15 minutes. How does a server that answers 3,000 lookups a second get the new ones? | Update the scores in the tree as searches arrive | |
The same three habits answer all four:
Do not spend your questions on the search engine behind the box. Spend them on what a suggestion is and how fresh it must be.
Swipe to see all columns
| Scope Decisions | ||
|---|---|---|
| Question | Agreed answer | Why it matters |
| What is matched? | The phrase must start with the typed letters. No typo correction | A prefix tree is enough. No fuzzy search (DD1) |
| What is a suggestion? | A plain text phrase. No pictures, no cards | An answer is 10 short strings: small enough to copy and cache anywhere (DD3) |
| Is the list personal? | No. Everyone who types "be" sees the same list | One index for all users, and one answer per prefix |
Out of scope (say this out loud): the search results themselves, personal suggestions, typo correction, suggestions with images or other rich content, and deciding which phrases break policy. We get the removal call; we do not make the judgment.
FR1 — Suggest. For a typed prefix, return up to 10 phrases that start with it, the most popular first. A prefix is what the user has typed so far, for example "be".
FR2 — Record. Take in every finished search and every click on a suggestion. These are the signals that say how popular a phrase is.
FR3 — Refresh. Turn the signals into new scores every 15 minutes and bring the new ranking to every server, without a pause in service.
FR4 — Remove. An admin can remove a phrase. It disappears for every user within 30 seconds, without a rebuild.
The key principle behind all four
Swipe to see all columns
| Five facts and the conclusions they do not supportRead each row as: the fact on the left does not, by itself, imply the claim in the middle. | ||
|---|---|---|
| Fact | Does not imply | Why the gap exists |
| The index finds the matching rows fast | The lookup is fast | 400,000 rows match "be". They still have to be sorted by score |
NFR1 — Latency. The list is on the screen within 100 ms of the key press, for 99 of 100 lookups.
NFR2 — Throughput. 60,000 lookups a second at peak.
NFR3 — Freshness. A search changes the ranking on every server within 30 minutes.
NFR4 — Availability. Lookups work 99.9% of the time, also during a rebuild, and also when the database or the batch job is down.
NFR5 — Safe updates. A bad build never reaches all users. The last good ranking keeps serving.
NFR6 — Fast removal. A removed phrase is gone for every user within 30 seconds.
| Capacity Thought Experiment | |
|---|---|
| Parameter | Value |
| Searches | 500 million a day: about 5,800 a second |
| Key presses per search | About 5, and each one is a lookup |
| Lookups, average | 2.5 billion a day: about 29,000 a second |
| Lookups, peak | Twice the average: about 60,000 a second |
| Phrases | 50 million, 25 characters on average: 1.25 GB of text |
The number that identifies the real system is the gap between reads and changes:
lookups 60,000 /s each must answer in a few milliseconds
ranking 1 change every 15 minutes, for everybody at once
removals a few a day but each must work within 30 seconds
Reads are constant and urgent. Changes are rare and arrive in bulk. So the design makes reads as cheap as possible and pays when the index is built. Numbers that the question does not give are illustrative.
Interviewer signal: candidates who say "500 million searches a day is 5,800 a second" have sized the wrong thing. Candidates who say "every key press is a lookup, so 5 times that, and twice again at peak: 60,000 a second, read-only, with one bulk change every 15 minutes" have found the system.
Three ideas shape everything:
At 60,000 lookups a second there is no time to find and sort. So the sorting is done once, when the index is built: every prefix gets its 10 best phrases stored right at its place in the index. A lookup walks to that place and reads the list.
A snapshot is a complete, frozen copy of the index. The servers never edit the one they are reading. Every 15 minutes a new snapshot is built somewhere else, loaded next to the old one, and swapped in with one pointer write. Reads need no locks. All servers hold the same file. And if a build is bad, the old snapshot is still there.
Rankings may be 30 minutes old. A removal may not be 30 seconds old. One mechanism cannot serve both. So rankings travel the slow path (batch, build, roll out), and removals travel a fast one: a tiny list that every server checks on every lookup.
The core recognition
This is a read-only index in memory, rebuilt in batch and swapped whole. The database holds the truth: the scores and the blocklist. The index is disposable: if every server lost it, it could be built again from the scores.
| Design Decisions | |
|---|---|
| Design choice | Reason |
| A prefix tree (trie) in the memory of every server | A lookup is a short walk and one read. No network call, no database |
| The top 10 stored on every node of the tree | The sorting is done once at build time, not 60,000 times a second |
One structure carries the design: the trie. Three small tables stand behind it. The thing to explain is the
toplist on every node: it is why a lookup never sorts.
A trie is a tree in which every node stands for a prefix. The node "be" is reached from the root by "b", then "e". Phrases that share a prefix share those nodes. Each node also stores top: the 10 best phrases that start with its prefix.
root
└─ b top: best movies, bed frame, best pizza near me, ...
└─ e top: best movies, bed frame, best pizza near me, beach weather, ...
├─ d top: bed frame, ...
└─ s top: best movies, best pizza near me, best fake id sites, best laptops, ...
Swipe to see all columns
| In the memory of every query node | ||
|---|---|---|
| Thing | What it holds | Comment |
| Trie node | Its letters, its children, and top: up to 10 phrase ids | About 100 million nodes. A chain of nodes with one child each is stored as one node, which saves most of the memory |
| Phrase table | Phrase id to text | 1.25 GB. A phrase is stored once, however many top lists name it |
A lookup, in words: write the prefix in lower case, walk one node per letter, read top, turn the ids into text, drop what is on the blocklist, answer.
Swipe to see all columns
| Signal event (in the event log) | ||
|---|---|---|
| Field | Type | Comment |
event_id | STRING | Unique per event |
phrase | STRING | The searched text, normalised: lower case, single spaces |
type | ||
Swipe to see all columns
| suggestion_scores | ||
|---|---|---|
| Field | Type | Comment |
phrase | STRING | Key |
score | FLOAT | The popularity. New score = 0.9 x old score + the searches and clicks of the last window |
Swipe to see all columns
| Supporting records | ||
|---|---|---|
| Record | What it holds | Why it exists |
snapshots row | version, window_end, object_key, checksum, status: BUILT, CANARY | |
The score rule is simple on purpose: a phrase that people stop searching fades by 10% every 15 minutes, and a row whose score falls under 1 is dropped. The exact weights are a product decision. The design only needs one number per phrase.
Swipe to see all columns
| Storage | ||
|---|---|---|
| Store | Data | Consistency |
| Kafka | The event log: every signal, for 7 days | Append-only. An event is never changed. A correction is a new event |
| PostgreSQL | suggestion_scores, snapshots, suppressed_phrases | The durable truth. The trie can always be rebuilt from it |
| Object storage | One snapshot file per trie version | Written once, never changed |
Three calls, with three different speeds: the lookup must be fast, the signal must be cheap, the removal must be quick to take effect.
Swipe to see all columns
| Endpoints | ||
|---|---|---|
| Call | Who calls it | What it does |
GET /v1/suggestions?prefix=be&limit=10 | The search box, on every key press | Returns up to 10 phrases, best first, and the snapshot version. Public, no login. Carries Cache-Control: public, max-age=10 |
POST /v1/signals | The search box, in the background | Takes a list of events (search, click). Appends them to the log and answers 202 at once |
DELETE /v1/suggestions/{phrase} | ||
The answer is the same for every user, so it can be copied freely. That one property is what makes the edge cache of DD3 possible.
Present the design as four short stories, each in its own colour on one whiteboard: Phase 1 answer a key press (black), Phase 2 record and count (blue), Phase 3 build and swap (green), Phase 4 remove a phrase (purple). The number on an arrow is the same number in the animation and in the step table.
Swipe to see all columns
| The four phases | |||
|---|---|---|---|
| Phase | Colour | Story | What it leaves behind |
| Phase 1: Answer a key press (FR1) | Black | alice types "be". A query node walks two steps in its trie and reads a list | A 10-second copy of the answer at the edge |
| Phase 2: Record and count (FR2) | Blue | alice searches "best pizza near me". At 12:15 a batch job counts the window | A new score in the database: 9,000 becomes 9,600 |
How to read the picture
Each phase below is an interactive walkthrough of the same picture. It plays on its own. You can pause it, step with the arrow keys, and click any component to read its role.
Goal: show 10 phrases for "be" within 100 ms, without searching or sorting anything.
/v1/suggestions?prefix=be&limit=10Browser → Edge cachea miss: pass it onNothing is written in this step.
Swipe to see all columns
| Phase 1 step by step (black arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | 12:03:05. alice types "be". Her browser sends GET /v1/suggestions?prefix=be&limit=10. The nearest edge location has no copy for "be". | Nothing |
| 2 | The edge passes the request on. The load balancer gives it to one of the 20 query nodes, in turn: q7. | Nothing |
Why it is built this way
Into the network. A request to a data centre on the same continent and back takes 30 to 80 ms. From another continent it can take 150 ms: more than the whole budget. So a faster node does not help the user. A closer answer does. That is the job of the edge cache (DD3).
Goal: note what people search without slowing them down, and turn the notes into scores every 15 minutes.
/v1/signalsBrowser → Signal APINothing is written in this step.
Swipe to see all columns
| Phase 2 step by step (blue arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | 12:03:10. alice picks "best pizza near me" from the list and searches. Her browser sends POST /v1/signals with two events: a click and a search. It is sent in the background: the result page does not wait for it. | Nothing |
| 2 | The Signal API normalises the phrase (lower case, single spaces) and appends both events to the event log. | |
Why it is built this way
Hardly. The signals are statistics: a phrase with 1,500 events in a window is not ranked differently with 1,499. A short outage of the log costs a little accuracy and nothing else. This is very different from an order or a payment, and it is why this path can be so simple.
Goal: bring the new ranking to 20 nodes that never stop answering.
SELECT phrase, score ... ORDER BY score DESCTrie builder → Scores DBNothing is written in this step.
Swipe to see all columns
| Phase 3 step by step (green arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | 12:18. The trie builder reads all scores, the best first: 50 million rows. Phrases on the blocklist are left out. | Nothing |
| 2 | The builder inserts the phrases from the highest score down. Every node on a phrase's path keeps the first 10 phrases that pass through it: those are its top 10. Three minutes. | Nothing |
| 3 | 12:21. The builder stores the trie as one file, | |
Why it is built this way
v42 turns out bad, going back is another pointer swap, not a rebuild.A search at 12:00:00 is counted at 12:15, built into v42 by 12:21, and on every node at 12:29: inside the 30 minutes of NFR3.
Because the alternative is a gap. If the node dropped v41 first, it could not answer for two minutes, and it would have nothing to go back to if the file were broken. Holding both costs 12 GB instead of 6 for a few minutes, which is why the nodes have 16 GB. Say it when you size the machines.
Goal: make one phrase disappear for every user within 30 seconds, without touching the trie.
/v1/suggestions/best%20fake%20id%20sitesAdmin → Admin APINothing is written in this step.
Swipe to see all columns
| Phase 4 step by step (purple arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | 12:40:00. dana, an admin, calls DELETE /v1/suggestions/best%20fake%20id%20sites with a reason. | Nothing |
| 2 | The Admin API writes one row to suppressed_phrases and answers 204 No Content. | suppressed_phrases |
Why it is built this way
v43 was built at 12:33, before dana's call, and still contains the phrase. The filter removes it all the same.active = false. The same poll picks it up, the nodes take the phrase off their set, and the next build includes it again.For a few minutes, no. Nine good suggestions are better than ten with a bad one. If the product insists on a full list, keep the top 12 on every node and return the first 10 that pass the filter. The next build fills the list anyway: the builder leaves the blocked phrase out and number 11 moves up.
The deep dives are the four questions from the top of the page. Each one compares three designs for the same scenario: a Bad one, which is usually the answer that sounds right; a Good one, which still leaves a gap; and a Great one, which holds. The answers start covered. Read the scenario, decide what you would build, then click each card.
Swipe to see all columns
| Deep Dive Map | |||
|---|---|---|---|
| Deep Dive | Topic | Scenario | NFR |
Scenario: alice types "be". Of the 50 million phrases, 400,000 start with these two letters. She must see the best 10 within 100 ms, and 60,000 such lookups arrive every second. Where do the 10 come from?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The phrases and scores are in a table already. Put an index on phrase and run SELECT phrase ... WHERE phrase LIKE 'be%' ORDER BY score DESC LIMIT 10 for every lookup.
Where it breaks. The index finds the rows that start with "be" quickly. But there are 400,000 of them, and the database must read them all and sort them by score to know which 10 are the best. At about a million rows a second that is 0.4 seconds for one lookup, four times the budget. And it gets worse exactly where the traffic is: the shorter the prefix, the more rows match, and short prefixes are the most common lookups of all. At 60,000 lookups a second the database does nothing else, and then it stops.
The idea. Do the sorting in advance. A job writes one list per prefix into Redis, an in-memory key-value store: the key sug:be holds the 10 best phrases for "be". A lookup is one call, GET sug:be.
What it fixes. No sorting at query time. One lookup costs one network call of about 1 ms, whatever the prefix.
What it still misses. Every phrase is copied into the list of each of its prefixes. With about 300 million distinct prefixes, 10 phrases each and 25 bytes a phrase, that is about 75 GB before overhead. Every 15 minutes the job rewrites those 300 million keys while users read them, so for minutes "b" shows the new ranking and "be" the old one. And every key press now depends on one shared store over the network: when Redis is slow, every search box is slow.
The key idea. Keep the lists, but store them in a tree that shares everything that can be shared, and put that tree inside the process that answers.
How it works
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure. The figure holds the boxes of all three designs; each tab lights up the ones it uses.
SELECT phrase ... WHERE phrase LIKE 'be%' ORDER BY score DESC LIMIT 10Browser → Query service → Scores DBNothing is written in this step.
Swipe to see all columns
| DD1 side by side | |||
|---|---|---|---|
| Bad: database query | Good: Redis list per prefix | Great: trie in memory | |
| Work per lookup | Find and sort 400,000 rows | One network call | Two steps in memory |
| Time for "be" | About 400 ms | About 1 ms | Microseconds |
Check it against the scenario
| One lookup, by prefix | |
|---|---|
| Situation | Outcome with the Great option |
| alice types "be" | Two steps, one read of 10 ids. Well under 1 ms inside the node |
| alice types "b" | One step. The shortest prefix is the cheapest lookup, not the most expensive |
The trade-off to name. The trie buys speed with memory and with a rebuild. About 4 of its 6 GB are the top lists, and every change of ranking means building it again. That is acceptable here because rankings change in bulk, every 15 minutes. If scores had to change within a second, this structure would be the wrong one.
It sorts once, outside the tree. The builder reads the phrases from the highest score down. When it inserts a phrase, it walks the phrase's path and adds the phrase id to the top list of every node on the way, unless that list already holds 10. Because better phrases always come first, the first 10 to pass a node are its 10 best. One pass over 50 million phrases fills every list.
"A prefix query with a sort is too slow: 'be' matches hundreds of thousands of phrases, and I would sort them on every key press. So I move the sort to build time. I keep a trie in the memory of each query node, and every node of the trie stores the top 10 phrases under it. A lookup walks one node per typed letter and reads a list, so its cost depends on the prefix length and not on the vocabulary. The trie is around 6 GB for 50 million phrases, and it is read-only, which means no locking on the read path and I can replicate it freely."
Follow-up: "Why not keep those lists in Redis?" — It works at moderate scale, but each key press pays a network hop to a shared store, the lists repeat every phrase many times, and refreshing 300 million keys is not atomic. In the node's own memory the read is local and the refresh is one swap.
Scenario: 12:15. The counts of the last window are in. "best pizza near me" must rise from number 3 to number 2 under "be", and likewise under "b", "bes", "best" and every longer prefix, on 20 nodes that answer 60,000 lookups a second. How do the nodes get the new ranking?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Skip the batch. Every query node reads the event log itself, and for each search it adds 1 to the phrase's score in its own trie. The ranking is always current.
Where it breaks. A changed score can change the top 10 of every node on the phrase's path: up to 18 lists for "best pizza near me", each fixed under a write lock. At 5,800 searches a second that is about 100,000 list updates a second on every node, fighting 3,000 lookups a second for the same locks. The 20 nodes read the log at different speeds, so the same prefix gives different lists depending on which node answers. And a node that restarts has an empty trie: it must replay days of events before it is useful.
The idea. Keep the batch job and the scores table. Every 15 minutes each node reads all scores, builds a fresh trie, and replaces its old one.
What it fixes. The trie is read-only between builds, so lookups need no locks. All nodes build from the same table, so they agree once they are done.
What it still misses. Twenty full scans of 50 million rows hit the database in the same minute, and each build takes the node's CPUs away from lookups for three minutes. To have room, the node drops the old trie before the new one is ready: during the build it cannot answer. And if the scores of this run are wrong, say a bug set them all to zero, all 20 nodes build the bad trie at once, and the good one is gone.
The key idea. Building and serving are different jobs for different machines. One builder makes the trie. The nodes only load a finished file and switch to it.
How it works
v42 and stores tries/v42.bin with a checksum. v41.bin stays.v41: 12 GB of 16. They keep answering from v41.current = v42. Lookups in flight finish on . No lookup sees half a trie.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure. The figure holds the boxes of all three designs; each tab lights up the ones it uses.
read search-signalseach of the 20 Query nodes → Event logNothing is written in this step.
Swipe to see all columns
| DD2 side by side | |||
|---|---|---|---|
| Bad: live updates | Good: each node rebuilds | Great: one build, one swap | |
| Who builds | Every node, all the time | Every node, every 15 minutes | One builder |
| Lookups during an update | Wait for locks | Slow, or not answered | Not affected |
Check it against the scenario
| The rollout of v42 | |
|---|---|
| Situation | Outcome with the Great option |
A lookup arrives on q1 during the swap | It started on v41 or on v42, and finishes on the one it started on |
The download of v42.bin breaks off | The checksum does not match. The node keeps v41 and tries again |
The scores of run r42 | |
The trade-off to name. The ranking is never fresher than one cycle: 15 minutes of counting plus up to 14 minutes of build and rollout. The nodes need twice the memory during a swap. And for six minutes the fleet serves two versions. In return, the read path has no locks, a bad build is caught on two machines, and going back is one pointer write.
A broken ranking throws no errors. It returns wrong lists, quickly. So the canary compares its answers with the rest of the fleet: the share of lookups with no suggestions, the length of the lists, how many of the top prefixes changed their number 1. If a tenth of the prefixes suddenly have a new best phrase, the scores are wrong, not the world.
"I never mutate the serving trie. A batch job writes new scores every 15 minutes, one builder turns them into a trie and uploads it as a versioned snapshot file. Each query node downloads the file, loads it next to the current trie and then flips one reference. Requests in flight finish on the old trie, new ones use the new trie, so there is no pause and no half-built state. I roll out to a couple of canary nodes first and compare their metrics before the rest of the fleet follows, and I keep the previous snapshot, so a bad build means everyone keeps serving the last good one."
Scenario: peak hour, 60,000 lookups a second. 40% of them are the 702 prefixes of one or two letters: 24,000 a second. Lookups that start with "s" are 11% of all lookups; those that start with "x" are 0.2%. How is the load spread?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. A big index is sharded. Make 26 shards, one per first letter, and let a router send "be" to shard b. Each machine holds only a slice of the trie.
Where it breaks. Letters are not equally popular. Shard s gets 11% of 60,000: 6,600 lookups a second. Shard x gets 120. One node handles 5,000, so shard s is over its limit while shard x is idle. Tomorrow another letter is hot, and the shards must be resized by hand. And when the node of shard q dies, every prefix that starts with "q" has no suggestions at all. And it solves a problem the system does not have: the whole trie is 6 GB.
The idea. 6 GB fits into one machine. Give all 20 nodes the full trie and let the load balancer send each lookup to the next node in turn.
What it fixes. Every node gets 3,000 lookups a second, whatever the letter. No prefix can overload one machine. When a node dies, the other 19 take about 3,160 each and nothing else changes.
What it still misses. All 24,000 short-prefix lookups a second still travel to the data centre, where the fleet works out the same 702 answers thousands of times. And a user far away pays about 150 ms for the round trip alone. The budget is 100.
The key idea. The answer for "be" is the same for everyone, for 15 minutes. So keep a copy of it close to the users, and let the nodes answer only what the copies cannot.
How it works
Cache-Control: public, max-age=10. A CDN with 50 edge locations keeps it for 10 seconds.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure. The figure holds the boxes of all three designs; each tab lights up the ones it uses.
/v1/suggestions?prefix=beBrowser → Router → Shard bNothing is written in this step.
Swipe to see all columns
| DD3 side by side | |||
|---|---|---|---|
| Bad: letter shards | Good: full copy per node | Great: full copy and edge cache | |
| Load per node at peak | 120 to 6,600 a second | 3,000 a second | About 2,000 a second |
| A hot letter | One shard overloads | No effect | No effect |
Check it against the scenario
| Peak hour | |
|---|---|
| Situation | Outcome with the Great option |
| The single prefix "s" is asked thousands of times a second | Almost all are answered at the edge. The nodes see at most 5 requests a second for "s": one per edge location every 10 seconds |
| A news event makes "ea" hot within a minute | Nothing to resize. The edge absorbs it, and the nodes are all the same |
q12 dies | The load balancer stops sending to it. 19 nodes take about 2,080 each |
| A new ranking is swapped in | Edge copies are at most 10 seconds old, so the edge follows within 10 seconds |
The trade-off to name. An edge copy can be 10 seconds stale. For rankings that change every 15 minutes this does not matter. For removals it does: those 10 seconds are part of the removal time in DD4, and the reason the copy does not live longer. The edge also only works because the answer is public and the same for everyone. Personal suggestions would lose it.
When it no longer fits in one machine's memory, even after rare phrases are dropped. Then split by something that spreads evenly, such as a hash of the first letters, never by the letter itself, and give every shard several copies. Sharding is a cost. Pay it for a problem you have.
"Traffic is very skewed towards short prefixes, so I do not shard by prefix: one shard would get most of the load, and losing it would take out a whole letter. The trie is about 6 GB, so every query node holds all of it and the load balancer can send any request to any node. On top of that, the response for a prefix is identical for all users, so I set a short max-age and let the CDN answer the hot short prefixes from the edge. That removes most of the hot traffic from my fleet and it fixes latency for users who are far from the data centre."
Follow-up: "Why only 10 seconds?" — Because the cache also delays removals. Ten seconds keeps a removed phrase visible for at most that long, and it already takes away almost all of the hot-prefix load.
Scenario: 12:40:00. "best fake id sites" is number 5 under "be". It breaks policy and must disappear for every user within 30 seconds. The next build will not be on every node before 12:59. And v43, which was built before the call, is being rolled out right now.
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The trie is built from suggestion_scores. Delete the phrase there, and the next trie will not have it.
Where it breaks. The query nodes do not read that table. They serve v42 and v43, and both contain the phrase. The first build without it, v44, is on every node at 12:59: 19 minutes, not 30 seconds. And the deletion does not last. A removed phrase is often a phrase people are curious about. They keep searching it, the next aggregation run counts those searches and writes the row again, and v45 shows the phrase once more.
The idea. Do not wait. The Admin API sends "remove this phrase" to all 20 nodes, and each node takes the phrase out of the top list of every node on its path.
What it fixes. Where the command arrives, the phrase is gone within a second.
What it still misses. The trie is no longer read-only, so lookups need locks again. q14 is swapping to v43 at this very moment: the edit lands on v42, then the pointer moves to v43, which still has the phrase. q7 was restarting and never got the command, and nobody notices. And the next snapshot is built from the scores, which know nothing about the removal.
The key idea. A removal is not a change of the index. It is a rule about what may be shown. Keep the rule in one durable place and apply it at the last moment.
How it works
suppressed_phrases. That row is the truth.v42 or v43: the same filter.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure. The figure holds the boxes of all three designs; each tab lights up the ones it uses.
DELETE FROM suggestion_scores WHERE phrase = ...Admin → Admin API → Scores DBbest fake id sitesdeleteSwipe to see all columns
| DD4 side by side | |||
|---|---|---|---|
| Bad: delete and wait | Good: edit every trie | Great: a blocklist | |
| Gone for every user after | 19 minutes | 1 second, on most nodes | At most 15 seconds |
| A swap in the same minute | Still visible anyway | The phrase comes back on that node | No effect |
Check it against the scenario
| 12:40:00, a removal during a rollout | |
|---|---|
| Situation | Outcome with the Great option |
q14 swaps from v42 to v43 at 12:40:02 | Its next poll, at most 5 seconds later, brings the new row. The filter works on v43 as it did on v42 |
q7 restarts at 12:40:01 | It loads the last LIVE snapshot and the full blocklist, and only then takes traffic |
The trade-off to name. Every lookup now does a little extra work: up to 10 checks against a set, which costs far less than a microsecond each. The filter can leave a list one short until the next build. And the removal time has a floor: the poll interval plus the edge copy, 15 seconds here. If 15 seconds were too slow, the nodes would need a push channel as well, and the edge an explicit purge.
A push is faster when it arrives. But a push can be missed: the node was restarting, or the message was dropped. Then someone must notice. A pull repairs itself: a node that was away simply asks again. If you add a push for speed, keep the poll as the safety net.
"Removals cannot wait for the rebuild cycle, and I do not want to edit a read-only trie on 20 nodes. So I separate the two. The admin call writes the phrase to a small suppression table. Every query node polls it every few seconds into an in-memory set and filters its top-K against that set just before it answers. The suppression list is the authority on what users may see: the trie may still contain the phrase, but it is never returned. The builder also excludes it from the next snapshot, and the row stays so that new searches cannot bring the phrase back."
| If the interviewer keeps going | |
|---|---|
| Question | Short answer |
| 6 GB per node is a lot. Can the trie be smaller? | Three steps. Store a chain of single-child nodes as one node (the design already does). Drop phrases under a score threshold: they cost memory and are almost never shown. Pack the nodes tightly. Together about 3 GB is realistic |
| Make the suggestions personal | Keep the global trie as the source of candidates. Store a few more per node, say 50, and re-rank them per user at query time with the user's own history, place and language. A trie per user is far too much memory. Personal answers cannot be cached at the edge |
| Other languages | One trie per language, chosen by the user's locale. Walk characters, not bytes: one Chinese character is three bytes. Languages without spaces between words need their own rules for what a prefix is |
| What should the browser do? | Wait about 50 ms after the last key press before sending, cancel the request for the previous prefix, and keep the answers of this session: going back from "bes" to "be" needs no request |
Every key press is a lookup. 5,800 searches a second become 29,000 lookups on average and about 60,000 at peak.
The index finds the rows that match "be" fast, and then 400,000 of them must be sorted. Sort once, when the index is built.
Then a lookup must visit every phrase under the prefix to rank them. The stored list is what turns a search into a read.
Every search rewrites up to 18 lists under a lock, and the nodes drift apart. Build a new trie beside the old one and swap.
The node cannot answer during the load and has nothing to go back to. Hold both for a few minutes, and buy the memory for it.
A bad build then reaches every user in the same minute. Two canary nodes first, and keep the previous file.
Letters are not equally popular, so one shard overloads while another idles. The trie fits in memory: give every node all of it.
The loaded tries still show it for 19 minutes, and new searches write the row again. A removal is a permanent rule in a blocklist.
The shape of a strong answer: count key presses, not searches. Show that a database query must sort and cannot keep up. Move the sort to build time with a trie that stores the top 10 on every node. Keep the trie in the memory of every query node, all of it. Feed it from a log, a batch job and a scores table. Build it once, ship it as a file, load it beside the old one and swap a pointer, canaries first. Put a short copy at the edge for the short prefixes. Remove phrases with a blocklist that every node checks.
Sort when you build, not when you answer
400,000 phrases start with "be". The trie node for "be" already holds its best 10. A lookup is two steps and one read, at 60,000 a second.
Never change what is being read
The serving trie is read-only. A new one is built elsewhere, loaded next to it, and swapped in with one pointer write. A bad build stops at two canaries, and the old file is still there.
Rules that change fast live beside the index
A removal is one row in a blocklist. Every node polls it every 5 seconds and filters each answer. With a 10-second edge copy, a phrase is gone for everyone in 15 seconds.
| What the interviewer expects at each level | |
|---|---|
| Level | A strong answer shows |
| Junior | The use case: the top 10 for a prefix within 100 ms. Why a LIKE query per key press is too slow, and why a trie fits prefix matching |
| Mid-level | Both paths: fast reads from a trie in memory, and a slow path of log, batch job and scores. The top 10 on each node. Why the whole trie is on every node |
| Senior | Names the hard parts unasked: a swap with no pause, canaries and going back, the memory for two tries, short prefixes at the edge, removal by blocklist and its 15 seconds. Covers trie size, what to monitor, and how the design would change for personal or instant rankings |
These aren't toy problems — they reflect real infrastructure challenges at companies that answer every key press of millions of users. If you want to walk through this design in a mock interview or get feedback on your own approach, book a session with us. We're here to help you sharpen your thinking, build your confidence, and land your next offer.
Pick an answer for each question, and you see at once whether it is right. Show explanation opens the answer, why it is right, and why each of the other options fails.
Question 1 of 10
500 million searches a day, about 5 key presses per search, and a peak of twice the average. How many lookups a second must the system handle at peak?
Question 2 of 10
A table of 50 million phrases has an index on the phrase column. Why is LIKE 'be%' ORDER BY score DESC LIMIT 10 still too slow?
Question 3 of 10
Why does a lookup in the trie cost the same with 50 million phrases as with 500 million?
Question 4 of 10
Precomputed lists in Redis, one key per prefix, also avoid sorting at query time. What is their main weakness compared with a trie in each node's memory?
Question 5 of 10
A query node has loaded v42 next to v41 and writes current = v42. What happens to a lookup that started a moment earlier?
Question 6 of 10
The trie is about 6 GB. Why do the query nodes have 16 GB of memory?
Question 7 of 10
Why does a new snapshot go to two canary nodes before the other 18?
Question 8 of 10
Lookups that start with "s" are 11% of the traffic, those with "x" 0.2%. What follows for the layout of the trie?
Question 9 of 10
Answers are cached for 10 seconds at 50 edge locations. At most how many requests a second do the 702 one- and two-letter prefixes still send to the query nodes?
Question 10 of 10
A phrase must be gone within 30 seconds. Why is deleting its row from the scores table not enough, and what is?
| Every search rewrites up to 18 lists under a lock, and 20 servers drift apart. Build a new tree once, ship it as a file, swap one pointer |
| DD3 | 40% of all lookups are one or two letters. How do you spread the load? | Shard the tree by first letter | Letters are not equally popular: "s" gets 55 times the load of "x". The tree is 6 GB: give every server all of it, and let an edge cache answer the short prefixes |
| DD4 | A phrase must disappear within 30 seconds. The next build is 19 minutes away | Delete it from the scores table | The servers do not read that table, and new searches write the row again. Keep a small blocklist beside the tree and check it on every lookup |
| How fresh is the ranking? | It follows the searches of the last 30 minutes | A batch every 15 minutes is enough. Nothing is ranked live (DD2) |
| May suggestions pause during an update? | No | The new index is loaded next to the old one and swapped in (DD2) |
| How fast must a removal be? | 30 seconds | Far faster than a rebuild. It needs its own path (DD4) |
| The new scores are in the database | Users see the new ranking | Servers answer from a tree in memory. It changes only when a new one is swapped in |
| The index holds 50 million phrases | It must be split over machines | It is 6 GB. It fits in the memory of every server |
| The phrase was deleted from the scores | The phrase is gone | The loaded trees still contain it, and tomorrow's searches bring the row back |
| The server answered in 1 ms | The user saw the list in time | Most of the 100 ms is the network between the user and the server |
| About 6 GB: the text, about 100 million nodes, and a list of up to 10 phrase ids on each node |
| One server | Up to 5,000 lookups a second, 16 GB of memory |
| Servers | 60,000 / 5,000 = 12 needed. Run 20: 3,000 a second each at peak |
| Signals | 500 million searches + 100 million clicks: 600 million events a day, about 7,000 a second |
| Signal storage | About 200 bytes each: 120 GB a day, 840 GB for 7 days |
| One 15-minute window | 600 million / 96 = 6.25 million events |
| The whole tree on every server, no shards |
| It is 6 GB. Any server can answer any prefix, so no letter can overload one machine |
| One builder, one snapshot file with a checksum | All servers load the same bytes. A broken file is noticed before it is used |
| Load next to the old tree, then swap a pointer | No lookup waits, and none sees a half-built tree |
| Two canary servers first | A bad build stops at 2 of 20 servers |
| A 10-second copy of every answer at the edge | Short prefixes are asked thousands of times a second. They are answered close to the user |
| A blocklist table, polled every 5 seconds | A removal works in seconds and survives every later rebuild |
current |
| A pointer to the trie that answers lookups |
| One write moves all new lookups to another trie (DD2) |
| Blocklist | A set of removed phrases | A few thousand entries. Checked on every lookup (DD4) |
ENUM |
search: the phrase was searched. click: it was picked from the suggestion list |
ts | TIMESTAMP | When it happened. Decides which 15-minute window counts it |
window_searcheswindow_clicksINT |
| The counts of the last window, kept for checking |
run_id | STRING | Which aggregation run wrote the row, for example r42 |
LIVEREJECTED| Tells the query nodes which trie file to load, and how far its rollout is (DD2) |
| Snapshot file | The whole trie as one file, for example tries/v42.bin, 6 GB | Every node loads the same bytes. Old files stay 7 days, for going back |
suppressed_phrases row | phrase, reason, created_by, active, updated_at | A phrase that must never be shown. The row is never deleted by a rebuild (DD4) |
| Memory of each query node |
| The trie, the phrase table, the blocklist |
Disposable. A restarted node loads the last LIVE file and the full blocklist |
| Edge cache | A copy of each answer, for 10 seconds | Disposable. May be up to 10 seconds old |
| An admin, logged in |
| Puts the phrase on the blocklist. Answers 204. The phrase is gone for every user within 15 seconds |
| Phase 3: Build and swap (FR3) |
| Green |
One builder makes snapshot v42. Two canary nodes swap first, then the other 18 |
Every node answers from v42 |
| Phase 4: Remove a phrase (FR4) | Purple | dana removes "best fake id sites". Every node filters it out within seconds | One row in the blocklist. No trie was edited |
| 3 |
q7 walks its trie: root, "b", "e". Two steps. The node "be" holds the ids of its 10 best phrases. Nothing is searched or sorted. |
| Nothing |
| 4 | q7 turns the ids into text and drops blocked phrases: there are none. It answers 200 OK with 10 phrases, snapshot v41, and Cache-Control: max-age=10. Under 1 ms inside the node. | Nothing |
| 5 | The edge location keeps the answer until 12:03:15 and passes it to alice. She sees: best movies, bed frame, best pizza near me, and seven more. | An edge copy of "be", for 10 s |
| 6 | 12:03:08. bob types "be". The copy is 3 seconds old, so the edge answers. No query node sees this request. | Nothing |
| 2 events in the log |
| 3 | The Signal API answers 202 Accepted. Nothing has been counted yet. | Nothing |
| 4 | 12:15:00. The aggregation job reads the events of 12:00 to 12:15 from the log: 6.25 million. It groups them by phrase. "best pizza near me": 1,200 searches and 300 clicks. | Nothing |
| 5 | The job works out the new scores: 0.9 x 9,000 + 1,500 = 9,600. It writes all 50 million rows in one bulk load, as run r42. Done at 12:18. | suggestion_scores: "best pizza near me" 9,000 becomes 9,600 |
tries/v42.binsnapshotsThe file. snapshots row v42: CANARY |
| 4 | The two canary nodes, q1 and q2, see the new row at their next poll. They download the file, check the checksum, and load v42 next to v41: 12 GB of their 16. They keep answering from v41. | Nothing |
| 5 | 12:23. Each canary writes current = v42. Lookups that started on v41 finish on v41. Then v41 is freed. No lookup sees a half-built trie. | q1, q2: current is v42 |
| 6 | 12:25. The canaries were healthy for two minutes: the builder sets v42 to LIVE. The other 18 nodes do the same, nine at a time, at 12:27 and 12:29. Under "be", "best pizza near me" is now number 2. | snapshots v42: LIVE. All 20 nodes: current is v42 |
| 3 | Every query node asks the database every 5 seconds: any rows newer than my last poll? There is one. It goes into the node's blocklist. By 12:40:05 all 20 nodes have it. | The blocklist of every node: one more entry |
| 4 | A lookup for "be" reaches a node. The node reads the 10 phrases of "be", drops the blocked one, and answers with 9. The trie is not changed. | Nothing |
| 5 | An edge copy made at 12:40:04 still shows the phrase until 12:40:14. By 12:40:15 no user sees it: 15 seconds after dana's call. | Nothing |
| 6 | 12:48. The builder of the next snapshot, v44, reads the blocklist and skips the phrase. "be" has 10 phrases again. The row stays, so later searches cannot bring the phrase back. | Nothing |
| DD1 |
| 400,000 phrases start with "be" |
| One lookup, 10 results, a few milliseconds |
| NFR1, NFR2 — Latency, throughput |
| DD2 | New rankings every 15 minutes, on nodes that never stop | "best pizza near me" must rise on 20 nodes | NFR3, NFR4, NFR5 — Freshness, availability, safe updates |
| DD3 | 24,000 lookups a second for 702 prefixes | Peak hour, uneven letters, far-away users | NFR1, NFR2 — Latency, throughput |
| DD4 | A phrase must be gone in 30 seconds | A removal in the middle of a rollout | NFR6 — Fast removal |
| The table only |
| About 75 GB in Redis |
| About 6 GB per node |
| A refresh | Always current | 300 million keys rewritten, mixed for minutes | The whole trie is replaced at once (DD2) |
| When the store is slow | Every lookup is slow | Every lookup is slow | There is no store to wait for |
v41v42 is REJECTED. The canaries swap back and everyone serves v41: 15 minutes older, and right.| Do the nodes agree? |
| No, they drift |
| Yes, after the build |
| Yes, same file |
| A bad run | Cannot be undone | On all 20 nodes at once | Stops at the 2 canaries |
| A node restarts | Replays days of events | Rebuilds: three minutes of scans | Downloads the last LIVE file |
On the canaries the share of empty or odd answers jumps. v42 is REJECTED after two minutes, on 2 of 20 nodes |
| 12:23 to 12:29: two versions are live | bob may see v42 from q1 and v41 from q9 for a few minutes. Both are valid rankings |
| A node dies |
| A letter has no suggestions |
| 19 nodes carry on |
| 19 nodes carry on |
| A far-away user typing "be" | 150 ms | 150 ms | About 20 ms |
| Memory per node | A slice of 6 GB | 6 GB | 6 GB |
v44 on, the builder skips the phrase. The row stays, so searches cannot bring it back.| A node that missed it |
| Does not apply |
| Shows the phrase until someone notices |
| Loads the list before it takes traffic |
| People keep searching it | It comes back | It comes back with the next snapshot | It stays blocked |
| The trie | Read-only | Edited in place, needs locks | Read-only |
| A Redis cache in front of the trie? | The trie lookup is already a read from local memory. A Redis call in front of it adds a network hop. It only pays when the answer needs real work after the trie, such as personal re-ranking |
| A phrase explodes right now. 15 minutes is too slow | A batch cannot go under its cycle. Add a small streaming counter for the last few minutes, keep its top phrases in a tiny second trie that is replaced every minute, and merge the two lists at query time |
| Someone tries to push a phrase up | Count distinct users, not events, and cap what one user can add per window |
| The database or the event log is down | Lookups go on: the nodes have the trie and the blocklist in memory. Rankings stop moving and removals cannot be entered until it is back. Lost signals cost a little accuracy |
| What do you monitor? | Lookup time at the node and at the edge. The share of lookups with no suggestions. The age of the loaded snapshot and of the last blocklist poll, per node. The edge hit rate |