SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design Search Autocomplete

Suggest the best completions after every keystroke, in a few milliseconds.

⏱ 30 min readMedium case studyIntermediate24 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design search autocomplete, like the suggestions under the Google search box.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Splitting the system in twoServing suggestions (fast, read-only) and building them (slow, offline) are different problems. A strong candidate draws them as two paths and does not mix them.
Latency thinkingSuggestions must appear while the user types. The budget is about 100 ms end to end, so every box, cache and network hop has to earn its place.
Choosing a data structure for a reasonA trie is the textbook answer. The interviewer wants to hear why a plain database query is too slow, and what to precompute at each prefix.
Freshness versus costUpdating on every search is far too expensive. How often you rebuild, and how a trending search gets in quickly, is the real trade-off.
Product judgementRanking, blocked terms, personalisation and privacy all change what a good suggestion is. Naming them shows you think about users, not only servers.

TL;DRThe whole design in 60 seconds

Autocomplete is a read-heavy lookup with a slow, separate data pipeline. For a typed prefix we return the top 5 most popular searches that start with it, in a few milliseconds. We never compute that at request time: the best 5 for every prefix are precomputed offline and kept in memory.

  • Scale: 10M users, 10 searches each a day, about 4 suggestion requests per search is 400M requests a day: about 5 thousand a second on average and 25 thousand at peak.
  • Serving path: the browser waits for a short pause (debounce), an edge cache answers popular prefixes, and a small fleet of suggestion servers answers the rest from an in-memory trie or prefix table. About 6 GB of data, so every server holds a full copy.
  • Data path: search logs go to Kafka. A batch job counts them (with time decay) and builds a new trie with the top 5 stored at each node. We ship it as a versioned snapshot and swap servers to it.
  • Freshness: a rebuild every hour or so. A small streaming job adds a fast overlay for trending searches, so a breaking story shows up in minutes, not hours.
  • Why not live updates: updating the top-5 lists on every search is about 29 thousand writes a second, all landing on the same hot nodes (the short prefixes). Batch plus an overlay is cheaper and good enough.
  • Quality: blocked terms are removed at build time, ranking uses frequency with recency, and personalisation is a light blend added at the end.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4How many suggestions, ranked by what, personal or global, latency, freshness, languages, safety.
2. Estimate3Requests per second, size of the index, edge cache, write rate if updated live.
3. API and data5One GET endpoint, the query log, the prefix to top-5 shape.
4. High-level design8Two paths: serving and building. Name the cache layers.
5. Deep dives15Top-5 precomputation, serving speed, build and update, then quality and edge cases.
6. Scale and failures7Hot prefixes, a bad build, a node down, a viral spike.
7. Wrap up3Recap, trade-offs, what you would add next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change your design. Hint: think about how fresh suggestions must be, whether they are personal, how fast they must appear, and what you must never suggest.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
How many suggestions do we show, and how are they ranked?The number sets the size of the precomputed list. The ranking rule decides what we count.The top 5 (up to 10). Ranked by how often people search for them, newer searches counting more.Store the top 5 at each prefix. Count with a time decay, not a plain total.
Are suggestions the same for everyone, or personal?Personal results cannot be fully precomputed or cached at the edge for all users.Global for now. Personal history can be a later improvement.One shared index and a shared edge cache. Personalisation is an optional layer on top.
How fast must suggestions appear, and what is the latency budget?This is the main non-functional requirement. It decides caching and where data lives.Under 100 ms end to end at the 99th percentile, as the user types.Everything on the read path is in memory. No database query at request time.
How fresh must they be? Does a breaking news search need to show within minutes?Freshness decides how often we rebuild and whether we need a streaming lane.Mostly stable, but a sudden surge should appear within about 10 minutes.Hourly batch rebuild plus a small trending overlay from a stream job.
How many users and searches, and how long can a query be?Turns into requests per second and the size of the index.10 million daily users, about 10 searches each. Prefixes up to 50 characters.About 5 thousand requests a second, 25 thousand at peak. A prefix longer than 50 is ignored.
Which languages and regions?Each language needs its own index, tokenisation and ranking, and may need its own region.English first, designed so more languages can be added.The index is keyed by language. Mention Unicode, and that some scripts need different handling.
Must we fix typos (did you mean)?Typo tolerance needs fuzzy matching, which is a much bigger problem than prefix lookup.Out of scope for now. Prefix match only.A plain trie is enough. Say fuzzy matching is a later extension.
Are there things we must never suggest?Offensive, illegal or private terms cause real harm and legal risk.Yes. A block list, and a way to remove a suggestion quickly.Filtering at build time, plus a fast removal path that does not wait for a rebuild.
Where does the input come from: a website, an app, or both?Clients decide debounce, local caching and how many requests we really get.Both. The client should not send a request on every keystroke.Client debounce, cancel of old requests, and a short local cache are part of the design.
Do we need to keep working if the suggestion service is down?Suggestions are helpful, not essential. Search itself must still work.Yes. Search must never depend on suggestions.The client treats failure as no suggestions. No retry storm.

Write the scope on the board

