Case Study 13 โ€” Search Autocomplete (Typeahead)

Design a search autocomplete / typeahead system like Google Search suggestions or Amazon product search โ€” as the user types, return relevant completions in milliseconds.

1. Problem

On each keystroke (or every few characters), the client sends a prefix query like "sys" and expects top-K suggestions ("system design", "system of a down", โ€ฆ) ranked by popularity and relevance, with latency low enough that the UI feels instant.

2. Requirements

Functional (MVP)

  • Return top K suggestions (e.g., 10) for a query prefix
  • Rank by popularity (search frequency) and basic relevance
  • Support personalization optionally (user's recent searches) โ€” phase 2
  • Handle prefixes of 1โ€“50 characters
  • Update suggestions as new trending queries emerge (near real-time or daily)
  • Multi-language / locale-aware results

Out of scope (initially)

  • Full web search results page
  • Spell correction across entire index ("did you mean") โ€” can add fuzzy layer later
  • Rich snippets (images, prices) in dropdown
  • Voice input processing

Non-functional

  • Ultra-low latency: p99 < 50 ms (often < 20 ms)
  • High read QPS: every keystroke = 1 request (with debouncing on client)
  • High availability โ€” autocomplete is on critical search path
  • Eventually consistent with trending updates (minutes delay OK)
  • Cost-efficient at billions of unique queries stored

3. Back-of-the-envelope estimates

These numbers are rough order-of-magnitude math โ€” not a capacity plan. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained โ‰ˆ 86,400 requests/day. Autocomplete breaks that rule because every keystroke can fire a request โ€” client debounce is essential to cut volume.

Why we estimate

Autocomplete sits on the critical search path with a p99 < 50 ms target. Estimates tell us:

  • Why you cannot run LIKE 'prefix%' on a database at request time
  • How client debounce changes QPS by 2โ€“3ร—
  • Whether the index must live in memory (yes, at this scale)

Assumptions

AssumptionValueWhy it matters
Daily active search users500MBase traffic volume
Keystrokes per search interaction8 (before debounce)Upper bound on raw calls
Client debounce150 msCollapses redundant requests
Effective API calls per search~3After debounce + min prefix length
Unique query strings in index~500MLong tail storage
Top-K suggestions returned10Fixed response size

Step A โ€” Traffic (QPS) with labeled arithmetic

Daily autocomplete requests:

Searches per day        = 500,000,000
Calls per search        = 3 (after debounce)

Daily requests          = 500M ร— 3 = 1,500,000,000 requests/day

Average QPS:

Average QPS = 1,500,000,000 รท 86,400
            โ‰ˆ 17,361 requests/second
            โ‰ˆ 17,000/s (round for interview)

Peak QPS (5ร— average, regional spikes higher):

Peak QPS โ‰ˆ 17,000 ร— 5 โ‰ˆ 85,000/s

Without debounce (why debounce matters):

Raw calls = 500M searches ร— 8 keystrokes = 4B requests/day
Raw QPS   = 4B รท 86,400 โ‰ˆ 46,000/s  โ†’ 2.7ร— worse than debounced

Index update traffic (async, off hot path):

Search log ingest: high volume, but batched every 1โ€“5 minutes
Write QPS to live trie: effectively 0 at request time โ€” full snapshot rebuild + swap

Step B โ€” Storage

Unique query strings (raw text):

Queries         = 500 million
Avg term length โ‰ˆ 30 bytes

Raw term text   = 500M ร— 30 B โ‰ˆ 15 GB

In-memory trie with top-K at each node:

15 GB raw terms + trie structure overhead + top-10 heaps per node
Total in memory โ‰ˆ 50โ€“100 GB (sharded across nodes)

Top 1M prefixes serve ~80% of traffic โ†’ fits easily in Redis + local LRU

Snapshot files (for rolling reload):

Serialized trie snapshot โ‰ˆ 50โ€“100 GB per locale โ†’ stored in S3, loaded at pod start

Step C โ€” Bandwidth

Response size per suggest call:

10 suggestions ร— ~40 B JSON each โ‰ˆ 400 B payload + overhead โ‰ˆ 1 KB/response

Peak egress โ‰ˆ 85,000/s ร— 1 KB โ‰ˆ 85 MB/s (modest โ€” latency, not bandwidth, is the constraint)

Search log ingest (write side):

500M searches/day ร— ~100 B log line โ‰ˆ 50 GB/day of raw logs โ†’ Kafka, not the suggest API

Step D โ€” Read:write ratio table

OperationTypeQPSNotes
GET /suggestRead~17k avg; ~85k peakMust be < 50 ms p99
Trie lookupReadSameO(prefix length) walk
L1/L2 cache hitRead~80% of prefix trafficHot prefixes
Search log appendWrite~5,800/s avgSeparate pipeline
Index rebuildWriteBatch every 1โ€“5 minZero-downtime pointer swap

Ratio: millions : 1 read-to-write on the hot suggest path โ€” classic read-heavy, precompute pattern.

What the numbers tell us

  • 17kโ€“85k read QPS with < 50 ms p99 โ†’ precomputed trie + top-K per node, not database queries
  • Client debounce cuts QPS ~3ร— โ€” mention it proactively in interviews
  • 50โ€“100 GB in memory โ†’ shard tries by first character or hash prefix across servers
  • 80% traffic on top 1M prefixes โ†’ Redis + in-process LRU cache is high ROI
  • Index updates are async โ€” batch rebuild from search logs; swap snapshot without downtime
  • Long tail (500M queries) is fine offline; hot path only walks a trie

Common mistake for this problem

Proposing Elasticsearch or SELECT ... LIKE 'prefix%' on every keystroke. At 85k QPS and 500M rows, that cannot hit p99 < 50 ms. The correct pattern is offline precomputation + in-memory serve + cache. Another mistake: forgetting debounce and overstating QPS by 2โ€“3ร—.

4. High-Level Design (HLD)

Components

ComponentRole
Autocomplete ServiceStateless API; lookup prefix โ†’ top-K
Prefix IndexTrie or sorted array + binary search per shard
Popularity CounterCount query frequencies from search logs (Flink/Spark)
Index BuilderMerges counts, builds new index snapshot periodically
Snapshot StoreVersioned index files for rolling reload
CacheHot prefix results (Redis + in-process LRU)
Log pipelineIngest raw searches โ†’ aggregate top queries

Flows

Query path (read)

  1. User types "sys" โ†’ client debounces โ†’ GET /suggest?q=sys&limit=10
  2. Autocomplete Service normalizes query (lowercase, trim)
  3. Check local LRU cache โ†’ Redis โ†’ in-memory trie shard
  4. Return JSON list in ~5โ€“20 ms

Index update path (write, async)

  1. Search logs stream to Kafka
  2. Counter job aggregates (query, count) windows
  3. Every N minutes, Builder merges with historical totals
  4. Builds new trie snapshot โ†’ uploads to S3
  5. Autocomplete pods reload snapshot with zero-downtime swap

Trade-offs

ApproachProsCons
Trie in memoryFast prefix walk O(prefix len)Memory heavy; rebuild complexity
Elasticsearch completion suggesterLess custom codeHarder to hit <10ms p99 at huge scale
DB LIKE 'prefix%'SimpleToo slow at billions of rows
Client debounce 150โ€“300 msCuts QPS 3โ€“5ร—Slightly less "live" feel
Global vs per-locale indexBetter relevanceMore shards to maintain

Interview answer: Precomputed trie + top-K heap per node, sharded by first character or hash prefix.

5. Low-Level Design (LLD)

APIs

GET /api/v1/suggest?q=system&limit=10&locale=en-US
โ†’ 200 {
  "query": "system",
  "suggestions": [
    { "text": "system design interview", "score": 98234 },
    { "text": "system of a down", "score": 45100 },
    ...
  ],
  "latencyMs": 4
}

GET /api/v1/suggest/health
โ†’ 200 { "indexVersion": "20260720-1430", "shardStatus": "OK" }

Optional: POST /internal/index/reload for controlled rollout.

Schema (metadata & analytics โ€” not the hot path)

query_stats (
  query_text     TEXT,
  locale         VARCHAR(10),
  daily_count    BIGINT,
  total_count    BIGINT,
  last_seen      TIMESTAMPTZ,
  PRIMARY KEY (locale, query_text)
)

index_snapshots (
  version        VARCHAR(30) PRIMARY KEY,
  locale         VARCHAR(10),
  blob_path      TEXT,
  record_count   BIGINT,
  created_at     TIMESTAMPTZ,
  is_active      BOOLEAN
)

-- Personalization (phase 2)
user_recent_searches (
  user_id        UUID,
  query_text     TEXT,
  searched_at    TIMESTAMPTZ,
  PRIMARY KEY (user_id, query_text)
)

The hot index lives in memory (trie files), not queried from Postgres per request.

Modules

SuggestController / SuggestService
PrefixIndex / TrieNode / TopKHeap
IndexLoader / SnapshotManager
QueryNormalizer / LocaleRouter
PopularityAggregator / IndexBuilderJob
SuggestCache (L1 LRU + L2 Redis)

Data structure โ€” trie with top-K at each node

Each trie node stores:

  • children: map char โ†’ node
  • topK: fixed-size max-heap or sorted array of { phrase, score } for full queries passing through this prefix
class TrieNode:
  children: Map<char, TrieNode>
  topK: List<Suggestion>  # size โ‰ค K, sorted by score desc

function insert(phrase, score):
  node = root
  for ch in phrase:
    node = node.child(ch)
    node.topK.addOrUpdate(phrase, score)  # keep only best K

Query "sys" โ†’ walk s โ†’ y โ†’ s โ†’ return node.topK.

Key algorithm โ€” suggest

function suggest(rawQuery, limit, locale):
  q = normalize(rawQuery, locale)   # lowercase, NFC unicode, trim
  if len(q) == 0: return trending(locale)  # optional: show trending when empty
  if len(q) > MAX_PREFIX: q = q[0:MAX_PREFIX]

  cached = cache.get(locale, q)
  if cached: return cached

  shard = shardFor(q, locale)       # e.g., first char 's' โ†’ shard 18
  node = shardIndex[shard].walk(q)
  if node is null: return []

  results = node.topK.take(limit)
  cache.set(locale, q, results, ttl=60s)
  return results

Key algorithm โ€” build index from logs

function buildIndexSnapshot(locale, windowHours=24):
  counts = aggregateSearchLogs(locale, windowHours)
  # Merge with historical decay: score = 0.7*today + 0.3*yesterday
  merged = mergeWithDecay(counts, historicalStats)

  trie = new Trie()
  for (phrase, score) in merged.sortedByScore():
    if isBlocked(phrase): continue   # profanity, spam
    trie.insert(phrase, score)

  snapshot = serialize(trie)
  uploadToS3(version, locale, snapshot)
  markSnapshotReady(version)

Key algorithm โ€” zero-downtime reload

function reloadIndex():
  meta = snapshotStore.latestActive(locale)
  newTrie = deserialize(download(meta.blob_path))
  atomicSwap(shardIndexes[locale], newTrie)  # pointer swap in memory
  localCache.clear()

Use double-buffering: readers always hold ref to current trie; writers build new trie then swap pointer atomically.

Client-side optimizations (mention in interview)

# Debounce: wait 150ms after last keystroke before API call
# AbortController: cancel in-flight request when user types next char
# Minimum prefix length 2 before calling API
# Cache recent prefixes client-side (sessionStorage)

Concurrency & correctness

ConcernApproach
Stale suggestions after reloadVersion header in response; client can ignore stale
Thundering herd on deployPre-warm cache; gradual pod rollout
Unicode normalizationNFC + locale-specific lowercasing (Turkish I/i)
Spam queries polluting indexMin count threshold; blocklist; rate limit writes to stats
Shard imbalance (a* hotter than z*)Shard by hash prefix, not only first char

Fuzzy matching (bonus): For typo tolerance, maintain separate n-gram index or use Levenshtein on top-1000 popular queries only โ€” full fuzzy on billions is too slow for p99.

6. Scale evolution

StageChange
MVPSingle trie in memory, nightly batch rebuild, one region
10k QPSRedis cache, horizontal API replicas, debounced clients
100k QPSSharded tries by prefix hash; edge CDN caching for top prefixes
GlobalPer-locale indexes; geo-routed replicas
PersonalizationBlend global top-K with user's recent searches (weighted merge)

7. Recap

  • Autocomplete is precomputation + cache, not ad-hoc DB search at request time
  • Store top-K at each trie node for O(prefix length) lookups
  • Cut QPS with client debounce and request cancellation
  • Update index async from search logs; swap snapshots without downtime

Practice: Explain trie vs Elasticsearch for this use case. Write suggest() pseudocode including cache and shard routing.