Google Search Autocomplete
An emergency suppression disappears when an old index generation is restored.
Topic tools
Layout updated
Problem statement
Design search autocomplete. As a user types, suggest popular queries that match the prefix and locale, and pick up trending queries within minutes.
Functional requirements
- Suggest matching queries as a user types.
- Support language-specific suggestions and ranking updates.
- Remove blocked suggestions quickly.
Non-functional requirements
- Aim for suggestion under 100 ms and 99.99% availability.
- Serve a complete index version and filter blocked suggestions.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 100M × 30 = 3B requests/day / 86,400 ≈ 34.7k |
| 150k × 1 KB response = 150 MB/s before protocol overhead |
| Illustrative 100M prefix-locale entries × 10 candidates × 32 bytes = 32 GB raw candidate references/scores |
| 100M completed searches/day ≈ 1,157 events/s; 500 bytes/event ≈ 50 GB/day |
| 1M changed queries/minute × 20 prefixes/query ≈ 333k candidate updates/s |
Entities
| Entity / logical owner |
|---|
| SearchEvent(eventId, normalizedQuery, eventTime, locale, region) |
| QueryStats((locale, query, bucket), count, scoreInputs) |
| PrefixSuggestions((generation, locale, normalizedPrefix), candidates) |
| IndexManifest(generation, baseVersion, overlayVersion, normalizationVersion, shards, checksums, sourceWatermark) |
| Local / regional Redis |
| Policy suppression set(version, deniedTermIds) |
API design
| Operation / input | Response and retry contract |
|---|---|
GET/v1/suggestions?prefix=new&locale=en-US&limit=5 | Stateless regional validates locale/length, normalizes input and returns {suggestions, indexVersion, freshness}. Client attaches request sequence and discards responses for older text. |
High-level design
How to draw this design
- Collect demand signalsSearch backend, Kafka, and raw archive
- Build suggestionsFlink statistics, prefix builder, and ranking
- Publish a generationImmutable snapshots, publisher, and registry
- Serve keystrokesAutocomplete , caches, prefix replicas, and suppression policy
Aggregate search signals and publish a verified prefix generation. Each keystroke reads that generation.
- State ownership
- The selects the active generation. Prefix replicas and caches serve its data.
- Scale
- Precompute the top results per prefix and cache hot prefixes.
- Correctness
- Switch the generation atomically and apply suppression before returning suggestions.
- Failure and recovery
- Retain the last verified index for rollback and cap costly lookup work.
- Edge
- Compute
- State
- Messaging
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 16 flow steps
High-level design component walkthrough
User / Browser
Debounce and sequence requests
Why, tradeoff and connected operations
An application or user-facing endpoint starts or receives this flow.
Tradeoff: Old responses can arrive late
Connected operations: Submit request; Pass validated input; Submit request
Autocomplete API
Pin generation; filter and return K
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: and policy checks
Connected operations: Submit request; Pass validated input; Pass validated input; Pass validated input; Pass validated input; Pass validated input
Local / Redis Cache
Replicate hot prefix lists
Why, tradeoff and connected operations
Local memory and Redis reuse the top suggestions for hot prefixes. This avoids repeatedly reading the serving index for identical requests. These are derived caches; the published index generation determines the underlying suggestions.
Tradeoff: Stale data and miss storms
Connected operations: Pass validated input; Persist state; Pass validated input
Search Backend
Emit completed query events
Why, tradeoff and connected operations
Isolate this operation so it can scale and fail independently from storage.
Tradeoff: Privacy and abusive input
Connected operations: Submit request; Publish event
Suppression Policy
Emergency term filtering
Why, tradeoff and connected operations
Make ownership/version changes explicit; downstream resources must reject stale owners.
Tradeoff: Independent freshness bound
Connected operations: Pass validated input; Pass validated input
RocksDB Prefix KV Replicas
Versioned base + overlay candidates
Why, tradeoff and connected operations
RocksDB stores precomputed prefix-to-suggestion lists locally on serving replicas. Direct key reads avoid a network database lookup for each typed character. An embedded key-value index fits this fixed query better than joining tables at request time.
Tradeoff: List duplication and memory
Connected operations: Persist state; Persist state
Kafka / Raw Archive
Durable event replay
Why, tradeoff and connected operations
Kafka retained partitioned stream. Key events by the domain ordering key; replay and independent consumers motivate this choice. rows remain in the source database; a relay publishes after commit. Buffer independent producers and consumers, with bounded and replay semantics.
Tradeoff: and data access cost
Connected operations: Publish event; Consume work
Flink / Query Statistics
Dedup and aggregate popularity
Why, tradeoff and connected operations
Compute derived state away from request handlers; checkpoints and govern recovery.
Tradeoff: Hot queries; state
Connected operations: Consume work; Persist state
Index Publisher
Activate complete
Why, tradeoff and connected operations
Make ownership/version changes explicit; downstream resources must reject stale owners.
Tradeoff: Fenced rollout and version skew
Connected operations: Pass validated input; Persist state; Pass validated input; Pass validated input
Prefix Index Builder / Ranking
Produce bounded prefix top-M
Why, tradeoff and connected operations
Build immutable RocksDB index artifacts; this is compute, not a database. Partition durable state by the documented lookup key; consistency follows the explicit replication policy.
Tradeoff: Prefix write amplification
Connected operations: Persist state; Persist state
Immutable Index Snapshots
Checksums and retained generations
Why, tradeoff and connected operations
Object storage keeps validated immutable index generations. Servers can download the same version and retain older versions for rollback. It distributes bulk index artifacts; it is not the live prefix-query database.
Tradeoff: Build and rollback storage
Connected operations: Persist state; Pass validated input
etcd Manifest Registry
publication and pinning
Why, tradeoff and connected operations
Consensus-backed small active-generation pointer; data artifacts remain immutable object storage. Make ownership/version changes explicit; downstream resources must reject stale owners.
Tradeoff: Control-plane availability
Connected operations: Pass validated input; Pass validated input
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Additional technical detail
1 · Requirements and interview contract
Given a typed prefix and locale, return the top 5–10 popular query suggestions, incorporate trends within 1–5 minutes and support regional/language differences. Exclude full search results, personalization, typo correction and ML training from the baseline. This article follows the accessible guided Search Autocomplete walkthrough in the Google Interview Prep chat, with explicit publication, privacy and recovery details added for revision.
- Targets: 100M DAU, 30 suggestion requests/user/day, approximately 35k average and 150k peak; below 100 ms and 99.99% availability. These are illustrative design assumptions, not Google production numbers.
- Semantics: suggestions can be slightly stale and differ between regions. Each response must use a coherent index generation. Blocked/private queries must be filtered according to an explicit policy freshness bound.
- Read path: precomputed prefix → top-K candidates, not a full scan of query logs for every keystroke. A failed indexing job must not stop serving the last valid index.
- Clarify: minimum prefix length, normalization, supported scripts, maximum input bytes, trend sensitivity and whether deleted/blocked terms need emergency suppression. Drive requirements → scale → model → → four deep dives → failures → final summary.
2 · Scale and capacity
| Assumption / calculation | Design implication |
|---|---|
| 100M × 30 = 3B requests/day / 86,400 ≈ 34.7k | Design for 150k peak plus regional failover. Client debounce and cancelled requests reduce work but capacity must use observed effective requests. |
| 150k × 1 KB response = 150 MB/s before protocol overhead | Keep payloads compact, cap K and avoid heavyweight ranking RPCs per keystroke. |
| Illustrative 100M prefix-locale entries × 10 candidates × 32 bytes = 32 GB raw candidate references/scores | Keys, strings, indexes and allocator overhead add substantially. Three replicas ≈ 96 GB raw; keeping old and new generations doubles that. Measure encoded size rather than promising all data fits one machine. |
| 100M completed searches/day ≈ 1,157 events/s; 500 bytes/event ≈ 50 GB/day | Completed queries drive popularity; suggestion impressions should not recursively amplify their own rank. Archive and multiply storage. |
| 1M changed queries/minute × 20 prefixes/query ≈ 333k candidate updates/s | Aggregate first and cap normalization/prefix length. Updating every prefix synchronously on every event creates hot writes. |
3 · APIs, entities and component choices
| / state | Choice and guarantee |
|---|---|
| GET /v1/suggestions?prefix=new&locale=en-US&limit=5 | Stateless regional validates locale/length, normalizes input and returns {suggestions, indexVersion, freshness}. Client attaches request sequence and discards responses for older text. |
| SearchEvent(eventId, normalizedQuery, eventTime, locale, region) | Search backend emits completed-query events to Kafka. Stable event identity supports bounded dedup. Object storage archives approved events for reproducible rebuilding. |
| QueryStats((locale, query, bucket), count, scoreInputs) | Flink aggregates into durable /analytical summaries with -consistent updates. Keep raw counts separate from ranking scores so reranking is reproducible. |
| PrefixSuggestions((generation, locale, normalizedPrefix), candidates) | Distributed index serves precomputed top-M candidates; M may exceed displayed K for filtering. Hash full key to distribute storage; replicate hot entries at serving nodes. |
| IndexManifest(generation, baseVersion, overlayVersion, normalizationVersion, shards, checksums, sourceWatermark) | Immutable object storage artifacts plus a small strongly consistent publisher registry. completeness precedes activation; one request pins one . |
| Local / regional Redis | Cache key includes generation, locale, prefix, limit/ranking-policy version as needed. Shared cache is optional when local replicated hot sets suffice; cache misses are bounded/coalesced. |
| Policy suppression set(version, deniedTermIds) | Separately distributed emergency denylist, checked after cache/index retrieval. A rollback of ranking must not roll back a safety deletion. Policy delivery has its own freshness . |
4 · Deep dive 1 — Trie versus precomputed KV
A shares prefixes and can keep top-K suggestions at selected nodes; lookup follows the prefix in O(prefix length) before returning K candidates. A compressed /FST can reduce memory. However, live mutation and distributing a giant introduce ownership, versioning and memory-management complexity. Prefix matching over Unicode also needs a precise normalization version; byte slicing can split characters incorrectly.
Choose precomputed prefix → top-M entries in a distributed index for this design. A serving node performs a direct lookup, then filters and returns K. Use normalized full prefix and locale in the partition key. Storing a list for every prefix duplicates candidates; mitigate with query IDs, compressed lists, maximum prefix length, minimum popularity and shared long-prefix structures. A query beginning with an unseen prefix returns no suggestions or a bounded locale fallback; never start an unbounded scan.
Ranking: use documented weighted short/long-window popularity and decay, with stable query-ID tie breaking. Cap contribution per actor/source and minimum cohort size to reduce spam and private-query leakage. For exact top-K over an allowed corpus, the build must consider all eligible candidates; a bounded read-time merge only guarantees top-K within its retained candidate set.
Tradeoff: is operationally simple and independently shardable but uses more storage; /FST favors compact immutable serving and more specialized tooling. Recovery: index shards are derived from versioned artifacts and query stats; restore a healthy replica or rebuild without blocking all locales. Different normalization versions must never share a cache namespace.
5 · Deep dive 2 — Freshness without synchronous write amplification
The search backend sends completed events → Kafka → checkpointed aggregator → query statistics. A builder periodically creates a stable base index using a cutoff . To hit a 1–5 minute freshness target, build smaller incremental overlays from new or changed query statistics and affected prefixes. The retrieves a bounded candidate list from base and overlay, deduplicates by query ID, applies current policy and ranks.
The overlay is a versioned replacement of candidate scores, not an unqualified extra count added to a base that may already include those events. Pin (base generation, overlay generation, source cutoffs) together. For a simple baseline, publish full/minibatch replacement generations every few minutes and add overlays only when rebuild cost requires them.
- : count normalized full queries before expanding prefixes. Hot queries can use salted local counters, then merge compact partials. Prefix builders process batches; a burst of events must not repeatedly rewrite the same short-prefix record.
- Event semantics: dedup stable IDs over the supported retry window; use event-time buckets with bounded lateness. Extremely late events feed the next rebuild rather than reopening unlimited state. Popularity tolerates some estimation, but record any sampling explicitly.
- Reproducibility: records input watermarks, normalization/ranking code versions and policy version. Replay a failed build against the same inputs; never publish a half-complete delta.
- Tradeoff/recovery: overlays improve trend freshness at the cost of merge complexity and extra reads. If aggregation or overlay publication fails, serve the base with a freshness indicator, catch up from retained events, and compact once a new base includes the overlay cutoff.
6 · Deep dive 3 — Hot prefixes and cache failure
Partitioning only by first character concentrates load on common prefixes. Hash (locale, complete prefix, generation) for storage balance, but remember that hashing cannot split one hot key. Replicate hot prefix lists in local caches across many serving nodes; load balancing spreads identical reads. Redis gives a shared regional layer when its hit rate justifies the extra hop.
Use request coalescing, , bounded index concurrency and a small prewarmed hot-prefix set. On Redis failure, do not allow 150k to bypass directly into an unprovisioned backing store. Serve last-known-good local entries within a freshness limit, shed excess requests and return an empty optional suggestion list when necessary. Searching itself remains available through the independent search service.
Clients debounce briefly, cancel obsolete requests and keep a monotonic request counter: if response for 'ne' arrives after 'new', discard it. Server cancellation is best effort and does not replace rate limits. Normalize case/Unicode according to locale without turning distinct meaningful queries into the same key accidentally. Cap request bytes and execution time to resist abuse.
Tradeoff: replication consumes memory and rollout bandwidth; stale local caches relax freshness. Recovery: prewarm a new generation progressively, use per-key single-flight and ramp traffic after an outage. Monitor hot-key , cache hit ratio, backing-store saturation and client-visible , not just fleet averages.
7 · Deep dive 4 — Atomic publication and multi-region
There is no assumed transaction across every record. Generation-keyed records plus a switch provide coherent publication. Retain N while requests and caches still refer to it; garbage-collect only after a grace period/reference check. Canary one locale or small traffic percentage, compare empty-result rate, policy violations and latency, then expand. Rollback changes the active to a verified retained version, preserving the latest suppression policy.
Replicate artifacts independently to each region. A region activates only complete local versions; global simultaneous activation is unnecessary. During a network partition, continue serving the last verified generation. A failed region redirects to another with an available locale index and sufficient read capacity; freshness may differ. The small publication authority uses fenced ownership/consensus, while serving continues if that is down.
Privacy/deletion: raw query logs can contain sensitive text. Apply , restricted access, aggregation thresholds and audit trails. An emergency suppression update must reach serving gates independently of a slow base rebuild. If policy freshness exceeds the permitted bound, suppress affected suggestions or fail closed for the affected cohort. Removing a query only in the next daily build is not timely deletion.
8 · Failure recovery and observability
| Scenario | Recovery and guarantee |
|---|---|
| Kafka / aggregator outage | Serve previous index; persist events in an explicitly durable backend if lossless counts are required, otherwise document bounded analytics loss. Restore checkpoints/replay and show freshness lag. |
| Builder crashes halfway through N+1 | Never activate incomplete . Resume deterministic artifacts or abandon generation; N remains readable. |
| Cache fleet failure / hot prefix | Local hot set, coalescing and concurrency limits protect index. Return fewer/no suggestions if necessary; do not delay search submission. |
| New normalization or ranking bug | Version keys, canary metrics and rollback; retain prior generation. Do not reinterpret old records in place. |
| Region fails during rollout | Route to a healthy region's complete , even if older. No cross-region on every read. |
| Suppressed query still in old cache | Apply latest suppression after cache retrieval. Alert on policy-version age and sampled blocked-term leaks. |
Track p50/ latency by locale/prefix length, empty response rate, request cancellations, source-to-index lag, oldest unprocessed event, version skew, build validation failures, memory usage, query privacy thresholds and suppression propagation. Cost includes candidate-list duplication, two retained generations, Redis memory, stream state, event and cross-region rollout bytes. Version schemas, replay a sample before migration and use per-locale rollback.
9 · Final architecture and repeat queue
I separate low-latency prefix serving from asynchronous popularity computation. Completed searches enter Kafka and a checkpointed aggregator; builders turn query statistics into versioned prefix-to-candidate indexes. Regional APIs use local/Redis caches and replicated lookups, pin one generation, filter current policy and return top-K. I distribute updates by full query, batch prefix changes and replicate hot reads. Base and overlay use explicit cutoffs to avoid double-counting scores. Immutable manifests enable complete activation and rollback; regions may serve different valid versions. Indexing failure costs freshness, while cache failure triggers bounded fallback. I monitor , index age and policy propagation.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Prepare suggestions before the user types | A key-value index repeats candidate lists. A compact prefix tree can save space, but needs more specialized building and lookup code. |
| Read one complete index version | Stage and test complete artifacts, then change the active pointer. Keep an older complete generation for rollback and keep suppression policy current. |
| Remove blocked suggestions independently of rebuilding | If required policy is too old, hide affected results instead of skipping the check. Safety can reduce result availability during policy outages. |
| What happens if a region fails? | Tighter global freshness needs more synchronization; regional activation accepts measured ranking staleness while keeping safety policy separate. |
| Rebuild suggestions without slowing down reads | More frequent rebuilds improve freshness but increase amplification, retained-state cost and rollout risk. |
Production scars & failure modes
An emergency suppression disappears when an old index generation is restored.
Look for: Compare active index, cache generation and independent suppression policy version.
Recovery and invariant: Apply suppression after cache/index retrieval and keep that policy independent of ranking rollback; atomically activate only complete index generations.
| Component / failure | Required behavior / recovery | Operational implication |
|---|---|---|
| Kafka / aggregator outage | Serve previous index; persist events in an explicitly durable backend if lossless counts are required, otherwise document bounded analytics loss. | Restore checkpoints/replay and show freshness lag. |
| Builder crashes halfway through N+1 | Never activate incomplete . | Resume deterministic artifacts or abandon generation; N remains readable. |
| Cache fleet failure / hot prefix | Local hot set, coalescing and concurrency limits protect index. | Return fewer/no suggestions if necessary; do not delay search submission. |
| New normalization or ranking bug | Version keys, canary metrics and rollback; retain prior generation. | Do not reinterpret old records in place. |
| Region fails during rollout | Route to a healthy region's complete , even if older. | No cross-region on every read. |
| Suppressed query still in old cache | Apply latest suppression after cache retrieval. | Alert on policy-version age and sampled blocked-term leaks. |
90-second interview summary
I would keep expensive ranking and index construction off the keystroke path. Completed search events enter Kafka, processing builds query statistics, and offline workers produce bounded prefix-to-candidate lists. Serving replicas use immutable RocksDB-backed generations, with local or Redis caches for popular prefixes.
A request normalizes its prefix, pins one and reads a bounded top-candidate list. It applies the required suppression policy after cache/index retrieval and returns the allowed suggestions. Popular prefixes need read replication; hashing many different keys does not distribute one exceptionally hot prefix.
Publication validates coverage and checksums before activating a compatible base/overlay . Old generations remain for in-flight requests and rollback. Suppression is independently versioned, so ranking rollback cannot restore a banned suggestion.
I would roll out by locale or a small cohort, measure empty results, policy violations, latency and generation lag, and budget rebuilding separately from serving. Regions may temporarily use different complete ranking generations while meeting the safety-policy freshness requirement. The tradeoff is precomputation, retained-generation memory and publication complexity in return for fast, bounded reads; fresher ranking increases update amplification and must not make serving depend on a partially built index.
Explain it without looking
Explain prepare suggestions before the user types
Reveal answer
Store a small ranked candidate list for each supported prefix.
Searching raw query history on every keystroke does too much work for the response deadline.
A key-value index repeats candidate lists. A compact prefix tree can save space, but needs more specialized building and lookup code.
Explain read one complete index version
Reveal answer
Pin compatible base and recent-update files through one .
Adding an update twice, once in the base and once in the overlay, can distort ranking inputs.
Stage and test complete artifacts, then change the active pointer. Keep an older complete generation for rollback and keep suppression policy current.
Explain remove blocked suggestions independently of rebuilding
Reveal answer
Filter results using current suppression rules after every cache or index read.
An old cached answer can still contain a blocked term while a new offline index is being built.
If required policy is too old, hide affected results instead of skipping the check. Safety can reduce result availability during policy outages.
Explain what happens if a region fails?
Reveal answer
Serve a complete local index and keep blocked suggestions filtered.
Coherent local generations preserve useful availability without pretending all regions switch at the same instant.
Tighter global freshness needs more synchronization; regional activation accepts measured ranking staleness while keeping safety policy separate.
Explain rebuild suggestions without slowing down reads
Reveal answer
Precomputation moves cost off the keystroke path but creates publication and memory costs.
Serving and rebuilding compete for finite memory and bandwidth even when the read lookup is simple.
More frequent rebuilds improve freshness but increase amplification, retained-state cost and rollout risk.
Revision checklist
Revision checklist
- Reconstruct prepare suggestions before the user types: Store a small ranked candidate list for each supported prefix.
- Reconstruct read one complete index version: Pin compatible base and recent-update files through one .
- Reconstruct remove blocked suggestions independently of rebuilding: Filter results using current suppression rules after every cache or index read.
- Reconstruct what happens if a region fails?: Serve a complete local index and keep blocked suggestions filtered.
- Reconstruct rebuild suggestions without slowing down reads: Precomputation moves cost off the keystroke path but creates publication and memory costs.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope prefix suggestions, latency, and freshness. Estimate queries per keystroke and identify hot prefixes. |
| 15–30 min | High-level design | Draw the online prefix lookup and the offline statistics, ranking, and index publication pipeline. |
| 30–45 min | Deep dives | Explain precomputed top results and generation changes. Show where blocked suggestions are filtered. |
| 45–55 min | Failure and recovery | Walk through an invalid index publication or a hot-prefix surge. Roll back to a verified generation and protect the serving path. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough