Skip to content

Design Search Autocomplete (Typeahead)

Intermediate 75 min read Part 17 of 18

Design search autocomplete: trie with top-k per prefix, log pipeline, precomputed results, browser and edge caching, prefix sharding, trends, personalisation.

The Problem#

You type "how to m" into a search box. Before you finish the word, a list drops down: "how to make pancakes", "how to meditate", "how to make money online". You press the down arrow and Enter, and you have saved half the typing. This is search autocomplete, also called typeahead or query suggestions.

It looks like a small feature, but at the scale of a large search engine or e-commerce site it is a hard system to build:

  • It must be very fast. Suggestions must appear while the user is still typing. People type a character every 100–300 ms, so a suggestion that arrives after 500 ms is for a prefix the user has already left behind. The whole round trip, including the network, should take well under 100–150 ms, which leaves the server only a few milliseconds.
  • It is read-heavy at an extreme. One search can produce 5–10 suggestion requests, one per keystroke or pause. So the autocomplete service gets several times more requests than the search service itself.
  • It must reflect what people search for, and change with it. Rankings come from billions of past queries. When news breaks, a query nobody typed yesterday must appear within minutes.
  • It must be safe. The system is "putting words in the user's mouth". Offensive, defamatory or private suggestions are a real harm and a legal risk.

A real-world analogy. Imagine a librarian at a help desk who has heard every question asked in the library for years. As soon as you say "How do I…", the librarian already has a short card ready for the most common ways that sentence ends, written in advance, sorted by how often people asked. The librarian does not search the archive while you talk. They just pick up the right card. Every night an assistant rewrites the cards from the day's questions. A second assistant at the door listens for sudden new questions ("is the river flooding?") and pins a note on the top of the right card within minutes. That is the whole design: precomputed answers per prefix, rebuilt offline from logs, with a fast path for trends.

This case study designs such a system. It uses ideas from Caching Fundamentals, Batch vs Stream Processing, Partitioning and Sharding and Content Delivery Networks (CDN).

Clarifying Questions#

QuestionWhy it mattersAssumed answer
What are we completing: search queries, product names, people, places?Query completion learns from logs; entity completion (contacts, products) indexes a catalogueSearch queries, like a web search box, with notes on entities
How many suggestions, and how fast?Drives the latency budget and the size of precomputed listsTop 5–10, visible within about 100 ms of a keystroke
What is the scale?Sizing of caches, shards and the pipeline1B searches a day, global users
How are suggestions ranked?Popularity only, or freshness, location and personal history tooPopularity with time decay, plus trending and light personalisation
How fresh must suggestions be?Daily batch is simple; minutes needs streamingBase rankings daily or hourly, trending queries within about 10 minutes
Do we match only prefixes, or words in the middle and typos?Middle-of-string and fuzzy matching need different indexesPrefix of the whole query first; word-prefix and typo tolerance as extensions
Which languages and scripts?Normalisation, tokenisation, input methods for Chinese, Japanese and KoreanMany languages, one index per language or market
Is the list personalised?Personalised responses cannot be shared through CDN cachesGlobal suggestions plus the user's own recent searches
Must we filter content?Policy filtering is a must for a public productYes: offensive, sexual, violent, hateful and private suggestions removed, with fast takedown
Are there regional differences?"football" means different things in different countriesSuggestions depend on country and language
Mobile and web?Clients can debounce, cache and prefetchBoth; we control the client code

Requirements#

Functional#

  1. As the user types, return up to 10 suggested completions for the current prefix, ranked by relevance.
  2. Rank by how often a query is searched, weighted towards recent searches, in the user's language and region.
  3. Show newly trending queries within minutes of the trend starting.
  4. Show the user's own recent matching searches first, with a way to delete them.
  5. Never show suggestions that violate content policy, and support removing a suggestion everywhere within minutes.
  6. Accept common variations: case, accents and extra spaces. Handling simple typos is a stretch goal.

Non-Functional#

  1. Latency: server-side p99 under 20 ms, end-to-end p95 under 100 ms for most users. Suggestions that come late are worse than useless.
  2. Throughput: about 100k requests per second on average and 300k+ at peak, before caching.
  3. Availability: 99.99%. If autocomplete fails, search still works, so it must fail quietly (show nothing) rather than slow down the search box.
  4. Freshness: base index rebuilt at least daily. Trending queries visible within about 10 minutes.
  5. Scalability: grow with traffic by adding replicas, and with vocabulary by adding shards.
  6. Consistency: eventual is fine. Two users seeing slightly different suggestions for a few minutes is harmless.
  7. Privacy: a query only becomes a suggestion if many distinct users searched for it, so a private search ("my neighbour's name plus address") never leaks to others.
  8. Cost: serve from memory on a modest fleet; heavy computation happens offline.

Capacity Estimation#

Requests.

  • Assume 1B searches a day. An average query is about 20 characters, or 3–4 words.
  • Sending a request on every keystroke would mean 20 requests per search. Clients debounce: they wait for a short pause, for example 50–100 ms, before sending. They also skip prefixes they already have answers for. Together that brings it to about 6 requests per search.
  • 1B × 6 = 6B requests a day ≈ 70k requests/s on average. Traffic follows the daytime of the biggest markets, so peak is about 3 times the average, ≈ 210k/s. Plan for 300k/s.
  • Short prefixes are extremely repetitive. With only 26 letters, there are 26 one-letter, 676 two-letter and 17,576 three-letter lowercase Latin prefixes. They are very hot and almost the same for everyone in a market. Browser and CDN caches can absorb a large share, plausibly 30–60%, so origin servers see perhaps 100–200k/s at peak.

Response size and bandwidth. Ten suggestions of about 30 bytes each, plus JSON overhead, come to about 500 bytes, or about 200–250 bytes compressed. At 300k/s × 500 B = 150 MB/s ≈ 1.2 Gbit/s, spread across regions. Bandwidth is not the problem. Latency is.

Compute.

  • A lookup in an in-memory structure takes 10–100 µs. Most of the server cost is HTTP handling, decompression, serialisation and logging, so a realistic figure is 5–20k requests/s per core.
  • 200k/s at 10k/s per core is 20 cores of pure work. With headroom, several regions and N+2 redundancy, that is a few dozen servers globally. This is a small fleet for a huge request rate, because all the expensive work happens offline.

Vocabulary and index size.

  • Many queries are seen only once. Google has said that roughly 15% of the queries it sees each day are new. One-off queries cannot become suggestions anyway: they are too rare and may be private.
  • Keep queries searched by at least K distinct users over a window, for example K = 20 over 30 days. Assume 200M qualifying queries per large market set.
  • Query strings: 200M × ~25 B ≈ 5 GB.
  • Trie nodes: an upper bound is 200M × 20 characters = 4B, but shared prefixes collapse this a lot. A compressed (radix) trie might have a few hundred million nodes.
  • Storing a precomputed top-10 list at every node, as 10 × 4-byte query ids = 40 B, plus about 30 B of node overhead, comes to about 20–70 GB per full copy. That fits in RAM on one large machine, but it is uncomfortable to rebuild and reload. Hence pruning (Deep Dive 1) and sharding (Deep Dive 5).

Logs.

  • Search logs: 1B searches × ~100 B (normalised query, time, language, country, pseudonymous user id, result click) ≈ 100 GB/day raw, about 20–30 GB compressed. Keeping 90 days for aggregation is about 2–3 TB.
  • Suggestion impression and click logs, which say "which suggestions were shown and which was chosen": 6B × ~60 B ≈ 360 GB/day. Sample them, for example at 5%, for ranking work.

Pipeline.

  • A daily batch job reads about 100 GB of compressed logs and computes counts and decayed scores. A Spark job on a modest cluster finishes this in well under an hour.
  • The streaming trend detector reads about 12k searches/s on average and about 40k/s at peak. That is easily handled by a small Flink or Kafka Streams job.

Core Entities#

  • Query: a normalised query string with its language and market. This is the unit we suggest.
  • QueryStats: per query and market, the counts per day or hour, distinct-user counts, click-through rate and the computed score.
  • Prefix suggestion list: for a prefix, market and language, the precomputed top-k queries with their scores. This is the serving data.
  • Index snapshot: an immutable, versioned build of all prefix lists for a market, split into shards and stored as files.
  • Trending entry: a query whose recent rate is far above its baseline, with a short-lived boost score.
  • User history entry: a query the user searched, with the time. It is stored on the device, and server-side for signed-in users who allow it.
  • Policy rule: a blocked term, pattern or exact suggestion, with a reason, scope and creation time.

API Design#

GET /v1/suggest?q=how%20to%20m&lang=en&market=US&limit=8
  Response 200, Cache-Control: public, max-age=900
  {
    "prefix": "how to m",
    "suggestions": [
      { "text": "how to make pancakes", "kind": "query" },
      { "text": "how to meditate",      "kind": "query" },
      { "text": "how to make money online", "kind": "query" }
    ],
    "index_version": "us-en-2026-12-03T02",
    "trending_version": 4417
  }
 
GET /v1/suggest/personal?q=how%20to%20m          (signed in)
  Authorization: Bearer ...
  Response 200, Cache-Control: private, no-store
  { "history": [ { "text": "how to mount a tv", "id": "h_91" } ] }
 
DELETE /v1/history/h_91                          (remove one past search)
 
-- internal, not public --
search events -> Kafka topic search-log:
  { "q_norm": "how to mount a tv", "lang": "en", "market": "US",
    "uid_hash": "...", "ts": 1764729600, "clicked": true,
    "via_suggestion": true, "suggestion_rank": 2 }
 
POST /internal/policy/removals   { "pattern": "...", "scope": "global" }

Notes on the API:

  • The global endpoint is cacheable by anyone, browsers and CDNs, because the response depends only on (q, lang, market, limit). That is why the personal part is a separate request that is private and never cached in shared caches. Merging happens on the client.
  • Normalise the cache key. The client lower-cases, trims and collapses spaces before building the URL, so "How to M", "how to m" and "how to m" hit the same cache entry. The server normalises again and does not trust the client.
  • index_version lets clients and support tools see which build served a response. A change of version is also a natural point to change cache keys if a bad build must be flushed.
  • Suggestion clicks are not a separate API. The search request records that it came from suggestion number 2, which feeds ranking (Deep Dive 2).

