All lessonsDay 14B-Building blocks2026-10-10

Design Search Autocomplete: Trie, Sampling, Sharding

You type dinner into Google and suggestions appear before you finish the word. Type d and you get results. Type di and the list changes again. The system answers every keystroke in under a tenth of a second.

24k / 48k QPS24,000 QPS average, 48,000 peak: 10 million users x 10 searches x 20 keystrokes, divided by 86,400 seconds, times 2 for peak.
100 ms100 ms budget: slower than this causes visible stuttering.
Top 55 suggestions: ranked by historical frequency, prefix match only.
0.4 GB/day0.4 GB new per day: 20 percent of queries are new, 20 bytes each.

Key points

O1Derive QPS and storage growth from DAU, searches, characters, and new query ratio.
O2Break down a prefix lookup into find, collect, and sort steps with Big-O for each.
O3Argue when to rebuild weekly versus update a node, and when to add a shard.
01

Problem: every keystroke is a query


Requirements for this lesson:

  1. (1)Fast response time: return within 100 ms.
  2. (2)Relevant: match only at the beginning of the query.
  3. (3)Sorted: top 5 by historical frequency.
  4. (4)Scalable: handle high traffic volume.
  5. (5)Highly available: stay up when part of the system is offline, slow, or has network errors.

Scope limits: English only. Lowercase alphabetic characters only. No spell check or autocorrect.

Back of the envelope math:

Exhibit 1: QPS and growth calculator

Drive it: move the sliders. The math below tracks the draft formula exactly. Try 20 searches per day or 30 characters and watch average QPS cross the 48,000 peak line.

10M
10
20
20%
Average QPS
23,148

DAU x searches x chars / 86,400

Peak QPS (2x)
46,296

average x 2

New data / day
0.40 GB

DAU x searches x 20 bytes x new %

Same fanout as typing dinner: 6 requests for 6 prefixes. Every keystroke is a backend query unless cached.

High level design splits into two services:

The naive query path is one table with query and frequency columns:

Show code: naive SQL
SELECT * FROM frequency_table WHERE query LIKE 'prefix%' ORDER BY frequency DESC LIMIT 5

Type tw and you might get twitter, twitch, twilight, twin peak, twitchprime. This works for small data. It breaks (4) at large scale because the database becomes the bottleneck on every keystroke.

02

Mental model: a tree that remembers winners


Picture a trie (pronounced try, from retrieval). It is a tree for strings.

Example paths: tree, try, true, toy, wish, win.

To rank results, each query node also stores frequency:

The trick is this: every node also remembers the winners below it. The node for be stores [best: 35, bet: 29, bee: 20, be: 15, beer: 10]. The node for bu stores [buy: 14]. Reading suggestions is then just reading a short list already sitting on the prefix node.

Exhibit 2: trie explorer, one post end to end

