Books Deep-Read · System Design Interview Vol 1 · Ch 13

Design a Search Autocomplete System

System Design Interview Vol 1 · Ch 13 · Alex Xu · 2020

中文 →

What is this chapter about?

You type two letters into a search box and a list of suggestions drops down; you tap one and you're gone. That's search autocomplete. Chapter 13 of System Design Interview asks you to build it from scratch. It looks like the most modest problem in the book, and it has the most lopsided ratio between reading and writing of any chapter in it.

A strange thing first

You probably assume autocomplete is "searching for you while you type." It's the opposite — it never searches. If it actually ran a search, you'd have finished typing the word first. What it does is look up a table that was sorted long ago: every letter you press just collects an answer that was written down in advance.

Why this was hard

The difficulty is volume. Ten million people searching ten times a day is a hundred million searches; but one search takes about twenty keystrokes, and every keystroke is its own request — so the backend absorbs two billion requests a day, twenty thousand-odd per second, double that at peak. And each one has to come back in the blink of an eye; any slower and the dropdown visibly stutters. Asking a database to sift billions of past searches for "the five most popular ones starting with tr" is too slow even once, let alone twenty thousand times a second.

How it pulls this off

Two moves.

First, arrange every past search into a tree of forks, letter by letter: press t and you take one fork, press r and it forks again — every junction in the tree stands for one beginning. Reaching the "tr" junction then depends only on how many letters you typed, and not at all on whether the store holds a hundred million rows or ten billion.

The second move is the real trick: plant a signpost at every junction ahead of time, reading "from here on down, the five most popular are these." Now the query never has to walk any further — arrive at the junction, copy the sign, done. What gets written on the signs is recomputed overnight, once a week, from the previous week's search logs, and never crosses paths with the daytime queries at all.

What it costs you

The price is plain: the sign was planted last week, so a phrase that caught fire yesterday won't be suggested today — getting breaking terms in within minutes means building a second, real-time pipeline, and complexity and cost go up together. Most products don't need it.

One line to remember

Autocomplete isn't search, it's a lookup: arrange popular searches into a tree that forks letter by letter, and write "the top five" into every junction ahead of time. Daytime just fetches signs; rewriting them is an offline job that runs once a week.

Want the mechanisms, the numbers and the diagrams? → Switch to the deep read