Functional (must do)
  • •Return the top 5 suggestions for the prefix a user has typed
  • •Rank by popularity, with recent searches counting more
  • •Update the suggestions regularly, and let a sudden surge in searches show quickly
  • •Never show blocked terms, and let us remove one fast
  • •Support more than one language (English first)
Non-functional (how well)
  • •Latency: under 100 ms end to end at p99, while the user is typing
  • •Scale: 10M daily users, about 5 thousand requests per second on average, 25 thousand at peak
  • •Available: 99.99%. If it fails, search still works (suggestions simply do not appear)
  • •Fresh: a new trend should show within about 10 minutes
  • •Cheap per request: almost all answers come from a cache or memory
Out of scope (say it)
  • •Typo correction and “did you mean”
  • •Full personalisation and search history screens
  • •The search results page itself
  • •Voice and image search
🎤
Say it out loud
“Let me confirm the scope. We return the top 5 suggestions for a typed prefix, ranked by popularity with recent searches counting more. Suggestions are global for now, English first, under 100 milliseconds at the 99th percentile. About 10 million daily users with 10 searches each, so a few thousand requests a second. A big surge should show within about 10 minutes. We must never show blocked terms. Typo correction and personal history are out of scope, and search itself must keep working if suggestions fail. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: requests per second (average and peak), how big is the index, and what would live updates cost? Is memory or write rate the real constraint?

Assumptions (say them first)

AssumptionValue
Daily users10 million
Searches per user per day10
Suggestion requests per search (after debounce)about 4
Peak compared with average5 times
Edge cache hit rate on suggestion requestsabout 60%
Distinct searches kept in the index (after dropping the rare long tail)10 million, about 25 characters each
Trie size after sharing prefixesabout 100 million nodes
Memory per node (children plus the top 5 ids)about 60 bytes
One suggestion server (all in memory)about 10,000 lookups per second
Size of one responseabout 500 bytes
Log line per completed searchabout 100 bytes

The arithmetic, line by line

WhatMathsResult
Searches per day10,000,000 × 10100 million
Suggestion requests per day100,000,000 × 4400 million
Requests per second (average)400,000,000 ÷ 86,400about 4,600, call it 5 thousand
Requests per second (peak)5,000 × 525 thousand
Reaching the origin at peak (40% miss the edge)25,000 × 0.410 thousand per second
Index memory (trie with top 5 per node)100,000,000 nodes × 60 bytes6 GB, fits on one machine
Servers needed at peak10,000 per second ÷ 10,000 per server, then × 2 for headroom2, so run 6 (two per zone, three zones)
Response bandwidth at peak25,000 × 500 bytes12.5 MB per second (about 100 Mbit/s)
Search log per day100,000,000 × 100 bytes10 GB per day (70 GB a week)
Log after 1 in 100 sampling10 GB ÷ 100about 100 MB per day
Writes per second if the top 5 were updated on every search100,000,000 × about 25 prefixes ÷ 86,400about 29 thousand per second
What the numbers tell us about the design
  • •The index is small (6 GB). Every serving node can hold a full copy, so scaling reads is about copies, not splitting the data.
  • •25 thousand requests a second at peak is easy for memory lookups, but 60% never need to reach us at all. Caching is the biggest saving.
  • •Live updates would mean about 29 thousand writes a second, and most land on the short prefixes shared by everyone. That argues for batch rebuilds plus a small trending lane.
  • •The log is only 10 GB a day, so counting it in a batch job is cheap, and sampling makes it cheaper still.
  • •Latency is dominated by the network and the debounce, not by the lookup. A trie lookup takes microseconds.
🎤
Say it out loud
“Let me do the maths. Ten million users times ten searches is a hundred million searches a day. With about four requests per search, that is four hundred million requests, about five thousand a second, twenty-five thousand at peak. The index is about a hundred million trie nodes at sixty bytes, so six gigabytes: every server holds a full copy. Most requests hit a cache, so only about ten thousand a second reach the origin, and a few servers handle that. The number that worries me is writes: updating the top five on every search would be about twenty-nine thousand writes a second on the hottest nodes. So we build the index in batches and add a small fast lane for trends.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the one call the client makes, what comes back, and the two tables behind it: where the searches are counted, and where the finished suggestions live.

Endpoints

MethodPathRequestResponseNotes
GET/v1/suggest?q=wor&lang=en&limit=5200 { v: 8421, q: "wor", suggestions: [{ text, score? }] }No body, so it caches well. Cache-Control with a short max-age (about 60 s). Anonymous and cheap. An empty list for an unknown prefix, never an error.
POST/v1/events/search{ q, lang, ts, session }202 AcceptedSent by the search page when a search is completed, not on each keystroke. Goes to the log pipeline. Fire and forget.
POST/v1/admin/blocks{ term, reason }201 { blockId }Operators only. Takes effect on the next filter refresh (seconds), not the next rebuild.
GET/v1/admin/indexnone200 { liveVersion, builtAt, nodes, size }For operations: which index version is live and how old it is.

Data model