High-Level Design#

We build the design one requirement at a time. There are two paths with very different shapes:

  • The serving path handles hundreds of thousands of tiny reads per second, and must answer in milliseconds from memory.
  • The data path handles a large but slow flow of logs, which is turned into rankings in batch jobs and a streaming job.

The key idea is to move all the work from the serving path to the data path. At request time we look up an answer that was computed in advance. We never compute it then.

1) Return suggestions for a prefix, fast#

Naive approach. Keep a table of (query, count) and run SELECT query FROM queries WHERE query LIKE 'how to m%' ORDER BY count DESC LIMIT 10.

  • A B-tree index on query can find the range of strings starting with "how to m" efficiently, because a prefix is a range in sorted order.
  • But it must then read every match to sort by count. For the prefix "h", that is tens of millions of rows per keystroke. At 100k requests per second, no database survives this.

A trie. A trie, or prefix tree, is a tree where each edge is a character, and the path from the root to a node spells a prefix. All queries that start with "how to m" live in the subtree under the node for that prefix. Finding the node takes as many steps as there are characters in the prefix, independent of the number of queries. But finding the top 10 in a big subtree would still mean walking the whole subtree.

A trie with top-k per node. The fix is to precompute the answer at every node. Each node stores the k best completions in its subtree, say k = 10, sorted by score. A request then:

  1. walks down the trie for the prefix, about 10–20 steps in memory, and
  2. returns the list stored at that node.

There is no searching and no sorting. The lookup takes microseconds, whatever the vocabulary size. The cost moves to build time and memory, which are cheap and offline. Deep Dive 1 covers building it and keeping it small.

An even simpler equivalent: a prefix → top-k key-value table. For every prefix up to some length, store the list directly, for example in a sorted string table, RocksDB or a hash map. It is the same idea, flattened: one hash lookup instead of a walk. It uses more memory, because each prefix repeats its own key, but it is easy to shard by prefix and to serve from a generic key-value store.

2) Learn what people search for: the data collection pipeline#

Suggestions come from what users actually searched. The pipeline is:

  1. Log. The search service writes one event per submitted search to Kafka: normalised query, language, market, a pseudonymous user id, a timestamp, and whether a suggestion was used.
  2. Land. A sink writes the events to object storage as hourly, compressed columnar files, for example Parquet. This is the durable raw log.
  3. Aggregate. A batch job (Spark, or any MapReduce-style engine) reads the last N days and computes, per (market, lang, query): counts per day, the distinct-user count, and a time-decayed score. It filters spam, bots and queries below the privacy threshold.
  4. Filter. Policy rules remove disallowed queries.

The output is a table of perhaps 200M (query, score) rows per market group. This is the input to the index builder.

3) Turn rankings into precomputed suggestions and ship them#

The index builder reads the scored queries and builds the trie or prefix table for each market and language, with top-k lists at every node. It writes the result as immutable snapshot files, one set per shard, to object storage with a version number such as us-en-2026-12-03T02.

Serving nodes poll for new versions, download the files, load them into memory alongside the current version, run sanity checks, and then atomically switch a pointer to the new version. Rolling back means switching the pointer back. Serving never writes, so there are no locks, no replication protocol and no consistency problem: every node serves a read-only copy. This is a very robust way to serve read-mostly data.

A daily build is too slow for breaking news. A streaming job (Flink or Kafka Streams) also reads the search log and keeps counts per query in short sliding windows, for example 5 and 60 minutes. It flags queries whose recent rate is far above their normal rate. These go into a small trending index, perhaps tens of thousands of entries, which is published every minute or so.

At request time, the suggest service merges the trending entries that match the prefix into the base list using a boost score. This is the classic batch plus speed layer split: the batch layer is complete and correct, the speed layer is fast and approximate (see Batch vs Stream Processing).

5) Personalise without breaking caching#

The user's own past searches are the strongest signal for what they will type next. Keep them on the device (local storage, up to a few hundred entries) and, for signed-in users who allow it, in a history service keyed by user id.

The client shows matching history entries first, marked so the user can tell them apart, then the global suggestions. Because the global list is identical for everyone in a market, it stays cacheable. The personal part is small, private and fetched separately, or not fetched at all when the device has it locally.

6) Make it fast for the user: caching at every layer#

Most autocomplete requests never need to reach our servers:

  • The browser or app caches responses by prefix, so backspacing and retyping are free. The client also filters a longer prefix locally from the list it already has, when that list is complete enough.
  • The CDN caches global responses at the edge with a TTL of minutes. Hot short prefixes are served 20–40 ms from the user instead of 150–300 ms across an ocean.
  • The service keeps an in-process cache of the hottest prefixes, and the data itself is in memory.

See Content Delivery Networks (CDN) and Deep Dive 6.

The full high-level design#

The serving path, from keystroke to answer:

The data path, from searches to new indexes:

Components:

  • Client: normalises input, debounces, cancels stale requests, caches answers by prefix, and merges local history with global suggestions.
  • CDN: caches global responses at the edge for minutes. It absorbs most traffic for short, hot prefixes.
  • Suggest API: a stateless front tier. It normalises the prefix, picks the shard, merges trending results, applies policy, and returns the list.
  • Suggest shards: in-memory, read-only copies of the index for a range of prefixes, replicated several times per region.
  • Trending index: a small, fast-changing list of bursting queries, broadcast to all shards or API nodes.
  • Policy filter: a last check against blocked suggestions, updated within seconds, independent of index builds.
  • History service: private, per-user recent searches. It is never cached in shared caches.
  • Kafka and the log sink: collect search events durably. They are the source of truth for everything the system learns.
  • Batch aggregation: turns raw logs into scored queries, with privacy and spam filters.
  • Index builder: turns scored queries into sharded, immutable snapshot files.
  • Stream job: detects trends in minutes and publishes the trending index.

Key Flows#

A user types "how to m"#

  1. The client waits for a short pause (80 ms) so a fast typist does not send a request for every character.
  2. It normalises the prefix, so equivalent inputs share one cache key.
  3. Local cache and history are checked first. A history match is shown at once, before the network answers.
  4. The CDN edge misses for this key, so it forwards to the nearest region. The next user in that area typing the same prefix gets a hit.
  5. The API sends the prefix to the shard that owns it. The shard walks its trie and returns the stored top-k list in microseconds.
  6. The API merges matching trending entries, applies the policy filter, and trims the list.
  7. The response is cacheable for 15 minutes, and the edge stores it. The client renders history first, then global suggestions without duplicates.

If the user types another character while this request is in flight, the client either cancels it or ignores its response when it arrives. Only the response for the latest prefix is shown (Deep Dive 9).

A nightly index build and rollout#

  1. The orchestrator (Airflow or a similar scheduler) starts aggregation for each market once the day's logs are complete.
  2. Aggregation computes the scores and applies the privacy threshold and bot filters.
  3. The builder creates the trie and per-node top-k lists, splits them by prefix range, and writes files plus a manifest listing files, checksums, shard ranges and statistics.
  4. Quality checks run before publishing. For example, the number of queries must be within 10% of yesterday's, a fixed list of "golden" prefixes must return sensible results, and no blocked term may appear.
  5. Shard nodes pick up the new manifest. A canary set of nodes goes first. Each node loads the new version next to the old one, runs smoke queries and switches atomically.
  6. Monitoring compares error rate, latency and suggestion click-through on the canary before the rest of the fleet switches. A bad build is rolled back by switching the pointer back, which takes seconds.

Data Model#

The serving index and its policy inputs:

The statistics that feed the index, and the per-user data. PREFIX_TOPK lists are built from QUERY_STATS scores at build time:

Where each entity lives. Use Choosing a Database: A Decision Guide as the frame. There is no single database here, because each dataset has a different access pattern:

  • Raw search logs: Kafka for transport, and object storage (S3, GCS) with Parquet files for durable history. They are append-only, read in bulk by batch jobs, and cheap per terabyte.
  • QUERY_STATS: a table produced by the batch job. Store it as Parquet in the data lake, or in a warehouse such as BigQuery or Hive tables. It is read and rewritten in bulk, never per request.
  • PREFIX_TOPK and INDEX_VERSION: the serving index. It is written as immutable files (a custom trie format, an FST, or RocksDB SST files) and loaded into memory on serving nodes. The manifest, with its version history and status (building, published, active, rolled_back), sits in a small strongly consistent store such as PostgreSQL or etcd, because rollouts depend on it.
  • TRENDING_ENTRY: produced by the stream job, published as a small file or a compacted Kafka topic, and held in memory on API nodes. It is tiny: tens of thousands of entries.
  • USER_HISTORY: a wide-column store such as Cassandra or DynamoDB, with partition key user_id and clustering by searched_at DESC. "Latest 50 for this user" is a single-partition read. A TTL, for example 90 days or the user's chosen setting, bounds it.
  • POLICY_RULE: PostgreSQL as the source of truth, with an audit trail, pushed to every serving node as an in-memory set plus a Bloom filter for fast negative checks.

Keys and indexes.

  • Queries are identified by (market, lang, query_norm). Inside an index build, each query gets a dense integer id, so top-k lists store 4-byte ids instead of strings.
  • The serving index is "keyed" by the prefix path itself.
  • History needs only the user partition key. A delete marks the row (deleted = true) and also removes it from the device.

Retention.

  • Raw logs with pseudonymous ids are kept for a limited window, for example 30–90 days, as privacy policy allows. After that, only aggregated counts above the privacy threshold remain.
  • Keep the last few index versions for fast rollback, and older ones for a few weeks for debugging.
  • Trending entries expire after hours.
  • History follows the user's settings and is deleted when the user deletes it or closes the account.

Deep Dives#

1) How does a trie with top-k per prefix work, and how do we keep it small?#

Basic: a plain trie, with the top-k found at query time. Walk to the prefix node, then traverse its whole subtree, collecting (query, score) pairs and keeping the best k in a min-heap. The cost is the size of the subtree. Near the root that is millions of nodes, and short prefixes are exactly the most common requests. This is too slow.

Better: store the top-k list in every node. At build time, compute each node's list bottom-up:

  1. A leaf, or a node that ends a query, contributes its own query and score.
  2. A node's list is the best k items among its own query, if it ends one, and the lists of its children.
  3. Merging c child lists of length k with a heap costs about O(c·k·log k). Summed over all nodes, the build is roughly linear in the trie size times k. That takes minutes for hundreds of millions of nodes on one large machine, or it can be parallelised by top-level subtree.

At query time: walk len(prefix) steps and return the list. The lookup no longer depends on how many queries share the prefix.

Each node above stores its own best completions. The request for "how to m" stops at that node and returns its list. It never visits the thousands of queries below it.

Memory problems and their fixes.

  • Pointer overhead. A naive node with a 256-entry child array wastes memory. Use sorted child arrays, or a hash map only for nodes with many children.
  • Long chains. "how to tie a tie" has long stretches where each node has only one child. A radix tree (compressed trie, also called a Patricia trie, from Morrison's 1968 paper on PATRICIA) merges each single-child chain into one edge labelled with a substring. This cuts node counts several-fold for natural-language queries.
  • Repeated top-k lists. In a single-child chain, every node has the same list. Store the list once at the top of the chain. Lists also store 4-byte query ids instead of strings, and scores can be dropped from storage if the list is sorted and the scores are not needed at serve time.
  • Deep nodes. Lists near the leaves rarely matter. Nobody needs precomputed suggestions for a 35-character prefix that matches only three queries. Prune: store lists only down to a depth limit, or only for nodes whose subtree has more than k queries. Below that, a short DFS over the small subtree is fast.
  • Flat succinct formats. For the largest indexes, pack the trie into arrays. A finite-state transducer (FST) shares both prefixes and suffixes, and can attach outputs such as weights to paths. Lucene uses FSTs for its term dictionary and for its completion suggester, which is what Elasticsearch's completion suggester runs on. Building an FST from sorted input needs only one pass, in linear time, using an algorithm described by Daciuk, Mihov, Watson and Watson in 2000.

Best: choose the representation by scale, and keep it simple to rebuild.

  • Up to a few million queries, for example a product catalogue: a prefix → top-k hash map or a sorted array with binary search, in the memory of every API node. There is no separate service.
  • Hundreds of millions of queries: a compressed trie or FST with pruned top-k lists, built offline and memory-mapped from a file. Memory-mapping lets a node load a new version quickly and lets the OS share pages between processes.
  • The prefix → top-k table in a key-value store (RocksDB, or Redis for small markets) is the most operationally boring choice. It is easy to shard by prefix, and every engineer can debug it.

Whatever the format, it is immutable and rebuilt rather than updated in place. In-place updates of top-k lists along a path are possible: when a query's score rises, walk up its path and update each ancestor's list. But they need locking or copy-on-write, and they make builds non-reproducible. Freshness comes from the trending layer instead (Deep Dive 7).

2) How are suggestions ranked?#

Basic: total count of all time. Rank by how many times each query was searched. Old queries dominate forever: "world cup 2014" stays above "world cup 2026" for years. Rare but rising queries never break in.

Better: time-decayed popularity, with quality signals.

  • Exponential decay. Each day's count is weighted by how old it is: score = Σ_days count_d × 2^(−age_d / H), where H is the half-life, for example 7 days. A search from 7 days ago counts half as much as one today, and one from 14 days ago counts a quarter. This can be updated incrementally: score_today = score_yesterday × 2^(−1/H) + count_today. The daily job does not need to re-read 90 days of logs. It only multiplies yesterday's scores and adds today's counts.
  • Distinct users, not raw counts. One bot or one obsessive user searching 10,000 times should not create a suggestion. Count distinct users per query, for example with HyperLogLog sketches per day (see Probabilistic Data Structures for Big Data). Then rank on a blend, or cap each user's contribution.
  • Suggestion click-through rate. If "how to make pancakes" is shown 1M times and chosen 300k times, it serves users well. A suggestion that is shown often but never chosen should drop. CTR is biased by position, because the first slot gets clicks just for being first, so compare each item's CTR with the typical CTR for its slot.
  • Result quality. A query that leads to a search with no results, or to quick abandonment, is a poor suggestion even if it is popular.

Best: learning to rank on top of candidate generation. Split the problem:

  1. Candidates: the precomputed top-k per prefix, with k larger than shown, for example 30–50.
  2. Re-ranking: a lightweight model scores each candidate with features: decayed popularity, trend boost, CTR by position, query length, language and region match, freshness, and, for personalisation, similarity to the user's recent searches. Gradient-boosted trees are a common choice, because they take a few microseconds per candidate.
  3. Diversity: avoid ten nearly identical suggestions ("how to make pancakes", "how to make pancakes easy", "how to make pancakes fluffy"). Penalise candidates that share a long prefix with one already chosen, so the list covers more of the user's possible intents.

The re-ranker runs on the API tier for the 30–50 candidates. That adds well under a millisecond and keeps the index itself simple. Train it on suggestion logs: the label is "was this suggestion selected". Correct for position bias with randomised experiments, or with an estimate of how likely each slot is to be examined. Evaluate offline with metrics such as mean reciprocal rank (the average of 1/rank of the chosen suggestion) and keystrokes saved, then confirm with A/B tests.

3) How is the data collection pipeline built, and how do we keep it clean and private?#

Basic: increment a counter in a database on every search. UPDATE queries SET count = count + 1 WHERE query = ? at about 12k searches per second on average, with very hot rows ("facebook", "weather"). It produces lock contention on hot rows, puts a write load on the same store the suggestions are read from, and leaves no raw history to recompute from when the scoring formula changes.

Better: log first, aggregate later.

  • Log events, not counters. Each search becomes an event in Kafka, partitioned by a hash of the normalised query, so all events for a query reach the same partition for stream processing. Events are small (about 100 B). At 40k/s at peak, that is 4 MB/s: a tiny Kafka cluster.

  • Keep the raw log in object storage as hourly Parquet files. Raw data is the most valuable asset in the pipeline. With it, a better scoring formula or a bug fix can be applied to the past 90 days by re-running the batch. Without it, mistakes are permanent.

  • Aggregate in batch. A daily (or hourly) Spark job:

    1. groups by (market, lang, query_norm);
    2. counts searches and distinct users, using HyperLogLog sketches or exact COUNT(DISTINCT) at this scale;
    3. updates decayed scores (Deep Dive 2);
    4. writes QUERY_STATS.

    This is a classic MapReduce shape. The map step emits (query, 1, user), and the reduce step sums and de-duplicates. Combiners make the shuffle small: most of the 1B events per day collapse into the 200M distinct queries before crossing the network.

  • Normalise once, consistently. The same normalisation function (Unicode NFKC normalisation, case folding, whitespace collapsing, optional accent folding by market) must run in the logging path, the batch job, the index builder and the request path. Otherwise a query is counted under one key and looked up under another. Package it as a shared library with versioned tests.

The batch job in numbers. The daily job reads about 25 GB of compressed Parquet (1B events), and the combiners reduce it to about 200–300M partial aggregates before the shuffle. Joining today's counts with yesterday's 200M decayed scores is a sort-merge join on (market, lang, query_norm). On a cluster of a few dozen cores, the whole job runs in 20–40 minutes. Most of the cost is the shuffle and the join, not the counting. Storing scores in files sorted by the join key turns the join into a cheap merge, and that file order is also the sorted order the index builder needs.

Best: add the filters that make the data trustworthy.

  • Bot and abuse filtering. Automated traffic can be a large share of raw queries. Drop events from known crawlers and from clients that fail bot checks. Down-weight users with absurd rates, and look for coordinated campaigns: many new accounts searching the same phrase to push it into suggestions, a known form of autocomplete manipulation. Requiring many distinct, established users per query defeats most cheap attacks.
  • Privacy threshold (k-anonymity style). A query becomes eligible only if at least K distinct users searched it in the window, for example K = 20–50. This prevents one person's unique search, such as an email address, a phone number, or a name plus a medical condition, from ever being suggested to someone else. Add pattern filters for things that look like PII (emails, phone numbers, card numbers, government ids) even above the threshold.
  • Sampling where precision is not needed. Impression logs for suggestions (6B a day) are sampled at 1–10% for CTR estimates. Search logs used for counts are not sampled, because rare queries would vanish.
  • Data retention and consent. Pseudonymous user ids are rotated or hashed with a secret salt, and raw events are deleted after the retention window. Users who opt out of history are excluded from personal history but can still be counted anonymously in aggregates, as the privacy policy allows.
  • Late and duplicate events. Mobile clients upload events late, and producers retry. Count by event time, not arrival time. Let daily partitions accept late data for a grace period, for example 48 hours, and rerun the last two days. Deduplicate retries by event id.

4) How do we build and roll out new indexes safely?#

Basic: rebuild in place. A cron job rewrites the live table while it serves. Readers see half-written data, and a bad build is live immediately with no way back.

Better: immutable, versioned snapshots with an atomic swap.

  • The builder writes a complete new version to new files, plus a manifest (version, market, shard ranges, file list, checksums, statistics). Nothing that is serving changes.
  • Each serving node loads the new version into memory beside the current one, which needs about 2 times the memory briefly, or memory-maps it. It verifies checksums and runs smoke queries, then flips one pointer. Requests in flight finish on the old version, and new requests use the new one.
  • Rollback is flipping the pointer back, or loading the previous manifest. Keep at least two previous versions on local disk.

Best: treat a build like a deployment, with gates, canaries and fast lanes for urgent changes.

  • Quality gates before publishing:

    • Size checks: number of queries and nodes within a few percent of the previous build.
    • Golden prefixes: a curated set with expected top results must still match.
    • Policy check: no blocked terms in any list.
    • A diff report: the biggest changes in top-10 lists for the top 10,000 prefixes, reviewed automatically against thresholds.

    A pipeline bug that drops half the logs shows up as a large size drop, so the build stops before users see it.

  • Canary: a few percent of nodes or traffic first, comparing suggestion CTR, empty-result rate, latency and errors with the previous version for 15–60 minutes. Then the rest of the fleet.

  • Delta builds for speed. A full build per market takes tens of minutes. For hourly freshness, the builder can rebuild only the subtrees whose top-k changed, or publish a small delta layer (prefix → replacement list) that serving merges over the base until the next full build. Most hourly changes touch a small fraction of prefixes.

  • Fast loading. A 16 GB index takes time to read and parse. If the file format can be used directly from memory (offsets instead of pointers), nodes can memory-map it. Loading becomes "map the file and touch the hot pages", which takes seconds, and the OS page cache shares the pages between processes on the same host. Pre-warm by replaying the top 100,000 prefixes before taking traffic, so the first users do not pay for page faults.

  • Distributing snapshots. Each region pulls the files from regional object storage, not from the builder, so a thousand nodes downloading 16 GB do not overload one origin. Large fleets use peer-to-peer distribution or staged copies: a few nodes per region download first and serve the rest.

  • Urgent removals bypass builds. Waiting for the next build to remove a harmful suggestion is too slow. The policy filter at serve time (Deep Dive 11) removes it within seconds, and the next build bakes the removal in.

5) How is the index sharded, and how do we deal with skewed prefixes?#

First ask whether to shard at all. A full copy at 20–70 GB fits in the memory of one large server, and the request rate is handled by replicas, not shards. Every replica can answer any prefix. Shard only when:

  • the index for a market no longer fits comfortably in memory with room for a second version during the swap;
  • build and load times for one huge file get too long; or
  • you want to scale memory and traffic separately for hot and cold parts of the key space.

The reference on sharding gives the right way to frame it: name the bottleneck, show why one machine cannot handle it, then choose the shard key and the distribution strategy.

Basic: shard by first character. Shard 1 has a, shard 2 has b, and so on. This is range-based sharding on the prefix. It is simple, and every request goes to exactly one shard, because the whole subtree of a prefix is on that shard. But natural language is very skewed: in English, many more queries start with "s", "c" or "p" than with "x", "q" or "z". So some shards hold far more data and get far more traffic than others. This is the hot spot problem.

Better: range sharding with split points chosen from the data.

  • Sort all prefixes and choose boundaries so that each shard has about the same load, weighted by traffic and memory, not the same number of letters. For example, shard 1 is a–ca, shard 2 is cb–fz, shard 7 is s–sh, and so on. Boundaries can fall inside a letter, at any prefix.
  • Store the boundaries in the index manifest. The API routes with a binary search over the boundaries. This is a small directory, but it is versioned with the index and cached on every API node, so it is not a separate service on the request path.
  • A prefix shorter than a boundary key, such as "s" when shards split at "sh", spans shards. The builder handles this by storing the top-k lists for all prefixes shorter than the split depth on every shard, or in a small "short prefix" table on the API tier. These lists are few (at most tens of thousands) and are the hottest keys anyway.

A worked example of choosing split points. The builder has, for every two-character prefix, two numbers from the last week: memory used by its subtree and requests per second that reached shards. Say the market's index is 48 GB and shard traffic is 60k requests per second, and the target is 6 shards of about 8 GB and 10k requests per second each. The builder walks the prefixes in sorted order, adding memory and traffic to the current shard. It closes the shard when either total would pass its target. A single two-character prefix that alone exceeds a target, for example "ho" in a market where "how to" queries dominate, is split further at three or more characters ("ho" to "how ", then "how t" onwards). Because the boundaries are recomputed at every build, the layout follows the data as language use shifts. Changing the layout costs nothing extra: the next version simply ships with new boundaries.

Why not hash sharding? Hashing the full prefix spreads load evenly, and is the usual default for sharding. Here it works only with the prefix → top-k table representation, where each prefix is an independent key: hash("how to m") mod N. It does not work with a trie, because the trie's value comes from keeping a subtree together. Hashing also costs locality: the lists for "how to m" and "how to ma" land on different shards, so a client prefetching the next prefixes talks to many shards. Both choices are valid. Range sharding suits a trie or FST. Hash sharding suits a flat key-value table, and consistent hashing then lets shards be added with little data movement (see Consistent Hashing).

Best: shard by market first, then by prefix range, with replicas sized to traffic.

  • Market and language are the first shard dimension. A user in Japan never needs the US English index, so each market's index is built and loaded on its own, often in the regions near its users. Small markets share nodes. Large markets get their own shard sets. This is also geo-sharding: the data a region needs lives in that region, which cuts latency, just as a ride-hailing system shards driver locations by city.
  • Replicas differ per shard. Shards that hold hot ranges get more replicas. Since every replica is read-only and identical, adding one is just "load the files and register with the load balancer".
  • Hot keys within a shard are handled by caching rather than more sharding. The top few thousand prefixes are in every API node's in-process cache and at the CDN, so they barely reach shards at all.
  • Rebalancing happens at build time. Each new build can choose new split points from the latest load statistics, and the manifest carries them. No data migrates between live nodes. New nodes simply load the new layout. This is a big advantage of immutable, rebuilt indexes over a mutable sharded database.

Cross-shard work is avoided by design. Every request goes to exactly one shard, because the shard key is the thing being looked up. The only scatter-gather case is fuzzy matching across the key space (Deep Dive 10), and that is limited to a small edit distance and run on a smaller index.

6) How do browser, CDN and server caches work together?#

Autocomplete traffic is close to the ideal case for caching. The responses are small, the same for everyone in a market, change slowly, and are heavily skewed toward a small set of keys. The reference guidance on caching applies directly: identify the bottleneck, decide what to cache and with what key, choose the pattern, set expiry and eviction, then handle the downsides.

Basic: cache only in the service, with cache-aside in Redis in front of the index. The index is already in memory, so a remote Redis call (0.5–1 ms) is often slower than the lookup it replaces (microseconds). A remote cache helps only when computing the answer is expensive, for example with heavy re-ranking. It does nothing for network distance.

Better: cache close to the user.

  • Client cache. The app keeps a map from prefix to response for the session, and possibly in local storage with a TTL. Backspacing from "how to ma" to "how to m" costs nothing. If the cached list for "how to m" contains fewer than k items, it is complete for its subtree: every query starting with "how to ma" that exists is already in it. The client can then filter longer prefixes locally with no request. Responses can include a complete: true flag for exactly this.
  • HTTP caching. Responses carry Cache-Control: public, max-age=900 (15 minutes) and a Vary on anything that changes the result, such as language. Many teams prefer putting the language and market in the URL, because Vary headers fragment caches unpredictably.
  • CDN edge caching. Requests for global suggestions are GETs with normalised query strings, so CDNs such as CloudFront, Fastly, Akamai or Cloudflare can cache them like static files. The edge is the read-through cache: on a miss it fetches from origin, stores and returns. Hit rates are high for short prefixes, which are both the most common and the slowest to compute without precomputation. A user in Mumbai whose origin is in Virginia saves about 200–250 ms per request on a hit.

Best: layer the caches, version the keys, and protect the origin.

  1. Device (0 ms) → edge (20–40 ms) → regional API with in-process cache (a few ms within the region) → shard memory (microseconds).
  2. Freshness by layer. Keep TTLs at the edge short enough for trends to appear quickly, 5–15 minutes. For the very hottest prefixes, a stale value can be served while the edge revalidates in the background (stale-while-revalidate). Trending boosts make TTL a trade-off: a 15-minute edge TTL means a new trend can take up to 15 minutes to show on short prefixes. Lowering the TTL for prefixes that just gained a trending entry, or purging those keys at the CDN, closes the gap.
  3. Stampede protection. When a hot key expires at the edge, many requests arrive at origin at once. Request coalescing at the CDN (collapsed forwarding) and in the API (single flight: one rebuild while others wait) prevent this, and jittered TTLs prevent many keys expiring together.
  4. Invalidation through versions. When a new index version is activated, caches do not need to be purged. Old entries simply expire within the TTL. For an urgent removal, purge affected prefixes at the CDN by key, or by surrogate key or cache tag, which most CDNs support. Then rely on the serve-time policy filter for anything still in flight.
  5. Never cache personal data in shared caches. The personal endpoint is private, no-store, so no CDN or proxy keeps it. This separation is what makes the global part cacheable at all.

When a celebrity announces something at 14:00, by 14:05 millions of people are typing the first letters of their name. A daily index will not show that query until tomorrow, and an hourly index only after an hour. Users notice: "autocomplete doesn't know what's happening".

Basic: rebuild the whole index more often. Hourly full builds cost a lot of compute and still lag by over an hour, once build, rollout and CDN TTLs are added.

Better: a streaming speed layer with burst detection.

  • A stream processor (Flink, Kafka Streams or Spark Structured Streaming) consumes the search log. It keeps counts per (market, query) in tumbling 1-minute buckets and sums them over sliding windows such as the last 5, 15 and 60 minutes.
  • Burst score: compare the recent rate with the query's normal rate. For example, take the 15-minute count divided by the expected 15-minute count from the base index (the decayed daily score scaled to 15 minutes), smoothed to avoid dividing by tiny numbers: burst = (recent + α) / (expected + α). A query with burst above, say, 10 and at least N distinct users in the window is trending. Using a ratio matters: "weather" always has a large count, but it is not trending.
  • Memory: tracking every query in the stream is costly, so the job keeps exact counts only for candidates. A Count-Min sketch estimates counts for all queries in fixed memory, and a heavy-hitters structure such as Space-Saving (Metwally, Agrawal and El Abbadi, 2005) keeps the top items. Queries the sketch reports as rising get exact counters (see Probabilistic Data Structures for Big Data).
  • Publishing: every 30–60 s, the job writes the current trending set (query, boost, expiry) per market to a compacted Kafka topic or a small file. API nodes hold it in memory: tens of thousands of entries, so megabytes.

A worked example. Suppose "aurora borealis tonight" normally gets about 30 searches per 15 minutes in the US market, according to its decayed base score. A solar storm is announced, and in the last 15 minutes it got 4,800 searches from 4,100 distinct users. With α = 50, the burst score is (4,800 + 50) / (30 + 50) ≈ 61. That is far above the threshold of 10, and the distinct-user count passes the minimum of 500, so it is trending.

Compare "weather": it gets 900,000 searches in the same window against an expected 850,000. Its burst score is about 1.06, so it is not trending, despite its huge count.

Now a brand-new phrase with 120 searches against an expected 0 has a burst score of (120 + 50) / 50 = 3.4. That is below the threshold, so it waits until more people search it. The α term is what stops tiny counts from producing huge ratios. It is a simple form of smoothing, and its value is tuned per market by checking which detections the editorial or safety team considers real.

Merging at serve time. For a prefix p, the API finds trending entries that start with p. A small sorted array of trending queries allows a binary search for the range. Each match is scored with base_score + boost × weight and merged into the top-k list from the shard. A trending query can appear even if it is not in the base index at all: brand-new names often are not.

Best: trust, but verify, and let trends decay.

  • Safety first. New trending queries are the most likely to contain harmful or manipulated content: rumours, names of private people in breaking news, coordinated pushes. Apply the policy filter strictly. Require more distinct users and spread across regions. For sensitive categories (people's names combined with crimes or health), hold the entry for review, or just suppress it.
  • Decay. The boost expires: for example, it halves every 30 minutes once the burst ends, and is gone after a few hours. By then the hourly or daily build has picked up real popularity, and the base index carries the query on its own merits.
  • Freshness end to end. Stream lag (seconds), publish interval (up to 60 s) and edge TTL (5–15 minutes for short prefixes) add up. To show trends within a few minutes, shorten edge TTLs for prefixes with trending matches, or skip edge caching for them while the trend lasts.
  • Lambda versus kappa. This design is a Lambda architecture: batch for completeness, streaming for speed, merged at read time. A kappa design runs everything as one stream job with long windows and reprocesses by replaying Kafka. It is simpler in theory, but the index build is naturally a batch step, so most teams keep the split (see Apache Flink and Stream Processing).

8) How do we personalise without losing cacheability or privacy?#

Basic: no personalisation. Everyone in a market sees the same list. It is cacheable and simple, but the most useful single signal, "you searched this before", is ignored.

Better: recent history on the client, merged with global suggestions.

  • The app or browser stores the user's last few hundred searches locally. When the user types, matching history entries show first, often with a clock icon and an "x" to remove them. This needs no server call at all, and it responds at once, before the network.
  • For signed-in users across devices, a history service stores recent searches by user_id (a wide-column store with a TTL). The client fetches the user's recent history once per session, or fetches matches per prefix from the private endpoint, and merges it locally.
  • The global response stays identical for everyone in a market, so CDN caching still works. Personalisation is a merge on the client, not a different global response.

Best: light server-side re-ranking with user features, kept off the shared cache path.

  • Context signals that apply to many users can be part of the cache key, because they have few values: language, country, and perhaps city for local queries ("weather", "pizza near"). The index can be built per market and per large city, a form of geo-sharding of the index.
  • Per-user signals cannot go into a shared cache key. For example, the user's topics of interest from past searches, such as "programming" for someone who searches "python" for code, not snakes. To use them, the API fetches more candidates from the global list (30–50) and re-ranks with a user feature vector cached per session. The response is marked private. This costs cacheability, so it is used only where it measurably helps. Many systems personalise only the order of the top few, or only for signed-in users with rich history.
  • Session context. The previous query in the session is a strong signal: after "flights to paris", the prefix "h" probably means "hotels in paris". Models trained on query sequences in logs can re-rank candidates conditioned on the previous query, again on the private path.
  • Privacy controls:
    • Users can see and delete their history and turn it off.
    • Deleting an entry removes it from the device, the history service and future personal re-ranking within seconds.
    • Personal history never flows into another user's suggestions. Only aggregated queries above the privacy threshold do.
    • Personal suggestions are visually marked, so a person sharing a screen understands why something appears.
  • How the merge works. The client receives up to 3 history matches and 10 global suggestions. It shows the history matches first, in recency order. It then removes from the global list any item equal to a history item, after normalisation, and fills the remaining slots with global items in order. This is deliberately simple and deterministic, so results do not jump between keystrokes. When server-side re-ranking is on, the API does the same merge, but interleaves with scores: final = global_score × (1 + β × personal_affinity), where β is tuned by experiment and capped, so personal signals can reorder the list but not flood it with unrelated items.
  • Shared devices are a real issue: a family computer shows one person's searches to another. Prefer signed-in history over device history where possible, and give an easy way to clear it.

9) What does the client do to make it feel instant?#

The client is half of the latency budget and most of the request volume. Done well, it can cut server traffic by half and make the box feel instant even on slow mobile networks.

Basic: send a request on every keystroke and render whatever comes back. This causes three problems:

  • It sends far more requests than needed, because fast typists produce 5–10 characters per second.
  • Responses arrive out of order. The request for "how" is slower than the one for "how t", so the old list for "how" overwrites the newer one, and the user sees suggestions that do not match what they typed.
  • On slow networks, requests pile up.

Better: debounce, cancel and check sequence.

  • Debounce: send only after the user pauses for 50–150 ms. Some clients also send immediately for the first character, then debounce. Tune the delay with experiments: too long feels laggy, too short wastes requests.
  • Cancel stale requests: abort the in-flight request when a new prefix is typed (an AbortController in browsers). Also tag each request with a sequence number and ignore any response whose sequence is not the latest, because cancellation is not guaranteed to win the race.
  • Cache by prefix in memory, and filter locally when a cached list is complete for its subtree (Deep Dive 6).
  • Minimum prefix length: some products start at 1 character, some at 2–3. Single-character lists are almost fully cached at the edge, so they are cheap. The decision is about usefulness, not load.

Best: prefetch, reuse connections and degrade gracefully.

  • Warm the connection. Open the TCP and TLS connection, HTTP/2 or HTTP/3, when the search box gets focus, not on the first keystroke. A new TLS connection over a mobile network costs 1–3 round trips, which can be 200–600 ms. Reusing one connection for all keystrokes removes that (see HTTP, HTTP/2, HTTP/3 and HTTPS).
  • Prefetch. On focus, prefetch suggestions for the empty prefix (popular or recent queries) and possibly for the user's likely first letters. Some clients prefetch the next likely prefix as well, though this trades bandwidth for latency.
  • Rendering: keep the dropdown stable. Do not reorder items under the user's cursor when a new response arrives. Highlight the part of each suggestion that completes the typed text. Support keyboard navigation, and announce changes for screen readers.
  • Fail quietly: if suggestions take longer than about 300–500 ms or fail, show nothing, or the last good list filtered locally. Never block typing or the search itself.
  • Measure what users see. Log client-side time from keystroke to render, and how often responses were discarded as stale. Server latency alone hides network and rendering time.

The latency budget for a user 50 ms from the nearest region, with a warm connection: debounce 80 ms (deliberate), network round trip 50 ms, edge or API processing 2–5 ms, render 5–10 ms. That is about 140 ms from the last keystroke, or 60 ms after the debounce. On an edge cache hit, the round trip falls to about 20 ms.

10) How do we handle case, accents, typos and different languages?#

Basic: lower-case and trim. "Café", "cafe" and "CAFE " now match each other only partly. Users who make a typo ("restuarant") get no suggestions. Languages without spaces or with input methods behave badly.

Better: a careful normalisation pipeline, applied the same way at build and query time.

  1. Unicode normalisation (NFKC) so that characters that look the same and have the same meaning, such as composed "é" and "e" plus a combining accent, become the same code points.
  2. Case folding, which is more than lower-casing for some languages. German "ß" and Turkish dotted and dotless "i" need locale-aware rules.
  3. Accent folding where the market expects it. Many users of French or Spanish type without accents, so "cafe" should match "café". But in some languages accents change meaning, so this is decided per language.
  4. Whitespace and punctuation: collapse spaces, drop most punctuation, and keep meaningful characters such as "c++" or "c#".

The index stores the normalised form as the trie key and the display form (the most common original spelling) as the value, so users see "Café de Flore", not "cafe de flore".

Typos. Fuzzy prefix matching finds suggestions whose prefix is within edit distance 1–2 of what was typed. The reference on search-optimised databases describes fuzzy search as tolerance for small misspellings, computed with edit distance: the number of characters to insert, delete or replace to turn one string into another. In a trie, this becomes a bounded search: walk the trie while tracking the edit distance of the path so far, and prune branches whose distance already exceeds the limit. A Levenshtein automaton (Schulz and Mihov, 2002) does this efficiently by intersecting an automaton of all strings within distance d with the trie or FST. Lucene's fuzzy queries use this approach.

Fuzzy lookups are far more expensive than exact ones, because one prefix explores many branches. So:

  • run fuzzy only when the exact prefix has few or no results;
  • limit the edit distance to 1 for short prefixes and 2 for longer ones;
  • require the first one or two characters to match exactly, since people rarely mistype the first letter; and
  • rank exact matches above fuzzy ones.

A cheaper alternative is a spelling-correction table built offline from logs: pairs like "restuarant" → "restaurant", learned from users who typed one and immediately searched the other.

Best: per-language handling, word-level matching and scripts.

  • Matching on any word, not only the start. Users type "pancakes how" or expect "iphone" to suggest "apple iphone 16". Index each suggestion also under the start of each word, or of significant words. This multiplies index entries by the number of words, so do it only for entity-style suggestions (products, places, people), and rank start-of-query matches higher.
  • Languages without spaces (Chinese, Japanese, Thai) need word segmentation for word-level matching. Prefix matching on characters still works for whole-query completion.
  • Input methods. Chinese users type pinyin ("beijing") that the keyboard converts to characters. Japanese users type kana that converts to kanji. Index suggestions also under their romanised or phonetic forms, so partial pinyin "bei" can suggest "北京". Korean Hangul syllables are composed of jamo, so a half-typed syllable should match at the jamo level.
  • Transliteration and mixed scripts. In India, many users type Hindi in Latin letters ("kaise kare"). The index can include both scripts for the same suggestion.
  • Right-to-left scripts (Arabic, Hebrew) mostly affect rendering, but normalisation must handle the extra marks those scripts use.

All of this is why each market or language gets its own index built with its own normalisation rules, rather than one global trie.

11) How do we keep suggestions safe, and remove a bad one within minutes?#

Suggestions are not search results. The user did not ask for them. The product volunteered them, so the bar is higher. Suggesting a defamatory phrase about a real person, a slur, or self-harm instructions causes real harm, and courts in several countries have heard cases about autocomplete suggestions. Large search engines publish autocomplete policies. Google's, for example, describes removing predictions that are violent, sexually explicit, hateful, or dangerous, among other categories.

Basic: a static blocklist of words, applied at build time. It misses new terms, matches innocent words that contain a blocked substring (the "Scunthorpe problem": a town name that contains an offensive substring), and a removal waits until the next build.

