Search autocomplete has very little time to be useful. A person types a few characters, and the service must suggest relevant continuations before the next keystroke makes the response obsolete. A technically correct answer that arrives too late can feel worse than no suggestion at all.

The challenge goes beyond prefix matching. Popularity changes, languages behave differently, private queries must not leak into public suggestions, and a small number of short prefixes can attract a large share of traffic.

In a system design interview, this makes autocomplete a good exercise in separating offline preparation from online decisions. We want to do expensive work ahead of time while preserving enough flexibility to return safe, fresh and relevant suggestions.

Introduction

We will design query suggestions for a large shopping site. When someone types “wire”, the service might propose “wireless headphones”, “wireless mouse” and “wireless charger”. Selecting a suggestion runs the site's full search; autocomplete does not need to return complete product results itself.

This scope matters. Completing known query phrases differs from finding arbitrary documents whose title contains the input. Both can support a search interface, but they lead to different index structures, ranking signals and update requirements.

Our design will cover requirements, capacity estimates, the API, candidate generation, ranking, client behaviour and safe updates. The estimates are assumptions for the interview, so we will explain how they influence the architecture rather than presenting them as facts about an existing company.

Clarify the Functional Requirements

The service returns a small ranked list of query suggestions for a partial input. Suggestions are filtered by locale and catalogue market, and selecting one opens the normal search experience. We will begin with public suggestions shared by users in the same market.

The system should support multiword prefixes, common spelling mistakes and recent trends. It should remove disallowed suggestions quickly and avoid displaying phrases that expose personal information or private enterprise content.

Personal search history is a separate optional source. If included later, it must remain scoped to the authenticated user and visually distinguishable where appropriate. We should not mix personal history into a shared cache key or a public popularity model accidentally.

Clarify whether suggestions may lead to zero results. For a shop, a phrase that was popular last year but now matches nothing may be a poor suggestion. However, checking the full catalogue synchronously for every candidate could consume the entire latency budget.

We will therefore maintain eligibility and approximate result availability in the prepared suggestion data, with a bounded freshness target. The full search still handles the current catalogue state when the person selects a suggestion.

Establish Latency, Availability and Freshness Targets

Assume the backend should normally answer within fifty milliseconds at the ninety-ninth percentile in its serving region. The complete user experience also includes network transit, browser scheduling and any client-side debounce interval.

Availability is important, but autocomplete is an enhancement to search. If the service fails, the user should still be able to submit the text they have typed. This gives us a useful degraded mode: an empty suggestion list rather than a blocked search box.

Popularity updates can arrive within minutes for ordinary phrases, while editorial removals need a much faster path. These are different freshness requirements and should not share one overnight rebuild schedule.

Ranking does not need to be globally identical at every instant. A short period in which regions use adjacent model versions is usually acceptable if both are safe and relevant. Permission and policy filtering may require stronger enforcement than trend scores.

Set a maximum input length, result count and computational budget. Autocomplete is exposed on a public interactive endpoint, so an unusually long prefix or expensive fuzzy request must not trigger unbounded processing.

Estimate Traffic from Typing Behaviour

Suppose the site has ten million daily active users, each beginning four search sessions per day. If client behaviour creates an average of five autocomplete requests per session, the service receives about 200 million requests per day.

That averages roughly 2,300 requests per second, but averages are not a capacity plan. Assume a peak ten times higher for the interview, around 23,000 requests per second, and validate the multiplier with real traffic if this were a production project.

The request rate depends strongly on client behaviour. Debouncing, minimum prefix length, cancellation and caching can reduce unnecessary requests. Mobile networks and input methods also change how typing events translate into actual API calls.

If a response contains ten short suggestions and modest metadata, assume around one kilobyte before protocol overhead as a rough planning value. At peak, that is tens of megabytes per second of response payload, distributed across regions and edge infrastructure.

For the corpus, assume twenty million eligible phrases with average display text around thirty bytes in a chosen encoding. Raw strings occupy hundreds of megabytes, but identifiers, ranking features, language information and index overhead add significantly more. Measure an actual index representation before deciding how many replicas fit in memory.

Define the API and Response Identity

A simple endpoint accepts the prefix, locale, market and a bounded limit:

GET /api/suggestions?q=wire&locale=en-GB&market=GB&limit=8

The response can include a request identifier, normalised query context, model version and suggestions:

{
"requestId": "request-8d4a",
"modelVersion": "suggestions-2026-09-13-04",
"suggestions": [
{
"id": "phrase-731",
"text": "wireless headphones",
"query": "wireless headphones"
}
]
}

Return display text separately from the internal lookup form. Normalisation may remove distinctions useful for matching, while the interface should retain correct spelling, accents and capitalisation.

Treat the requested locale and market as bounded validated values. Authorisation determines any private scope; a caller-provided tenant identifier must not grant access to another tenant's suggestions.

A stable suggestion identifier helps collect feedback without relying only on the displayed text. Include model and experiment context in event records so later analysis can determine which ranking produced a selection. Avoid exposing sensitive internal ranking features in every response.

Separate Candidate Generation from Ranking

Candidate generation finds a manageable set of phrases compatible with the input. Ranking orders that set using signals such as popularity, recency, catalogue relevance and quality. Keeping these stages distinct makes their performance and relevance tradeoffs easier to explain.

For a strict prefix match, typing “wire” can retrieve phrases beginning with those characters. Multiword matching may require more flexible token handling: “head wire” might be intended to find “wireless headphones”, depending on the product's search behaviour.

Do not add every possible matching rule at once. Begin with a clear baseline, evaluate failed user journeys and introduce token reordering or typo tolerance where it helps. Each broader matching rule increases candidate volume and the chance of irrelevant suggestions.

The online ranking stage should remain bounded. Retrieve perhaps dozens or a few hundred candidates, apply lightweight filters and scores, then return the best small set. Running a large model over the entire phrase corpus for every keystroke would be a different cost profile.

Offline jobs can compute expensive features and preselect popular candidates. Online requests add context that cannot be fully precomputed, such as current market, a recent trend adjustment or a user's permitted private history.

Choose an Index Structure for the Matching Contract

A trie stores characters along paths, making prefix traversal natural. Once the prefix node is found, the service needs the best descendant phrases. Walking the whole subtree for a common prefix is expensive, so nodes can retain precomputed top candidates.

That approach trades memory and update work for fast reads. Storing many candidates at every prefix duplicates identifiers across the structure. Changes in phrase scores may require updating several ancestor lists, which is manageable for some corpora and costly for others.

Compressed tries or finite-state representations can reduce memory by sharing common structure. Their operational complexity depends on the implementation and whether updates are incremental or produced as immutable snapshots.

An existing search engine may be a better starting point than building a custom structure. Elastic's completion suggester documentation describes a completion-oriented feature with options such as fuzzy matching and duplicate handling. Evaluate its documented constraints against the exact query-completion requirement.

For document-oriented search while typing, Elastic also provides a search-as-you-type field. That is a different retrieval model from a curated phrase dictionary. Explain which behaviour the product needs before selecting an index because its name sounds appropriate.

Normalise Input Without Destroying Meaning

The serving and indexing pipelines must apply compatible text processing. If ingestion lowercases or normalises text differently from the query path, logically equivalent input can miss suggestions that exist in the corpus.

Unicode can represent visually equivalent text using different code-point sequences. The Unicode normalisation specification defines canonical and compatibility forms. Choose a documented form deliberately; compatibility transformations can collapse distinctions that matter in some contexts.

Case folding, accent handling, punctuation and whitespace rules are additional decisions. Removing accents can help a user who types on a limited keyboard, but display text should preserve the original form. Locale-sensitive behaviour needs testing beyond an English-only example.

Languages without whitespace between words may require language-aware segmentation. A character prefix can still be useful, but assuming that every word is separated by an ASCII space will produce poor matching and highlighting.

Keep normalisation versioned with the index. A serving deployment using new rules against an old index can create a sudden relevance regression. A model manifest should identify the analyser configuration as well as the data snapshot and ranking version.

Rank Suggestions with Signals You Can Explain

A baseline score can combine long-term popularity, recent activity and catalogue quality. Use a transformed count so a single historically dominant phrase does not permanently bury every useful alternative.

For example, the ranking might reward the logarithm of qualified search frequency, add a decaying recent-trend component, and penalise phrases that often lead to immediate reformulation or no useful results. The exact weights are learned or tuned from evaluation, not universal constants.

Count qualified activity rather than every raw keystroke. A phrase repeatedly displayed because it is already ranked first should not automatically gain popularity merely from its impressions. Selections, submitted searches and downstream success provide different evidence and have different biases.

Freshness signals should be robust against small noisy bursts. A phrase used twice today and never before has a dramatic percentage increase but little evidence of broad relevance. Require enough support before promoting it widely.

Diversity also matters. Returning eight near-identical variations can waste the suggestion list. Group close duplicates or intents and reserve space for meaningfully different useful continuations, while retaining the exact-match options users expect.

Build the Offline Data Pipeline

Clients and search services emit events for suggestion impressions, selections, submitted queries and useful outcomes. A durable event pipeline feeds aggregation jobs that produce phrase statistics by time window, locale and market.

Filter automated abuse, malformed input and sensitive content before promoting phrases into the public corpus. Retain only the event data needed for the analysis, with an appropriate retention policy and access controls.

Aggregation jobs deduplicate repeated events where necessary and account for retries. A stable event identifier can prevent an acknowledgement failure from doubling a selection count. Approximate aggregation may be acceptable for ranking, but the approximation should not accidentally turn one user's repeated actions into a public trend.

Candidate phrases pass eligibility and quality checks before index construction. Store the reason for exclusion so operators can distinguish a normal low-support phrase from one deliberately suppressed by policy.

The resulting index is a derived artefact. Keep source aggregates and build configuration sufficiently durable to reproduce it. Serving replicas should not be the only place where ranking state exists, because rebuilding after a regional failure must not depend on copying a damaged process's memory.

Combine Stable Snapshots with Fast Updates

An immutable base snapshot gives predictable serving performance and simple rollback. Build it offline, validate it, distribute it to replicas and activate it only after the complete artefact is available.

A smaller incremental layer can carry recent trends or newly eligible phrases between base builds. Query both layers, deduplicate by canonical phrase identity and apply a consistent ranking policy before returning results.

The overlay needs size and age limits. If it grows indefinitely, the system eventually operates two full indexes with complicated precedence rules. Merge it into the next base snapshot and retain clear checkpoints for events already included.

Removal should have a fast path independent of popularity rebuilding. Maintain a small deny list or suppression layer that is checked before returning candidates. Apply the same policy to cached responses, or invalidate relevant caches when urgent removals occur.

Version every component used for a response: base snapshot, overlay progress, ranking configuration and policy rules. This makes an unexpected suggestion reproducible during an investigation instead of disappearing into a constantly changing collection of loosely related updates.

Serve Common Prefixes Efficiently

Short prefixes such as “a” or “s” can dominate request volume while matching huge portions of the corpus. A minimum prefix length reduces expensive low-information requests, although the appropriate threshold depends on language and user experience.

Cache public responses using all dimensions that affect eligibility and ranking, such as normalised prefix, locale, market and model version. Personalised results must use a separate scoped path or be assembled after the shared candidate cache.

An in-process cache can remove network overhead for the hottest prefixes. A shared cache can reduce duplicate work across instances, but an extra cache hop may not help if the index already fits in memory and queries are very cheap. Measure the actual path.

Replicate a manageable phrase index across serving nodes where possible. This lets any node answer a request locally and avoids query fan-out. If the corpus is too large, shard by meaningful scope such as market or language before considering fine-grained prefix partitioning.

Prefix-based sharding can create hotspots because traffic is highly uneven. Hash-based sharding distributes data more evenly but may require querying several shards and merging candidates. Explain the tradeoff and choose from measured corpus size and request distribution.

Make Client Behaviour Part of the Design

The browser should avoid sending a request for every intermediate input state unnecessarily. A short debounce can combine rapid typing, while a minimum prefix length and small local response cache reduce repeated calls.

Respect input method composition. Some keyboards generate intermediate states while a person is composing a character. Treating every composition event as a final query can produce irrelevant suggestions and excessive requests.

Cancellation helps reduce abandoned work, but it does not guarantee that a request already in flight stops everywhere. Associate responses with the current input sequence and ignore any response that belongs to an older query state.

For example, the response for “wir” may arrive after the response for “wire”. Without a sequence check, the interface can visibly jump backwards despite a correct server. The client should compare the request context with the current input before rendering.

Keep keyboard navigation, focus and screen-reader behaviour coherent. The WAI-ARIA combobox pattern provides guidance for accessible suggestion interfaces. A low-latency backend is only one part of an autocomplete experience that people can actually use.

Protect Against Privacy Leaks and Manipulation

Raw search logs can contain names, addresses, account identifiers and other sensitive strings. Popularity alone is not sufficient justification for turning a query into a public suggestion.

Use an eligibility pipeline with sensitive-pattern detection, minimum support requirements and appropriate human review paths. Minimum counts reduce some accidental exposure, but they are not a formal privacy guarantee and can be manipulated by coordinated traffic.

Private enterprise search requires authorisation before candidates become visible. Filtering full search results after selection does not undo a leak that already occurred when a confidential document title appeared in the suggestion list.

Rate-limit requests and feedback ingestion separately. Attackers may try to exhaust fuzzy matching or manufacture popularity for a phrase. Validate event provenance, detect abnormal activity and avoid trusting an arbitrary client-reported count.

Policy removals should be auditable and reversible by authorised operators. Record the affected phrase identity, scope, reason and time, while keeping sensitive evidence restricted. Operational controls need to propagate quickly without requiring a complete index rebuild.

Degrade Gracefully Under Failure

If a regional serving node fails, route to healthy replicas within a latency budget. If the latest overlay is unavailable, a validated base snapshot may continue serving safe suggestions with older trend information.

If policy state cannot be verified, choose the documented safe fallback for the affected scope. For some public deployments that may mean returning fewer curated suggestions; for private content it may mean returning none until authorisation can be established.

Bound candidate count, fuzzy expansion and ranking time. A difficult query should return a smaller useful set or no suggestions rather than consuming enough resources to delay unrelated requests.

Keep search submission independent from autocomplete availability. The browser can stop displaying the dropdown after a short timeout while leaving the search action functional. Repeated automatic retries for every keystroke can worsen an overloaded service, so use conservative retry behaviour.

Monitor memory during index replacement. Loading a new snapshot while retaining the old one can temporarily require nearly twice the index memory plus working space. Rollouts need capacity for that overlap, or a staged process that avoids killing nodes during activation.

Evaluate Relevance and Performance Together

Offline evaluation uses a held-out set of prefixes and expected useful suggestions. Measure whether relevant candidates appear near the top, whether the list contains duplicates, and whether locale and safety filters behave correctly.

Online metrics include suggestion selection rate, time to successful search and reformulation rate. A higher selection rate is not automatically better if prominent suggestions steer users towards poor results or distract them from their intended query.

Break outcomes down by locale, device class, prefix length and new versus frequent queries. Aggregate improvements can hide a serious regression for a smaller language group or mobile input method.

Performance tests should reproduce skewed prefixes, long-tail queries, overlay updates and model activation. Uniform random prefixes often produce cheap empty results, understating the cost of real popular traffic.

Track backend latency, client-observed response age, candidate counts, cache hit rates, suppression activity and zero-suggestion responses. Together these measurements show whether a problem lies in retrieval speed, ranking quality, stale responses or eligibility rules.