StoreKey and valueNotes
Search log (Kafka, then files)One line per completed search: time, query text, language, regionAppend only. 10 GB a day. The source for counting.
Query counts (batch output)query text → decayed countRebuilt on each run. About 10 million rows after dropping the rare tail.
Trie snapshot (the serving index)prefix → top 5 [(text, score)], held as a trie in memoryA file of about 6 GB. Versioned (v8421). Loaded by every serving node.
Prefix table (alternative)key: lang + prefix, value: the top 5 as a short listSame data in a key-value store such as Redis. Easier to shard and update in place.
Block listnormalised term → reasonA tiny table, checked at build time and again at serve time.
One answer (example)
GET /v1/suggest?q=wor&lang=en&limit=5

{ "v": 8421, "q": "wor",
  "suggestions": [ "world cup", "wordle", "world cup schedule", "world map", "word counter" ] }
📝Which store, and why
The read path needs a lookup by prefix in well under a millisecond, so the answer set lives in memory: either as a trie inside each serving process, or as a prefix table in Redis. The data is only about 6 GB and read-only between builds, so a full copy on every node is simplest and fastest. The slow data (the raw search log and the counts) lives in Kafka and object storage, and is processed in batches. A relational database with LIKE 'wor%' would scan or walk an index on every keystroke, which is far too slow at this volume.
🎤
Say it out loud
“The API is one GET: suggest with the prefix, language and a limit. It returns a version number and up to five strings, and it is cacheable for about a minute. Separately, the search page sends an event when a search is completed, and that goes to a log pipeline. Behind it, the serving index is a trie snapshot where each node stores its top five, about six gigabytes, loaded in memory on every server. The counts and the raw log live in Kafka and object storage and are only touched by the build job.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw two separate paths: the one a keystroke follows, and the one that turns yesterday's searches into today's suggestions. Where are the caches, and what never touches a database?
Autocomplete: two paths
⌨️Browser or appdebounce, local cache
→↓GET /suggest
🌍CDN / edge cachepopular prefixes, 60 s
→↓miss
⚖️Load balancer
→↓
Suggestion servers (copies)
🧠In-memory trietop 5 at every node
🛡️Block filterserve-time check
Collect
🔎Search servicecompleted searches
↓log (sampled)
📨Kafkasearch log
Build (offline)
🧮Batch jobcount, decay, filter
↓
🌳Trie buildertop 5 per prefix
↓
📦Snapshot storeversioned files
Fast lane
⚡Stream joblast 15 minutes, spikes
↓small overlay
➕Trend overlaymerged at serve time
Top: the serving path answers keystrokes from caches and memory. Bottom: the data path counts searches offline and ships a new snapshot.
ComponentWhat it does
Client (browser, app)Waits for a pause in typing (debounce, about 150 to 250 ms), cancels the request still in flight, and keeps a short local cache of answers it already has.
CDN / edge cacheAnswers the most popular prefixes close to the user, for about a minute. About 60% of requests end here.
Suggestion serversStateless readers. Each holds the whole trie in memory and answers a prefix in microseconds. Easy to add copies.
Block filterA small in-memory set of banned terms, checked on the way out. Lets us remove a suggestion in seconds.
Kafka search logReceives one event per completed search. Sampled when volume is high. The source for counting.
Batch job and trie builderCounts the log with a time decay, removes blocked terms, builds the trie with the top 5 at each node, and writes a versioned snapshot.
Snapshot storeHolds built indexes (object storage). Servers download the new one and swap to it. Old versions stay for a quick rollback.
Stream job and trend overlayCounts only the last few minutes. Finds sudden risers and publishes a small list that suggestion servers merge in.
Write path (follow one request)
  1. A user completes a search. The search service sends a small event (query, language, time) to Kafka. Nothing waits for this.
  2. Under heavy load the producer keeps only 1 in 100 events, because popular searches still show up clearly in a sample.
  3. Every hour a batch job reads the log, counts each query, applies a time decay so last week counts less than today, and drops anything blocked or very rare.
  4. The trie builder inserts the counted queries, then walks the tree to store the top 5 at every node (a heap of 5 per node).
  5. It writes the snapshot as v8422 with a checksum, and tests it on sample prefixes (a quick quality check).
  6. Servers fetch the file, load it next to the old one, and switch over one by one. If checks fail, they keep the old version and an alert fires.
Read path (follow one request)
  1. The user types “wor”. The client waits for a pause, cancels any older request, and checks its small local cache.
  2. It sends GET /v1/suggest?q=wor&lang=en. The CDN answers if it has a fresh copy for this prefix (about 60% of the time).
  3. On a miss the load balancer picks any suggestion server, since every one has the full index.
  4. The server walks 3 nodes of the trie (w, o, r) and reads the stored top 5. No sorting and no database.
  5. It merges the trend overlay for this prefix, removes anything on the block list, and cuts to 5.
  6. The response goes back with a short Cache-Control. The browser shows the list. Total time is a few tens of milliseconds, mostly the network.
🎤
Say it out loud
“Here is the picture, in two paths. The read path is fast and boring: the client debounces, a CDN answers the popular prefixes, and everything else goes to a stateless suggestion server that holds a six gigabyte trie in memory and reads the top five stored at the node for that prefix. No database, no sorting. The data path is slow and offline: searches go to Kafka, a batch job counts them with a decay and filters blocked terms, a builder produces a versioned snapshot with the top five at every node, and servers swap to it. A small streaming job adds a trend overlay so a breaking story does not wait for the next rebuild.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