Better: layered filtering at build time and serve time.

  • At build time, classify every candidate query:

    • Exact and pattern blocklists per language.
    • A machine-learned classifier for hate, sexual content, violence and harassment, run on the 200M queries offline, where seconds of compute per batch are fine.
    • PII detectors.
    • Rules for sensitive combinations, such as a person's name plus a crime, health condition or sexual orientation.

    Remove or down-rank anything flagged. Combine these with the privacy threshold (Deep Dive 3).

  • At serve time, apply a small, fast policy filter to every response. It checks suggestions against a set of removed queries and patterns that can change at any moment. In memory, a Bloom filter answers "definitely not blocked" for almost all suggestions in nanoseconds, and an exact set confirms the rare "maybe" answers. This filter is updated within seconds through a push channel, independent of index builds.

  • Context rules. Do not complete some prefixes at all, such as prefixes that strongly suggest self-harm, and show help resources instead where policy says so. Treat names of private individuals more strictly than public figures.

Best: an operations process with fast takedown, audit and abuse resistance.

  1. Takedown path: a policy team, legal team or automated detector files a removal → it is written to the policy store with a reason and audit trail → it is pushed to all API nodes within seconds → the CDN is purged by surrogate key for affected prefixes → the next index build bakes it in. The target is "gone everywhere in under 5 minutes".
  2. Precision matters too. Over-blocking hides legitimate queries, such as health questions or news. Review false-positive reports, and measure the share of suggestions removed per language.
  3. Manipulation resistance. Coordinated campaigns that try to create suggestions ("brand X scam") are countered by distinct-user thresholds, account-age weighting, anomaly detection on sudden phrase growth from new accounts or one network, and extra checks for trending entries (Deep Dive 7).
  4. Explainability. For any suggestion, internal tools show where it came from: index version, score, trend boost and filters passed. Investigating a complaint should take minutes, not a log search.

12) How do we keep it available and fast in every region, even when parts fail?#

Basic: one region, one cluster. Users far away pay 150–300 ms of network latency on every keystroke, which is fatal for a typeahead. A regional outage removes the feature for everyone.

Better: a full serving stack in every major region. Each region has API nodes and all the shards for the markets it serves, loaded from the same snapshot files, which are replicated to regional object storage. DNS or anycast routing sends users to the nearest healthy region (see DNS: The Domain Name System). Serving nodes are stateless apart from read-only data, so a region can be scaled or rebuilt from snapshots in minutes. Regions do not talk to each other on the request path.

Best: plan graceful degradation explicitly, because autocomplete is optional.

FailureDegraded behaviour
Trending stream lags or stopsServe base index only. Suggestions are slightly stale, which is barely noticeable.
Index build fails or is rejectedKeep serving the previous version. Alert if the index gets older than 48 hours.
History service slowSkip personal suggestions after a 20–30 ms timeout. Show device history and the global list.
A shard's replicas all unhealthyReturn the short-prefix table or an empty list for that range. Search still works.
Region overloadedShed load: raise the debounce through client config, serve stale from the CDN, drop personalisation and re-ranking.
Whole region downDNS failover to the next region. Higher latency, but the feature works.
  • Timeouts and budgets. The API gives each dependency a strict budget: shard lookup 5 ms, trending merge 1 ms, history 20 ms. On timeout, it returns what it has. A 10 ms answer without personalisation beats a 200 ms personalised one that arrives after the user typed three more characters. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
  • Do not retry on the hot path. By the time a retry would succeed, the prefix has changed. Hedged requests to a second replica after a p95 delay, for example 3 ms, are more useful for tail latency, and cheap here because lookups are tiny.
  • Separate the data path from the serving path. If Kafka, Spark or the builder are down for a day, serving does not notice, except that suggestions get a day older. This is the payoff of computing everything offline.
  • Index versions can differ between regions for a short time during rollout. That is acceptable, because a user rarely switches regions while typing. But the support tools must show which version a region served when investigating a complaint, which is why every response carries index_version.
  • Capacity for failover. Each region needs headroom to absorb a neighbour's traffic, perhaps 30–50% spare. Edge caching also reduces what a failover region must handle.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Computing top-k at request timeShort prefixes scan millions of entries, latency explodesPrecompute top-k per trie node or per prefix, lookups in microseconds (DD1)
One request per keystrokeSeveral times the needed traffic, out-of-order responsesDebounce, cancel stale requests, sequence numbers, client cache and local filtering (DD9)
Users far from origin150–300 ms per keystroke, suggestions arrive too lateCDN edge caching of global responses, serving stacks in every major region (DD6, DD12)
Skewed first lettersSome shards hold far more data and trafficRange split points chosen from load data, more replicas for hot ranges, short prefixes on API tier (DD5)
Hot prefixes like "a" or "fa"One key overloads a node or edgeIn-process cache of top prefixes, CDN request coalescing, replicas (DD5, DD6)
Bad index buildWrong or missing suggestions everywhereQuality gates, canary rollout, atomic swap, keep previous versions for instant rollback (DD4)
Pipeline outage or lost logsIndex goes stale or shrinksServe previous version, size checks reject shrunken builds, raw logs replayable from object storage (DD3, DD4)
Breaking news not suggestedProduct feels out of dateStreaming burst detection, trending index merged at serve time, shorter edge TTL for trending prefixes (DD7)
Harmful or defamatory suggestionUser harm, legal exposureBuild-time classifiers, serve-time policy filter updated in seconds, CDN purge, audit trail (DD11)
Private query leaks to othersPrivacy breachDistinct-user threshold, PII pattern filters, personal history kept on private path only (DD3, DD8)
Manipulation by botsFake or brand-damaging suggestionsDistinct established users, bot filtering, anomaly detection on sudden phrase growth (DD3, DD11)
History service slowEvery response waits, typeahead feels laggyStrict 20–30 ms timeout, device history as fallback, global list returned without personal part (DD8, DD12)

What Interviewers Expect#

Mid-level#

  • Clarify scale, latency and what is being completed. Then propose a trie and explain how a prefix lookup works.
  • Recognise that finding the top-k at request time is too slow, and store the top suggestions at each node.
  • Describe collecting search logs and recomputing counts periodically, and explain why the serving store is read-only.
  • Add caching with the right key, and explain debouncing on the client.

Senior#

  • Drive the split between an offline data path (logs → aggregation → index build → snapshots) and an in-memory serving path, and explain why it makes serving simple and robust.
  • Rank with time-decayed scores and distinct users, not raw counts.
  • Layer caching: browser, CDN and in-process. Keep personal data out of shared caches by splitting the global and personal responses.
  • Shard by market and then prefix range, explaining skew and why hash sharding fits a flat table but not a trie.
  • Add trending through a streaming layer merged at serve time, and roll out indexes with versions, canaries and rollback.

Staff+#

  • Quantify everything: requests per second after debounce and caching, index memory with and without pruning, edge hit rates for a Zipf-like distribution, and the end-to-end freshness of trends including TTLs.
  • Treat safety and privacy as first-class requirements: distinct-user thresholds, PII filters, serve-time takedown within minutes, manipulation resistance and audit.
  • Discuss ranking as candidates plus re-ranking, with position-bias-aware training, diversity, and offline and online metrics (MRR, keystrokes saved, selection rate).
  • Handle internationalisation: normalisation, input methods, word-level matching and fuzzy matching with bounded cost.
  • Design for degradation: autocomplete is optional, so every dependency has a timeout budget and a fallback, and the data path can fail for a day without users noticing.
Deep Dive: The mathematics of cache hit rates, trie size, decay and sketchesShow

Why small caches catch most of the traffic: Zipf's law. Query popularity roughly follows a Zipf distribution: the r-th most popular item is requested in proportion to 1 / r^s, with s close to 1 for search queries. With s = 1, the share of requests that go to the top C of N distinct items is about H_C / H_N, where H_n ≈ ln n + 0.577 is the n-th harmonic number.

Suppose an edge location sees N = 1 billion distinct prefix keys over a day.

  • A cache holding the top C = 10,000 keys serves about (9.2 + 0.58) / (20.7 + 0.58) ≈ 46% of requests.
  • With C = 1 million keys, which is a few hundred MB of small JSON responses, it serves about (13.8 + 0.58) / (20.7 + 0.58) ≈ 68%.

Real traffic per edge location is a slice of the total, with its own language mix and a fatter tail, so measured hit rates vary. But the shape explains the design: a modest cache in the right place absorbs most of the load. The long tail, meanwhile, must be served from an index that has every key.

Hit rate under a TTL. For one key requested at rate λ at an edge location with TTL T, each miss is followed on average by λT hits before the entry expires. So the hit ratio is λT / (1 + λT).

  • A hot prefix at λ = 10 per second with T = 900 s has a hit ratio of 9,000 / 9,001 ≈ 99.99%.
  • A tail prefix requested once an hour has λT = 0.25, so its hit ratio is 0.25 / 1.25 = 20%.

Lengthening the TTL helps only the middle of the distribution. It does nothing for very hot keys, which already hit, or for the far tail, which rarely repeats. It also delays trends. This is why TTLs of 5–15 minutes are a reasonable balance.

How big is the trie?

  • A radix trie over n strings, where every non-terminal internal node has at least two children, has at most about 2n nodes. Leaves and terminal nodes number at most n, and branching nodes are fewer than the leaves.
  • For n = 200M queries, that is at most 400M nodes.
  • With roughly 20 bytes of structure per node (edge label offset, child offsets), the structure is about 8 GB. The strings are about 5 GB.
  • Top-10 lists of 4-byte ids at every node would add 400M × 40 B = 16 GB, giving about 29 GB in total.
  • Now prune. Store lists only at nodes with at least 10 queries in their subtree. In a natural-language trie, most nodes are leaves or close to leaves, so suppose 80% of nodes fall below that threshold. Lists then shrink to about 3.2 GB, and the total is about 16 GB.

That fits a single 64 GB server with room for a second version during the swap. This arithmetic is what decides "replicate, don't shard" for many markets (Deep Dive 5).

