AlgoViz

Design Search Autocomplete (Typeahead)

medium 45 min

Suggest ten likely searches before a person finishes typing, within 100 ms, for 700,000 requests a second.

See it run

Answer a prefix, read a stored list, rebuild the index, catch a trend and rank.

Operations

Answer a prefix

From key press to list, on a path where every cache misses.

Step 1 of 15

Type and wait

Our systemClientCDN edgeGatewaySuggest serviceindexRedisRanker

prefix

ho

pause

80 ms

The person types ho. The client waits 50 to 100 ms for a pause. Why: ten key presses become about four requests, by assumption.

Step 1: Type and wait

def suggest(prefix, lang):    key = (VERSION, lang, normalise(prefix))    if hit := ranked_cache.get(key):        return hit    candidates = index.top(key, 100)    try:        best = ranker.score(candidates, timeout=0.020)    except Timeout:        best = candidates            # stored order    best = [c for c in best if not blocked(c)][:10]    ranked_cache.set(key, best, ttl=60)    return best
Latency
about 60 ms
Load
700,000/s peak
Edge answers
70% (assumed)

The filter runs after ranking too, so a removal works before the next build.

In the real world

The same search autocomplete doing real jobs. Pick one and step through it.

Traffic grows to three or four times normal.

Step 1 of 4

Normal peak

Our systemClientCDN edgeGatewaySuggest serviceindexRedisRanker
Origin
210,000/s

700,000 requests a second. The edge takes 70%.

Step 1: Normal peak

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Searching the subtree

    critical

    One letter can have millions of queries below it.

    Wrong
    node = find(prefix)return best(walk(node))
    Right
    return find(prefix).top[:10]
  • Writing to the live tree

    major

    58,000 searches a second would change lists that readers use.

    Wrong
    index.add(query)
    Right
    kafka.send(query)   # next snapshot
  • Pattern in a Redis delete

    major

    DEL takes exact key names, so nothing is removed.

    Wrong
    redis.delete("suggest:h*")
    Right
    key = f"suggest:{VERSION}:{prefix}"
  • Showing every reply

    major

    The reply for an older prefix may arrive last.

    Wrong
    show(reply.items)
    Right
    if reply.number == latest:    show(reply.items)
  • Timestamps as trend scores

    major

    They show which query was last seen, not how often.

    Wrong
    zadd("trending", {query: now})
    Right
    zincrby(f"trend:{minute}", people, query)

Interview tips

  • Open with the insight

    • Wide prefixes are few and repeated.
    • So compute and cache them.
  • Know the numbers

    • 700,000 a second at peak.
    • 23 GB index.
    • 95.5% answered by caches, assumed.
  • Two speeds

    • Hourly snapshot.
    • Overlay in minutes.
    • Device history at once.
  • Fail softly

    • Stored order, then stale, then empty.
    • Search must not wait.
    • Removal in seconds.