What to store at each prefix, and how to look it up

The problem: A user types “wor”. We need the five best searches that start with it in a few milliseconds. The set of searches under a short prefix is huge, so we cannot find and rank them at request time.

OptionHow it worksGoodBad
Database query with LIKESELECT text FROM queries WHERE text LIKE 'wor%' ORDER BY count DESC LIMIT 5.Trivial to write. Always has the latest counts.Scans or walks a big index on every keystroke. A short prefix matches millions of rows, so it is slow and expensive at 25 thousand requests a second.
Plain trie, rank at request timeWalk to the prefix node, then walk the whole subtree, collect words, and take the top 5.Simple. Small memory. The data structure is the textbook one.A short prefix has a huge subtree. “w” would visit millions of nodes per request. The cost grows with the data, not with the length of the prefix.
Trie with the top 5 stored at every nodeAt build time, compute and store the best 5 at each node. At request time, walk to the node and read the list.Lookup cost depends only on the prefix length (at most 50 steps). No sorting at request time.More memory (a list at every node). Any change in counts means updating every ancestor node, so we rebuild in batches.
Prefix to top-5 table in a key-value storeStore one row per prefix: key lang + prefix, value the 5 strings. Skip the tree.Simple to shard and cache. Easy to update one prefix. Any key-value store works.More rows than trie nodes, since each prefix is stored in full. Repeats the strings at every prefix.
Pick
A trie with the top 5 stored at every node, built offline and held in memory on every server

A request becomes a walk of at most 50 steps and a read of five strings. Its cost does not depend on how much data there is. All the hard work (counting, ranking, picking the best five) happens at build time, where we have lots of time and no user waiting.

The price is memory and update cost: each node carries a list, and one new search can change the lists of all its ancestors. That is fine in a batch rebuild, and it is exactly why we do not update live. Store ids or short pointers to the strings instead of the strings themselves, so the lists stay small. See the Trie topic for how the structure itself works.

PrefixTop 5 stored at that node (example)
wweather, world cup, weather today, wordle, web design
woworld cup, wordle, world cup schedule, world map, wordle hint
worworld cup, wordle, world cup schedule, world map, wordle hint
worlworld cup, world cup schedule, world map, world cup final, world news
💡Save memory with a compressed trie
Many nodes have only one child (for example “schedul” then “e”). A radix (compressed) trie merges such chains into one node holding a longer string. This can cut the node count by several times. Also cap the stored prefix length (say 20 to 50 characters): almost nobody types more, and the long tail costs a lot of memory.
Lookup (sketch)
function suggest(prefix: string): string[] {
  let node = root;
  for (const ch of prefix.toLowerCase()) {      // at most 50 steps
    node = node.children.get(ch);
    if (!node) return [];                       // unknown prefix: no suggestions
  }
  return node.top5;                             // precomputed at build time
}
🎤
Say it out loud
“I will compare four ways. A database LIKE query scans too much on every keystroke. A plain trie finds the prefix quickly but has to walk a huge subtree for short prefixes. So I would store the top five at every node, computed offline, which makes a lookup a walk of at most fifty steps and a read of five strings. The cost is memory and the fact that one new search changes all its ancestors, which is why I rebuild in batches. A radix trie and a prefix-length cap keep it to about six gigabytes.”
5.2

Making it fast: client, edge and the server fleet

The problem: The answer must appear while the user is typing, in under 100 ms, for 25 thousand requests a second at peak. The lookup is quick, so the time goes on the network, on useless requests, and on a few prefixes that everyone types.

OptionHow it worksGoodBad
Ask on every keystrokeThe client sends one request per character.The simplest client. Always the newest prefix.A 10-letter search is 10 requests, and most are out of date before the answer arrives. It multiplies server load for nothing.
Debounce and cancel on the clientWait about 150 to 250 ms for a pause, send once, and cancel any request still in flight.Cuts requests by a large share (about 40 to 60% in this model). No server work.The user waits the debounce time before the first answer. Too long feels slow, too short saves little.
Edge cache for popular prefixesAllow the CDN to cache GET /suggest for about a minute. The URL is the key.Answers close to the user and takes 60% of load off the origin. Free scaling for hot prefixes.Suggestions can be up to a minute old. Rare prefixes miss, so the cache helps the head, not the tail.
Shard the index by prefixSplit the trie: node group A owns words starting a to f, and so on. Route by the first characters.Each node holds less data.The index is only 6 GB, so this is not needed for size. It creates hot shards (“s”, “a”) and complicates routing and failure.
Pick
Debounce and cancel on the client, a CDN for popular prefixes, and a stateless fleet that holds the full index (no sharding)

The cheapest request is the one never sent, and the next cheapest is one answered at the edge. Debounce removes about half of the requests, and the edge removes most of the rest of the popular ones, so the origin sees roughly 10 thousand a second at peak. A handful of servers is enough, so we do not shard.

Because every server holds a full copy, any server can answer any prefix. There are no hot shards, no routing rule and no single node that matters. Failure handling is just “try another server”. We keep replicas in three zones and scale by adding copies.