Walk Through One Keystroke and One Update

The user types “wire” in the British catalogue. After the client decides the input is ready, it sends the normalised prefix with the current request sequence. The edge routes the request to a regional serving instance, which validates the input length, locale and market.

The instance checks its public response cache using those dimensions and the active model version. On a miss, it looks up candidates in the local base index and bounded trend overlay. Both sources return stable phrase identifiers with prepared features, so merging does not require database calls for every candidate.

The service removes duplicate identities, applies the current suppression rules and excludes phrases unavailable in this market. It scores the remaining bounded set, chooses a diverse top eight and returns display text with the request context. The browser renders the list only if that response still matches the current input sequence.

If the user selects “wireless headphones”, the browser records an event referencing the suggestion identifier, its position and the model version. The full search executes independently. Later, a qualified outcome event can indicate whether the user found a useful result, subject to the site's privacy and measurement rules.

Now a new product launch makes “wireless headphones with translation” popular. The aggregation pipeline observes qualified activity from enough independent sessions, checks eligibility and publishes an update to the trend layer. Serving nodes receive the versioned change and invalidate or naturally age out affected public response entries according to the freshness contract.

If that phrase is subsequently found to contain a policy issue, an authorised suppression update takes precedence over both the base index and trend layer. A node must not keep returning the phrase merely because its cached ranking was computed before the removal. This is why policy application and cache invalidation need an explicit relationship.

The walkthrough exposes the critical dependency graph. Ordinary requests depend on local serving data and bounded policy checks, while expensive aggregation happens outside the keystroke path. Full search availability remains separate, and user feedback improves later ranking without synchronously delaying the current response.

Explain How the Design Evolves

At a smaller scale, one managed search cluster with a completion index and a simple daily aggregation job may meet every requirement. Deploying a custom compressed trie, a global overlay and several cache layers before measuring demand would create unnecessary operational work.

As traffic grows, first identify whether the constraint is query CPU, index memory, update frequency or network distance. More read replicas solve a different problem from a smaller index representation. Better client debouncing solves a different problem from improving relevance for rare prefixes.

Personalisation can be introduced after the shared candidate stage. A small authorised history set can be merged with public candidates using clear precedence and deduplication. Keep private candidates out of shared caches and public training aggregates unless the data policy explicitly permits an appropriately processed use.

Typo tolerance can also expand gradually. Begin with exact prefix candidates, invoke a bounded fuzzy path only when the initial set is weak, and measure whether corrections improve completed searches. Short prefixes provide little evidence for a spelling correction, so aggressive fuzzy expansion there may mostly add cost and noise.

For international growth, separate evaluation sets and text-processing configurations by language where needed. A successful English configuration is not evidence that tokenisation, case handling or prefix lengths work equally well everywhere. Give local relevance failures an observable place in the metrics and review process.

In an interview, present these as conditional decisions. State the initial design, the measurement that would justify changing it, and the cost of the change. This demonstrates an architecture that can evolve from a workable baseline instead of a collection of components chosen solely because the prompt contains the words “at scale”.

Keep a small curated fallback set for important markets if the product benefits from suggestions during a broader outage. Review and version that set through the same eligibility process. A fallback that bypasses normal review can reintroduce phrases deliberately removed from the main index and undermine the safety of the otherwise careful serving path.

Summary

A scalable autocomplete service prepares most of its work offline and keeps the online path short: normalise input, retrieve bounded candidates, apply policy and context, rank, and return a small useful list.

Choose the index from the matching contract, estimate demand from actual typing behaviour, and treat short-prefix hotspots and model replacement as operational concerns. Versioned snapshots with a bounded update layer provide a practical route to both predictable reads and useful freshness.

The complete design also includes privacy filtering, accessible client behaviour and a search experience that survives autocomplete failure. In an interview, explaining these boundaries and tradeoffs demonstrates more than naming a trie: it shows how a fast prefix lookup becomes a dependable user-facing service.