System Design

C8

Search autocomplete

A user types a few letters and sees the queries they most likely want, before they finish. The lists change slowly, the reads are many, and each one must be fast.

Not startedSaved in this browser only.
  1. 1Rank at build time, not at read time. Every trie node stores its best 10 queries, so a keystroke is one walk and one list.
  2. 2Build from logs of submitted searches, with time decay, every hour. Add a streaming sketch for what started trending since the last build.
  3. 3Most of the 100 ms is network. Answer short prefixes from the edge and the browser; the server lookup takes under a microsecond.
  4. 4Filters and the personal layer run at read time, on top of the shared lists. The edge then caches what is the same for everyone.
C8
    A

    The prompt

    as the interviewer says it
    "Design the suggestions that appear as a user types a query, ranked by popularity, within 100 ms."
    questionanswer assumed
    How many searches?1 billion a day.
    100 ms from what to what?From a keystroke to the list on screen, p99.
    How many suggestions?5, completions of the typed prefix.
    How fresh?Popularity within an hour; a new trend within minutes.
    Personal?A layer of the user's own recent searches.
    Languages?One trie per language. Spelling correction is a follow-up.
    Unsafe queries?Never suggested; a block takes effect in seconds.

    Before I draw anything, I confirm the scale, how fresh suggestions must be, and whether they are personal.

    B

    Requirements

    as numbers
    functional
    Return the 5 most popular queries that start with the typed prefix.
    Rank by recent popularity; include trending queries.
    Put the user's own recent matches first.
    Never suggest a blocked query.
    non-functionaltarget
    Keystroke to list on screenp99 < 100 ms
    Availability99.9%; fail silent
    Freshness of popularity< 1 h
    New trend visible< 5 min
    A block takes effect< 1 min

    Reads are one per keystroke and the lists change hourly, so I precompute everything and serve from memory and caches.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Lookups per searchone per keystroke; seeded log (measured)≈ 16.4
    Lookups1 B × 16.4 ÷ 86,400≈ 190,000/s; 3× peak ≈ 569,000/s
    Past the edge cache× (1 − 79.6%), the 10,000 hottest prefixes cached≈ 39,000/s at the servers
    Trie memory10 M queries × 532 B (measured per query)≈ 5.3 GB per copy
    Redis, one key per prefix10 M × 6.3 keys × 111 B≈ 7.0 GB
    Response5 × 21 B + JSON ≈ 200 B≈ 304 Mbit/s from the edge
    Search log1 B × 100 B100 GB a day

    Inputs are the assumed answers in panel A. Lookups per search, the edge share and bytes per query come from the lab's seeded log of 20,760 queries. The 10 M distinct queries assume rare queries are dropped. Method: R2.

    About 190,000 lookups a second, 569,000 at peak. The edge takes most of them; the trie for 10 million queries is about 5.3 GB, so one server holds it.

    D

    API

    endpoints, caching, status codes
    callforcachingsuccesserrors
    GET /v1/suggest?q=pi&lang=englobal listpublic, a few minutes, keyed by q and lang200 + 5 items400 too long
    GET /v1/suggest/me?q=pipersonal itemsprivate, no-store200 + up to 2 items401
    GET /v1/search?q=pizza+near+methe search itselfnone200400
    DELETE /v1/me/history/{query}forget one searchnone204404
    PUT /v1/admin/denylist/{query}block a suggestionnone204403
    • The search call, not the suggest call, writes the log. Keystrokes are not searches.
    • Normalise before the cache key: lower case, trimmed, single spaces. "Pi" and "pi" share one entry.

    The global list is a cacheable GET per prefix. The personal layer is a separate private call, so the edge never caches anything personal.

    E

    Data model

    the trie, and the key per store
    a top-3 trie: each node keeps the best 3 below it·pastaianoezzatop at "p"pizza 90pie 70pasta 60top at "pi"pizza 90pie 70pizza dough 40top at "piz"pizza 90pizza dough 40pizza near me 40filled node: a query ends here"sta": a run of one-child nodes, drawn as one" dough" and " near me" continue below "za"
    storekeyholds
    Servicetrie nodeChildren sorted by byte; ids of the best 10 below; a count of queries below.
    Object storagetrie/{lang}/{version}One built trie per language and hour; servers load the newest good one.
    Redishist:{user}List of the last 20 searches: LPUSH, then LTRIM.
    Redistrend:{lang}Sorted set of trending queries by rate, rewritten every minute.
    RedisdenySet of blocked queries, read by servers every few seconds.
    Redisac:{prefix}The alternative design: one sorted set per prefix with its top 10.
    Event logsearchesTime, normalised query, language. The input of every build.

    The figure is the lab's unit-test example: scores are searches a day.

    The trie node stores its children and its top list. Redis holds what changes between builds: history, trending and the denylist.

    F

    The architecture

    click a step; its path lights up
    Browserpause, prefix cacheCDN edgeglobal listsEvent logsubmitted searchesSuggest servicetrie in memoryStream jobsketch, last hourBatch buildhourly, decayedRedishistory, trending, denylistObject storagetrie versions

    Step 1: Type

    • The browser waits for a short pause in typing, then asks for the prefix.
    • It keeps answers in memory, so a backspace costs no request.
    • The edge caches the global list per prefix for minutes.

    If it fails

    The request is slow or fails: show nothing. Suggestions are a convenience; the search box still works.

    Reads go browser, edge, service, memory. Writes are the search log, an hourly build to object storage, and a stream job for trends.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    ServiceTrie with a top list per nodeA lookup is one walk; median 131 ns in the lab.Routing tables, prefix rules
    ServiceCount-min sketch with a heapHeavy queries of the last hour in 152 kB, whatever the number of distinct queries.Heavy hitters (B10)
    RedisSorted sets: ZADD, ZRANGE REV with a countThe key-per-prefix design; also the trending list.Leaderboards
    RedisStrings: GET of a joined listThe smallest key-per-prefix form: 12.3 MB against 14.5 MB.Any precomputed answer
    RedisLists: LPUSH, LTRIMA capped history per user.Recent items
    RedisPipelining130,651 prefix keys loaded in 0.6 s.Bulk loads
    CDNEdge cache keyed by URLThe 10,000 hottest prefixes take 80% of lookups.Static files (B5)
    BrowserA pause before sending; an in-memory map of answersFewer requests; a backspace is free.Any search box
    Event logDurable, replayable streamOne source for the batch build and the stream job.Analytics (B7)

    The trie gives me a sub-microsecond lookup. The edge and the browser absorb most keystrokes. Redis holds the small, fast-changing layers.

    H

    Deep dive: trie or prefix keys

    where the ranking happens
    designper keystrokestatus
    LIKE 'pi%' on a query table, ORDER BY countA range scan and a sort over every matchNot approved
    Trie, rank the subtree at read timeVisits every query under a short prefixNot approved
    Trie with a top 10 per node, in processp50 131 ns, p99 453 ns; 11.0 MBApproved
    Redis sorted set per prefixp50 129 µs, p99 225 µs; 14.5 MBApproved
    Redis string per prefixp50 128 µs; 12.3 MB; no in-place updateRebuilt lists only
    One sorted set, ZRANGE BYLEXReturns matches in alphabetical order, not by popularityNot approved
    Search engine completion suggesterBuilt in; another cluster to runYou already run one

    Lab: 20,760 queries, 130,652 nodes, 130,651 prefix keys, 20,000 typed prefixes drawn by keystroke traffic. Building the trie took 34 ms.

    build the triepseudo code
    build(scores, K):
      FOR EACH query q with score > 0, unless blocked1:
        walk or create one node per byte of q2
        mark the last node: q ends here
      fill(node):                                 // children first3
        candidates = node's own query
                   + top list of every child
        node.top = best K of candidates by score4
    1. 1The safety list removes a query at build time. A read-time denylist covers the hours until the next build.
    2. 2130,652 nodes for 20,760 queries: shared prefixes share nodes.
    3. 3A node's best 10 are among its own query and its children's best 10, so one pass up the tree fills every list.
    4. 4K = 10 stored; 5 are shown, so filters still leave a full list.
    Tested source Go: build
    Go: buildgo
    
    // Build inserts every query with a positive score that skip does not reject, then fills each
    // node's top list bottom-up: a node's best K come from its own query and its children's best K.
    func Build(queries []string, scores []float64, k int, skip func(string) bool) *Trie {
      t := &Trie{K: k, Queries: queries, Scores: scores, root: &node{}}
      t.nodes = 1
      terminal := map[*node]int32{}
      for i, q := range queries {
        if scores[i] <= 0 || (skip != nil && skip(q)) {
          continue
        }
        n := t.root
        for j := range len(q) {
          n = t.child(n, q[j])
        }
        terminal[n] = int32(i)
      }
      var fill func(n *node)
      fill = func(n *node) {
        var cand []int32
        if id, ok := terminal[n]; ok {
          cand = append(cand, id)
          n.below = 1
        }
        for _, e := range n.kids {
          fill(e.n)
          cand = append(cand, e.n.top...)
          n.below += e.n.below
        }
        slices.SortFunc(cand, t.better)
        n.top = slices.Clip(cand[:min(k, len(cand))])
        t.stored += len(n.top)
      }
      fill(t.root)
      return t
    }
    
    look up a prefixpseudo code
    lookup(prefix):
      node = root
      FOR EACH byte b of prefix:
        node = child of node with byte b          // binary search1
        IF none: RETURN []
      RETURN node.top                             // ranked at build time2
    1. 1Children are sorted by byte; a node has at most a few dozen.
    2. 2No sort and no scan at read time. That is why a lookup takes nanoseconds.
    Tested source Go: lookup
    Go: lookupgo
    
    // Lookup walks one node per typed byte and returns the stored top list: no ranking, no scan of
    // the subtree. visited is the number of nodes touched, root included.
    func (t *Trie) Lookup(prefix string) (top []int32, visited int) {
      n := t.root
      visited = 1
      for j := range len(prefix) {
        b := prefix[j]
        i := sort.Search(len(n.kids), func(i int) bool { return n.kids[i].b >= b })
        if i == len(n.kids) || n.kids[i].b != b {
          return nil, visited // no query starts with this prefix
        }
        n = n.kids[i].n
        visited++
      }
      return n.top, visited
    }
    
    the Redis design: one key per prefixpseudo code
    load(trie):                                 // after each build
      FOR EACH node, 1,000 per pipelined round trip1:
        ZADD ac:{prefix} score1 q1 ... score10 q10
    read(prefix):
      ZRANGE ac:{prefix} 0 4 REV2                // one round trip
    1. 1130,651 keys loaded in 0.6 s in the lab.
    2. 2Highest score first. A string key holding the joined list is smaller and is read with one GET.
    Tested source Go: load and read
    Go: load and readgo
    
    // Load writes every prefix up to maxLen bytes, 1,000 prefixes per pipelined round trip. It
    // returns the number of prefixes written.
    func (s Store) Load(ctx context.Context, t *Trie, maxLen int, sorted bool) (int, error) {
      pipe := s.RDB.Pipeline()
      n := 0
      flush := func() error {
        if _, err := pipe.Exec(ctx); err != nil {
          return fmt.Errorf("load prefixes: %w", err)
        }
        return nil
      }
      err := t.Walk(maxLen, func(p string, top []int32) error {
        if sorted {
          zs := make([]redis.Z, len(top))
          for i, id := range top {
            zs[i] = redis.Z{Score: t.Scores[id], Member: t.Queries[id]}
          }
          pipe.ZAdd(ctx, s.zkey(p), zs...)
        } else {
          qs := make([]string, len(top))
          for i, id := range top {
            qs[i] = t.Queries[id]
          }
          pipe.Set(ctx, s.skey(p), strings.Join(qs, "\n"), 0)
        }
        n++
        if n%1000 == 0 {
          return flush()
        }
        return nil
      })
      if err != nil {
        return n, err
      }
      return n, flush()
    }
    
    // Lookup reads the top `show` queries of one prefix: one round trip either way.
    func (s Store) Lookup(ctx context.Context, p string, show int, sorted bool) ([]string, error) {
      if sorted {
        out, err := s.RDB.ZRangeArgs(ctx, redis.ZRangeArgs{Key: s.zkey(p), Start: 0, Stop: show - 1, Rev: true}).Result()
        if err != nil {
          return nil, fmt.Errorf("zrange %q: %w", p, err)
        }
        return out, nil
      }
      v, err := s.RDB.Get(ctx, s.skey(p)).Result()
      if errors.Is(err, redis.Nil) {
        return nil, nil
      }
      if err != nil {
        return nil, fmt.Errorf("get %q: %w", p, err)
      }
      out := strings.Split(v, "\n")
      return out[:min(show, len(out))], nil
    }
    

    I precompute a top 10 per prefix. In process it is a trie: 131 ns and 11.0 MB for the lab log. In Redis it is a key per prefix: 129 µs and 14.5 MB.

    I

    See it: type a query

    recorded from the lab trie: 20,760 queries, 130,652 nodes
    1. pizza near me130,408 a day
    2. piano lessons18,408 a day
    3. pie for two3,070 a day
    4. pillow review1,156 a day
    5. pillow994 a day
    nodes visited: 3
    1. root25 children · 20,760 below
    2. p8 children · 797 below
    3. i4 children · 34 below
    this keystroketrie in the serviceone Redis key per prefix
    WorkWalk 3 nodes, return the stored listOne ZRANGE on ac:pi
    Median time in the lab131 ns129 µs, a network round trip
    Ranking at read timeNone: the build stored the top 10None: the build wrote the top 10

    The page holds every prefix of the 150 most searched queries and of the samples; other prefixes exist in the trie but are not shipped. Scores are searches a day with a 1-day half-life, from a seeded log of 10 M searches a day.

    Each keystroke moves one node down. The list at that node was ranked by the last build, so the work is the walk and nothing else.

    J

    Deep dive: building from the log

    counts, decay, a new trie every hour
    rank"s", 7-day average"s", 1-day half-life
    1stock market today 59,269snow day closures 57,967
    2solar eclipse glasses 56,267stock market today 56,302
    3synonym 25,611synonym 25,076
    4spell check 24,435spell check 24,395
    5speed test 23,263speed test 23,213
    rank"so", 7-day average"so", 1-day half-life
    1solar eclipse glasses 56,267sourdough starter 22,386
    2solar panels 22,458solar panels 22,129
    3sourdough starter 22,421soup recipes 17,644
    4soup recipes 16,916solar eclipse glasses 8,700
    5solitaire 8,268solitaire 8,104

    Searches a day, recorded from the seeded log. One query peaked six days ago; one has grown all week.

    score and shippseudo code
    score(q) = SUM over 7 days d of count[d][q] x w(d)
                 / SUM of w(d)
    w(d) = 0.5 ^ (age of d in days / half-life)   // half-life = 1 day1
    hourly job2: read the counts, score, build, upload
    servers: load the new trie, swap one pointer3
    1. 1Yesterday counts half, two days ago a quarter. A shorter half-life follows news faster and jumps more.
    2. 2Counts per day are a small table; scoring and building take seconds to minutes. The hour is a freshness choice.
    3. 3Readers keep the old trie until the swap; the old one is freed when its last reader finishes.
    Tested source Go: decay
    Go: decaygo
    
    // Scores is each query's searches a day, weighted by age: a search d days old counts
    // 0.5^(d / halfLife), and the sum is divided by the total weight. halfLife = 0 means no decay, a
    // plain 7-day average.
    func (l Log) Scores(halfLife float64) []float64 {
      out := make([]float64, len(l.Queries))
      total := 0.0
      for d := range 7 {
        w := 1.0
        if halfLife > 0 {
          w = math.Pow(0.5, float64(6-d)/halfLife)
        }
        total += w
        for i, c := range l.Counts[d] {
          out[i] += float64(c) * w
        }
      }
      for i := range out {
        out[i] = math.Round(out[i]/total*10) / 10
      }
      return out
    }
    
    • Drop queries searched by too few distinct users: they add memory and can leak private text.
    • Count submitted searches, not keystrokes. A half-typed word is not a query anyone wanted.

    I count submitted searches per day and weight each day by its age with a 1-day half-life. Last week's spike fades, and this week's rise climbs.

    K

    Deep dive: trending, filters, personal

    layers at read time
    "st", hourly build onlywith trending
    stock market todaystorm warning tonight (trending)
    stretching routinestock market today
    study timerstretching routine
    steak near mestudy timer
    stopwatchsteak near me

    The new query had 6,000 searches in an hour of 419,364; the sketch estimated 6,000. Sketch: 7 rows of 5,437 counters, 152 kB, for 20,763 distinct queries.

    "fa", no safety listwith the safety list
    fake id card (blocked)falafel ideas
    fake doctors note (blocked)falafel sauce
    falafel ideasfalafel near me
    falafel saucefalafel for kids
    falafel near mefalafel calories
    "pa", anyonea user who searched "paris museums" and "pad thai near me"
    pasta recipeparis museums (yours)
    pancake recipepad thai near me (yours)
    passport renewalpasta recipe
    parking near mepancake recipe
    paint colorspassport renewal
    serve one prefixpseudo code
    serve(prefix, user):
      list = up to 2 of user1's recent queries that start with prefix
      global = trie.top(prefix)                   // stored 102
             + trending queries that start with prefix
      FOR EACH item of global, highest score first:
        IF NOT denied(item)3 AND NOT in list: add it
      RETURN the first 5
    1. 1Personal items go first, but at most 2, so the global list still shows.
    2. 2The node keeps 10; filters can drop several and still leave 5.
    3. 3The read-time denylist. It acts in seconds; the next build removes the query for good.
    Tested source Go: serve
    Go: servego
    
    // Serve builds the list a user sees: up to `show` items from the user's own recent queries that
    // match, then trending queries, then the trie's stored list, with denied queries dropped at read
    // time. The trie stores more than it shows, so a read-time filter still fills the list.
    func (t *Trie) Serve(prefix string, show int, personal []string, trending []Suggestion, deny func(string) bool) []Suggestion {
      var out []Suggestion
      seen := map[string]bool{}
      add := func(s Suggestion) {
        if len(out) < show && !seen[s.Query] && (deny == nil || !deny(s.Query)) {
          seen[s.Query] = true
          out = append(out, s)
        }
      }
      for _, q := range personal { // the personal layer: at most 2, newest first
        if strings.HasPrefix(q, prefix) && len(out) < 2 {
          add(Suggestion{Query: q, Source: "personal"})
        }
      }
      top, _ := t.Lookup(prefix)
      var global []Suggestion
      for _, id := range top {
        global = append(global, Suggestion{Query: t.Queries[id], Score: t.Scores[id], Source: "trie"})
      }
      for _, s := range trending {
        if strings.HasPrefix(s.Query, prefix) {
          global = append(global, s)
        }
      }
      slices.SortStableFunc(global, func(a, b Suggestion) int { return cmp.Compare(b.Score, a.Score) })
      for _, s := range global {
        add(s)
      }
      return out
    }
    
    find trending queriespseudo code
    FOR EACH search in the stream:
      sketch.add(query)                           // count-min, fixed memory1
      heap keeps the 50 largest estimates
    EVERY minute, FOR EACH query in the heap:
      rate = estimate x 24                        // a day at this hour's pace
      IF rate >= 2 x score in the last build2: publish it
    1. 1An estimate is never below the true count; it is above by at most a small share of all searches.
    2. 2Heavy is not new. Only a query well above its batch rate counts as trending; popular queries stay with the build.
    Tested source Go: trending
    Go: trendinggo
    
    // HourStream is the last hour of searches: today's counts spread over 24 hours, plus a query that
    // nobody searched before this hour. The events are shuffled, as a stream would deliver them.
    func HourStream(l Log, seed uint64, burst int) []string {
      var ev []string
      for i, q := range l.Queries {
        for range l.Counts[6][i] / 24 {
          ev = append(ev, q)
        }
      }
      for range burst {
        ev = append(ev, Trending)
      }
      r := rand.New(rand.NewPCG(seed, 3))
      r.Shuffle(len(ev), func(i, j int) { ev[i], ev[j] = ev[j], ev[i] })
      return ev
    }
    
    // Trends counts a stream in a count-min sketch and keeps the k heaviest queries in a heap; its
    // memory is fixed, whatever the number of distinct queries. A heavy query counts as trending only
    // when its rate in the stream is at least lift times its rate in the last batch build.
    func Trends(stream []string, k int, eps, delta float64, baseline func(string) float64, lift float64) ([]Suggestion, *sketches.CountMin) {
      cms := sketches.CountMinFor(eps, delta)
      top := sketches.NewCMSTopK(k, cms)
      for _, q := range stream {
        top.Add(q)
      }
      var out []Suggestion
      for _, it := range top.Top() {
        rate := float64(it.Count) * 24 // searches a day at this hour's pace
        if rate >= lift*baseline(it.Key) {
          out = append(out, Suggestion{Query: it.Key, Score: rate, Source: "trending"})
        }
      }
      return out, cms
    }
    

    The trie is the shared base. Trending adds what is new since the build, the denylist removes what must go now, and the user's history goes on top.

    L

    Deep dive: caching and sharding

    most keystrokes never reach a server
    cache the hottest prefixesshare of all lookups
    10023.1%
    1,00053.7%
    10,00079.6%
    100,00099.0%
    8 shardsbusiest ÷ meanstatus
    By hash of the first letter1.82Not approved
    By ranges of two-letter prefixes, cut by load1.31Approved
    Hot range: add replicas of that shardas neededApproved
    Whole trie on every server1.00While it fits in memory

    Range cuts in the lab: co, he, la, pi, sm, to, we. One-letter prefixes are 6.2% of lookups and only a few dozen keys: the edge serves them.

    100 ms budgetcostsource
    Browser cache hit0 networkno request
    Edge 500 km away≈ 5 ms round trip200 km per ms in fiber (B5)
    Origin 4,000 km away≈ 40 ms round tripsame arithmetic
    New connection+1 or more round tripskeep connections open (B1)
    Trie lookupp99 453 nslab
    Redis key lookupp99 225 µslab
    Pause before sendingevery ms countscomes out of the same 100 ms
    shard by prefix rangepseudo code
    range shards:
      load[two-byte prefix] = keystrokes under it, per day
      cut the sorted prefixes into 8 ranges of equal load1
      one-byte prefixes: edge cache, on no shard2
    route(prefix): the shard whose range holds prefix[0:2]
    1. 1Cut by keystroke load, not by key count: "we" for weather carries far more than "xy".
    2. 2The hottest keys of all are the shortest. A cache in front of every shard takes them.
    Tested source Go: shards
    Go: shardsgo
    
    // ShardByFirstByte puts every prefix on the shard of its first byte, by hash. All of "s..." lands
    // on one shard. One-byte prefixes are served from a cache in front of every shard, so they are
    // left out here too.
    func ShardByFirstByte(loads []Load, shards int) []float64 {
      out := make([]float64, shards)
      for _, l := range loads {
        if len(l.Prefix) < 2 {
          continue
        }
        h := uint32(l.Prefix[0]) * 2654435761 // Knuth's multiplicative hash
        out[h%uint32(shards)] += l.Lookups
      }
      return out
    }
    
    // ShardByRange cuts the sorted two-byte prefixes into contiguous ranges of equal load. One-byte
    // prefixes are served from a cache in front of every shard, so they are left out.
    func ShardByRange(loads []Load, shards int) (perShard []float64, bounds []string) {
      two := map[string]float64{}
      var keys []string
      var total float64
      for _, l := range loads {
        if len(l.Prefix) < 2 {
          continue
        }
        k := l.Prefix[:2]
        if _, ok := two[k]; !ok {
          keys = append(keys, k)
        }
        two[k] += l.Lookups
        total += l.Lookups
      }
      sort.Strings(keys)
      perShard = make([]float64, shards)
      s := 0
      var acc float64
      for _, k := range keys {
        if acc+two[k]/2 > total*float64(s+1)/float64(shards) && s < shards-1 {
          s++
          bounds = append(bounds, k)
        }
        perShard[s] += two[k]
        acc += two[k]
      }
      return perShard, bounds
    }
    

    The 1,000 hottest prefixes take 54% of lookups, so the edge absorbs most traffic. If one trie no longer fits, I shard by ranges of two-letter prefixes cut by load, not by first letter.

    M

    Failure cases

    what breaks, and why typing still works
    eventresultwhy it is safesaved by
    A suggest server diesIts connections drop.The next keystroke goes to a replica; every replica holds the whole trie of its shard.Replicas
    A build produces a bad trieWrong or empty lists.Size and sample checks gate the upload; servers keep the last good version.Versioned files
    The batch build stops for a dayPopularity is a day old.Decayed scores move slowly; trending covers what is new.Stream job
    The stream job stopsNo new trends.The trending list expires; suggestions fall back to the build.TTL
    Redis is downNo history, trending or denylist reads.Servers keep the last denylist in memory and serve the trie alone.Last known copy
    An unsafe query starts trendingIt could be suggested.Trending passes the same denylist; an operator blocks it in seconds.Denylist
    A news event makes one prefix hotOne shard gets the load.The edge caches that prefix; add replicas of the shard.CDN
    The suggest call is slowThe list is late.The browser drops answers for an older prefix and shows nothing rather than a stale list.Browser
    N

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1trie in one process2+ edge, browser cache3+ hourly builds, replicas4+ trends, history in Redis5+ shards by prefix rangemore load →
    Capacity against this prompt's demand1k10k100k1M10M100MDemand: keystrokes, average: 189,759 lookups per secondDemand: keystrokes, average189,759Demand: peak: 569,277 lookups per secondDemand: peak569,277Demand: past the edge: 38,711 lookups per secondDemand: past the edge38,711Service: trie, 8 threads: 30,282,432 lookups per secondService: trie, 8 threads30,282,432Redis: sorted set, 8 clients: 30,941 lookups per secondRedis: sorted set, 8 clients30,941Redis: string, 8 clients: 31,966 lookups per secondRedis: string, 8 clients31,966lookups per second, log scale
    stepaddit handlesmove up when you see
    1One process with a trie built nightly from the log.About 30,282,000 lookups a second on 8 threads in the lab; the network is the limit.Users far away see slow lists; one process is one point of failure.
    2Edge and browser caching of the global list per prefix.The 10,000 hottest prefixes take 80% of lookups.Lists are a day stale; news queries are missing.
    3Hourly builds and replicas behind a load balancer.Popularity within an hour; any replica answers.Trends need minutes, not an hour; users want their history.
    4Stream job and Redis for trends, history and the denylist.A new query appears within a minute of its rise.One trie no longer fits a server, or one language dominates.
    5Shards by prefix range, per language, with hot ranges replicated (X2).This prompt needs about 39,000 lookups a second past the edge and 5.3 GB per trie copy.Top of the ladder.

    Demand from panel C. Capacity measured in the lab on one shared laptop, 8 clients, median of 3 runs. Redis rates are network round trips on one machine; read them as orders of magnitude.

    I start with a trie in one process built nightly. I add edge caching, then hourly builds with replicas, then trends, and shard only when one trie stops fitting.

    O

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    The user misspells: "piza". What do you suggest?Try the exact prefix first. If it finds little, look up prefixes within one edit, or use an n-gram index, and rank those lower.B8
    Can "shoes" match "running shoes"?Index each word start as well, or serve from an inverted index of words. The trie alone matches only the start.B8
    How do you count trending queries without a counter per query?A count-min sketch with a heap: fixed memory, an estimate never below the truth. Compare its rate with the batch rate.B10
    Why hourly batches and a stream, not only a stream?The batch reprocesses the whole log and fixes any stream error; the stream adds minutes of freshness on top.B7
    A prefix is very hot. What changes?It is cached at the edge already; add replicas of its shard and keep the cache time long for short prefixes.B4
    How do you protect privacy?Suggest only queries searched by many distinct users. Keep history per user, let them delete it, and never cache it at the edge.O5
    The trie outgrows one server.Shard by prefix range cut by load, route by the first two letters, and replicate hot ranges.X2
    P

    Drill

    predict, then reveal

    0 of 9 known

    1. Why store a top list at every node instead of ranking the subtree at read time?

    2. What does storing a top 10 at every node cost in memory?

    3. Trie in the service, or one Redis key per prefix?

    4. A query was huge six days ago and is rare today. How do you stop suggesting it?

    5. A new query appears in the last hour: "storm warning tonight". The hourly build has not seen it. How does it reach users?

    6. A blocked query must vanish now, not at the next build. How?

    7. Can the edge cache the personal layer?

    8. How many requests does one search cost, and how do you cut them?

    9. You shard the trie by first letter. What goes wrong?

    Q

    Numbers to say

    measured or derived
    demand
    About 190,000 lookups a second, 569,000 at peak.
    per search
    About 16.4 lookups, one per keystroke.
    edge
    10,000 prefixes take 80% of lookups.
    trie
    p50 131 ns; about 532 B per query.
    Redis
    p50 129 µs a lookup; about 699 B per query as sorted sets.
    memory
    10 M queries ≈ 5.3 GB of trie.
    network
    Fiber: about 200 km per ms; 500 km ≈ 5 ms round trip.

    Go and Redis 8 on an 8-core laptop shared with other runs. Log: seed 7, 20,760 queries.