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.
- 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.
- 2Build from logs of submitted searches, with time decay, every hour. Add a streaming sketch for what started trending since the last build.
- 3Most of the 100 ms is network. Answer short prefixes from the edge and the browser; the server lookup takes under a microsecond.
- 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.
"Design the suggestions that appear as a user types a query, ranked by popularity, within 100 ms."
| question | answer 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.
| 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-functional | target |
|---|---|
| Keystroke to list on screen | p99 < 100 ms |
| Availability | 99.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.
| quantity | arithmetic | result |
|---|---|---|
| Lookups per search | one per keystroke; seeded log (measured) | ≈ 16.4 |
| Lookups | 1 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 memory | 10 M queries × 532 B (measured per query) | ≈ 5.3 GB per copy |
| Redis, one key per prefix | 10 M × 6.3 keys × 111 B | ≈ 7.0 GB |
| Response | 5 × 21 B + JSON ≈ 200 B | ≈ 304 Mbit/s from the edge |
| Search log | 1 B × 100 B | 100 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.
| call | for | caching | success | errors |
|---|---|---|---|---|
| GET /v1/suggest?q=pi&lang=en | global list | public, a few minutes, keyed by q and lang | 200 + 5 items | 400 too long |
| GET /v1/suggest/me?q=pi | personal items | private, no-store | 200 + up to 2 items | 401 |
| GET /v1/search?q=pizza+near+me | the search itself | none | 200 | 400 |
| DELETE /v1/me/history/{query} | forget one search | none | 204 | 404 |
| PUT /v1/admin/denylist/{query} | block a suggestion | none | 204 | 403 |
- 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.
| store | key | holds |
|---|---|---|
| Service | trie node | Children sorted by byte; ids of the best 10 below; a count of queries below. |
| Object storage | trie/{lang}/{version} | One built trie per language and hour; servers load the newest good one. |
| Redis | hist:{user} | List of the last 20 searches: LPUSH, then LTRIM. |
| Redis | trend:{lang} | Sorted set of trending queries by rate, rewritten every minute. |
| Redis | deny | Set of blocked queries, read by servers every few seconds. |
| Redis | ac:{prefix} | The alternative design: one sorted set per prefix with its top 10. |
| Event log | searches | Time, 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.
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.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Service | Trie with a top list per node | A lookup is one walk; median 131 ns in the lab. | Routing tables, prefix rules |
| Service | Count-min sketch with a heap | Heavy queries of the last hour in 152 kB, whatever the number of distinct queries. | Heavy hitters (B10) |
| Redis | Sorted sets: ZADD, ZRANGE REV with a count | The key-per-prefix design; also the trending list. | Leaderboards |
| Redis | Strings: GET of a joined list | The smallest key-per-prefix form: 12.3 MB against 14.5 MB. | Any precomputed answer |
| Redis | Lists: LPUSH, LTRIM | A capped history per user. | Recent items |
| Redis | Pipelining | 130,651 prefix keys loaded in 0.6 s. | Bulk loads |
| CDN | Edge cache keyed by URL | The 10,000 hottest prefixes take 80% of lookups. | Static files (B5) |
| Browser | A pause before sending; an in-memory map of answers | Fewer requests; a backspace is free. | Any search box |
| Event log | Durable, replayable stream | One 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.
| design | per keystroke | status |
|---|---|---|
| LIKE 'pi%' on a query table, ORDER BY count | A range scan and a sort over every match | Not approved |
| Trie, rank the subtree at read time | Visits every query under a short prefix | Not approved |
| Trie with a top 10 per node, in process | p50 131 ns, p99 453 ns; 11.0 MB | Approved |
| Redis sorted set per prefix | p50 129 µs, p99 225 µs; 14.5 MB | Approved |
| Redis string per prefix | p50 128 µs; 12.3 MB; no in-place update | Rebuilt lists only |
| One sorted set, ZRANGE BYLEX | Returns matches in alphabetical order, not by popularity | Not approved |
| Search engine completion suggester | Built in; another cluster to run | You 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(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- 1The safety list removes a query at build time. A read-time denylist covers the hours until the next build.
- 2130,652 nodes for 20,760 queries: shared prefixes share nodes.
- 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.
- 4K = 10 stored; 5 are shown, so filters still leave a full list.
Tested source Go: build
// 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
}
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- 1Children are sorted by byte; a node has at most a few dozen.
- 2No sort and no scan at read time. That is why a lookup takes nanoseconds.
Tested source Go: lookup
// 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
}
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- 1130,651 keys loaded in 0.6 s in the lab.
- 2Highest score first. A string key holding the joined list is smaller and is read with one GET.
Tested source Go: load and read
// 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.
- pizza near me130,408 a day
- piano lessons18,408 a day
- pie for two3,070 a day
- pillow review1,156 a day
- pillow994 a day
- root
- p
- i
| this keystroke | trie in the service | one Redis key per prefix |
|---|---|---|
| Work | Walk 3 nodes, return the stored list | One ZRANGE on ac:pi |
| Median time in the lab | 131 ns | 129 µs, a network round trip |
| Ranking at read time | None: the build stored the top 10 | None: 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.
| rank | "s", 7-day average | "s", 1-day half-life |
|---|---|---|
| 1 | stock market today 59,269 | snow day closures 57,967 |
| 2 | solar eclipse glasses 56,267 | stock market today 56,302 |
| 3 | synonym 25,611 | synonym 25,076 |
| 4 | spell check 24,435 | spell check 24,395 |
| 5 | speed test 23,263 | speed test 23,213 |
| rank | "so", 7-day average | "so", 1-day half-life |
|---|---|---|
| 1 | solar eclipse glasses 56,267 | sourdough starter 22,386 |
| 2 | solar panels 22,458 | solar panels 22,129 |
| 3 | sourdough starter 22,421 | soup recipes 17,644 |
| 4 | soup recipes 16,916 | solar eclipse glasses 8,700 |
| 5 | solitaire 8,268 | solitaire 8,104 |
Searches a day, recorded from the seeded log. One query peaked six days ago; one has grown all week.
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- 1Yesterday counts half, two days ago a quarter. A shorter half-life follows news faster and jumps more.
- 2Counts per day are a small table; scoring and building take seconds to minutes. The hour is a freshness choice.
- 3Readers keep the old trie until the swap; the old one is freed when its last reader finishes.
Tested source Go: decay
// 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.
| "st", hourly build only | with trending |
|---|---|
| stock market today | storm warning tonight (trending) |
| stretching routine | stock market today |
| study timer | stretching routine |
| steak near me | study timer |
| stopwatch | steak 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 list | with the safety list |
|---|---|
| fake id card (blocked) | falafel ideas |
| fake doctors note (blocked) | falafel sauce |
| falafel ideas | falafel near me |
| falafel sauce | falafel for kids |
| falafel near me | falafel calories |
| "pa", anyone | a user who searched "paris museums" and "pad thai near me" |
|---|---|
| pasta recipe | paris museums (yours) |
| pancake recipe | pad thai near me (yours) |
| passport renewal | pasta recipe |
| parking near me | pancake recipe |
| paint colors | passport renewal |
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- 1Personal items go first, but at most 2, so the global list still shows.
- 2The node keeps 10; filters can drop several and still leave 5.
- 3The read-time denylist. It acts in seconds; the next build removes the query for good.
Tested source Go: serve
// 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
}
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- 1An estimate is never below the true count; it is above by at most a small share of all searches.
- 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
// 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.
| cache the hottest prefixes | share of all lookups |
|---|---|
| 100 | 23.1% |
| 1,000 | 53.7% |
| 10,000 | 79.6% |
| 100,000 | 99.0% |
| 8 shards | busiest ÷ mean | status |
|---|---|---|
| By hash of the first letter | 1.82 | Not approved |
| By ranges of two-letter prefixes, cut by load | 1.31 | Approved |
| Hot range: add replicas of that shard | as needed | Approved |
| Whole trie on every server | 1.00 | While 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 budget | cost | source |
|---|---|---|
| Browser cache hit | 0 network | no request |
| Edge 500 km away | ≈ 5 ms round trip | 200 km per ms in fiber (B5) |
| Origin 4,000 km away | ≈ 40 ms round trip | same arithmetic |
| New connection | +1 or more round trips | keep connections open (B1) |
| Trie lookup | p99 453 ns | lab |
| Redis key lookup | p99 225 µs | lab |
| Pause before sending | every ms counts | comes out of the same 100 ms |
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]- 1Cut by keystroke load, not by key count: "we" for weather carries far more than "xy".
- 2The hottest keys of all are the shortest. A cache in front of every shard takes them.
Tested source Go: shards
// 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.
| event | result | why it is safe | saved by |
|---|---|---|---|
| A suggest server dies | Its connections drop. | The next keystroke goes to a replica; every replica holds the whole trie of its shard. | Replicas |
| A build produces a bad trie | Wrong or empty lists. | Size and sample checks gate the upload; servers keep the last good version. | Versioned files |
| The batch build stops for a day | Popularity is a day old. | Decayed scores move slowly; trending covers what is new. | Stream job |
| The stream job stops | No new trends. | The trending list expires; suggestions fall back to the build. | TTL |
| Redis is down | No history, trending or denylist reads. | Servers keep the last denylist in memory and serve the trie alone. | Last known copy |
| An unsafe query starts trending | It could be suggested. | Trending passes the same denylist; an operator blocks it in seconds. | Denylist |
| A news event makes one prefix hot | One shard gets the load. | The edge caches that prefix; add replicas of the shard. | CDN |
| The suggest call is slow | The list is late. | The browser drops answers for an older prefix and shows nothing rather than a stale list. | Browser |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One 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. |
| 2 | Edge 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. |
| 3 | Hourly builds and replicas behind a load balancer. | Popularity within an hour; any replica answers. | Trends need minutes, not an hour; users want their history. |
| 4 | Stream 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. |
| 5 | Shards 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.
| question | answer | deeper |
|---|---|---|
| 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 |
0 of 9 known
Why store a top list at every node instead of ranking the subtree at read time?
What does storing a top 10 at every node cost in memory?
Trie in the service, or one Redis key per prefix?
A query was huge six days ago and is rare today. How do you stop suggesting it?
A new query appears in the last hour: "storm warning tonight". The hourly build has not seen it. How does it reach users?
A blocked query must vanish now, not at the next build. How?
Can the edge cache the personal layer?
How many requests does one search cost, and how do you cut them?
You shard the trie by first letter. What goes wrong?
- 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.