Systemsfor Aravinda
0 / 78 core
Week 10 · Case studies

Design search autocomplete

1.5 hours · core path

Read first: Search indexes, Caching

In one sitting

A keystroke is too late to run a search. You build a trie or an edge n-gram map with the top suggestions already sitting on each prefix, cache the prefixes everyone types, and let a new query wait for the next build. The prefix that matters is a single letter, and adding partitions does not split that one key.

Every keystroke is a deadline. The person at the search box is not waiting for you to scan an inverted index. They are waiting for a handful of strings that you already attached to the prefix they just typed.

Requirements

The user is someone typing a query. After each new character the box shows a short list of completions. The product you are designing is query autocomplete: suggestions are previous queries, scored by how often people issued them. Document-title autocomplete is the same shape with a different score, and you can say so if the interviewer turns that way.

It must:

  • Return the top suggestions for a prefix. Assumption: five suggestions, each a query string and nothing else.
  • Answer from data that is already shaped for the prefix. The request path is a lookup.
  • Accept new popular queries over time, behind the index build, not inside the keystroke.
  • Tolerate a stale suggestion. A query that fell out of fashion yesterday can still appear this morning.

Non-goals, said out loud so you stop designing them:

  • Full-text search with positions and snippets. That is the search index. Autocomplete is a prefix map.
  • Spelling correction, synonyms, and personalization. A personal re-rank of five global suggestions is a later experiment. A trie per user is not the design.
  • Strong consistency with the moment a query was first typed. This index is a derived store. It lags.

Latency budget, as an assumption you state: the list is back within about 100 ms at p99, so the interaction feels tied to the key. A round trip inside one datacenter is 0.5 ms on the usual teaching list, which you can reread on the latency numbers page. The user’s network is the expensive hop. You get one cheap lookup after that, not a fanout of search shards.

Estimation

Assumptions, all of them interview assumptions and none of them a company’s traffic:

  • 100 million people use the box in a day.
  • Each person issues 5 queries.
  • The client sends a request on every character, with no debounce. Average query length sent to the server is 8 characters. This is an upper bound. A real client should debounce, and you will say that the estimate is the pessimistic one.
  • Peak is 3 times the average. The usual planning band is 2x to 5x. Three is a choice inside that band.
  • A response is about 500 bytes on the wire. Five short strings plus framing.
  • The dictionary you keep is the top 20 million queries over a rolling 7 days. Average stored length is 16 characters.

A day has 86,400 seconds. The interview shortcut of 100,000 seconds is a bit generous, so it understates the rate. Show both.

queries per day     = 100e6 * 5           = 500e6
keystroke requests  = 500e6 * 8           = 4.0e9 per day

average QPS         = 4.0e9 / 86,400      = 46,300
shortcut            = 4.0e9 / 100,000     = 40,000
peak, assumption 3x                       = 139,000 QPS

bandwidth, peak     = 139,000 * 500 bytes = 70e6 bytes/s
                                            about 70 MB/s

Seventy megabytes a second of suggestions is not the bottleneck. A million requests a day would have been about 12 per second. You are three orders of magnitude above that, and you are still nowhere near a bandwidth problem. The problem is how much work one of those requests does, and how uneven the prefixes are.

Storage of the serving map. The builder inserts the 20 million queries into a trie and writes the top five suggestions onto each node. With no prefix sharing that is 20e6 * 16 = 320 million character nodes. Assumption: shared English prefixes cut the node count to about a third, 110 million nodes. Each node keeps a character, a few child pointers, and five suggestion ids with scores. Call that 80 bytes, and treat the 80 as an assumption about a compact layout, not a measurement of a runtime.

nodes, with the one-third sharing assumption = 110e6
artifact size = 110e6 * 80 bytes             = 8.8e9 bytes
                                             about 9 GB

Nine gigabytes fits in RAM on one serving machine. Three copies for loss of a machine is 27 GB of RAM across the fleet, not a cluster-sizing exercise. If the sharing assumption is wrong and the artifact is 25 GB, it still fits on a large box. You measure the built file. You do not shard this because a formula told you to.

What you replicated is the artifact. What you cache is the hot prefixes in front of it, which is the cache on the path.

High-level design

flowchart LR
  typer[Person typing]
  box[Search box]
  cache[Prefix cache]
  head[Hot prefixes on every node]
  trie[Immutable prefix map]
  side[Recent side index]
  log[Query count log]
  builder[Offline builder]
  typer --> box --> cache
  cache --> head
  cache --> trie
  cache --> side
  box --> log --> builder --> trie