Decay maths. With a half-life of H days, the daily decay factor is d = 2^(−1/H). For H = 7 days, d ≈ 0.906.

  • A query searched c times every day converges to a steady score of c / (1 − d) ≈ 10.6c. The effective window is about H / ln 2 ≈ 10 days.
  • A brand-new query with constant daily volume reaches half of its steady score after H = 7 days. That is far too slow for news. It is the mathematical reason the trending layer exists.
  • When a query stops being searched, its score halves every 7 days. So "world cup" suggestions fade within weeks after the tournament, not years.
  • Choosing H is a product decision. Short half-lives favour news; long ones favour evergreen queries. It can differ by category if a classifier labels queries.

Count-Min sketch for stream counts. A Count-Min sketch (Cormode and Muthukrishnan, 2005) is a d × w array of counters with d hash functions. Each event increments one counter per row. An estimate is the minimum across the rows. It never underestimates. With w = ⌈e / ε⌉ and d = ⌈ln(1/δ)⌉, the overestimate is at most εN with probability at least 1 − δ, where N is the total count.

For a 15-minute window at 12k searches per second, N ≈ 10.8M.

  • Choosing ε = 10⁻⁵ bounds the error at about 108 counts, with w ≈ 271,829.
  • δ = 0.001 gives d = 7.
  • With 4-byte counters, that is 271,829 × 7 × 4 B ≈ 7.6 MB per window per market. It is tiny, and accurate enough to flag queries rising from hundreds to tens of thousands.

HyperLogLog for distinct users. HyperLogLog (Flajolet, Fusy, Gandouet and Meunier, 2007) estimates distinct counts with standard error about 1.04 / √m using m registers. With m = 2¹⁴ registers, the error is about 0.8% in about 12 KB. A 12 KB sketch for every one of 200M queries per day would be 2.4 TB, which is absurd. So HLL is used only for the head of the distribution. Exact distinct counts for the tail come from the batch shuffle (GROUP BY query, user), and sparse HLL encodings handle small sets compactly. Knowing where an approximation pays off, and where it does not, is the real skill here.

Request rate after each layer. Start with 300k requests per second at peak, from 1B searches with about 6 requests each after debounce. Suppose client caches absorb 15% (backspaces, repeated typing) and the edge absorbs 50% of the rest. Then origin sees 300k × 0.85 × 0.5 ≈ 128k/s. Of that, in-process caches of the top 100k prefixes on API nodes absorb perhaps another 30%, leaving about 90k/s for the shards. At 10k requests per second per core, that is 9 cores of work worldwide. The fleet is sized by memory, latency and redundancy, not by CPU.

Deep Dive: Building autocomplete on a search-optimised database insteadShow

Not every product needs a custom trie service. If the vocabulary is a catalogue (products, places, people, documents) rather than billions of past queries, a search-optimised database often does the job with far less engineering.

What a search-optimised database does. A normal database query like WHERE name LIKE '%term%' cannot use a B-tree index when the pattern starts with a wildcard, so it scans every row. Search engines such as Elasticsearch and OpenSearch, built on Apache Lucene, instead keep an inverted index: a map from each term to the list of documents that contain it. Building it involves three steps:

  • Tokenisation: splitting text into terms.
  • Normalisation: lower-casing, removing accents.
  • Stemming: reducing "running" and "runs" to "run", so different forms of a word match.

Search engines also support fuzzy matching by edit distance, and they scale like other distributed databases, by sharding the index across nodes and replicating each shard. See Elasticsearch and Search Systems.

Three ways to do typeahead in Elasticsearch:

  1. Completion suggester. A dedicated field type stores the input strings, with weights, in an in-memory FST per index segment. Prefix lookups are very fast and return the top-weighted completions. It supports fuzzy prefixes and contexts (filters such as category or location). The limits: it matches only from the start of the input, unless you index several inputs per item, and weights are static per document, so changing popularity means re-indexing.
  2. Edge n-grams. At index time, an analyser emits every prefix of every word as a term: "pancake" becomes "p", "pa", "pan", up to the whole word. A normal term query on the typed prefix then matches. It is flexible: it matches any word in the text, and ranks with the full scoring machinery, including popularity boosts through function scores. But the index grows several-fold, and queries are slower than the completion suggester.
  3. search_as_you_type field type. A convenience field that builds the prefix and shingle (word-pair) subfields automatically, aimed at the "match words in any position as I type" case.

Postgres and Redis options for smaller systems.

  • PostgreSQL: a B-tree index with the text_pattern_ops operator class makes LIKE 'pref%' an index range scan. The pg_trgm extension, with GIN or GiST indexes, supports substring and similarity search on trigrams. Full-text search uses tsvector columns with GIN indexes and prefix matching via to_tsquery('pan:*'). For tens of thousands to a few million items with modest traffic, this avoids any new system.
  • Redis: a sorted set with all members at score 0 can be queried lexicographically with ZRANGE ... BYLEX for prefix ranges, which is fast for exact prefixes. To get the top-k by popularity, store a separate sorted set per prefix, scored by popularity. That is the prefix → top-k table again, built in Redis. It is fine for small vocabularies. The reference describes Redis's own full-text search support as immature compared with dedicated search engines.

Keeping the search index in sync. If the catalogue lives in PostgreSQL, use change data capture to stream inserts, updates and deletes into Elasticsearch in near real time. The alternative is dual writes from the application, which drift when one write fails (see Change Data Capture and the Outbox Pattern). The challenge is the usual one for a derived store: monitoring lag and rebuilding the index from scratch when mappings change.

Caching search results. Repeated searches are common, so cache them.

  • Application cache: in Redis, with a key built from every parameter that changes the result (prefix, filters, language, page size) and a TTL. Invalidation is the hard part. A new product does not know which cached prefixes it belongs to. So rely on short TTLs, or tag cache entries (for example by category) and purge by tag when data changes.
  • Engine caches: Elasticsearch has a shard-level request cache that can store whole search responses, mainly for aggregation-heavy requests, and a node-level query cache for filter results. Both are invalidated when the shard's data refreshes.
  • CDN: cache results at the edge, but only when they are not personalised: the same query must give the same answer for every user.

When to choose what:

SituationGood fit
Up to a few million catalogue items, moderate trafficPostgreSQL prefix or trigram indexes, or a prefix table in Redis
Catalogue with filters, any-word matching, relevance tuningElasticsearch or OpenSearch with edge n-grams or search_as_you_type, CDC from the main database
Fast prefix completion of a curated list with weightsElasticsearch completion suggester
Billions of logged queries, global traffic, strict latencyCustom offline-built trie or FST with in-memory serving, as in this case study

The core idea is the same in every row: do the work at index time, so the request does a lookup. What changes is who builds and serves the index, and how much control you need over ranking, freshness and safety.

Deep Dive: Updating the trie in real time instead of rebuilding itShow

This design rebuilds the index offline and adds a small trending layer. Some products want every new query reflected within seconds, such as a social network with fast-moving hashtags, or an internal tool with a small, fast-changing catalogue. What does real-time updating of a trie with top-k lists involve?

The update rule. When query q's score rises from s to s′, walk from the root along q's path. At each ancestor node:

  • if q is already in the node's top-k list, update its score and re-sort;
  • if not, and s′ is greater than the smallest score in the list, insert q and drop the smallest.

When a score falls, the problem is harder. If q leaves a node's top-k list, the node needs the next-best item from its subtree, which it does not store. Options are to keep a longer list than shown (for example 2k entries, shown k), and refill it at the next rebuild, or to recompute from the children's lists, which are themselves bounded.

Cost. Each update touches at most len(q) nodes, about 20, each with a small list of k items. That is around 20 × k operations, roughly a microsecond of work. At 12k searches per second, a single node handles this easily. The problems are not CPU:

  1. Concurrency. Readers walk the trie while writers modify lists. Locks on hot nodes near the root ("h", "ho") would serialise everything. The usual answer is copy-on-write: build a new version of each modified node and swap the parent's pointer atomically. Readers see either the old node or the new one, never a half-updated list. Old nodes are freed once no reader can still be using them, with read-copy-update (RCU) style reclamation or garbage collection. This is a persistent data structure technique: each update creates a new root path, sharing everything else.
  2. Replication. Every replica must apply the same updates. Feed them all from the same ordered stream, such as a Kafka partition per market. Each replica applies updates independently and reports its offset, so replicas are eventually consistent and can be checked by offset.
  3. Write amplification. With 50 replicas per market and 12k updates per second each touching 20 nodes, the fleet performs about 12 million node updates per second, all of them to keep slightly fresher scores. Most score changes do not change any top-k list, so filter first: only send updates that would change a list at some node, which the stream job can estimate.
  4. Reproducibility. A trie that has been mutated for weeks is hard to compare with an offline build, and hard to debug. Most teams who do real-time updates still rebuild from scratch nightly and use real-time updates only between rebuilds.

Safety. Real-time updates also mean that a manipulated or harmful query can enter suggestions within seconds. The policy filter and distinct-user thresholds must run in the update path too, which makes the stream job heavier.

Verdict. For web-scale query autocomplete, the batch build plus a trending overlay gives nearly all the freshness value at a fraction of the complexity. Real-time updates fit smaller indexes where every item matters, such as a team's document titles, contact lists, or hashtags in a live event. A simpler alternative is to rebuild a small index entirely every minute: 1 million items build in about a second. The guiding question is the same as everywhere in this design: where is the cheapest place to do the work, and how fresh does the answer really need to be?

Deep Dive: Variants: people typeahead on a social network and product searchShow

Interviewers often change the scenario. Two common variants change the data source and the ranking, and show which parts of the design carry over.

Variant A: "search for people and pages" typeahead on a social network. When you type "ali" on a social network, you expect your friend Alice first, then pages and people you have a connection to, then famous accounts. Global popularity alone is wrong here: the best answer is different for every user.

  • Data source: the social graph and entity metadata (names, aliases, popularity), not query logs.
  • Index: an inverted index from name prefixes to entity ids. "ali" maps to everyone with a name token starting with "ali". Facebook described its system for this, Unicorn, in a VLDB 2013 paper ("Unicorn: A System for Searching the Social Graph", Curtiss and others). It is an in-memory inverted index over the graph, where posting lists can hold edges such as friend:<user_id>. Typeahead queries are then set operations, such as "people whose name starts with ali AND who are friends of me, OR friends of friends of me", evaluated across many index shards, then ranked.
  • Personal first-degree cache: the most effective trick is to send the client its own first-degree connections (friends, followed pages, recent interactions) ahead of time, a few thousand entries, ranked by affinity. Most typeahead hits come from this small personal set and are matched entirely on the device. Server queries are needed only for the long tail.
  • Ranking: affinity (how often you interact), mutual connections, recency, and the entity's global popularity. The response is personal, so it is never cached in shared caches.
  • Sharding: documents are spread across shards by entity id, so a query must fan out to all shards and merge (scatter-gather). The fan-out is limited to a few hundred candidates per shard, and the personal set handles most traffic. This is a case where cross-shard queries are accepted, because the index cannot be split by the thing being looked up: the friend filter depends on the user.