LayerWhat it savesStaleness
Client debounce and cancelAbout half of all requests never leave the deviceNone
Client local cacheTyping a letter and deleting it again costs nothingSeconds, per session
CDN / edge cacheAbout 60% of the remaining requestsUp to a minute
Suggestion server memoryNo disk, no database, microsecond lookupsUntil the next snapshot
📝Where the time actually goes
A trie lookup takes microseconds. A typical request is the debounce (150 ms), plus the network (about 20 to 50 ms), plus a few ms on the server. Even a client that debounces for 150 ms feels instant, because the answer lands before the next keystroke. Try the playground below to see how debounce and the edge change the request count.
💡Hot prefixes are mostly an edge story
The first one or two letters (“a”, “s”, “th”) get a huge share of traffic. Do not shard to solve it. Let the edge cache absorb it, and keep full copies on every server so any node can answer.
🎤
Say it out loud
“For speed I would remove requests before I speed up any request. The client waits for a pause and cancels older requests, which about halves the traffic. A CDN caches popular prefixes for about a minute and answers around sixty percent of what is left. The origin is then about ten thousand requests a second, which a few stateless servers handle. I would not shard the index: it is six gigabytes, so every server holds a full copy, any server can answer any prefix, and a hot prefix is the edge cache's problem, not a hot shard.”
5.3

Building and updating the index

The problem: Popularity changes. Last week's top search fades and today's surge has to appear. But every search touches the top-5 lists of all its prefixes, and short prefixes are shared by almost everyone, so updating live means a flood of writes onto a few very hot nodes.

OptionHow it worksGoodBad
Update on every search (live)For each completed search, update the count and fix the top 5 at every prefix of the query.Always current.About 29 thousand writes a second, and the shortest prefixes get a write from nearly every search. Hot nodes, locks, and a lot of churn for tiny changes in ranking.
Periodic batch rebuildEvery hour or day, count the log offline, build a new trie, ship a snapshot.Cheap, simple and easy to test. Serving nodes are read-only. Easy rollback to the last good version.Stale between runs. A surge waits for the next build.
Batch plus a trending overlayBatch builds the stable index. A stream job watches the last 15 minutes and publishes a small list of risers that servers merge at request time.Fresh for what matters (surges), cheap for the rest. Keeps the read path simple.Two systems and a merge step. The overlay needs care so it cannot flood the list with junk.
Sample the log and keep counts in a sketchKeep only 1 in 100 events, or count in a Count-Min Sketch and keep heavy hitters.Shrinks the data and the cost by two orders of magnitude. Popular searches survive sampling.Rare searches vanish from the counts. Counts become estimates, which is fine for ranking.
Pick
A batch rebuild every hour on a sampled, time-decayed count, plus a small streaming trend overlay

Ranking does not need exact counts. A search that is twice as popular still ranks higher with a 1 in 100 sample, so we sample, and the log goes from 10 GB to about 100 MB a day. The batch job is then trivial to run, and the whole index is rebuilt rather than patched, so the serving path never writes.

The cost of batch is staleness, so we add the overlay only for the case where staleness hurts: a sudden surge. The stream job counts the last few minutes, compares them with the normal rate, and publishes the top few risers for the overlay. Deploy the new index as a versioned snapshot, load it beside the old one, switch, and keep the old one for rollback.

Decayed score (one common choice)
score(query) = sum over days d of  count(query, d) × 0.5^(age_in_days(d) / half_life)

half_life = 7 days  →  yesterday counts ~90%, a week ago 50%, two weeks ago 25%
Today's count is the total only for today; trending uses a much shorter window (15 min).
StepDetailWhy
SampleKeep 1 in 100 completed searches (or all, if volume is small)Ranking survives sampling. Cost drops 100 times.
NormaliseLowercase, trim, collapse spaces, strip odd characters“Weather” and “weather ” must count as one
FilterDrop blocked terms, personal data patterns, very short or rare queriesSafety, privacy and a smaller index
Count with decayWeighted sum aboveRecent behaviour wins, old fades
Build and verifyTrie plus top 5, then test sample prefixes against the last versionCatch a bad build before it ships
Ship and swapVersioned snapshot, load beside the old one, switch node by node, keep the old oneZero downtime and instant rollback
⚠️Do not forget the swap
Servers must not serve a half-loaded index. Load the new file into memory first, then flip a pointer. During a rollout two versions are live for a minute or two, so the same prefix can briefly give different answers on different servers. That is acceptable for suggestions, and the version number in the response lets you debug it.
🎤
Say it out loud
“I would not update on every search: that is about twenty-nine thousand writes a second, and the shortest prefixes get hit by almost every search. Ranking does not need exact counts, so I sample the log, count with a time decay, and rebuild the whole trie every hour, then ship it as a versioned snapshot and switch servers over with a rollback ready. The serving path never writes. To handle a breaking story I add a small stream job over the last fifteen minutes that publishes a few risers as an overlay, merged at request time. That gives hourly cost with a ten-minute freshness for what matters.”
5.4

Quality: ranking, safety, languages and personal results

The problem: Fast is not enough. Suggestions must be useful, safe and fair. Popularity alone ranks the wrong things, a single offensive suggestion is a headline, and every language and user needs something a bit different.