The box normalizes the prefix: trim, case-fold. Assumption for this design: Latin letters. A writing system where one character is already selective changes what “the first character” means, and you should say you did not design that input method.

The cache key is the prefix plus the generation number of the map. A hit returns five strings. A miss reads the immutable map. If the prefix is young, the miss path also reads a small side index of the last build interval and merges by query id. The result fills the cache.

The query log is an append of normalized queries. It is not on the user’s timer except as a cheap async write. The builder counts, builds a new map, smoke-checks it, and flips a pointer. Serving never mutates the map in place.

Deep dive

One structure, two layouts

A trie is a tree of characters. The path from the root spells the prefix. An edge n-gram index stores each prefix as its own key: the query “noodle soup” becomes the keys “n”, “no”, “noo”, and so on, each pointing at that query. Both are prefix structures. The trie shares the bytes of “noo” across “noodle soup” and “noodle shop”. The n-gram map repeats the key and is easy to drop into a hash table or into a search cluster you already run. The request path does not care which builder you used. It cares that the value is already the answer.

You store the top five at the node, or on the n-gram key, at build time. Insert queries from the highest score to the lowest. Each node holds a list of five. Once a node is full, a worse query does not displace anyone. A rare query is absent from the node “n” and present on “noodle so”, once the prefix is selective enough that the query enters the top five. That is the long tail. You did not drop it. You refused to pin it to a prefix it cannot win.

Doing that update on the keystroke path is the wrong place. It races, it makes a read depend on a write, and it makes the hottest node the most written node. The builder owns the top-five lists. The serving artifact is immutable.

Score, stated as a starting point and not as a ranker you will defend to a research team: the count of times the query was issued in 7 days. Term frequency and inverse document frequency are the starting point when you are completing document titles instead of queries. Say which product you are in.

The single-letter prefix

Length-1 requests are 1/8 of the keystroke traffic if every query really sends 8 characters.

length-1 QPS, average = 46,300 / 8 = 5,800
assumption: the hottest letter is 12 percent of length-1 traffic
hottest letter, average         = 700 QPS
hottest letter, peak at 3x      = 2,100 QPS

assumption: 12 percent of queries start with that same letter
shard-by-first-letter, peak     = 0.12 * 139,000 = 16,700 QPS

Two thousand requests a second for one cache key is easy if the value is five strings you already computed. It is fatal if each request walks the subtree of that letter and sorts it. The subtree of a single letter is a large fraction of the dictionary. Precomputing the top five turns a scan into a hash get. That is the whole trick.

The matching failure mode is a hot key. Hashing prefixes across more machines spreads “noodle s” away from “mountain”. It does not spread the key “s”, because there is one key. Partitioning does not fix a key that is hot. The head of the distribution is tiny and read-mostly, so you replicate it instead of partitioning it. The 26 length-1 prefixes, and a few thousand common longer ones, are a megabyte. Put that head on every serving node and read it locally. Partition the tail. The cache in front still absorbs the repeated reads and keeps a stampede off the map.

When the cached head expires, every current typist misses at once. One filler rebuilds the key and the rest wait. That is single-flight. The memcache paper’s lease is the same idea with a token so a slow filler cannot write an old value over a newer one. Here the map generation in the cache key does that job: an old filler writes an old generation, and readers are asking for the new one. Probabilistic early refresh, the idea of refreshing before the TTL with a probability that rises as expiry nears, is how you avoid a synchronized cliff. You do not need a formula you have not derived. You need one refresher, not a thousand.

A client debounce belongs in the design even though the estimate ignored it. A 100 ms pause before sending collapses a burst of keystrokes into the prefix the person actually paused on. You still design the server for the client that forgets, because a buggy client will send every character and retry.

Index lag

Indexing is asynchronous. The map is a generation, built on a timer. Assumption: the builder runs every 10 minutes. A query that becomes popular at 12:00 can be missing until 12:10. For the prefix “s” that does not matter, because the top five are stable. For a new product name it matters.

The side index is a second, small map over the queries seen since the last successful build. Same shape, top five per prefix, built continuously from the count log. On a cache miss you read both maps and merge by query id. If an id is in both, keep the side index score for that id, because it is the fresher count. Do not add the scores. Adding them double-counts the queries that were already in the main map. The merged value is what you cache, with a short TTL, so a viral prefix becomes a hot key that is still cheap.

If the builder fails, you keep the previous generation and the side index grows. The failure looks like staleness, not like an empty box. You only flip the pointer after a smoke check: the new map must still contain a fixed list of head queries, and it must be within a sane size of the last artifact. A corrupt generation that you swap in blindly empties the box for everyone at once.

