Case study: Search autocomplete

Topic 8 of 15 in Week 7: Classic case studies13 min readIntermediateFree course

Overview

Autocomplete (typeahead) suggests completions as the user types. Every keystroke can be a request, so it’s one of the highest-QPS features in a search product, with a tight latency budget. The key idea is to precompute answers so serving is a quick memory lookup.

Try the exercise first: 45 minutes, then compare.

1. Requirements

Functional

  • Given a prefix, return the top 10 suggestions ranked mainly by popularity.
  • Suggestions update at least daily; trending queries ideally within an hour.
  • No offensive or unsafe suggestions.

Non-functional

  • Very low latency: under 100 ms end to end, so the server part must take a few milliseconds.
  • Very high QPS and high availability; slightly stale suggestions are fine.

2. Estimates

Text
searches      : 1B / day
requests      : ~5 autocomplete calls per search (after debouncing) → 5B / day ≈ 60,000 / s
peak          : ~3× → ~180,000 / s
distinct queries kept: say 100M popular queries × ~30 bytes + top-k lists → tens of GB → shard it

3. API

Text
GET /v1/suggest?q=syst&lang=en&limit=10
→ 200 {"suggestions": ["system design", "systemctl", "system of a down", …]}
Cache-Control: public, max-age=300

4. Data structure

A trie with top-k suggestions at each node. From the root, the path s, sy, sys leads to the node for the prefix sys; other branches include syn, sa and sal. Each node stores its top completions with counts, for example the node sys stores system design, systemctl and sysadmin jobs. To serve the prefix sys, walk three nodes and return the stored list; the answer is precomputed.

A trie (prefix tree) stores strings character by character. Finding all completions of a prefix by walking every descendant and sorting would be slow for short prefixes like “s”. Instead, each node stores the top-k completions for its prefix, computed when the trie is built. A request walks down at most a few dozen nodes and returns the stored list.

Memory optimisations: compress chains of single-child nodes (radix tree), store only queries above a popularity threshold, and keep the stored lists short.

5. High-level design

Search autocomplete design. The serving path, under 100 milliseconds: as the user types, for example syst, requests go to a CDN or cache of hot prefixes, then to a stateless suggest API, then to trie shards partitioned by prefix. The client waits about 150 milliseconds after the last keystroke and cancels stale requests. The build path runs hourly or daily: query logs are aggregated into counts and filtered, tries with top-k per node are built, and a new version is published and swapped into the trie shards. Trending queries can be added from a stream job, unsafe suggestions are filtered before publishing, and personal recent searches are merged on the client or by the API from a per-user store.

Build path (offline)

  1. Collect search queries from logs.
  2. Aggregate counts per normalised query over a time window, with decay so recent popularity matters more.
  3. Filter: drop rare queries (privacy and noise), spam, offensive and unsafe terms, and personal data.
  4. Build tries with top-k lists per node, one per shard and language.
  5. Publish versioned snapshots to object storage; servers load the new version and swap atomically.

Serving path

  • Suggest API servers are stateless; trie servers hold the snapshot in memory.
  • Shard by prefix (for example by the first one or two characters), balanced by traffic, not by alphabet (“s” gets far more traffic than “x”). Replicate each shard for throughput and availability.
  • Cache: responses for common prefixes are identical for everyone, so they’re cached at the CDN and in the browser for minutes.

6. Deep dives

Client-side optimisations

  • Debounce: wait ~100–150 ms after the last keystroke before requesting.
  • Cancel in-flight requests when a newer prefix is typed.
  • Cache responses in the browser; going back from “syste” to “syst” needs no request.
  • Optionally prefetch the next likely prefixes.

A daily rebuild misses breaking news. Add a streaming job that counts queries over the last hour, detects terms rising sharply, and publishes a small “trending” structure that the API merges with the main suggestions.

Personalisation

Merge the user’s own recent searches (stored per user, or on the device) with global suggestions. Keep the global results cacheable by doing personal merging on the client or as a thin layer in the API.

Safety

Suggestions shape what people search for, so filtering matters: block lists, classifiers for hateful or dangerous completions, and a fast path to remove a suggestion from serving immediately (an override list checked at request time).

7. Trade-offs and bottlenecks

  • Precomputing top-k makes reads fast but builds slower and memory larger.
  • Prefix sharding can be uneven; split hot prefixes into finer shards.
  • Snapshot swaps must be atomic and versioned to roll back bad builds.

8. Follow-up questions

  • Typo tolerance? Fuzzy matching against the trie (edit distance) or a spell-correction step.
  • Multiple languages? Separate tries per language and locale.
  • Ranking beyond popularity? Combine popularity with freshness, location and personalisation scores at build or serve time.

Recap

Autocomplete serves precomputed answers: tries whose nodes store the top-k completions for each prefix, built offline from aggregated and filtered query logs and published as versioned snapshots to in-memory servers sharded by prefix. Edge and browser caching plus client debouncing cut request volume, and a streaming pipeline adds trending queries.

Exercise

Design it yourself (45 minutes)

Set a 45-minute timer and design search autocomplete for a large search engine: as users type, show the top 10 suggestions for the current prefix, ranked by popularity, within 100 ms. Assume 1 billion searches per day, an average query of 4 words (~20 characters), and suggestions updated at least daily (trending topics within an hour would be nice). Use the framework, then compare.

Text
1. Clarifying questions:
2. Functional requirements:
3. Non-functional requirements:
4. Estimates:
5. API:
6. Data structures:
7. High-level design (serving + building):
8. Deep dives (top-k per node, sharding, freshness, filtering):
9. Trade-offs and bottlenecks:

Summary

  • Precompute: store the top-k completions at every trie node so each request is a short walk with no sorting.
  • Build tries offline from aggregated, filtered query logs and publish versioned snapshots.
  • Serve from memory on servers sharded by prefix with replicas; cache hot prefixes at the edge and in the browser.
  • Reduce request volume on the client with debouncing, cancellation and caching.
  • Add freshness with a streaming trending pipeline and filter unsafe suggestions before publishing.