Lesson 3 · Minutes 20-30

Search Autocomplete: Scaling It

Problem

Between minute twenty and minute thirty the interviewer stops asking what the design does and starts asking what it costs. Four questions come, each aimed at a different part of the board:

  • A single typed letter makes the server read tens of millions of nodes.
  • While the rebuild runs, no trie exists to answer from.
  • Traffic and vocabulary both grow tenfold, past what one server holds or serves.
  • The browser sends every letter to the servers, though many of them never needed the trip.

The Search Under One Letter

"Thirty-three million nodes for one letter. What do you do about that?" You stop searching. The answer to a search changes only once a day, so work it out once a day and store it on the node: the IDs of the top five completions beneath it. A lookup now walks at most about 24 nodes, one per character of a query. At 100 nanoseconds a node that is about 2.4 microseconds, more than a million times less than 3 seconds.

Once the answer sits on the node, the walk is not needed either. A plain table from prefix to five completions answers with one read by key, and the trie, that tree of letters, lives on only in whatever builds the table. You do not have to settle that now, and you can say so: "Table or trie is a choice I'm leaving open until the deep dive."

Either way the price is memory and updates. Five IDs of 8 bytes each on 500 million entries is 20 GB, which takes the 25 GB to 45. The query text, 50 million queries at 24 characters, is another 1.2 GB, so call it 46 GB. That just fits half of one 100 GB machine, and the next probe shows why half is the number to hold on to. The other price is that one new count can change lists all the way up its path, which is harmless once a day and ruinous once a search.

The Rebuild

"The new counts are in, and rebuilding takes the trie away for 50 seconds. What do users see?" They see no change, because the index in service is never the one being built. Build apart, swap at once. The search log feeds the daily count job, a log in the sense of Chapter 6's Queues, Logs and Pub-Sub, which keeps its lines and lets a batch reader come for them at its own pace.

A new box, the builder, turns the counts into a new index, applies the block list of terms never to suggest, and writes one versioned file to object storage. The server loads that file beside the old index, and one pointer flip moves every reader to the new one. A rollback is the same flip backwards, for as long as the old index is in memory, and a reload of the old file after that.

The alternative is to update in place, and it loses on arithmetic. At peak there are 10,000 counted searches a second. Each can touch up to 24 entries, one per prefix on its path, so that is 240,000 checks a second of whether a top five has changed, on the very entries readers use most. That is more than twice what one machine does at 100,000 a second, spent on freshness Scope did not ask for.

The swap has three costs. Two indexes sit in memory for the minutes the load takes, 92 of 100 GB, which is why the index had to fit in half a machine. Suggestions run about a day behind, which Scope allowed. And a bad index can reach everything at once, because one flip moves every reader; the deep dive takes that up.

Ten Times Everything

"Growth has been good: ten times the traffic, ten times the vocabulary. Is this still one box?" No, and the answer is two limits with two different fixes, so size them apart. The rate comes first, and it is what gives out first. Assume each server runs at half of one machine's 100,000, which is 50,000. Today's 60,000 is already past that. Ten times 60,000 is 600,000 keystrokes a second, and that is 12 servers. The index is read-only between swaps, so those copies need no coordination at all.

Memory comes second. Ten times 46 GB is 460 GB, and at 50 GB a server that is about 10 partitions. With two copies of each you have 20 servers, more than the rate asks for, so memory decides.

Split by a hash of the whole prefix, because every lookup names one exact prefix, and in Chapter 3's Range, Hash and Directory that is the case a hash serves in one partition. A split by first letter is the habit, and you reject it out loud. Letters are far from even, so a few partitions would carry most of the traffic, and you would need a shard map, a table of which letters live where, that exists only to repair the choice.

Then the hot keys. With 6 letters a search, the three shortest prefixes are half of all keystrokes. Counting letters alone, there are 26 of length one, 676 of length two and 17,576 of length three, about 18,000 in all. Assume about 150 bytes each, and that is under 3 MB. So each app server keeps them in memory until the next swap. That is the local tier of Chapter 2's When the Cache Hurts, with no expiry to choose, and 300,000 keystrokes a second never reach a partition.

