Low-Latency Search Box Completion Platform
Hard · System Design · Software Engineer · Onsite
Prompt
Architect an interactive search-box completion platform that delivers ranked query and entity completions on each keystroke as a person types (for example, returning top completions when a mobile or web user enters "inv" within an end-to-end P95 < 100 ms latency budget).
Scope & Expectations
- Interfaces and index design: Define request/response schemas, text normalization rules, data models, and lookup structures (contrasting in-memory prefix trees against inverted indexes).
- Ranking, personalization, and latency: Detail candidate retrieval, ranking features, per-user personalization, multi-layer caching, and how the server budget fits inside
P95 < 100 ms. - Freshness, backfills, and experimentation: Lay out near-real-time trend/entity ingestion, urgent takedowns, idempotent historical backfills, and online A/B testing hooks.
- Scale and resilience: Explain horizontal scaling across traffic and corpus growth, validation gates, and graceful degradation when dependencies fail.
Step-by-step walkthrough
Clarify requirements and product scope
Autocomplete looks like a simple string-matching problem at first glance, but four real-world constraints collide at once: every keystroke must finish a full network round trip in under 100 ms, results must feel personal while staying mostly shared in memory, an offline-built index must still show new trends within minutes, and mining other people's searches must never leak private data.
Agree on the concrete product scope with the interviewer first. Assume we are designing the main search box of a large consumer financial and everyday-services app on mobile and web, returning three kinds of suggestions:
- Query completions: popular phrases other users searched (such as
"investor tax form"). - Entities: structured objects the app knows about, such as product features (
"Invest automatically"), help articles, financial products, and merchants. Tapping an entity opens that screen directly instead of running a text search. - Recent searches: the signed-in user's own past searches (such as
"invest in index funds").
Functional requirements
- Return up to 8 ranked suggestions per request, including character ranges so the UI can highlight the matched prefix.
- Match from the start of the string for query completions, and from the start of any word for entity names (typing
"auto"matches"Invest automatically"). Matching ignores uppercase/lowercase, accents, and extra spaces. - Personalize results for signed-in users; return global and trending suggestions for anonymous visitors.
- Surface newly created entities and surging search terms within 5 minutes, and hide removed or offensive suggestions within 1 minute.
- Log every served suggestion list and user selection for ranking models and A/B experiments, and let users delete individual or all recent searches.
Non-functional requirements
- Latency: P95 end-to-end latency under 100 ms as perceived by the user (meaning 95% of requests finish in under 100 ms, including mobile network travel).
- Availability: 99.9% uptime for suggestions, with graceful degradation: pressing "Search" must always work even if the suggestion service is completely down.
- Privacy: never suggest a rare phrase typed by only one or a few people, because users regularly paste names, street addresses, or account numbers into search boxes.
Out of scope for v1: executing the full search results page, fuzzy typo correction (covered as a follow-up), and voice transcription.
- Query completions: popular phrases other users searched (such as
Back-of-the-envelope scale and latency math
Before choosing databases or caches, estimate traffic, memory size, and time per network hop. On the client, debouncing means waiting a brief pause (say 50 ms) after each keystroke before firing a request so fast typing does not send a request on every single letter.
Traffic Daily active users (DAU) 50M Searches per user per day 4 -> 200M searches/day Suggest requests per search ~5 (after debouncing) -> 1B requests/day Average QPS 1B / 86,400 s = ~11,600 req/s Peak QPS (3x average) ~35,000 req/s -> size fleet for 50,000 req/s Corpus (per locale; numbers below for en-US) Eligible query completions 10M (typed by >= 50 distinct users in 30 days) Entities 2M entities x ~2 names/aliases each = 4M names Total indexed strings 10M queries + (4M names x ~2.5 word starts) = ~20M strings Index RAM (indexing prefixes up to 20 characters deep) Trie nodes (worst-case upper bound) 20M strings x 20 chars = 400M nodes x 16 B = ~6.4 GB Precomputed top-30 ID lists at most (20M / 31) nodes/depth x 20 depths = ~12.9M lists 12.9M lists x 30 IDs x 4 B = ~1.55 GB Suggestion metadata records 12M items x ~100 B (text, type, scores) = ~1.2 GB Total per replica ~9.15 GB (~9 GB; much less in practice due to shared prefixes) Serving fleet Per-server throughput ~3,000 req/s at server P95 < 25 ms (verify by load test) 3 regions (each sized for 50% of global 50k peak = 25k req/s): 9 servers + 1 spare = 10/region Event logs Served-list impressions 1B/day x ~500 B = ~500 GB/day raw Selections ~80M/day (assuming 40% of searches click a suggestion)Why the list memory bound (
20M / 31per depth) holds: at any single character depthd, every node represents a differentd-letter prefix, so their subtrees do not overlap across the 20M indexed strings. If we only store a precomputed top-30 list on nodes with at least 31 strings below them, at most20,000,000 / 31 = ~645,000nodes at depthdcan qualify.Two numbers shape the entire architecture:
- ~9 GB fits comfortably in a single server's RAM (even ~18 GB while swapping an old and a new snapshot side by side). Every API server can hold a complete local copy of the index, eliminating cross-server fan-out and hot-shard bottlenecks on common first letters like
"s"or"t". - Most of the 100 ms budget goes to the mobile network. A cellular round trip to a nearby region takes roughly 50-70 ms at P95 (~60 ms typical), leaving the backend at most 25 ms for everything on the server.
- ~9 GB fits comfortably in a single server's RAM (even ~18 GB while swapping an old and a new snapshot side by side). Every API server can hold a complete local copy of the index, eliminating cross-server fan-out and hot-shard bottlenecks on common first letters like
API design and out-of-order protection
A CDN (Content Delivery Network) is a global fleet of edge proxy servers near users that caches public HTTP responses, and TTL (time to live) is how many seconds a cached response can be reused before expiring. We use
GETfor reads so anonymous requests can be cached at the CDN edge, and echo a per-session sequence numberseqto prevent stale network responses from overwriting newer ones.GET /v1/suggest?q=inv&locale=en-US&limit=8&types=query,entity,recent&session=s_41b&seq=4 Authorization: Bearer <token> (optional; omitted for anonymous visitors) 200 OK Cache-Control: private, max-age=60 (anonymous responses use: public, max-age=60) { "q": "inv", "seq": 4, "request_id": "sg_5d8a19c2", "index_version": "2026-11-26.en-US.3", "experiments": ["rank_v14:treatment"], "complete": false, "suggestions": [ { "id": "e:feature:auto_invest", "type": "entity", "text": "Invest automatically", "highlight": [[0, 3]], "source": "global", "action": {"kind": "open", "target": "app://auto-invest"} }, { "id": "r:7b2e", "type": "recent", "text": "invest in index funds", "highlight": [[0, 3]], "source": "personal" }, { "id": "q:94a1", "type": "query", "text": "investor tax form", "highlight": [[0, 3]], "source": "trending" } ] } POST /v1/suggest/events batched client telemetry: {request_id, suggestion_id, position, action, ts} DELETE /v1/me/recent-searches/{id} remove one saved search DELETE /v1/me/recent-searches clear all saved searchesWhy each response field earns its place:
User types "in" (seq=3) ----(slow mobile packet, 95 ms)-------------------> arrives 2nd (IGNORED: 3 < 4) User types "inv" (seq=4) --------(fast packet, 40 ms)------> arrives 1st (SHOWN: newest_seq becomes 4)seqprevents UI flicker: mobile packets can arrive out of order. The client tracksnewest_seqand discards any response whoseseq < newest_seq.Cache-Control: privatevs.public: any response for a signed-in user (including an emptyq=""tap that shows their recent searches) is markedprivateso a shared CDN never leaks one user's history to another. Anonymous responses arepublic, max-age=60.complete: truecuts network calls on rare prefixes: the server setscomplete: trueonly when zero matching candidates were cut off bylimit, node top-K caps, or mixing rules (and the profile lookup succeeded). Because every match for"inve"is also a match for"inv", the client can filter that short list locally for further keystrokes without calling the server.- Server-side impression logging: the server asynchronously logs what it served alongside
index_versionandexperiments, so ranking data stays accurate even when mobile clients drop telemetry batches.
Data model and text normalization
Text normalization is a deterministic function that turns messy raw text (such as
" Ínvest Automatically! ") into a clean canonical form ("invest automatically") by applying Unicode compatibility normalization (NFKC), lowercasing, stripping accents for matching while keeping the originaldisplay_textfor rendering, and collapsing extra spaces.suggestions suggestion_id, type (query | entity), display_text, normalized_text, locale, entity_ref, category, global_score, trend_score, ctr_prior, quality_flags entity_names entity_id, name, kind (official | alias), locale (streamed via CDC) base_index_file immutable binary snapshot per (locale, index_version): header (normalizer_version), packed trie array, top-30 ID arrays, suggestion metadata table (~9 GB) fresh_index small in-memory trie of <= 100k trending queries and new entities (rebuilt every 60 s) user_recent key-value store: user_id -> up to 50 {normalized_text, display_text, last_used, count}, TTL 90d user_affinity feature store: user_id -> category weights & recent entity IDs (refreshed daily) blocklist versioned set of blocked {normalized_text, suggestion_id, entity_id, regex_pattern} kafka_events suggest_served, suggest_selected, search_submitted daily_aggregates (date, pipeline_version, normalized_query) -> search_count, select_count, distinct_usersTwo modeling details prevent silent bugs:
- One versioned normalizer everywhere: if the offline builder strips hyphens while the live API server keeps them,
"e-statement"becomes unsearchable. We embednormalizer_versioninbase_index_fileand make servers refuse to load a snapshot built with a mismatched normalizer. - Word-start indexing for entities only: an entity like
"Invest automatically"is inserted into the trie at"invest automatically"(full-string match) and at"automatically"(word-start match, tagged with a boolean flag so full matches still rank higher). Long user queries are indexed only from character 0 so short words do not pull in noisy mid-sentence phrases.
- One versioned normalizer everywhere: if the offline builder strips hyphens while the live API server keeps them,
High-level architecture
Change Data Capture (CDC) is a pattern that tails a database's write log and streams row creations, renames, and deletions as real-time events. Combining CDC with stream aggregation and daily batch builds gives us three clean update speeds while keeping the live read path almost entirely in RAM.
Mobile / Web Client (50 ms debounce, session prefix map, drops seq < newest_seq) | v CDN Edge (caches anonymous GET responses for 60 s; bypassed for signed-in users) | v Regional Load Balancer ---> Suggest API Servers (stateless, 10 per region, 3 regions) | In local RAM: | - Base Trie Snapshot (mmap, ~9 GB) | - Fresh Trie (~100k items, pushed every 60 s) | - Blocklist (pushed every 5 s) | - Tree Ranker + Experiment Config | +--> [Parallel, 15 ms hard timeout] User Profile KV (recent + affinity) +--> [Async, non-blocking] Kafka: suggest_served Nearline Path (minutes) Kafka events ---> Stream Aggregator (1-min windows) ---> Trending Queries --+ Entity DBs --CDC--> New / Renamed Entities ---------------------------------+--> Fresh Index Builder (every 60 s -> API RAM) Fast Removal Path (seconds) Safety Admin / Automated Flag ---> Blocklist Service --(push every 5 s)--> API RAM + CDN Tag Purge Daily Batch Path (hours) Raw Logs (90d lake) ---> Daily Query Rollups ---> Privacy (>=50 users) & PII Filters ---> Base Index Builder ---> Validation Gates ---> Blob Store (last 3 versions) ---> API ServersOn every keystroke that reaches a
Suggest APIserver:- Normalize
q, and immediately fire the async read toUser Profile KV(for signed-in users). - While that network read is in flight, look up top candidates in local RAM from both the
Base Trieand theFresh Trie(under 1 ms). - Merge global, trending, and personal candidates (~60 total), score them with the in-memory ranker, strip anything matching
Blocklist, and return the top 8.
- Normalize
Deep dive 1: Prefix trie with precomputed top-K
A trie (prefix tree) is a tree data structure where each edge is one character, so walking
"i" -> "n" -> "v"lands on the single node representing every indexed string starting with"inv". Compare the three main ways to retrieve the best 8 completions for"inv":- Relational B-tree range scan (
WHERE text >= 'inv' AND text < 'inw'): finds the alphabetical range fast, but for a 1-letter prefix like"i"it must scan and sort hundreds of thousands of rows by score on every keystroke. - Search-engine inverted index (edge n-grams): flexible for multi-word queries, but short prefixes have massive posting lists and add an extra network hop to a search cluster.
- In-memory trie with precomputed top-K lists: walking at most 20 characters and reading one pre-sorted array of 30 IDs takes a few microseconds with zero network hops.
Why
K = 30when the UI shows only 8? Keeping 30 global candidates gives the online reranker enough headroom to boost items matching the user's personal category affinities (and replace any item caught by a fresh blocklist addition) before slicing to 8.(root) | 'i' (i) top=[id1, id4, id2, ...] <-- size > 30: stores precomputed top-30 IDs / \ 'n' 'r' (in) (ir) top=None <-- size <= 30: no list saved; walk small subtree on demandOffline, the daily builder inserts normalized strings up to
MAX_DEPTH = 20characters and fillsnode.topbottom-up:import heapq K = 30 # Precomputed candidates stored per busy trie node MAX_DEPTH = 20 # Prefixes longer than 20 chars share the depth-20 node class TrieNode: def __init__(self): self.children = {} # char -> TrieNode self.entries = [] # suggestion IDs whose indexed prefix ends at this node self.top = None # best K distinct IDs in subtree, stored only if subtree size > K def finalize_trie(node, score_fn): """Compute node.top bottom-up. Returns (best K distinct IDs, total entry insertions below).""" pool = list(node.entries) subtree_size = len(node.entries) for child in node.children.values(): child_best, child_size = finalize_trie(child, score_fn) pool.extend(child_best) subtree_size += child_size # Deduplicate IDs because one entity can appear via multiple aliases or word starts distinct_ids = [] seen = set() for suggestion_id in pool: if suggestion_id not in seen: seen.add(suggestion_id) distinct_ids.append(suggestion_id) best_k = heapq.nlargest(K, distinct_ids, key=score_fn) if subtree_size > K: node.top = best_k return best_k, subtree_sizeMerging only each child's
best_kis exact: any ID excluded from a child's top 30 already lost to 30 distinct higher-scoring IDs inside that child alone, so it can never place in the parent's top 30 either.At query time, if
len(prefix) > 20, we walk to depth 20 and filter the returned IDs against their full indexed strings so longer prefixes stay exact:def collect_small_subtree(node, score_fn): """Enumerate all distinct IDs below a node with <= K entries.""" found = set() stack = [node] while stack: curr = stack.pop() found.update(curr.entries) stack.extend(curr.children.values()) return sorted(found, key=score_fn, reverse=True) def lookup_candidates(root, prefix, score_fn, indexed_strings_by_id): """Return up to K highest-scoring candidate IDs matching `prefix`.""" node = root for ch in prefix[:MAX_DEPTH]: node = node.children.get(ch) if node is None: return [] raw_ids = node.top if node.top is not None else collect_small_subtree(node, score_fn) if len(prefix) <= MAX_DEPTH: return raw_ids # For prefixes > 20 chars, verify the full prefix against the candidate's indexed strings return [ sid for sid in raw_ids if any(s.startswith(prefix) for s in indexed_strings_by_id[sid]) ]In production, the builder serializes this trie into flat byte arrays (child characters and 4-byte integer offsets instead of Python object pointers) and servers load it via
mmap(memory-mapped file)—an OS mechanism that maps a file on local SSD directly into virtual memory pages, avoiding deserialization CPU spikes and garbage-collection pauses.- Relational B-tree range scan (
Deep dive 2: Personalization, ranking, and the 25 ms server budget
A shared global trie cannot hold a personalized list per user, so we split retrieval into shared candidate generation followed by lightweight per-user reranking over at most ~60 candidates:
- Up to 30 from the base trie (global popularity + historical click-through rate).
- Up to 10 from the fresh trie (surging queries and entities added in the last 24 hours).
- Up to 10 matching recent searches from
user_recent(scanned in microseconds over the user's <= 50 saved searches). - Up to 10 matching entities the user interacted with recently from
user_affinity.
Reranking model: a Gradient-Boosted Decision Tree (GBDT) ranker (an ensemble of shallow decision trees, such as LambdaMART, that evaluates tabular numbers in C++ without GPU overhead) scores each candidate using four small feature groups:
- Global quality: log of time-decayed search volume, smoothed selection rate, trend velocity.
- Prefix match quality: full-prefix vs. word-start match,
len(typed_prefix) / len(suggestion)ratio, exact match flag. - Personal affinity: recency and frequency in
user_recent, cosine/dot-product match with the user's category weights (e.g., banking vs. investing). - Request context: app screen (home tab vs. help center), mobile vs. web, hour of day.
Scoring 60 candidates across 300 depth-6 trees is
60 x 300 x 6 = 108,000simple threshold comparisons—well under 1 ms on a single CPU core. Post-processing deduplicates identical normalized strings, enforces diversity caps (at most 3 recent searches, at least 1 entity if a strong match exists), removes blocklisted entries, and slices tolimit = 8.De-biasing training labels: users click position 1 far more often simply because their eyes start at the top—an effect called position bias. To avoid teaching the model to blindly repeat yesterday's rank 1, 1% of traffic randomly swaps adjacent candidate pairs to measure position-specific click drop-off, and training weights each click inversely by its position's observation probability. Offline, we track Mean Reciprocal Rank (MRR) (average of
1 / clicked_position) and keystrokes saved (len(selected_text) - len(typed_prefix)).End-to-end P95 latency budget (< 100 ms target) Mobile cellular round trip + TLS (warm connection) ~60 ms Server budget <= 25 ms +-- Load balancer + routing 2 ms +-- Normalize + base & fresh trie lookups < 1 ms (runs in parallel with KV read) +-- User Profile KV read 10 ms P95 (hard 15 ms timeout) +-- GBDT rerank (~60 candidates) + mixing rules 1 ms +-- Blocklist check + JSON serialization 1 ms +-- Event logging 0 ms (async local ring buffer -> Kafka) Total P95 ~80 ms (~20 ms safety margin)Because
User Profile KVis the only remote call on the read path, its 15 ms timeout acts as a circuit breaker: if the profile store slows down, the server immediately ranks the ~40 global and fresh candidates, incrementspersonalization_skipped, and still answers within 20 ms.Deep dive 3: Freshness, privacy filters, and idempotent backfill
No single pipeline can be simultaneously cheap, privacy-audited over 30 days, and instant within seconds. Three specialized paths divide the job:
- Daily batch index (high precision, 24 h cadence): instead of rescanning 30 days of raw logs (
30 x 500 GB = 15 TB) every night, a daily job aggregates only yesterday's 500 GB intodaily_aggregateskeyed by(date, pipeline_version, normalized_query)and combines the last 30 daily summaries using exponential time decay (7-day half-life). - Nearline fresh index (< 5 min latency): a streaming job counts normalized queries in 1-minute tumbling windows and compares the last 60 minutes against the same weekday/hour over the prior 4 weeks. Queries spiking significantly above baseline and searched by at least 50 distinct signed-in users in the last hour join CDC entity updates in the
Fresh Index Builder, which compiles a tiny trie every 60 seconds and pushes it to API servers. Worst-case end-to-end delay: ~1 min window + ~1 min build + up to 60 s anonymous CDN TTL = ~3 minutes. - Emergency blocklist (< 1 min removal): rebuilding a 9 GB file is too slow when a harmful or trademarked term appears. Safety tools write to the
Blocklist Service, which pushes deltas to API servers every 5 seconds and issues a CDN cache-tag purge for that locale's anonymous suggestions. Every server checks final candidates against in-memory hash sets (suggestion_id,entity_id,normalized_text) before serializing the response.
Privacy and anti-abuse gates (both batch and nearline):
- 50-distinct-user threshold (k-anonymity): a query string enters the shared index only after at least 50 distinct accounts searched it (counting each user at most once per query per day so a single bot loop cannot inflate counts). Tracking
(query_hash, user_hash)pairs across 30 days takes~200M/day x 30 x 16 B = ~96 GBin batch storage and blocks personal names, addresses, and account numbers from ever appearing to strangers. - PII and safety scrubbers: regex rules strip strings with long digit runs (card, SSN, phone, routing numbers) or email patterns regardless of user count, followed by an automated toxicity classifier.
Idempotent backfill: when we improve normalization or fix a logging bug across the past two weeks, we re-run the daily aggregation over raw logs (retained 90 days) under a new
pipeline_version = v15. Writing to(date, v15)replaces whole partitions cleanly without adding ontov14counts, builds a candidate base index, and validates it behind an experiment flag before promotion.- Daily batch index (high precision, 24 h cadence): instead of rescanning 30 days of raw logs (
Multi-layer caching, scaling, and A/B experimentation
Caching from outside in:
- Client session cache: stores
prefix -> responsein memory for the current search session so pressing Backspace ("inve"->"inv") renders in 0 ms with zero network traffic, and renders local device recent searches immediately on focus. - CDN edge cache: caches anonymous
GET /v1/suggestresponses for 60 s, keyed by(lowercased_trimmed_q, locale, limit, experiment_bucket). Because there are only 26 single-letter and 676 two-letter Latin prefixes, short prefixes achieve a near-100% edge hit rate. - Inside the API tier (no Redis in front of the trie): adding a remote Redis cache in front of an in-memory trie would turn a 5-microsecond RAM read into a 1-2 ms network hop. Only
User Profile KVresponses optionally use a short 60-second in-process LRU cache (when load balancers use sticky consistent hashing onuser_id, with explicit eviction onDELETE /recent-searches).
Scaling axes:
- Traffic growth: add stateless API replicas; each loads the 9 GB snapshot from object storage onto local NVMe SSD and serves any prefix. Stagger daily 9 GB downloads across 60 minutes into a secondary memory slot, smoke-test locally, and flip an atomic pointer.
- Corpus growth: partition by
localefirst (en-US,es-US, etc.). Only if a single locale ever exceeds single-machine RAM (for example, indexing hundreds of millions of merchant SKUs), shard the trie by traffic-balanced prefix ranges ("a"-"c","d"-"h", ...) so each request still routes to one shard with zero scatter-gather fan-out.
A/B experimentation hooks:
- Zero-hop assignment: servers compute
hash(user_id_or_device_id, experiment_salt) % 10000in memory from pushed config, organized into orthogonal layers (one layer for UI/debounce, one for candidate generation, one for ranking) so concurrent tests do not collide. - Sample size math: with a 40% baseline suggestion acceptance rate (
p = 0.40), detecting a 1% relative improvement (delta = 0.004, from 40.0% to 40.4%) at 80% statistical power and 5% significance requires16 x p x (1 - p) / delta^2 = 16 x 0.24 / 0.000016 = 240,000searches per arm. Because we randomize by user rather than by individual search (and a user's searches correlate), we multiply by a variance inflation factor (~2-3x) and run for 1-2 full weeks; even 1% of 200M daily searches yields ~2M searches/day per arm. - Interleaving (weaving ranker A's and ranker B's suggestions into a single list per keystroke and comparing which model's picks win clicks) screens new ranking features with ~10x less traffic before a full A/B test.
- Client session cache: stores
Failure modes, validation gates, and trade-off summary
Failure scenario User impact Automated system response User Profile KVslow or unreachableSuggestions stay fast, just non-personalized 15 ms timeout trips; rank global + trending candidates and increment personalization_skippedFresh index stream job stalls Breaking trends pause; normal autocomplete works Keep serving last good fresh trie + base trie; page on-call if fresh trie age > 10 min Bad daily base index (broken scorer or empty join) None (blocked before serving) Pre-publish validation gates reject snapshot; servers keep previous snapshot (last 3 kept on blob store) Blocklist service unreachable Existing blocks stay enforced Servers never clear local blocklist on error; if stale > 1 hour, disable log-mined query completions and serve curated entities only API server or whole region crash Brief retry or +20-40 ms cross-region RTT Stateless restart mmaps snapshot from local SSD in seconds; DNS shifts traffic to remaining regions (each sized for 50% global peak)Extreme traffic spike Graceful load shedding Skip profile fetch first, then shed excess requests fast with 503; client keeps displaying previous keystroke's list and normal search still worksAutomated index validation gates (before any server swaps to a new daily snapshot):
- Total suggestion count is within
+-5%of yesterday's snapshot. - Across the top 10,000 prefixes, top-8 overlap with yesterday is
>= 70%(catches accidental score inversions). - Zero entries match the active blocklist or PII regexes, and a golden test suite of critical app intents (
"invest","tax form","routing number") passes. - Canary rollout on 1 server per region for 30 minutes verifying P95 latency, error rate, and suggestion acceptance rate.
Summary of core trade-offs:
- In-memory precomputed top-K trie vs. distributed search index: microsecond lookups and zero network hops, traded against offline rebuilds and simpler prefix/word-start matching.
- Full index replicas vs. sharding: zero hot-prefix skew and trivial scaling while the locale fits in ~9 GB of RAM.
- Shared candidates + online GBDT reranking: keeps 99% of index RAM shared across all users while delivering personal ordering within a 25 ms server budget.
- Three-tier freshness (24 h batch, 60 s fresh trie, 5 s blocklist) + 50-user privacy gate: meets strict trend and takedown SLAs while guaranteeing personal search strings never leak to strangers.
- Total suggestion count is within
Intuition & how it works
Think of a live search-box completion platform like a librarian standing at the front desk with a giant tabbed flipbook instead of running into the back stacks on every syllable you speak. Under each tab ("i", "in", "inv"), the librarian has already printed the 30 best matching items in ranked order overnight, alongside a tiny sticky note of topics trending in the last few minutes and a quick glance at your personal checkout card. Because the heavy sorting happened ahead of time, answering a keystroke is just flipping to one tab, blending in your personal picks, crossing off any recalled titles, and reading the top 8 lines aloud in milliseconds.
The obvious beginner design—running SELECT text FROM queries WHERE text LIKE 'inv%' ORDER BY score DESC LIMIT 8 against a database on every keystroke—collapses immediately at scale. A single-letter prefix like "i" matches hundreds of thousands of rows, and sorting them 50,000 times per second blows far past the 100 ms human-perception limit (especially once a 60 ms mobile network round trip eats most of that budget). Relying on a CDN cache alone also falls short because signed-in users expect their own recent searches mixed in, while rebuilding one static index once a day is too slow to catch breaking trends within 5 minutes or hide harmful suggestions within 1 minute.
Walk through a concrete 4-step trace when a signed-in user types "i", "n", "v" on their phone:
- Client debounce and sequencing: waiting 50 ms (debouncing, pausing briefly so fast keystrokes coalesce) skips
"i"and sendsGET /v1/suggest?q=inv&seq=2(and if an earlierseq=1response arrives late over cellular, the app ignores it because1 < 2). - Parallel in-memory + profile lookup (10 ms): the API server normalizes
"inv"and simultaneously fetches the user's recent searches ("invest in index funds") from a fast key-value store (15 ms hard timeout) while walking"i" -> "n" -> "v"in a local trie (a character-by-character prefix tree in RAM) to grab 30 pre-sorted global IDs ("Invest automatically", ...) plus 2 matches from a tiny 60-second fresh trie ("investor tax form"). - Lightweight reranking and safety filter (2 ms): an in-memory Gradient-Boosted Decision Tree (GBDT) model (a fast ensemble of shallow decision trees) scores those ~33 candidates using global popularity, prefix match ratio, and user affinity, enforces diversity caps, and drops anything in an in-memory blocklist pushed every 5 seconds.
- Fast response (~75 ms total perceived): the server returns the top 8 JSON items in ~15 ms total server time (~75 ms with the mobile round trip) and logs the impression asynchronously to Kafka without slowing down the user.
Key trade-offs
- Precomputed top-K per trie node vs. query-time index sorting. Pre-storing the top 30 candidate IDs on every trie node that has more than 30 strings below it turns retrieval into a 20-step pointer walk plus a single array read (a few microseconds). The trade-off is that global scores are static until the next daily build, requiring a separate 60-second fresh trie for trends and a 5-second blocklist push for urgent removals.
- Skipping precomputed lists on small subtrees (
<= 30items). Storing a 30-ID array on every trie node would waste tens of gigabytes on deep, rare prefixes. Only materializingnode.topwhen a subtree holds at least 31 strings caps list RAM at(20M / 31) x 20 depths x 120 B = ~1.55 GB, trading a tiny microsecond walk of<= 30items on rare prefixes for massive memory savings. - Full in-memory replicas vs. prefix sharding. At ~9 GB per locale (loaded via
mmap, an OS feature that maps a flat disk file directly into virtual memory without object garbage-collection overhead), putting the entire index on every API server means any server answers any prefix with zero cross-node fan-out and zero hot-shard skew on popular letters like"s". The cost is 18 GB of peak RAM during atomic version swaps and daily 9 GB snapshot downloads; sharding is deferred until a single locale exceeds one server's memory. - Shared candidate retrieval + online personal reranking. Keeping one shared trie for global/trending items and merging in a user's
<= 50recent searches at request time keeps index memory constant regardless of user count, and lets the server shed personalization cleanly if the profile store is slow. The limitation is that a niche item outside the global top 30 and outside the user's own history will not surface on short prefixes. - Three freshness speeds vs. one real-time mutable index. Mutating a multi-gigabyte trie concurrently on 50,000 requests/s invites lock contention and makes bad ranking updates instant outages. Splitting updates into a validated 24-hour batch build, a 60-second fresh trie (~100k items), and a 5-second blocklist keeps reads lock-free and safe, at the operational cost of maintaining three pipelines and merging results at read time.
- 50-user k-anonymity privacy threshold vs. long-tail recall. Requiring at least 50 distinct users (counting at most one search per user per day) before a query enters the shared corpus discards legitimate rare searches, which we accept because even a single leaked name, address, or account number in autocomplete is an unacceptable privacy failure.
- CDN edge caching limited to anonymous traffic. Signed-in responses (including empty-prefix recent-search lists) carry personal history and must use
Cache-Control: private, so CDN edge caching (60 s TTL, or cache expiration window, purged on blocklist updates) offloads anonymous traffic while signed-in latency relies on multi-region deployment and client-side session caching.
Common mistakes
- Budgeting all 100 ms to backend servers. A mobile cellular round trip consumes 50-70 ms before your code runs a single line; without budgeting ~25 ms for the server, the design misses P95 in production.
- Running
LIKE 'pre%'database queries or putting Redis in front of an in-memory trie. SQL prefix scans sort huge match sets on short prefixes, and calling a remote Redis cache adds a 1-2 ms network hop in front of a 5-microsecond local RAM lookup. - Ignoring out-of-order network responses. Without an incrementing
seqechoed by the server, a slow response for"i"arriving after"inv"overwrites the dropdown with stale completions. - Mining raw search logs without k-anonymity and PII scrubbing. Suggesting queries typed by 1 or 2 users inevitably leaks personal names, emails, or financial account numbers to strangers.
- Waiting for an index rebuild to delete harmful suggestions (or forgetting the CDN). Daily rebuilds take hours, and filtering only on API servers leaves offensive text live in CDN edge caches unless blocklist updates also purge cached anonymous entries.
- Mismatched text normalization between offline indexing and live serving. If the batch pipeline strips accents or punctuation differently from the API server, valid prefixes silently return empty lists.
- Training the ranker on raw clicks without correcting position bias. Users click rank 1 heavily just because it sits on top; without randomized pair swaps and inverse-propensity weighting, the model learns to freeze yesterday's ordering forever.
- Coupling search execution to autocomplete health. If the suggestion endpoint times out, pressing Enter in the search box must still submit the user's raw text directly to search.
Follow-up questions
- How can you incorporate typo-tolerant completions (such as matching "invesment" to "investment") while staying inside a 25 ms server budget? Only trigger fuzzy matching when exact lookup returns fewer than 3 candidates and the normalized prefix is at least 4 characters long (short 1–3 letter prefixes are almost never clear typos and have huge branching factors). Start with a fast in-memory dictionary of high-confidence prefix rewrites mined from session logs where users backspaced
"invesment"into"investment", and fall back to a bounded 1-edit-distance (Levenshtein/Damerau) trie walk tagged with anis_fuzzy = truefeature so the ranker scores exact matches higher. - How quickly does a sudden surge query surface, and how do you stop coordinated bots from poisoning shared completions? Once 50 distinct users search the phrase, the 1-minute streaming aggregator flags its surge against the 4-week seasonal baseline and the 60-second fresh index builder pushes it to API servers, making it visible in ~2 minutes (~3 minutes worst case behind the 60 s anonymous CDN cache). Botnets are blocked because each signed-in account contributes at most one vote per query per day, newly created or unverified accounts and suspicious IP/ASN clusters are excluded from distinct-user counts, and the 5-second blocklist can strip anything that slips through.
- How would the indexing topology evolve if the searchable catalog expanded 20x to 200 million items? At ~180 GB per locale, a single replica no longer fits comfortably in one machine's RAM, so we partition the locale's trie across shards by traffic-balanced prefix ranges (for example
"a"-"ba","bb"-"co", ... chosen so query QPS is even across shards). Every request with>= 2characters routes directly to the single shard owning its prefix with zero scatter-gather fan-out, while 0- and 1-character prefixes are served from a tiny replicated top-1,000 head cache on every gateway.
Follow-up questions
- How can you incorporate typo-tolerant completions (such as matching "invesment" to "investment") while staying inside a 25 ms server budget?
- How quickly does a sudden surge query surface, and how do you stop coordinated bots from poisoning shared completions?
- How would the indexing topology evolve if the searchable catalog expanded 20x to 200 million items?
Similar questions
- Scalable REST and Streaming Randomness Platform
- Distributed Key-Value Store Using Consistent Hashing
- Stakeholder Alignment for Home-Screen Product Ranking
- Leading Through a Late-Stage Payment Roadmap Pivot
- Completed Trips from Sensor Events
- Showcasing Engineering Impact and Teaching a Technical Concept
More SoFi interview questions
- Showcasing Engineering Impact and Teaching a Technical Concept Medium
- Scalable REST and Streaming Randomness Platform Hard
- JVM Memory Reclamation, Singleton Trade-Offs, and SOLID Design Medium Pro
- Runner-Up Tag in Flat Triplet Records Medium Pro
- Permit-Bounded Concurrent Task Executor Medium Pro
- Reachable Vertices from a Source Node Easy Pro
- Stakeholder Alignment for Home-Screen Product Ranking Medium Pro
- Leading Through a Late-Stage Payment Roadmap Pivot Medium Pro
- Completed Trips from Sensor Events Easy Pro
- Dictionary with O(1) Latest-Entry Lookup Medium Pro