OptionHow it worksGoodBad
Pure popularityRank by decayed search count only.Simple and explainable. Works well for most prefixes.Old giants crowd out new things. No sense of intent, place or person. Can surface harmful terms.
Popularity with safety filtersSame ranking, plus a block list, patterns for private data, and a fast removal path.Removes the worst risks cheaply. Block list works at build time and serve time.Needs people to maintain the list. Cannot catch everything.
Blend global and personalLook up the global top 5, then mix in the user's own recent searches, ranked first.Feels smart and relevant. Works for repeat searches.Cannot be cached at the edge per user. Needs privacy care. More work per request.
Learned rankingUse click and selection data to train a model that scores candidates (frequency, recency, location, device).Best quality. Learns what people actually pick.More infrastructure and monitoring. Harder to explain. A later step, not the first version.
Pick
Popularity with decay, safety filters at build time and serve time, and personal results as a light layer on top

Start with what is reliable: a decayed popularity score and a strong safety filter. These give most of the value with a design that stays simple and cacheable. Personalisation is a thin layer: the global answer is shared and cached, and the user's own recent searches (kept on the device or in a small per-user store) are merged in front at the end, so the main path stays the same.

Measure the quality instead of arguing about it. Track how often a user picks a suggestion, how far down the list they pick (mean reciprocal rank), and how many keystrokes suggestions save. Run A/B tests on ranking changes, and use the results to decide if a learned ranker is worth building.

ConcernApproach
Offensive or illegal termsBlock list applied when building, and again at serve time. An operator can add a term and it disappears in seconds.
Private data in the log (names, emails, numbers)Pattern filters, minimum count threshold (a query must be searched by many different users to be kept), and a short retention period.
Many languagesOne index per language, tokenisation and normalisation per script. Right-to-left and no-space scripts need their own handling. Pick the index from the language header or setting.
Location and timeA small regional index for strong local effects (city names, local events), used as a boost on top of the global one.
Ties and stabilityBreak ties by a fixed rule (score, then alphabetical), so the list does not flicker between builds.
Cold start for a new termThe trending overlay promotes it once it surges. A brand new term with few searches is correctly ignored.
🧠Privacy is part of the design
A suggestion is shown to other people, so a query only becomes a suggestion if many different users searched for it. One person typing their own name or address must never appear. Say this out loud: it shows judgement.
🎤
Say it out loud
“Quality has three parts. For ranking, I start with a decayed popularity score, which is simple, cacheable and good for most prefixes. For safety, I filter blocked terms at build time and again at serve time so we can remove one in seconds, and I only keep a query that many different users searched, to protect private data. For personalisation, I keep the global answer shared and cached, and merge the user's own recent searches in front at the end. I would measure it by selection rate and how far down the list people pick, and only build a learned ranker if the data says it is worth it.”
VisualizerTyping, debounce, the edge cache and freshnessType a search and change the debounce and the edge cache to see how many requests the typing really costs. Then pick how often the index is rebuilt and slide the time forward to see when a trending search finally shows up.
Client debounce (wait for a pause before asking)
Edge cache for popular prefixes
Top 5 for “wo”
  1. 1world cup800
  2. 2wordle600
  3. 3world cup schedule500
  4. 4world map350
  5. 5wordle hint300
Keystrokes
2
Requests sent
1
after debounce
Edge hits
1
popular prefixes
Reached origin
0
Felt delay
170 ms
illustrative
PrefixNext key inWhat happened
w110 msskipped: next key came in under 150 ms
wo95 mssent, answered by the edge
2 keystrokes became 1 requests. 1 were answered by the edge and 0 reached the origin. The last answer felt like about 170 ms after the final key (150 ms debounce + 20 ms to answer).
Freshness: a new trending search appears

The last full rebuild finished at minute 0. At minute 70, “world cup final” starts to surge. How long until it can show in suggestions?

How often is the index rebuilt?
Trending lane (small stream job that adds a fast overlay)
■ not in suggestions yet■ visible| now
Appears after
50 min
freshness lag
Right now
not yet
“world cup final” still has its old count (40) because the next rebuild has not run. For “wo” it is not in the top 5.

A simplified model with fixed numbers (no random values). Counts are searches this week. A prefix is “popular” when at least 800 searches sit under it. Latencies (20 ms edge, 70 ms origin) and the typing pattern are illustrative. The rebuild lag is the time to the next rebuild after minute 70.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
If traffic doubles, what breaks first? If a bad index ships, what do users see? If a node dies, or one search goes viral, what changes?

What breaks first, and the fix

BottleneckFix
Hot prefixes (“a”, “s”, “the”) get a huge share of requestsCache them at the edge for about a minute. Every server holds a full copy, so any node can answer. No hot shard exists.
Request volume grows 10 timesAdd stateless suggestion servers (the index is read-only), put more of the answers in the CDN, and tighten the debounce on the client.
Index grows past one machine's memoryCompress it (radix trie, shorter stored prefix, ids instead of strings), drop the rare long tail, or split by language. Only then shard by prefix.
Build job gets slow as the log growsSample the log, count with a distributed job, and keep incremental counts (yesterday's count plus today's) instead of re-reading everything.
Snapshot download storms (many servers fetch 6 GB at once)Stagger the rollout, use a peer-to-peer or tiered cache for files, and compress the snapshot.
Trend overlay noiseRequire a minimum number of different users and a clear jump over the normal rate. Cap the overlay at a few entries per prefix.

