← Building blocks

Suggest as the user types

Data processing & searchsenior

Prefix search over millions of terms in under 50 ms.

Say it like this

Suggestions have to appear within about 50 milliseconds of each keystroke, so I precompute the top results for every prefix offline and serve them from memory, and I only touch a search engine for the long tail.

Basic solution

Build a trie or a sorted prefix index with precomputed top-k per prefix, held in memory and refreshed offline.

trieElasticsearch completion suggesterRedis sorted sets

Precomputed prefix lists, one lookup per keystroke

An offline job builds the top-k list for every prefix and swaps it into memory. The hot path is a single lookup, with the shortest prefixes cached at the edge and a small live layer for terms created since the last build.

How it works

  1. An offline job builds the set of terms to suggest (usernames, hashtags, past queries) and gives each a popularity score from recent usage, for example how often it was searched or used in the last 30 days.
  2. For every term, the job writes out every prefix up to a cap such as 20 characters, and for every prefix computes the top k terms by score. The result is a map from prefix to a short list of ids: this is the precomputed-prefix index. A trie is the same idea stored more compactly, with shared prefixes stored once and the top-k list kept at each node.
  3. The index is loaded into memory on the suggestion servers, or into Redis as one sorted set per prefix, and replicated to every region so the lookup is close to the user.
  4. On each keystroke the client sends the current prefix, debounced so it sends at most one request every 100 ms. The server does one lookup of that prefix and returns the stored top k; the hot path is a single hash lookup or one ZRANGE, with no scanning or sorting.
  5. Prefixes of one or two characters are the hottest keys and have the largest lists, so their responses are cached at the CDN or on the client, and their result size is capped.
  6. The index is rebuilt on a schedule (hourly for trending terms, daily for the rest) and swapped in atomically. New terms appear after the next rebuild, or sooner through a small live layer of recent terms that the server merges into results at query time.

Why precompute

  • A live prefix query over 100M terms on every keystroke is a range scan followed by a sort by popularity, under a 50 ms budget at thousands of requests per second; precomputing turns it into a lookup.

Worked example

User and hashtag search box on the news feed

  • 50M users, 30M hashtags, each with a 30-day popularity score; average term length 12 characters; keep top 10 per prefix.
  • Prefix count: with a 20-character cap, each term contributes up to 12 prefixes on average but prefixes are shared heavily; in practice about 150M distinct prefixes for 80M terms.
  • Index size: 150M prefixes x (10 ids x 8 bytes + overhead) = roughly 15 GB as a flat prefix map; a compressed trie with shared prefixes brings it to 4 to 6 GB. Fits in memory on each of a handful of suggestion servers, or in a Redis cluster with sorted sets.
  • Traffic: 50M DAU, 2 searches per day, 6 keystrokes each after debouncing: 600M suggestion requests per day, 7K per second average, 25K per second at peak. A single lookup per request at 0.2 ms CPU is a few cores; the network round trip dominates, so replicate per region to keep it under 20 ms.
  • Hot prefixes: the 36 single-character prefixes take about 15 percent of requests; cache their responses at the CDN for 60 seconds, which removes them from the origin entirely.
  • Rebuild: hashtags trend within minutes. Hourly rebuild of the hashtag index (30M terms, a few minutes of batch work) plus a live layer of the last hour's new terms in a small in-memory set merged into results; the user index rebuilds daily.
  • Fuzzy and personal: typo tolerance (one edit) multiplies candidate prefixes by about 50; personalisation (friends first) is a re-rank over the top 50 instead of 10, done in the suggestion server with a per-user friend set from cache. Both stay inside the budget because the base lookup is cheap.

Variants and when each wins

Precomputed prefix map

  • A hash map or Redis sorted sets from each prefix to its top k ids. It wins on simplicity and lookup speed; memory grows with the number of prefixes and the size of k.

Trie with per-node top k

  • A tree where each node is one more character and holds the top k for the prefix it spells, so shared prefixes are stored once. It wins on memory for the same lookup cost; it is harder to update in place, so it is usually rebuilt and swapped.

Search engine completion suggester

  • Elasticsearch or OpenSearch build a weighted finite-state structure per shard with fuzzy matching and context filters built in. It wins when a search cluster already exists and you need typo tolerance; it adds a network hop and a fan-out across shards.

Live prefix query on a sorted index

  • A database or Redis range scan on the prefix with a popularity sort at query time. It wins up to a few million terms because there is nothing to build; beyond that the scan and sort blow the latency budget.

Recommendation: a precomputed prefix index in memory or Redis for the main set, a small live layer for new terms, and the search engine only for fuzzy or long-tail queries that miss the precomputed index.

Failure modes

Single-character prefix storms

  • Suggestion p99 spikes to hundreds of milliseconds at peak. It happens because the one-character prefixes are the hottest keys with the largest payloads, and they all live on one shard. Cache responses for prefixes under three characters at the CDN or on the client, cap each payload at 10 items, and replicate the hot keys across nodes.

Stale trends

  • A hashtag everyone is using today does not autocomplete until tomorrow. It happens because the index is rebuilt only once a day. Rebuild the trending set hourly, and keep a live layer of terms created since the last build that is merged into results at query time.

Request per keystroke without debounce

  • Traffic is five times what the estimate predicted and most responses are thrown away. It happens because the client sends a request on every character and renders replies as they arrive, out of order. Debounce to one request per 100 ms, cancel the in-flight request when a new character is typed, and ignore any response for a prefix the user has already moved past.

Index swap takes the service down

  • A minute of errors every hour. It happens because the server loads the new index into the same memory the old one occupies, so requests fail while the load is in progress. Build the new index beside the old one, swap a pointer atomically, then release the old one.

Offensive or private terms suggested

  • A private username or a banned word appears as a suggestion. It happens because the term set was built from raw data without applying the product's filters. Apply the same block lists and privacy flags the product uses when building the term set, and remove terms promptly when they are reported.

Interviewer follow-ups

Answer out loud before you open each one.

Why store the top k per prefix instead of walking the trie at query time?

Walking a trie from a short prefix visits every term beneath it, which for a two-letter prefix can be millions, and then needs a sort by popularity. Storing the top k at each node makes the query a single lookup regardless of how many terms share the prefix.

How do you add a brand-new term within minutes without rebuilding everything?

Keep a small live layer: an in-memory set of terms created since the last build, with their prefixes indexed on insert. At query time merge the live layer results with the precomputed list and re-sort the combined top k; the next scheduled rebuild folds them in.

How would you personalise suggestions without a per-user index?

Fetch a slightly larger candidate list, say the top 50 rather than 10, then re-rank in the suggestion server with a per-user signal from cache such as followed accounts or recent searches. The shared index stays shared; personalisation is a cheap re-sort at the end.

What is the memory estimate and how would you cut it?

Distinct prefixes times the stored list size: around 150M prefixes with 10 ids each is about 15 GB flat. Cut it by capping prefix length, storing ids rather than strings, dropping k for long prefixes where few terms remain, and using a compressed trie so shared prefixes are stored once.

Connections

Built on
Trie · Inverted index
Pairs with
Full-text and fuzzy search · Cache the hot reads · Serve static bytes from the edge · Process large data offline · Spread a hot key

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon CloudFrontCDNCloud CDN, Media CDNAzure Front DoorCloudflare, Fastly, Akamai
Amazon EC2 Auto ScalingSuggest serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon EMRIndex builderDataprocAzure Databricks, HDInsightApache Spark, Databricks
Amazon DynamoDBTerms + popularityFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra