Skip to content
Visual explainer 3h to learn 5 steps

Search autocomplete

Design a low-latency typeahead with tries, ranking and periodic rebuilds.

By Invicly Tech, , in System Design Deep Dive. About 12 minutes to read.

Topic 26 of 33

In short

Search autocomplete suggests popular completions as a user types, within about 100 ms. Precompute top-k suggestions per prefix in a trie built offline from query logs, serve it from memory, and cache aggressively.

Explained simply

Typeahead, or autocomplete, is the list of suggestions that appears under a search box while you type. Type 'how to b' and you may see 'how to boil an egg'. It saves typing, fixes spelling and guides people toward searches that will find something.

The hard part is speed. A new request goes out on nearly every keystroke, and the suggestions must appear within about 100 milliseconds or the feature feels laggy. That is far less time than a normal search takes, so the system cannot do much work per request.

The trick is to do the heavy work ahead of time. A background job counts which searches are popular, builds a prefix tree (called a trie) from them, and stores the best few suggestions for every prefix right in the tree. Answering a request is then just a quick lookup in memory.

Popular searches change, especially during news events, so the tree is rebuilt regularly and swapped in all at once. Caches in the browser, at the edge, and on the servers handle the very common short prefixes so most requests never reach the core service.

Press Play on a diagram to walk through it one step at a time.

FlowHigh-level architecture
  1. 1
    Query logs

    Every search is logged

  2. 2
    Aggregation job

    Count query frequencies hourly or daily

  3. 3
    Trie builder

    Build trie with top-k per node

  4. 4
    Suggestion servers

    Serve trie snapshot from memory

  5. 5
    Cache and CDN

    Cache hot short prefixes

  6. 6
    Client

    Debounced requests per keystroke

SequenceFetching suggestions
Browser
Cache
Suggest server
  1. 1User types "syst", debounce 50 ms
    Browser to Browser: User types "syst", debounce 50 ms
  2. 2GET /suggest?q=syst
    Browser to Cache: GET /suggest?q=syst
  3. 3Miss, forward
    Cache to Suggest server: Miss, forward
  4. 4Walk trie to node "syst"
    Suggest server to Suggest server: Walk trie to node "syst"
  5. 5Top 5 stored at node
    Suggest server to Cache: Top 5 stored at node
  6. 6system design, systemd, ...
    Cache to Browser: system design, systemd, ...
CompareCustom trie service vs search engine suggester
Custom trie service
  • Top-k precomputed per node
  • Very low, predictable latency
  • Full control of ranking
  • You build and run the pipeline
Search engine suggester
  • Elasticsearch completion suggester
  • In-memory FST per shard
  • Less code to maintain
  • Ranking limited to its features

In depth

Requirements and the latency budget

Clarify: suggestions are prefix matches of past popular queries; show 5 to 10; support many languages; filter offensive terms; personalisation and spelling correction are nice to have. The key non-functional requirement is latency: under about 100 ms from keystroke to suggestions on screen.

Split that budget. Network round trip on mobile might take 30 to 60 ms, rendering about 10 ms, so the server has maybe 10 to 20 ms. That rules out querying a database or scanning anything at request time.

Estimate volume too. With 10 million daily users doing 10 searches each, and requests on about 6 of the keystrokes per search, that is 600 million requests a day: around 7,000 per second on average and perhaps 20,000 at peak. Reads massively dominate; the index only changes when it is rebuilt.

  • Server budget: about 10 to 20 ms
  • Reads only on the hot path; writes happen in batch
  • Top 5 to 10 suggestions per prefix

Fitting the trie in memory

A plain trie with one node per character is large. Three techniques keep it manageable. First, only include queries that were searched at least a few times in the period; the long tail of one-off queries is huge and rarely useful as a suggestion. Second, compress chains of single-child nodes into one node holding a string (a radix tree), which cuts the node count dramatically. Third, store the top-k list at each node as small integer IDs pointing into a table of query strings, not as copies of the strings.

Rough maths: 50 million distinct queries kept, about 4 to 5 nodes each after compression, so a few hundred million nodes; at tens of bytes each, that is on the order of tens of GB. That fits on a large-memory server, so many systems simply replicate the whole trie on every suggestion server. When it does not fit, shard by prefix, choosing split points by traffic rather than alphabet, because far more queries start with s than with x.

Ranking suggestions

Raw all-time counts make suggestions stale: last year's big event would stay on top forever. A common fix is time decay: each day's count is multiplied by a decay factor, so score = sum of count_day x 0.9 ^ (days ago), for example. Recent popularity weighs most, and old spikes fade.

Other signals refine the order: freshness (trending queries from the last hour), location (people in Mumbai and London type the same prefix for different things), language, and personal history (your own past searches can be merged in on the client or by a small per-user lookup). Quality signals matter too: prefer queries that led to clicks, not ones people immediately rewrote.

Filtering is part of ranking: remove offensive, dangerous or legally problematic suggestions with a blocklist and classifier at build time, with an emergency override list that is applied instantly at serve time.

The build pipeline

Search logs flow into a log system such as Kafka and land in a data lake. A batch job (for example in Spark), daily or hourly, aggregates counts per normalised query (lower-cased, trimmed), applies decay and filters, and keeps queries above a threshold. A builder then creates the trie with top-k at every node, serialises it into a compact file, and stores it with a version number in object storage.

Suggestion servers download the new version, load it into memory next to the old one, run a few sanity checks (does 'face' still suggest 'facebook'?), and then atomically switch a pointer. Requests in flight finish on the old trie; new ones use the new trie. Rolling back is just switching the pointer back.

For trending topics, a streaming job counts the last few minutes of queries and feeds a small trending overlay that the server merges with the main trie's results.

CycleThe index rebuild loop
  1. 1
    Collect logs

    Search events into Kafka and the lake

  2. 2
    Aggregate

    Counts with decay, filters applied

  3. 3
    Build trie

    Top-k per node, serialised with a version

  4. 4
    Validate

    Size and sanity checks

  5. 5
    Swap in

    Load beside the old one, flip a pointer

  6. Back to step 1

Caching at every layer

Most typeahead traffic is for very short, very common prefixes, which makes caching extremely effective.

In the browser: debounce input (wait about 50 to 150 ms after a keystroke), cancel requests that are no longer needed with AbortController, cache responses per prefix for the session, and reuse earlier results: if 'syst' returned 10 items, the client can filter those locally for 'syste' while waiting for fresh results.

At the edge: responses for prefixes of one or two characters are identical for everyone in a region, so a CDN can cache them for a few minutes with a Cache-Control max-age. Personalised results should not be CDN-cached, or must be cached per user.

On the servers: a small in-process LRU cache of hot prefixes avoids even the trie walk. Together these layers mean the trie servers see only a fraction of keystrokes.

LayersWhere a suggestion request is answered
  1. 1
    Browser

    Debounce, session cache, local filtering

  2. 2
    CDN edge

    Short, non-personal prefixes, cached minutes

  3. 3
    Suggestion server cache

    In-process LRU of hot prefixes

  4. 4
    In-memory trie

    Walk the prefix, read stored top-k

  5. 5
    Trending overlay

    Merged recent spikes

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Define requirements and latency goals~35m
  2. 2
    Estimate query volume~35m
  3. 3
    Design a trie with top-k suggestions~35m
  4. 4
    Rank by popularity~35m
  5. 5
    Rebuild and cache the index periodically~35m

Key points

  • Store top-k completions at each trie node so lookup is O(prefix length).
  • Rebuild the trie offline and swap snapshots instead of updating live.
  • Shard the trie by prefix range when it no longer fits one machine.
  • Debounce keystrokes and cache results in the browser too.

Key terms

Tap a card to flip it. 0/5 known

Examples

text
Scale: 10M DAU * 10 searches * 6 keystrokes = 600M/day
  ≈ 7,000 QPS average, ~20,000 QPS peak

TrieNode {
  children: map<char, TrieNode>
  top5: [("system design", 98000), ("systemd", 41000), ...]
}

suggest(prefix): node = walk(prefix); return node.top5

Volume estimate and a trie node with cached top-k.

Building a trie with top-k at each node

This builder inserts each query with its score and, at every node along the way, keeps the k best queries for that prefix. Step 1: walk or create a node per character. Step 2: at each node, add the query and keep only the top k by score. Step 3: a lookup walks the prefix and returns the stored list, with no subtree search. Real builders sort queries first and use compact arrays, but the idea is the same.

python
import heapq
class Node:
    def __init__(self): self.kids, self.top = {}, []

def build(queries, k=5):
    root = Node()
    for q, score in queries.items():
        node = root
        for ch in q:
            node = node.kids.setdefault(ch, Node())
            node.top = heapq.nlargest(k, node.top + [(score, q)])
    return root

def suggest(node, prefix):
    for ch in prefix:
        if (node := node.kids.get(ch)) is None: return []
    return [q for _, q in node.top]

Time-decayed ranking in practice

Two queries share the prefix 'world'. 'world cup final' got 1,000,000 searches 30 days ago and few since. 'world news today' gets 60,000 searches every day. Step 1: use decay 0.9 per day. Step 2: the old spike now counts 1,000,000 x 0.9^30, about 42,000. Step 3: the steady query's score is roughly 60,000 x (1 + 0.9 + 0.81 + ...), which approaches 60,000 / 0.1 = 600,000. Step 4: 'world news today' ranks first, as users expect. Tune the decay rate so real spikes rise within hours but fade within weeks.

Quick reference

  • Budget: about 100 ms end to end, about 10 to 20 ms on the server
  • Store top-k at every trie node so a lookup is a walk of the prefix length
  • Prune rare queries and compress single-child chains (radix tree)
  • Rank with time decay: score = sum of daily counts x decay^age
  • Rebuild offline, load beside the old trie, then flip a pointer
  • Debounce 50 to 150 ms and cancel stale requests in the browser
  • CDN-cache short non-personal prefixes; never CDN-cache personal results
  • Shard by prefix using traffic-based split points, not the alphabet

Common mistakes

  • Computing top-k by traversing the whole subtree at query time.
  • Updating the trie in real time under heavy read load.
  • Forgetting to filter offensive or unsafe suggestions.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why is top-k stored at each trie node rather than computed per request?

Question 2

2Which change helps trending queries appear quickly without rebuilding the whole trie every minute?

Question 3

3Why should trie shards be split by traffic rather than one shard per letter?

Question 4

4Which responses are safe to cache at a CDN?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Estimate peak suggestion QPS for 50 million daily users, 4 searches each, 8 characters typed per search, with debounce cutting requests to half the keystrokes and peak at 3x average.

  2. Exercise 2medium

    Write browser JavaScript that debounces the input by 100 ms, cancels the previous request, and caches results per prefix.

  3. Exercise 3hard

    A harmful suggestion is trending and legal asks for it to be removed within 5 minutes. The next trie rebuild is in 6 hours. Design the mechanism.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a trie the only way to build autocomplete?
No. Search engines offer prefix suggesters (Elasticsearch's completion suggester uses an in-memory finite state transducer), and smaller apps can use a sorted list with binary search or an indexed prefix query. Tries with precomputed top-k shine at very high traffic.
How do I add spelling correction to typeahead?
A common approach is fuzzy prefix matching that allows one or two character edits (edit distance), tried only when exact prefixes return few results, because fuzzy search is much more expensive.
Should autocomplete be personalised?
It helps, especially showing a user's own recent searches. Keep it a light layer: merge a short personal list with the global suggestions, and keep personal data out of shared caches.
ShareXLinkedInWhatsApp