What if a part fails?

FailureHow the design copes
A suggestion server diesThe load balancer health check removes it. Any other node has the full index, so nothing is lost. The client treats a timeout as no suggestions.
A bad index is built (empty, wrong, or full of junk)Verification before shipping (size, sample prefixes, comparison with the last version). Keep the old version and roll back by pointing servers to it.
The batch job fails or is lateServers keep serving the last good snapshot. Suggestions get a little stale. Alert if the index is older than a threshold.
Kafka or the log pipeline is downSearch events are fire-and-forget, so searching is unaffected. Buffer in the producer for a short time, then drop. Counts for that period are lower.
A query goes viral in minutesThe stream job's overlay promotes it in about 5 minutes, and the CDN's short max-age lets the new answer through. Hourly rebuild includes it after.
An offensive suggestion is reportedAdd it to the block list. The serve-time filter removes it in seconds, and the next build drops it. Purge the CDN entries for the affected prefixes.
What to monitor
  • •Latency at p50, p99 at the edge and at the origin, and the edge hit rate
  • •Requests per second and the share removed by debounce (client-side metric)
  • •Index version on each server, and its age (alert if older than expected)
  • •Selection rate and position of the picked suggestion (a quality signal)
  • •Block-list size, removal times, and the number of reports
  • •Build job duration, input size, and the difference from the last index (a sudden big change is a warning)
Security and abuse
  • •Treat every prefix as untrusted input: limit length, allow only normal characters, and never build queries from it.
  • •Rate limit by IP and key, and block clients that hammer the endpoint (a scraper can copy the whole index by walking prefixes).
  • •Never suggest a query that few distinct users searched, to protect private data. Keep logs for a short, fixed time.
  • •Guard against poisoning: a bot searching a bad phrase thousands of times should not get it into the top 5. Count distinct users, not raw searches.
  • •Escape output on the page. A suggestion is text from other people and must never be inserted as HTML.

Step 7Wrap upabout 3 min

Autocomplete is a fast read path over a precomputed index, fed by a slow offline pipeline. The client debounces and a CDN answers popular prefixes. Stateless suggestion servers hold a six gigabyte trie with the top five stored at every node, so a lookup is a short walk and a read. A batch job counts a sampled, time-decayed search log and ships a versioned snapshot every hour, with a small streaming overlay for trending searches. Safety filters, a distinct-user threshold and a thin personal layer keep the suggestions good and safe.

Trade-offs you made

DecisionWhat we gainWhat it costs
Precompute the top 5 at every nodeA lookup costs the prefix length, not the data size. No sorting at request time.More memory, and any change needs a rebuild of the ancestors.
Batch rebuild instead of live updatesNo hot writes. Read-only servers, easy rollback.Suggestions are up to an hour stale without the overlay.
Full copy of the index on every serverNo sharding, no hot shards, any node can answer.Memory per node and big snapshot downloads. Works only while the index fits.
Edge cache with a one-minute lifetimeAbout 60% less load, answers close to the user.A removed suggestion can linger for up to a minute unless purged.
Sample the log and use decayed counts100 times less data, and recent behaviour wins.Counts are estimates, and the rare long tail is lost.
Global answers with a thin personal layerShared caching stays possible. Personal feel where it matters.More work per request for signed-in users, and privacy care.
If we had more time, we would…
  • •Typo tolerance: fuzzy matching with edit distance, or a second index of common misspellings.
  • •A learned ranker using selection data, tested by A/B experiments.
  • •Per-region indexes and better handling of local events and places.
  • •Entity suggestions (people, places, products) with rich cards, not only text.
  • •A shadow build that compares the new index with the live one on real traffic before switching.
🎤
Say it out loud
“To recap: a fast read path and a slow offline pipeline. The client debounces, a CDN answers popular prefixes, and stateless servers hold a six gigabyte trie with the top five at every node, so a lookup is a short walk. A batch job counts a sampled, decayed search log and ships a versioned snapshot every hour, with a small stream overlay for trends. The main trade-offs are batch against live updates, and a full copy on every server against sharding. With more time I would add typo tolerance and a learned ranker.”

Q&ACross-questions (24)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Speed and the read path

The interviewer wants to hear you remove work, not only speed it up.

Data structure and storage

They want to see that you chose the structure for a reason, and know what it costs.

Building, freshness and quality

This is where interviewers separate a memorised answer from a thought-through one.

Failures, scale and curveballs