Drive it: type a prefix or tap a chip. The explorer walks the same example trie from the draft and reads the cached top list sitting on that node. No subtree walk at read time.

    Follow one key: prefix be maps to [be: 15, bee: 20, beer: 10, best: 35] style entries in the draft table, ranked best first. Prefix bee maps to [bee: 20, beer: 10]. Prefix bu holds only [buy: 14].
    03

    Mechanism: from keystroke to top 5


    Define p as prefix length, n as total nodes, c as children of a node.

    Basic lookup for top k, with k = 2 and prefix tr:

    Step 1. Find the prefix node tr. Cost: O(p).
    Step 2. Walk the subtree and collect valid children that form queries. Here: [tree: 10], [true: 35], [try: 29]. Cost: O(c).
    Step 3. Sort and take top k. Here: [true: 35], [try: 29]. Cost: O(c log c).

    Total: O(p) + O(c) + O(c log c). This breaks (1) in the worst case because it can walk the whole trie.

    Two optimizations fix the path:

    A. Limit max prefix length. Users rarely type long queries. Cap p at about 50. Find becomes a small constant, effectively O(1).

    B. Cache top queries at each node. Since users need only 5 to 10 suggestions, store top 5 on every node at build time. Return becomes O(1).

    Result after both: O(1) to find the node plus O(1) to return the cached list.

    Exhibit 3: lookup stepper for prefix tr, k = 2

    Drive it: press Next or Play. Each step lights the active stage and shows the Big-O cost from the draft.

    Find trO(p), p = 2 here
    CollectO(c): tree 10, true 35, try 29
    Sort top 2O(c log c): true 35, try 29
    Cached O(1)cap p at 50, store top 5
    1. Find the prefix node tr. Walk 2 chars from root. Cost O(p).
    2. Walk the subtree and collect valid children: [tree: 10], [true: 35], [try: 29]. Cost O(c).
    3. Sort and take top k = 2: [true: 35], [try: 29]. Cost O(c log c). Total O(p) + O(c) + O(c log c).
    4. Optimized: cap p at about 50 and cache top 5 per node. Find plus return is O(1) + O(1).
    Without caching the worst case walks the whole trie and breaks (1). With caching the read is a single list lookup.

    Live path in production:

    1. Browser or app sends search?q=di through AJAX. AJAX avoids a full page refresh.
    2. Request hits a load balancer, then an API server.
    3. API server reads Trie Cache, a distributed in memory cache holding a weekly snapshot of the trie.
    4. On cache hit, return the 5 cached queries.
    5. On cache miss, replenish from Trie DB. A miss happens when a cache server is out of memory or offline. This path protects (5).

    Failure case to predict: Trie Cache loses a hot prefix shard. Latency jumps because API servers fall through to Trie DB for the same prefix at 48,000 peak QPS. The fix is replenishment plus browser caching. Google caches autocomplete in the browser for one hour with cache-control: private, max-age=3600. That absorbs repeat typing without touching the backend.

    Exhibit 4: live path and hot shard failure

    Drive it: toggle hit versus miss, then press Lose hot shard to replay the failure at 48,000 peak QPS. Watch latency and where repeat keystrokes are absorbed.

    BrowserAJAX q=di, no refresh
    Load balancerto API server
    API serverreads Trie Cache
    Trie Cacheweekly snapshot
    Latency
    12 ms hit

    Hit path: Browser to LB to API to Trie Cache. Returns 5 cached queries in about 12 ms, inside the 100 ms budget.

    Miss path replenishes from Trie DB and protects (5). Browser cache with max-age=3600 holds suggestions for one hour.
    04

    Weakness, fix, and price


    Weakness 1: real time updates are too expensive.
    Updating the trie on every query slows the query service and wastes work because top suggestions change little day to day. This breaks (1) and (4).

    Fix: move writes offline. The pipeline is:

    Price: suggestions go stale for a week. A breaking news query will not appear until the next build.

    Exhibit 5: weekly offline pipeline

    Drive it: step through the write path. Reads stay fast because all heavy work happens offline on a schedule.

    Analytics Logsappend only, raw
    Aggregatorsweekly counts
    Aggregated Datatime + frequency
    Workersasync build
    Trie DBpersistent trie
    Trie Cacheweekly snapshot
    Query serviceuntouched by writes
    Reads O(1)top 5 per node
    1. Queries append to Analytics Logs. No index, no write to the serving trie, so (1) holds.
    2. Aggregators reshape huge logs into usable counts, weekly in this design.
    3. Aggregated Data holds weekly rows with time and summed frequency.
    4. Workers build the trie asynchronously on schedule.
    5. Built trie lands in Trie DB, the persistent store.
    6. Trie Cache takes a weekly snapshot for fast reads. Price: one week of staleness.
    Breaking news waits for the next build. Twitter style products shorten the interval instead.

    Weakness 2: logging everything costs too much.
    Fix: data sampling. Log only 1 out of every N requests. Price: frequencies are approximate. For top 5 ordering that error is usually acceptable.

    Exhibit 6: sampling simulator

    Drive it: raise N to log fewer requests. Each dot is a keystroke for one post. Lit dots are logged. Ordering of the top 5 usually survives even when counts are approximate.

    1 in 5
    loggedskipped

    Sampling cuts log volume by N while keeping top 5 order mostly stable. That is the price worth paying.

    Weakness 3: deletes cannot wait a week.
    Hateful, violent, sexually explicit, or dangerous suggestions must vanish now.

    Fix: add a filter layer in front of Trie Cache. It removes unwanted suggestions per filter rules. Physical removal from the database happens asynchronously so the next weekly build is clean. Price: one more hop and a rule set to maintain.

    Filter checkTry the explorer above with prefix tr: imagine one entry flagged hateful. The filter layer drops it before the response leaves, even though Trie DB still holds it until the async cleanup and next weekly build.

    Weakness 4: one server cannot hold the trie.
    Naive sharding splits by first character. Two servers: a to m and n to z. Three servers: a to i, j to r, s to z. Up to 26 servers for 26 letters. Beyond that, shard on second or third level. Queries starting with a split into aa to ag, ah to an, ao to au, av to az (illustrative ranges).

    This breaks (4) because distribution is uneven. Far more words start with c than with x.

    Fix: analyze history and shard by load. A shard map manager keeps a lookup of where rows live. If s alone has about as many queries as u through z combined, keep s on one shard and u to z on another. Price: routing depends on the map. The map must be maintained and consulted.

    Exhibit 7: sharding by distribution, not alphabet

    Drive it: switch schemes. Naive alphabet splits overload the c and s shards. Load based sharding balances by history via the shard map manager. Type a prefix to see its shard.

    Illustrative ranges for second level splits of a: aa to ag, ah to an, ao to au, av to az. Beyond 26 servers, shard deeper.

    Trie storage has two options, each with a price:

    OptionHow it worksPrice
    Document storeSerialize the weekly trie snapshot, store as a document. MongoDB is an example.Simple snapshot and replace. Must load and deserialize to serve.
    Key-value storeMap every prefix to a key. Map node data to a value. Prefix be maps to [be: 15, bee: 20, beer: 10, best: 35]. Prefix bee maps to [bee: 20, beer: 10].Fast key lookup per prefix. Many keys to write on each rebuild.

    Trie update has two options:

    05

    Code: a tiny trie that caches top 5


    This Python example follows the chapter mechanism. It builds a trie, stores frequency, and caches top 5 at each node. Values below are illustrative.

    Show code: runnable Python trie
    class Node:
        def __init__(self):
            self.children = {}  # char -> Node, max 26 in English lowercase
            self.is_query = False
            self.freq = 0
            self.top = []  # cached list of (freq, query), max 5
    
    class Autocomplete:
        def __init__(self, k=5):
            self.root = Node()
            self.k = k  # line that matters: matches requirement (3), top 5
    
        def insert(self, query, freq):
            node = self.root
            path = [node]
            for ch in query:  # line that matters: capped at ~50 chars in prod for O(1) find
                node = node.children.setdefault(ch, Node())
                path.append(node)
            node.is_query = True
            node.freq = freq
            # line that matters: Option 2 update, fix ancestors up to root
            for i, anc in enumerate(path):
                prefix = query[:i]
                self._refresh(anc, prefix, query, freq)
    
        def _refresh(self, node, prefix, query, freq):
            # keep every candidate under this prefix, then keep best k
            candidates = {}
            self._collect(node, prefix, candidates)
            ranked = sorted(candidates.items(), key=lambda x: -x[1])
            node.top = ranked[:self.k]  # line that matters: space for time
    
        def _collect(self, node, prefix, out):
            if node.is_query:
                out[prefix] = node.freq
            for ch, child in node.children.items():
                self._collect(child, prefix + ch, out)
    
        def search(self, prefix):
            node = self.root
            for ch in prefix:
                if ch not in node.children:
                    return []
                node = node.children[ch]
            return node.top  # line that matters: O(1) return, no subtree walk
    
    # illustrative frequencies from the chapter shape
    ac = Autocomplete(k=5)
    for q, f in [("best", 35), ("bet", 29), ("bee", 20), ("be", 15), ("beer", 10), ("buy", 14)]:
        ac.insert(q, f)
    print(ac.search("be"))  # expect best, bet, bee, be, beer in order

    Notes on lines that matter: k=5 encodes requirement (3). Capping prefix length makes find O(1). Caching top on insert trades space for time. Updating the full ancestor path shows why direct updates are slow. Returning node.top shows why reads stay fast and why weekly rebuilds are preferred.

    06

    Field guide: who uses which piece and why


    07

    Interview ears and judgment quiz


    Follow up: How do you support multiple languages?
    Answer: store Unicode characters in trie nodes. Unicode covers writing systems modern and ancient. Sharding by first character no longer means 26 shards.

    Follow up: What if top queries differ by country?
    Answer: build different tries per country and store them in CDNs for response time. Why: ranking is local popularity, not global.

    Follow up: How do you support trending real time queries?
    Answer: the weekly design will miss them because workers have not rebuilt yet and a full build takes too long. Ideas only: shard to shrink the working set, weight recent queries higher in ranking, and move to stream processing since data arrives continuously.

    Judgment quiz

    Q1Predict: Trie Cache evicts prefix tr during peak 48,000 QPS. What happens to latency and to Trie DB load, and which two caches absorb the next identical keystrokes?

    Latency jumps because every tr keystroke hits Trie DB at peak QPS. After replenish, Trie Cache serves again, and browser cache with max-age 3600 absorbs repeat typing for one hour without backend hits.

    Q2Compare: weekly replace versus direct node update for beer 10 to 30. Which protects (1) at 24,000 QPS and which risks stale hateful suggestions unless paired with what layer?

    Weekly replace keeps the query path O(1) and protects (1) at 24,000 QPS. Direct update must fix bee, be, b, and root, so it is slow. Weekly builds go stale for a week, so hateful suggestions need the filter layer in front of Trie Cache with async DB cleanup.

    Q3Choose under tradeoff: logging budget is cut in half but (1) must hold. Do you sample 1 in N more aggressively, shorten the rebuild interval, or add shards? Argue cost to accuracy, freshness, and capacity.

    Sampling 1 in N more aggressively cuts log volume while (1) holds because reads stay O(1) from cache. Price is approximate frequencies, acceptable for top 5. Shortening rebuilds hurts freshness cost and build load. Adding shards adds capacity for (4) but does not cut logging cost.

    Sources: draft requirements and math (10M DAU, 100 ms, top 5, 0.4 GB per day); trie lookup with O(p) plus O(c) plus O(c log c) and O(1) cached path; weekly pipeline, sampling, filter layer, and prefix sharding patterns; Python trie with cached top 5.