Tradeoffs

Choice What you gain What you spend
Trie built offline, top five stored on the node A keystroke is one lookup Suggestions lag the build interval
Edge n-grams in a search index you already run One less system to operate Fat keys for short prefixes, and the same hot key
Recompute the top five on read A simpler build The letter s scans a huge subtree under load
Replicate the head, partition the tail The hot key is served locally on every node A publish must reach every node, and the tail needs a routing rule
Cache the prefix with a generation in the key Repeated keystrokes never touch the map A flush or a new generation is a miss storm you have to single-flight
Side index merged on the miss path A breakout query appears inside a minute A bad merge double-counts or hides the main score
Wait for two characters before querying You delete the most useless, most common requests The box feels dead on the first letter, and the hot key moves to a set of digraphs that is still skewed

Failure modes

  • The prefix cache dies, and the map was built to be scanned rather than looked up. Symptom: latency of the letter s goes to the timeout, the box spinners, and clients retry. Retries are safe, because this is a read, and they are also a retry storm on the one key you cannot partition. The fix is the precomputed value, single-flight, and a client that does not retry a 50 ms lookup three times inside a 100 ms budget.
  • The builder is down for an afternoon. Symptom: nothing new appears, and the side index is asked to cover a longer window than you sized. The live path stays up. Cap the side index and accept that a six-hour outage means six hours of lag, not a rebuild on the request path.
  • A publish swaps in a bad artifact. Symptom: empty suggestions for head prefixes you know are popular. The smoke check and the pointer swap exist so the last good generation remains the one readers see.
  • You shard by the first letter because the picture looks balanced on a whiteboard. Symptom: one machine holds every prefix under s, and a traffic spike on that letter is a hot partition. More shards with the same key do not move it. Replicate the head.
  • The count pipeline double-sends a log file and you add scores in the merge. Symptom: a handful of queries glue themselves to the top of common prefixes and will not leave until the next clean build. Merge by id, do not sum across generations.
  • A bot walks the alphabet. Symptom: length-1 QPS stops looking like the estimate. A rate limit at the edge, covered on the rate-limiting page, is how you say no before the cache does extra work. Debounce does not save you from a bot.

Consistency here is lag, and you already chose it. There is no durability story on the keystroke. The durable objects are the count log and the last good generation. Lose the log’s tail and the next build is short a few minutes of counts. The box keeps working.

In the interview

Spend the first five minutes on the user, the five suggestions, the 100 ms budget, and the decision that the request path is a lookup of a precomputed prefix. Sketch the box, the cache, the immutable map, and the builder off to the side. Say the number: on the order of 50,000 lookups a second average at the assumed audience, and a serving artifact around 10 GB.

Skip ranking theory, input-method editors, and anything that sounds like a search-relevance roadmap. If they want document titles instead of queries, change the score and keep the structure.

The question that usually follows is the hot prefix, or “when does a new query show up?” Answer the letter first. The value is small, the key is one key, you replicate it, and you never compute it on read. Then answer lag with the generation and the side index, and say how the merge avoids double-counting.

Check yourself

Why does storing the top five suggestions on the prefix node change the cost of the letter s?

Without the stored list, a read of that letter walks a large fraction of the dictionary and sorts it, and every typist does that walk. With the list, the builder did the walk once per generation and the read is a hash get of five ids. The hot key is still one key. It is just no longer an expensive key.

You have 4 billion keystroke requests in a day. What is the average rate, and what does the 100,000-second shortcut get wrong?

A day is 86,400 seconds, so 4.0e9 / 86,400 is about 46,300 per second. Dividing by 100,000 gives 40,000. The shortcut is low by about 14 percent because 100,000 is larger than 86,400. Fine for a first pass. The wrong place to stop.

A new query is typed a million times in two minutes. The main map rebuilt twenty minutes ago. Where should the suggestion come from, and what bug double-counts it?

From the side index, merged with the main map on the cache miss. If the query is already in the main map, keep one score, the fresher one. Adding the side count to the stored count counts the same traffic in both places and pins the query to the top of a short prefix.

The cache TTL expires for every head prefix at the same moment. What happens, and which fix matches the problem?

Every current typist misses, and they all miss on a handful of keys. That is a stampede. One filler per key rebuilds the value and the others wait. Adding partitions does not help, because each of those keys is still one key. A generation in the cache key plus single-flight keeps an old filler from winning the race.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes; Facebook memcache, NSDI 2013.