AI Hints
Home›System Design Tutorial›Case Study: Autocomplete and Key-Value
System Design · Lesson 109 of 120

Search Autocomplete

Tries and top results.

⏱ 2 min read▶ Video at 2:12:33🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

You type b l u into Shoply's search box, and suggestions appear instantly. Blue mug, blue towel, bluetooth speaker. They must appear in under a hundred milliseconds, as you type every letter.

Search Autocomplete
From the video: Search Autocomplete
  • Type b-l-u
  • Suggestions appear
  • Under 100 ms, every letter

A trie with top results

The classic structure is a trie, a tree where each step is one letter. Every node stores the most popular searches that start with that prefix. So answering is just walking down a few letters, and reading the stored list. Run it. Typing b l u returns the top three searches, ordered by how often people search them.

trie.pypython
searches = {"blue mug": 900, "blue towel": 400, "bluetooth speaker": 750,
            "black pot": 300, "blue lamp": 120}

trie = {}
for phrase, count in searches.items():
    node = trie
    for ch in phrase:
        node = node.setdefault(ch, {"_top": []})
        node["_top"] = sorted(node["_top"] + [(count, phrase)], reverse=True)[:3]

def suggest(prefix):
    node = trie
    for ch in prefix:
        node = node.get(ch, {"_top": []})
    return [p for _, p in node["_top"]]

print("bl  ->", suggest("bl"))
print("blu ->", suggest("blu"))
Output
bl  -> ['blue mug', 'bluetooth speaker', 'blue towel']
blu -> ['blue mug', 'bluetooth speaker', 'blue towel']

Why store the top results

Storing the top results in every node is the key trick. Without it, we'd have to search the whole subtree below the prefix, and sort, on every keystroke. With it, a suggestion is a few steps down the tree and one read. We trade memory, and slower updates, for very fast reads.

keyvalue
Each nodestores its top 3–10
Querywalk the prefix, read
Costmore memory
Updatesrebuilt periodically

Summary

A trie stores phrases letter by letter, and keeping the top results at every node makes suggestions instant. Next, running autocomplete at scale.

Key takeaways
  • One letter per step
  • Top results in each node
  • Fast reads, slow updates
Next up: Autocomplete at Scale — fast suggestions