Expect the interviewer to break something and ask what happens.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Suggestions must be personal to each userKeep the global index and cache. Add a per-user layer (device history or a small per-user store) merged in front at the end, with a strict timeout and a global fallback. Care about privacy and retention.
Typo tolerance, such as suggesting weather for wetherPrefix match is not enough. Add fuzzy matching with an edit-distance index, or a second index of common misspellings mapped to the right query. Costs more memory and CPU per request.
Results must be fresh within a minute everywhereA bigger streaming path, a very short CDN lifetime, and frequent overlay updates. Costs more load on the origin and a more complex pipeline. Say what freshness is really worth.
Autocomplete for a catalogue of 100 million products (not searches)Data comes from the catalogue, not a log. Rank by sales and popularity, update on catalogue changes, and consider a search engine with prefix queries because filtering by category is needed too.
Support suggestions inside the middle of a phrase, not only the startA trie only matches the start. Index every word (or n-gram) and use an inverted index, or a suffix structure. More memory, and more work to rank across words.
The index grows to 500 GB (many languages, long tail)Split by language and region first, then shard by prefix with replicas for hot prefixes. Add routing, and plan for hot shards and a scatter rule for short prefixes.
Suggestions must work offline on a phoneShip a small compressed index of the most popular few hundred thousand queries to the device, and refresh it daily. Local lookup, no network.
Add rich suggestions (people, places, products with pictures)Entities have ids and metadata, so the trie stores ids and a second lookup fetches the card. More data per answer and more caching rules.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing a trie. Never asks about ranking, freshness, personalisation or safety.Asks for the number of suggestions, ranking, latency, freshness and scale, and writes them down.Also asks what must never be suggested, whether search must survive a suggestion outage, and states what is out of scope (typos, personal history).
EstimationNo numbers, or says the data is huge.Requests per second, index size and the log size, with correct arithmetic.Finds the number that drives the design: 6 GB means a full copy on every server, and 29 thousand live writes a second argues against live updates.
DesignOne box called autocomplete service with a database behind it.A trie with the top five at each node, a cache layer, and a separate offline build.Draws two clear paths, serving and building, with versioned snapshots, an overlay for trends, and fast removal for blocked terms.
Deep dive depthSays use a trie and stops.Explains precomputing the top five, debounce and caching, and batch building.Compares at least three options for each hard part, with costs: LIKE against trie against stored top five, live against batch, shard against copy.
Trade-offs and failureAssumes everything works and everything is fresh.Names staleness, memory and a bad build as risks, with a rollback.Quantifies the trade-offs, handles a viral query, a bad index, and an offensive suggestion, and says what would change at 10 times scale.
CommunicationJumps between topics and lists techniques.Follows the steps in order and explains choices.Summarises after each step, checks in with the interviewer, and speaks about users and product quality, not only servers.

AvoidCommon mistakes on this question

MistakeDo this instead
Running a database query with LIKE on each keystrokePrecompute the top five per prefix and serve from memory. Say why the query cannot keep up.
Ranking at request time by walking the subtreeStore the best five at every node during the build, so a request is a short walk and a read.
Updating the index on every searchDo the maths: about 29 thousand writes a second on hot nodes. Rebuild in batches, and add a small trending overlay.
Sending a request on every keystrokeDebounce on the client, cancel old requests, and cache answers locally.
Sharding a 6 GB indexPut a full copy on every server. Shard only when the index will not fit, and say why you would not do it earlier.
Ignoring safety and privacyBlock list at build and serve time, a distinct-user threshold, short log retention, and a fast removal path.
Mixing the serving path and the build path in one drawingDraw them as two paths with different speed needs, joined by a versioned snapshot.
Forgetting a rollback for a bad indexVersion the snapshot, verify it before switching, switch gradually, and keep the last good one.

Revise60-second revision sheet

  • ✔Scale: 100M searches a day × 4 requests is 400M requests, about 5 thousand a second, 25 thousand at peak. The index is about 6 GB.
  • ✔Core idea: precompute the top 5 at every trie node offline, so a request is a short walk and a read. No database and no sorting at request time.
  • ✔Two paths: serving (client, CDN, stateless servers in memory) and building (log, batch count, trie builder, versioned snapshot).
  • ✔Remove requests first: client debounce (about 150 to 250 ms) and cancel, local cache, and a CDN for popular prefixes (about 60%).
  • ✔No sharding at 6 GB: a full copy on every server, so any node answers any prefix and there are no hot shards.
  • ✔Do not update live: about 29 thousand writes a second on hot nodes. Batch rebuild every hour on a sampled, decayed count.
  • ✔Trends: a small stream job over the last 15 minutes publishes an overlay, so a surge shows in about 5 to 10 minutes.
  • ✔Safety: block list at build time and serve time, a distinct-user threshold for privacy, and a CDN purge for removals.
  • ✔Ship data like code: versioned snapshot, verify, switch node by node, keep the old one for rollback.
  • ✔Measure: selection rate, position of the pick (MRR), keystrokes saved, zero-suggestion rate. Test ranking changes with A/B.

Read these topics next

Trie (Prefix Tree)→

The data structure itself: how a trie stores and finds prefixes.

Caching Strategies→

Cache-aside, expiry and what to cache at each layer.

CDN→

How popular prefixes are answered close to the user.

Count-Min Sketch→

Counting a huge stream with a tiny, fixed amount of memory.

Heap and Priority Queue→

How the best 5 are kept at each node.

Batch vs Stream Processing→

The offline rebuild and the trending lane.

Kafka Deep Dive→

The search log that feeds the counts.

Hot Keys→

Why short, popular prefixes are an edge-cache problem.

← Previous
Design a Web Crawler
Next →
Design File Storage (Dropbox)