Variant B: product search autocomplete for an online shop. Typing "wireless h" should suggest "wireless headphones", "wireless headphones noise cancelling", and perhaps a direct product link.

  • Two sources merged:
    1. Query completions from the shop's own search logs, built as in this case study, but with smaller volume. A few million queries fit in memory on every API node.
    2. Catalogue entities (categories, brands, products) from the product database, indexed through CDC in a search engine with edge n-grams.
  • Business rules:
    • Hide suggestions that lead to zero results or out-of-stock products, which needs a near-real-time stock signal.
    • Boost categories with promotions, carefully, because users notice irrelevant boosts.
    • Never suggest products the user cannot buy in their country.
  • Freshness is driven by the catalogue, not only by trends. A product launch should be suggestible the moment it goes live, so entity suggestions come from the CDC-fed index rather than nightly logs.
  • Rich suggestions: a product image, price and rating in the dropdown. This makes the response larger (1–5 KB) and dependent on price and stock. Use short TTLs at the edge, or fetch rich details in a second call for the top one or two items.

What carried over and what changed:

AspectWeb query autocompletePeople typeaheadProduct autocomplete
SourceQuery logsSocial graph and entitiesLogs plus catalogue
IndexTrie or FST, top-k per prefixInverted index with graph edgesSmall trie plus search-engine index
PersonalisationLight, on a private pathCentral to rankingModerate
Shared cachingHeavy, at browser and CDNAlmost nonePartial, short TTL
ShardingBy market and prefix rangeBy entity id, with scatter-gatherOften none needed
Freshness driverTrendsGraph changesCatalogue and stock

The constants are the precomputed index, the in-memory lookup, the strict latency budget, the client behaviour (debounce, cancel, stale-response handling), and the safety filters.

Deep Dive: Real systems and what they teachShow
  • Lucene and Elasticsearch. Lucene stores its term dictionary as an FST and provides suggesters built on weighted FSTs. Elasticsearch's completion suggester exposes this with per-segment in-memory structures. The lesson is that a compact, immutable, offline-built automaton is the standard engineering answer for fast prefix lookups. Segments are immutable and merged in the background, the same "build new, swap atomically" idea as our index snapshots.
  • Facebook's Unicorn (VLDB 2013) showed typeahead over a social graph as an inverted-index problem with graph-aware set operations, served from memory and sharded across many machines. Facebook's earlier engineering writing on typeahead also described loading a user's first-degree connections into the browser in advance, so most lookups never leave the device.
  • LinkedIn's Cleo was open-sourced around 2012 as the technology behind LinkedIn's typeahead. It offered both a generic typeahead over large entity sets and a network-aware typeahead over a member's own connections. That split is a good example of designing around the observation that most lookups hit a small, personal set.
  • Twitter's typeahead.js is a widely used front-end library. It made the client-side techniques of Deep Dive 9 standard practice: prefetching a dataset into local storage, filtering locally, falling back to remote calls, and rate-limiting requests.
  • Google's published autocomplete policies describe removing predictions in categories such as sexually explicit, hateful, violent and dangerous content, and having processes for legal removal requests. This shows that the safety pipeline of Deep Dive 11 is part of the product, not an afterthought. Google also documents that predictions reflect real searches and can be influenced by language and location, which matches the per-market indexes here.
  • The data structures have deep roots. Edward Fredkin introduced the word "trie" in 1960, from "retrieval". Morrison's PATRICIA (1968) gave the compressed form. Minimal acyclic automata built incrementally from sorted input (Daciuk and others, 2000) gave the FST-style dictionaries used today. Autocomplete is a modern product built on some of the oldest ideas in string processing.
Deep Dive: Measuring, testing, evolving and operating autocompleteShow

What "good" means: metrics.

  • Selection rate: the share of searches that used a suggestion. It is the headline engagement metric.
  • Keystrokes saved: characters the user did not have to type, divided by the length of the final query. It directly measures effort saved.
  • Mean reciprocal rank (MRR): for searches that used a suggestion, the average of 1 / position. MRR rises when the chosen item moves up the list.
  • Zero-suggestion rate: the share of prefixes with no suggestions. It catches broken markets or normalisation bugs.
  • Latency as users see it: time from keystroke to rendered list, at p50, p95 and p99, from client telemetry. Also the stale-response discard rate.
  • Safety: reports per million impressions, time-to-takedown, and the share removed by each filter.

Several of these trade off against each other. More aggressive trending raises freshness but also risk. More personalisation raises MRR but lowers cacheability. So decisions are made with A/B experiments that report the whole set, not one number.

Offline evaluation before experiments. Replay a day of real typing sessions against a candidate index. For each session, simulate the user typing the final query character by character, and record when the final query first appeared in the top k and at which position. This gives offline keystrokes-saved and MRR in minutes, without exposing users. Use it to compare scoring formulas, half-lives and pruning settings. Then run online experiments only for the promising ones.

Testing the system:

  • Unit and property tests for normalisation. Round-trips, idempotence (normalising twice changes nothing) and per-language cases (Turkish "I", German "ß", composed and decomposed accents). Normalisation bugs are the most common source of "it suggests nothing for X".
  • Build determinism. The same input logs and code must produce the same index bytes. This makes diffs between builds meaningful, and bugs reproducible.
  • Golden prefix suites per market, which act as quality gates (Deep Dive 4).
  • Load tests with a realistic, Zipf-like prefix mix and real typing timings, not uniform random strings. A uniform mix makes caches look useless and shards look evenly loaded, both wrong. See Capacity Planning and Load Testing.
  • Failure tests:
    • Kill shard replicas, and check the fallback.
    • Stop the trending stream, and check that the base index still serves.
    • Publish a deliberately bad build, and check that gates catch it.
    • Slow the history service, and check that the timeout keeps total latency within budget.

Evolving the system in stages. Measure, find the bottleneck, fix it, repeat. Do not start at the end state.

  1. Start: a prefix → top-k table built nightly by a SQL job over the search logs, loaded into the memory of each API server, with HTTP caching headers. For one market and tens of millions of searches a day, this is enough.
  2. Global users: add a CDN, and serving stacks in two or three regions loading the same snapshot files.
  3. Freshness: add the streaming trending layer, and hourly delta builds.
  4. Scale of vocabulary: move to a compressed trie or FST format, prune deep lists, and shard large markets by prefix range.
  5. Quality: add the re-ranker, personalisation on the private path, diversity, and the full safety pipeline.

Operating it:

  • Dashboards per market: request rate, edge hit rate, origin latency, active index version and age, trending lag, zero-suggestion rate and selection rate.
  • Alerts:
    • Index age above 48 hours.
    • A drop in selection rate of more than a few percent in one market, which usually means a bad build or a normalisation regression.
    • Edge hit rate falling, which can mean a cache-key bug such as an unnormalised parameter.
    • Trending lag above 5 minutes.
  • Runbooks:
    • Roll back an index version.
    • Remove a suggestion everywhere: policy store, then push, then CDN purge.
    • Disable trending for a market.
    • Raise client debounce through remote config during an overload.
  • Ownership is shared. Search infrastructure runs the serving and pipeline. A ranking team owns scoring and experiments. Trust and safety owns policies. Clear interfaces (scored-query tables, the policy store, index manifests) let each team move independently.

Security notes. The suggest endpoint is public and cheap per request, so protect it with rate limits per client and IP at the edge (see Rate Limiting and Throttling). Reject very long inputs, for example over 100 characters, because they would never match and only waste work. Never reflect user input into HTML without escaping. Suggestions are text supplied by other users, so the client must render them as text, never as markup.

Key Takeaways#

  • Precompute, then look up. A trie with the top-k completions stored at each node, or a flat prefix → top-k table, turns every request into a microsecond lookup. All the expensive work moves to offline builds.
  • Learn from logs. Search events flow through Kafka into object storage. Batch jobs compute time-decayed, distinct-user scores with bot filters and a privacy threshold. Raw logs are kept so any scoring change can be replayed. See Batch vs Stream Processing.
  • Ship indexes like deployments. Use immutable, versioned snapshots, quality gates, canaries, atomic swaps and instant rollback. Serving nodes are read-only replicas, with no locks and no consistency protocol.
  • Cache at every layer. Client cache with local filtering, CDN edge caching of the global response, and in-process caches for hot prefixes. Zipf-shaped traffic means modest caches absorb most requests. Keep personal data on a separate private path so the global response stays cacheable. See Caching Fundamentals and Content Delivery Networks (CDN).
  • Shard only when the numbers say so. First by market and language, then by prefix ranges with split points chosen from load data. Hashing suits a flat table, not a trie. Hot prefixes are solved by caching and replicas. See Partitioning and Sharding.
  • Trends need a speed layer. Streaming burst detection with sliding windows and sketches publishes a small trending index every minute, merged at serve time, with stricter safety checks and decaying boosts. See Probabilistic Data Structures for Big Data.
  • Personalise by merging, not by fragmenting. Device history first, a private history service for signed-in users, and re-ranking of global candidates only where it pays.
  • The client is half the system. Debounce, warm connections, cancel stale requests, ignore out-of-order responses, and fail quietly.
  • Normalise consistently and respect languages. Use the same normalisation everywhere, per-market indexes, input-method and transliteration support, and bounded-cost fuzzy matching for typos.
  • Safety is part of the product. Use build-time classifiers, distinct-user thresholds against leaks and manipulation, a serve-time policy filter updated within seconds, and fast takedown with audit.
  • Degrade gracefully. Every dependency has a timeout budget and a fallback. The data path can be down for a day while serving carries on. Autocomplete must never slow down search itself.