The bill is a load balancer and a routing tier of app servers, which now know the short prefixes and where each long one hashes, and which hold the query text, 12 GB at this size, because a partition keeps only IDs. That leaves the partitions about 450 GB, still about 10 of them. A swap now rolls through the fleet one server at a time, so two versions serve side by side and one user may see two lists. And a removed term has one more place it must reach.

The Client

"You've scaled the servers for 600,000 requests a second. Did the browser need to send all of them?" No, and this is the question you held back in the first design. The browser changes in three ways. It waits about 50 milliseconds after a letter, which catches the letters that come in a burst. It reuses what it holds: a prefix typed again, or a longer prefix under an answer that listed fewer than five, since fewer than five means that answer already holds everything beneath it. And it ignores a late answer for a prefix the user has passed, or a slow "ap" overwrites "app".

Assume the wait and the reuse drop one request in three, so 600,000 becomes 400,000. Because everyone sees the same five, the browser and the edge may hold answers for hours, the promise of Chapter 2's The Edge: CDNs as a Black Box. Take the short prefixes as half of what remains, and they stop at the edge. That leaves 200,000 a second reaching the origin. The reader you parked in Scope, 225 milliseconds away, now gets common prefixes from somewhere nearby.

It costs 50 of the 200 milliseconds, out of the 100 Scope left spare, so 50 remain for a slow connection and drawing. It also costs logic on every client, with old versions that never update, and edge answers that outlive a swap or a removal by their expiry. The index count does not change, because memory set it. Two hundred thousand a second would take 4 servers at 50,000 each, and the index still asks for 20. What this buys is a smaller app tier, less egress, and the far reader.

Two Paths on One Board

The fast path now runs from a browser with a short wait and a local map of answers, to the edge, on a miss to a load balancer, to app servers holding the short-prefix table and the query text, and on to an index in about 10 hash partitions with two copies each. The slow path sits beside it: search log, count job, builder, a versioned file in object storage, and the swap.

Say the separation in so many words, since the rest of the round leans on it: "There are two paths now, and they never touch. The fast path only reads, so copies are free. The slow path only writes files, so it can take an hour and nobody waits."

The full design
Fast path Slow path Browsershort wait, local map Edgeshortest prefixesNEW App serversprefixes, query textNEW Load balancerany serverNEW Index partitions10, two copies eachNEW Object storageversioned fileNEW Buildernew index, block listNEW Search logfinished searches Count jobonce a day prefix miss long prefix counts swap readwriteasynccache missNEWsince the first design
Interview Pitfalls
  • Answering the rate and the memory with one change, when they have different fixes. The interviewer asks which limit it fixed, and one of them is still there.
  • Sharding by first letter out of habit, then explaining a shard map that only repairs the choice.
  • Treating the client as out of scope, on a problem where it is a third of the load.
  • Adding the wait without saying what it spends of the 200 milliseconds.
What Interviewers Listen For
  • The index called read-only between swaps, with the consequence drawn: copies need no coordination.
  • The working that short prefixes are half the traffic and fit in 3 MB.
  • The swap's cost in memory and the rollback, in one sentence.

Knowledge Check

Storing each prefix's top five on its node ends the search. What does that cost?

  • A search of the whole subtree the first time a prefix is requested
  • About 20 GB of memory, and lists that one new count can rewrite
  • A network call to object storage on each lookup that misses the list
  • Less exact answers, since each list holds only an estimate of the top

Why does updating the live index in place lose to a daily rebuild here?

  • Each of 10,000 searches a second checks up to 24 lists readers depend on
  • A read-only index cannot be changed at all without restarting the server
  • Counted searches arrive too slowly to keep a live index worth reading
  • The search log holds 50 GB a day, which is too much to apply in memory

At ten times the size, what sets the number of servers holding the index?

  • The rate: 600,000 keystrokes a second at 50,000 a server is 12 servers
  • The letters: each of the 26 first letters needs a partition of its own
  • The memory: 460 GB at 50 GB a server is 10 partitions, 20 with copies
  • The swap: each of the 12 rate servers needs a spare for the second index

What does the browser's 50-millisecond wait spend?

  • Bandwidth, for a second request that repeats the letters it held back
  • Edge memory, because every answer must now be held there for longer
  • A quarter of the 200-millisecond gap, gone before the request leaves
  • Server time, because each request now brings more letters to search

You got correct