What you'll learn: By the end of this lesson you will be able to run an autocomplete design round: size the traffic, define a cacheable API, choose between a trie, a prefix table and a search-engine suggester, rank and refresh suggestions without leaking private queries, put the right cache layers in front, and rehearse the failures that matter, such as a bad index build.
Think of a helpful shop assistant who finishes your sentences. You say "oa", and before you stop she offers "oat milk, oatmeal, oat flour". She does not search the whole shop for each letter. She has a short list in her head for every beginning she has heard before, refreshed each morning, and she never offers anything the shop would be embarrassed by. If she mishears you, you lose a second; if she forgets the list, you lose the sale.
Autocomplete is that assistant. This is an educational reference design, not the verified internal architecture of any company, and it names no company. It is a case study: it applies the ideas of Search and recommendation systems: retrieve, rank, learn and search engines and the inverted index to one small, very hot feature, and does not re-teach them. The running example is the search box of the ShopStream grocery marketplace. The browser side of the same feature (debouncing, cancelling stale requests, keyboard and screen-reader behaviour) is the front-end autocomplete lesson, named here in plain text because it is written separately.
Verified on 2026-12-02 against the Elasticsearch, Redis, RFC 9111, RFC 5861, Unicode UAX 15 and Google Search Help documentation named below. All traffic numbers are illustrative assumptions; the arithmetic was checked with Node on the same date.
The core idea
Autocomplete is a lookup, not a search. A full search scores documents against a query at request time. Autocomplete answers "what do people usually type next, given these first characters?", and almost everything about that answer can be computed before the request: which phrases exist, how popular they are, and the top few for every beginning. At request time the system does a cheap read of a precomputed list. That single move explains the rest of the design: it makes latency independent of ranking, it makes responses cacheable, and it makes the hard problems offline ones: freshness, safety and privacy.
Three illustrations run through the lesson:
- Minimal example: the shopper types
oaand the service returns three suggestions from a prefix table. - Realistic example: the ShopStream search box, mixing product names, brands, categories and popular queries per region.
- Failure example: a truncated index build that silently empties suggestions for many prefixes.
Requirements and scope
Functional
- Given a prefix (and region, locale), return up to 8 ranked suggestions.
- Suggestion kinds: products, brands, categories, and popular queries. A product suggestion carries an id so selecting it can skip the results page.
- Show the user's own recent searches for the empty or short prefix, privately.
- Light typo tolerance for prefixes of three or more characters.
- New catalogue items appear in suggestions within minutes; trending queries within about an hour.
Out of scope: the full results page and its ranking (see the search lesson linked above), spelling correction of whole queries, voice input, and the browser behaviour.
Non-functional (assumptions, illustrative)
| Requirement | Target |
|---|---|
| Server latency | p99 under 50 ms from request arrival to response (the browser also pays network time on top) |
| Availability | Higher than search: if suggestions are down, search still works, so degrade to "no suggestions", never to an error |
| Freshness | New products in minutes; query popularity in about an hour |
| Safety | A removed suggestion disappears everywhere within minutes, faster than the next full build |
| Privacy | No phrase is suggested because of a single user; personal history is never shown to anyone else |
| Cost | Serving cost is dominated by cache misses, so cache behaviour is a first-class requirement |
Back-of-envelope estimate
Inputs are illustrative assumptions, using ShopStream's shared figures where they exist (2,000,000 daily active users, 100,000 products per region).
| Quantity | Assumption | Result |
|---|---|---|
| Searches per daily user | 3 | 2,000,000 x 3 = 6,000,000 per day |
| Suggest requests per search | 4 (after the browser waits for a pause in typing) | 24,000,000 per day |
| Average rate | 24,000,000 / 86,400 | about 278 per second |
| Peak rate | 5 times average | about 1,389 per second |
| Edge cache hit ratio | 80% | origin sees about 278 per second at peak |
| Suggestion corpus | 100,000 product names plus brands, categories and the most popular queries | 200,000 phrases kept |
| Trie size, upper bound | 200,000 phrases x 18 characters = 3,600,000 nodes x 100 bytes | about 360 MB |
| Distinct prefixes up to length 6, upper bound | 200,000 x 6 | 1,200,000 |
| Query log | 6,000,000 events x 120 bytes | about 0.72 GB per day |
The takeaways: the request rate is modest, so a handful of replicas serve it. The index is small, so one full copy fits in memory on each server and we shard by region, not by prefix. The bound of 360 MB is an upper bound because tries share prefixes, so real size is lower. If the corpus were a thousand times larger (a web-scale case) the answer changes: you would shard by prefix range and keep only a hot head in memory. Say that out loud; it shows you know which number carries the design.
API design
Two endpoints, because their cacheability differs.
GET /v1/suggest?q=oa®ion=south&locale=en-IN&limit=8
-> 200 Cache-Control: public, max-age=60, stale-while-revalidate=120
{ "version": "2026-12-02T09",
"suggestions": [
{ "text": "oat milk", "kind": "query" },
{ "text": "Oat drink 1l", "kind": "product", "id": "p_5521" },
{ "text": "oats and cereals", "kind": "category", "id": "c_48" } ] }
GET /v1/me/recent-searches?limit=5
-> 200 Cache-Control: private, no-store
{ "items": ["oat milk", "eggs"] }
POST /v1/suggest-events (beacon: shown list, position selected, query id)
-> 204
- The shared endpoint is a pure function of
(q, region, locale)and the index version. That is what lets a CDN or edge cache answer it. HTTP caching defines the knobs.max-agemakes a response stale after the given number of seconds (RFC 9111, section 5.2.2.1),s-maxageoverrides it for shared caches (5.2.2.10), and the unqualifiedprivatedirective says a shared cache must not store the response (5.2.2.7). So the personal list usesprivateand the shared list usespublicwith a shortmax-age. - Do not mix personal data into the shared response. The client merges recent searches with shared suggestions. If the server merged them, every response would be per-user and uncacheable.
Varyis a cache-key decision. If the response depends onAccept-Language, RFC 9111 section 4.1 says a cache must not reuse it unless the listed request headers match, and aVary: *response can never match. So prefer puttingregionandlocalein the URL, and keepVaryminimal.stale-while-revalidate(RFC 5861, section 3) lets a cache keep serving a stale response for a stated number of seconds while it revalidates in the background, which hides refresh latency from the typist.stale-if-error(section 4) lets it serve a stale response when the origin fails with a 500, 502, 503 or 504. Both suit suggestions: a slightly old list beats a blank box.- The
versionfield names the index snapshot that produced the answer. Without it, "suggestions got worse at 09:00" is unanswerable. - The events beacon reports what was shown and what was chosen, with positions: the same logging principle as in the search lesson, and the input to the next build.
Data model
Figure 1. The tables behind the service. How to read this: the CANDIDATE table is the product of two sources, the catalogue and the query log. PREFIX_ENTRY is derived: it can always be rebuilt from candidates. A SNAPSHOT is one versioned build of the whole prefix table, which is what makes rollback a pointer change.
- Normalization is part of the key. Lowercase, trim and collapse spaces, and apply Unicode normalization before comparing. Unicode's UAX 15 explains why: one visible character can have several code-point sequences (a precomposed letter, or a base letter plus a combining mark), so a binary comparison calls them different unless both sides are normalized to the same form. The same annex warns that the compatibility forms (NFKC, NFKD) must not be blindly applied to arbitrary text, so pick the form on purpose and test it with your languages.
- Keep display text separate from the key. The key is for matching; the display text keeps case, accents and brand spelling. Redis's documentation shows the same trick for its sorted-set range lookups: store a normalized first part, then the original, and show the second part.
- The query log is pseudonymous and short-lived. Keep aggregated counts, not a lifetime record of each user's text.
High-level design
Figure 2. The reference design. How to read this: the top row is the request path and must be fast; the lower rows run in the background and may be an hour behind. The only link between them is the snapshot: replicas load a validated, versioned build and swap to it, so serving never waits on building.
The request path is deliberately dull. The edge cache answers popular prefixes. A miss reaches a stateless API server that normalizes the prefix, reads the top candidates from its in-memory index, drops anything on the live blocklist, and returns. The private recent-searches read is a separate call.
Minimal example (illustrative). The tiny corpus has seven phrases: oat milk, oatmeal, oat flour, olive oil, onion, orange juice and organic eggs. Counting each distinct beginning gives 50 prefixes. The prefix o maps to all seven, oa to the three oat items, and oat to the same three. A lookup for oa is one key read that returns the stored top list, say oat milk, oat flour, oatmeal, in the order the builder computed.
Deep dive 1: the prefix index
Three structures fit. They differ in how much work moves to the request.
| Option | How it answers | Strength | Weakness |
|---|---|---|---|
| Trie with top-k at every node | Walk the prefix, return the node's stored list | Exact, tiny code, fast | Memory for the lists; rebuilding means a new trie |
| Prefix table (key is the prefix, value is the list) | One hash or key lookup | Simplest, trivially replicated and cacheable | Only works up to a maximum prefix length |
| Search-engine suggester | Engine's completion or edge n-gram fields | Reuses an engine you already run; supports fuzziness and filters | Memory-resident structures, rebuild and operational tuning |
The trie and the prefix table
A trie stores one letter per edge. Walking o, a, t reaches the node for oat. Storing the top k completions at every node turns the query into a walk plus a read, with no search of the subtree. The cost is memory: every node carries a list. A prefix table is the same idea flattened: the key is the prefix string and the value is the ordered list, which any key-value store or in-process map can hold. Cap the prefix length (say 12 characters): beyond it, the matching set is small enough to filter the full phrase list directly. The estimate above gives the size bound: 1,200,000 prefixes up to length 6 is comfortably in memory.
Redis shows why the data structure matters. Its ZRANGEBYLEX command returns members of a sorted set between two strings, but its documentation says it works when all members were inserted with the same score, and that if scores differ the returned elements are unspecified. A same-score sorted set therefore gives you lexicographic prefix ranges but no popularity order. It is fine for "list all names starting with oa" and the wrong tool for "the top 8 by score". Its documentation also says the command is deprecated as of Redis 6.2.0, a reminder to check the current command before designing around it.
The search-engine option
Elasticsearch's completion suggester is built for search-as-you-type, and its documentation says it is optimized for speed because it uses data structures that enable fast lookups but are costly to build and are stored in memory. Weights rank suggestions and come back as the score. Duplicate suggestions from different documents can be removed with skip_duplicates, which the documentation warns can slow search because more suggestions must be visited. The suggester also supports fuzzy queries, with fuzziness defaulting to AUTO, min_length to 3 and prefix_length to 1. Suggestions become visible after a refresh, deleted documents are never shown, and contexts (category or geo) filter or boost them. Its documentation also notes that the completion index is entirely heap resident and that multi-shard completions run in two phases, so a single shard performs better.
The other engine route is analysis-time: the search_as_you_type field type builds shingle subfields and an edge-n-gram _index_prefix subfield, and the edge_ngram tokenizer emits n-grams anchored to the start of each word. Its documentation says its defaults (min_gram 1, max_gram 2) are almost entirely useless and must be configured, that it should be used only at index time, and that query terms longer than max_gram may not match. That is a trade: more indexed terms for simple, general queries.
on each replica?"} A -->|no| B["Shard by prefix range,
hot head in memory"] A -->|yes| C{"Already run a search
engine with a suggester?"} C -->|yes| D{"Need your own score
and instant rollback?"} D -->|no| E["Engine suggester"] D -->|yes| F["Prefix table or trie
from an offline build"] C -->|no| F
Figure 3. A first-pass choice of index. How to read this: size comes first, because it decides whether sharding is needed at all. Then the question is whether you want the engine's convenience or control of ranking and versioned rollback. This reference design takes the lower-right path.
Decision for ShopStream. A precomputed prefix table, loaded from a versioned snapshot. It makes latency independent of ranking, makes every response cacheable, and turns a bad build into a rollback of one pointer. The engine suggester is the right call for a small team that already runs the engine and accepts its rebuild and memory behaviour.
Deep dive 2: ranking, freshness and privacy
Scoring with decay
A candidate's score combines a base weight (catalogue items start with a weight from sales or margin) and recent popularity from the query log. Raw counts favour old giants, so apply a time decay: each day's count is multiplied by 0.5 raised to (age in days divided by a half-life). With an illustrative half-life of 7 days:
| Phrase | Counts (age in days: searches) | Raw total | Decayed score |
|---|---|---|---|
| A: "oat milk" | 1 day: 400, 8 days: 300, 30 days: 1,000 | 1,700 | 549.4 |
| B: "oat drink 1l" | 1 day: 900, 8 days: 50, 30 days: 10 | 960 | 838.3 |
By raw total A leads; after decay B leads, because most of A's volume is a month old while B is surging. (The weights are 0.9057, 0.4529 and 0.0513 for ages 1, 8 and 30 days; the scores were computed with Node.) The half-life is a product choice: short values chase trends and amplify noise, long values are stable and slow to react.
The refresh pipeline
- Aggregate events into counts per normalized phrase, region and day, in a stream or batch job (see stream processing basics).
- Apply thresholds. A phrase must come from at least N distinct pseudonymous users (illustrative N = 20) before it can be suggested. This is the privacy rule: nobody's rare, private or sensitive query becomes a public suggestion.
- Filter and rank. Remove blocklisted phrases, apply the decay, keep the top k per prefix.
- Validate. Compare the candidate snapshot with the current one: entry count within an expected band, a fixed set of "golden prefixes" returning non-empty lists, no blocklisted phrase present.
- Publish and swap. Write the snapshot, then replicas load it in the background and switch atomically. Keep the previous version loaded for rollback.
A full rebuild every hour (illustrative) meets the "about an hour" target for popularity. New products must not wait an hour, so a small fresh overlay (the last few minutes of catalogue events) is merged into the lookup result at serve time and folded into the next snapshot.
Safety is a live path, not only a build step
Google's help page on autocomplete says its predictions reflect real searches, are not assertions of fact, and that automated systems and enforcement teams remove predictions that violate its policies. The design lesson is general: popularity-based suggestions can surface content you would not endorse, so have two layers. The build-time filter keeps blocked phrases out of every snapshot. The serve-time blocklist is a small, fast-updating set checked on each response and pushed to replicas in seconds, so a complaint about one suggestion is fixed in minutes instead of at the next build. Edge-cached copies also need to expire: that is the reason for a short max-age and for purge hooks on emergency removals.
Deep dive 3: caching and the request path
Autocomplete traffic has a sharp head. Single-character and two-character prefixes are asked constantly, so a few thousand keys carry most requests. Three cache layers help, in order:
- Browser. Reuse a response for a prefix the user just typed (the browser lesson covers this).
- Edge or CDN. Key:
(region, locale, normalized prefix). Withmax-age=60andstale-while-revalidate, popular prefixes almost never reach the origin. The 80% hit ratio in the estimate is an assumption; measure it and tunemax-agefrom it. - In-process. The index itself is an in-memory map; the lookup is a few microseconds of CPU.
Figure 4. The request path. How to read this: only a miss reaches the origin, and the origin does three cheap steps. The private call bypasses shared caches by design.
Add request coalescing at the edge (concurrent misses for one key become one origin call) so a cold prefix cannot stampede the API; the problem and cures are in cache stampede and hot keys. Add a per-client rate limit (rate limiting): suggestion endpoints are public and scrapable, and a scraper walking every prefix would otherwise read your whole corpus.
Deep dive 4: typos and other languages
Typos are expensive on a prefix index: a wrong first letter lands in a different subtree. Treat fuzzy matching as a fallback, not the default path: if the exact prefix returns fewer than k suggestions and the prefix is at least three characters, try a bounded fix (edit distance of one, first character fixed) against the candidate list. Elasticsearch's suggester defaults line up with that shape: fuzzy applies from a minimum length of 3 and a fixed prefix length of 1. Anything beyond that belongs to the full search, which has a spelling-correction pipeline of its own.
Other languages and scripts need their own normalization and, for languages without spaces, a different notion of "beginning". The reference design keeps one prefix table per (region, locale) and states plainly which locales it supports; adding a locale is adding a build, not changing the serving code.
Bottlenecks and scaling
- The index build is the heavy job: aggregation over the query log, then ranking. Partition by region and run regions independently so one region's failure cannot stop the others.
- Memory per replica is the serving cost. If the corpus grows past a comfortable share of memory, cap prefix length, drop the long tail of rare phrases, or shard by prefix range.
- Snapshot load can spike CPU and memory. Load into a second structure, then swap a pointer, and stagger replicas so not all swap at once.
- Edge purge and TTL control how fast a removal propagates; the blocklist must reach the edge as a purge, not only the origin.
- Hot keys. The one-character prefixes. Edge cache plus coalescing handles them; see the cache lessons.
Failure drills
| Failure | What users see | Design response |
|---|---|---|
| Truncated or empty snapshot | Suggestions vanish for many prefixes | Validation gate (count band, golden prefixes); never swap a failed build; roll back to the previous version |
| Suggest API down | No suggestions | Browser shows nothing and search still works; stale-if-error can serve stale from the edge |
| Query-log pipeline lags | Stale popularity | Show "snapshot age" on the dashboard; serving is unaffected |
| Bad phrase surfaces | An embarrassing suggestion | Serve-time blocklist plus edge purge; review the filter rule that missed it |
| Cache stampede after a deploy | Origin spike | Coalescing, staggered replica warm-up, longer stale-while-revalidate |
| Scraper walks all prefixes | Origin load, corpus copied | Per-client rate limit; thresholds so rare phrases never appear |
| Normalization bug after a release | "Café" and "cafe" disagree | Golden tests per locale; the version field shows which build produced it |
| One region's build fails | That region's list ages | Regions are independent; keep the old snapshot; alert on age |
Each drill ends with the blast radius: which region, which prefixes, for how long. A global snapshot with no per-region isolation turns a local fault into a global one.
Trade-offs worth stating
| Decision | Option A | Option B | How to choose |
|---|---|---|---|
| Computation | At request time | Precomputed lists | Precompute; latency and cache hit ratio depend on it |
| Index | Engine suggester | Own prefix table | Engine if you run one and accept its limits; own table for control and rollback |
| Freshness | Rebuild often | Overlay for new items | Overlay; rebuilds stay cheap and safe |
| Personalization | Server merges | Client merges | Client; keeps the shared response cacheable |
| Ranking | Raw counts | Decayed counts | Decay, with a half-life set by product need |
| Rare phrases | Show everything | Minimum distinct-user threshold | Threshold, for privacy and safety |
| Removal | Next build | Live blocklist plus purge | Live blocklist; builds are too slow for incidents |
Interview cheat sheet
| Step | What to say | Key numbers (illustrative) |
|---|---|---|
| Requirements | Lookup of precomputed top-k; fresh in minutes; safe; private | p99 50 ms, 8 suggestions |
| Estimate | Modest request rate, small corpus, cache head dominates | 1,389 per second peak, 200,000 phrases, about 360 MB bound |
| API | Cacheable shared endpoint plus private recents; version field | max-age 60 s |
| Data | Candidates, prefix table, snapshots, blocklist | Prefix length cap 12 |
| Design | Edge, stateless API, in-memory index, offline build with validation and swap | Hourly build, minute overlay |
| Failures | Bad snapshot, bad phrase, stampede, scraper | Roll back by pointer |
Build it
There is no lab for this case study. A good practice exercise is in the exercises below: write the prefix table builder on a small list of phrases and check it against hand-computed answers, such as the 50 prefixes of the seven-phrase example. Nothing on this page was run beyond the arithmetic in the estimate and the decay example.
In practice: a bad build at 2 a.m.
This is an educational scenario on ShopStream with illustrative numbers.
This is a realistic scenario, not a case history.
The situation
ShopStream's hourly suggestion build runs at the top of every hour. One night the aggregation job reads a partially written day of query logs. The builder produces a snapshot with about a tenth of the usual entries and publishes it. Within minutes, shoppers typing o, e or m see no suggestions.
Starting architecture
Figure 2 without the validation step: the builder publishes whatever it produces, replicas swap to the newest snapshot as soon as it lands, and nothing compares it with the previous one.
Options considered
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| A. Alert on empty-suggestion rate and fix by hand | No build change | Users see the fault first; slow | The fault is frequent |
| B. Validate before publish and keep the previous snapshot loaded | Bad builds never reach users | Build code and golden prefix lists to maintain | The golden list is stale or too short |
| C. Always merge the new snapshot into the old one | Never loses entries | Removed phrases linger; harder to reason about | Blocklist removals must take effect |
The decision
Option B. The builder compares entry count with the last good snapshot (a band of, say, 20 percent either way, illustrative), checks that 200 golden prefixes return non-empty lists and that no blocklisted phrase appears, and only then publishes. Replicas load a snapshot only if its state is validated, and keep the previous one as a fallback. A mid-load failure keeps serving the old snapshot.
Rollout and verification
Run the validator in report-only mode for a week and compare its verdicts with reality. Then enable gating in one region. Drill it: deliberately feed a truncated input in staging and confirm the snapshot is rejected and the old version keeps serving. Dashboards: snapshot age, entry count against the previous build, empty-suggestion rate per prefix length, cache hit ratio and origin rate, blocklist size.
The 2 a.m. failure
The page says: "empty-suggestion rate 34 percent". The validator is not yet live in one region.
First checks: the version in responses, snapshot entry count against the previous build, and the last successful log-aggregation time. Mitigation: set the pointer back to the previous snapshot; edge copies expire within the 60-second max-age, with stale-while-revalidate smoothing the switch. Follow-up: turn the validator on everywhere, and fail the build job when its input day is incomplete.
Architect's notes
- Version everything that serves. The
versionin the response is what lets you answer "which build did this user see?". - Make rollback a pointer change. If it needs a rebuild, it will be done too late.
- Decide the privacy threshold with the owner of the product. It is a product rule, not an engineering detail.
- Keep the live blocklist tiny and boring. It will be used in a hurry.
- Do not let the shared response depend on the user. Personal data and shared caching do not mix.
Common mistakes
- Computing suggestions at request time with a general search, which makes latency and cost depend on ranking.
- Merging personal data into the cached response, so nothing can be cached or it leaks.
- Raw counts without decay, so old favourites crowd out what people want now.
- No minimum-user threshold, so a private query becomes a public suggestion.
- Swapping to an unvalidated snapshot.
- Relying on the next build to remove a bad phrase.
- Skipping normalization tests, then finding that
Caféandcafelive in different keys.
Key takeaways
- Autocomplete is a lookup of precomputed top-k lists, not a request-time search.
- The request path is small and cacheable; the hard problems are offline: ranking, freshness, safety and privacy.
- Size the index before choosing a structure: if a full copy fits in memory, shard by region, not by prefix.
- A prefix table or trie with top-k at each node, or an engine suggester, are the real options; a same-score sorted set gives prefix ranges but not popularity order.
- Rank with time decay, require a minimum number of distinct users, and keep a live blocklist beside the build-time filter.
- Version snapshots, validate before publishing, and make rollback a pointer change.
- Put personal data in a separate private call so the shared response stays cacheable.
Practice exercises
Exercise 1 (30 min). For the seven phrases in the minimal example, list all 50 distinct prefixes and the top-3 list for o, oa and or if the scores are oat milk 90, oatmeal 40, oat flour 30, olive oil 80, onion 70, orange juice 60 and organic eggs 20.
Exercise 2 (1 hour). Using the decay formula with a half-life of 3 days instead of 7, recompute phrases A and B from the worked example. Does the order change? Write one sentence on what the half-life choice says about the product.
Exercise 3 (2 hours). Specify the snapshot validator: the exact checks, the bands, the golden prefixes per locale, and what the builder and replicas do on each failure. Then write the alert that tells you the validator itself has stopped running.
Related reading
- Search and recommendation systems: retrieve, rank, learn: the theory this case applies.
- Search engines and the inverted index: analysis and index internals.
- ShopStream: search, notifications and media: the project stage that built the first search.
- Cache strategies and cache stampede and hot keys.
- Stream processing basics: the aggregation behind the refresh pipeline.
- Rate limiting.
Official documentation
- Elastic, Suggesters, search_as_you_type field type and Edge n-gram tokenizer.
- Redis, ZRANGEBYLEX.
- IETF, RFC 9111: HTTP Caching and RFC 5861: HTTP Cache-Control Extensions for Stale Content.
- Unicode, UAX 15: Unicode Normalization Forms.
- Google Search Help, Autocomplete predictions and policies.