Case study: design search autocomplete
A senior-level walkthrough of typeahead: the numbers behind a request per keystroke, a trie against a sorted array with range top-k, trending queries with decayed counts and heavy hitters, client and edge caching, and abuse, with tested C#.
Case studyApplied32 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 2 data models
- 1 API design
- 7 code samples
- 8 interviewer follow-ups
- 3 self-checks
On this page16 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Caching, Replication and sharding, Network performance for system designers
- Turn "suggest as you type" into numbers: requests per keystroke, an index small enough to replicate, and a latency budget the network dominates.
- Compare a trie with precomputed top-k, a sorted array with range top-k and an FST, and say what each costs in memory and update speed.
- Keep suggestions fresh with a static base index, a decayed-count overlay and a heavy-hitters summary of the stream.
- Cut load at the client and the edge with debouncing, prefix reuse and a prefix cache sized from a Zipf curve.
- Handle quality and abuse: one normaliser, privacy thresholds, a serve-time blocklist and manipulated counts.
7 code samples (369 lines), collapsed so the explanation stays in focus.
Type three letters into a search box and a list appears. It looks like a trivial feature, and it is one of the most demanding read paths in a search product: a request on nearly every keystroke, an answer expected before the next one, and a dataset that is small enough to hold in memory but is never allowed to go stale or say something it should not. This lesson designs it the way a senior round would: the high-level design (HLD) first, then the low-level design (LLD) with tested C#, then the follow-ups an interviewer uses to push.
It is a close cousin of caching and of the network lesson, because most of the latency is the trip, not the lookup.
Spend the first minutes on questions. Each answer changes the design.
| Ask | Why it matters |
|---|---|
| What are we completing: past queries, products, people, places, or a mix? | The corpus and the signals differ. Past queries mean mining logs. A catalogue means indexing it |
| Ranked by popularity, recency, the user's history, location? | Personalisation multiplies the index (per user or segment) and the cache keys |
| What is the latency target, and what does the client do on each keystroke? | About 100 ms feels instant. Every keystroke is a request unless the client holds back |
| How fresh must it be? | "Trending within minutes" needs a streaming path. "Updated daily" is a batch job |
| Typos? | Fuzzy matching costs far more than exact prefix matching |
| Which languages and scripts? | Normalisation, scripts without spaces, right-to-left text, and input methods that compose characters |
| What must never be suggested? | Blocked terms, personal queries, manipulated counts |
Functional: given a prefix and a locale, return the best few completions, ranked; reflect new searches within minutes; hide forbidden suggestions. Non-functional: p99 latency of tens of milliseconds at the server and about 100 ms at the client, availability higher than search itself (the box must never block typing), a build that cannot publish a bad index, and a cost that scales with replicas, not with queries. Out of scope: the search results page, spelling correction beyond a fallback, and the recommendation of products.
State assumptions out loud; they are illustrative and the interviewer may change them.
searches: 5B a day, 23 characters typed per search on average
requests: ~6 per search after debouncing = 30B a day
30B / 86,400 s = ~350,000/s, ~1M/s at peak (x3)
queries: keep those seen by enough users: ~100M x ~25 B = ~2.5 GB
index: sorted array ~3 GB; trie with top-8 lists ~25 GB (10x text)
either fits in one server's memory, so replicate it
response: 8 suggestions x ~25 B + JSON = ~400 B
1M/s x 400 B = ~400 MB/s = ~3.2 Gbit/s at peak, before a CDN
latency: client pause 100+ ms; round trip 20 to 80 ms; server 1 to 3 msFour conclusions:
- A million requests a second against a few gigabytes. Shard when the data does not fit; here it does. Replicate the whole index on every server and scale by adding replicas. Sharding by prefix would only create hot shards (more words start with "s" than with "x").
- The network dominates the latency. About 100 ms is where a response starts to feel immediate (Nielsen's response-time limits). A server answering in 2 ms cannot help a user who is 150 ms from the nearest data centre. The lever is distance and connection reuse: an edge location nearby, and a warm HTTP/2 or HTTP/3 connection with TLS resumption, so a request costs one round trip. See the network performance lesson.
- The traffic is very cacheable. Short prefixes repeat across all users, and popular queries repeat their longer prefixes too. A CDN cache keyed on the normalised prefix and locale takes most of the load.
- The client multiplies or divides the load by about 4. Without debouncing, a 23-character search is 23 requests. With it, about 6. This is the cheapest optimisation in the system.
- query
- q (the prefix, as typed), limit (default 8, maximum 10), locale (for example en-US)
- note
- cacheable with Cache-Control: public, max-age=60. The server normalises q first, and the CDN key is the normalised prefix plus locale
- 200returns { "suggestions": [{ "text": "system design", "score": 0.93 }, ...], "index_version": "2026-11-11T04" }
- 204no suggestions for this prefix
Personalised suggestions (a user's own recent searches) are a separate, small layer, merged on the client or the server and served with Cache-Control: private, so one person's history is never cached for another.
The serving index is not a database. It is a versioned, immutable file built offline from aggregated logs.
querytext
normalised: one canonical form, the same function as at serve time
PKSHARD KEYlocaletext
PKdaydate
daily aggregates, so decay can be applied at build time
PKsearchesbigint
usersbigint
distinct users: the privacy and abuse signal
Only queries searched by enough distinct users, and not blocked, reach the index.
versiontext
for example 2026-11-11T04
PKlocaletext
PKlocationtext
path of the serialised, immutable index file
checksumtext
statustext
building, validated, canary, live, retired
Servers download, verify, load and swap atomically. The previous version stays for rollback.
Read it as two paths that never wait for each other. The serving path is a lookup in an immutable in-memory index plus a merge with a small trending overlay, behind an edge cache. The build path turns the search log into a new index file, filters it, validates it and publishes it, and servers swap it in. A slow or failed build means stale suggestions, never errors.
The query is a prefix and the answer is the best k completions. Two facts make it cheap. All strings sharing a prefix are contiguous when the strings are sorted. And the answer for a prefix depends only on the queries beneath it, so it can be precomputed.
| Structure | Lookup | Memory | Update | Notes |
|---|---|---|---|---|
| Trie with the top-k at every node | Follow the prefix, return the stored list: O(length + k) | Highest: a child table and a k-entry list per node | Rebuild, or push a changed score up its path | The standard answer: no work at query time |
| Sorted array with range top-k | Two binary searches for the range, then the best k in it: O(k log n) | Lowest: each query once, plus a tree of maximum scores | Rebuild; immutable arrays are cache friendly | All queries with a prefix are one contiguous range |
| FST (finite state transducer) | Walk the automaton, take the best weights | Very compact: shares prefixes and suffixes | Immutable; rebuild | What Lucene-based suggesters use, held in memory |
| Inverted index with edge n-grams | One term lookup per n-gram | Large | Incremental | Flexible (words in the middle, fuzzy matching); heavier |
The last row is the full-text machinery with a twist: the search and inverted indexes lesson explains posting lists, ranking and segments, which is what makes that row incremental.
The trie with top-k at every node. Follow the prefix and return the list stored there. Nothing is computed at query time. The price is memory: each node carries a child table and a list of k entries, and a score change touches every ancestor, which is why it is rebuilt offline.
C# · SuggestionTrie, Node
using System;
using System.Collections.Generic;
using System.Linq;
public sealed class SuggestionTrie
{
private sealed class Node
{
public readonly Dictionary<char, Node> Children = new Dictionary<char, Node>();
public readonly List<(string Query, long Score)> Top = new List<(string, long)>();
}
private readonly Node _root = new Node();
private readonly int _k;
public int NodeCount { get; private set; } = 1;
public int StoredEntries { get; private set; }
public SuggestionTrie(int k) { _k = k; }
public void Add(string query, long score)
{
var node = _root;
Offer(node, query, score); // the empty prefix lists the overall best
foreach (char c in query)
{
if (!node.Children.TryGetValue(c, out var child)) { child = new Node(); node.Children[c] = child; NodeCount++; }
node = child;
Offer(node, query, score);
}
}
private void Offer(Node node, string query, long score)
{
int before = node.Top.Count;
node.Top.Add((query, score));
node.Top.Sort((a, b) => b.Score != a.Score ? b.Score.CompareTo(a.Score) : string.CompareOrdinal(a.Query, b.Query));
if (node.Top.Count > _k) node.Top.RemoveAt(node.Top.Count - 1);
StoredEntries += node.Top.Count - before;
}
public IReadOnlyList<string> Suggest(string prefix)
{
var node = _root;
foreach (char c in prefix)
if (!node.Children.TryGetValue(c, out node)) return Array.Empty<string>();
return node.Top.Select(t => t.Query).ToList();
}
}The sorted array with range top-k. Store every query once, sorted. Two binary searches give the range of queries that start with the prefix. The best query in that range comes from a segment tree of maximum scores. To get the next best, split the range around the winner and put both halves on a priority queue: the best remaining query is always at the top. That costs O(k log n) per lookup, and the memory is one entry per query plus the tree.
C# · SortedSuggestions
using System;
using System.Collections.Generic;
using System.Linq;
public sealed class SortedSuggestions
{
private readonly string[] _queries; // sorted by ordinal comparison, so a prefix is a contiguous range
private readonly long[] _scores;
private readonly int[] _tree; // bottom-up segment tree: the index of the best entry in each segment
private readonly int _n;
public SortedSuggestions(IEnumerable<(string Query, long Score)> items)
{
var sorted = items.OrderBy(i => i.Query, StringComparer.Ordinal).ToArray();
_n = sorted.Length;
_queries = sorted.Select(i => i.Query).ToArray();
_scores = sorted.Select(i => i.Score).ToArray();
_tree = new int[2 * _n];
for (int i = 0; i < _n; i++) _tree[_n + i] = i;
for (int p = _n - 1; p >= 1; p--) _tree[p] = Better(_tree[2 * p], _tree[2 * p + 1]);
}
// Higher score wins; on a tie the alphabetically earlier query (the lower index) wins.
private int Better(int a, int b) => _scores[a] > _scores[b] || (_scores[a] == _scores[b] && a < b) ? a : b;
private int LowerBound(string key)
{
int low = 0, high = _n;
while (low < high)
{
int middle = (low + high) / 2;
if (string.CompareOrdinal(_queries[middle], key) < 0) low = middle + 1; else high = middle;
}
return low;
}
private int BestIn(int left, int right) // inclusive range
{
int best = -1;
for (left += _n, right += _n + 1; left < right; left >>= 1, right >>= 1)
{
if ((left & 1) == 1) { best = best < 0 ? _tree[left] : Better(best, _tree[left]); left++; }
if ((right & 1) == 1) { --right; best = best < 0 ? _tree[right] : Better(best, _tree[right]); }
}
return best;
}
public IReadOnlyList<string> Suggest(string prefix, int k)
{
int low = LowerBound(prefix);
int high = LowerBound(prefix + char.MaxValue); // the first query after every query that starts with the prefix
var result = new List<string>();
if (low >= high) return result;
var ranges = new PriorityQueue<(int Best, int Left, int Right), (long Score, int Index)>(
Comparer<(long Score, int Index)>.Create((x, y) => x.Score != y.Score ? y.Score.CompareTo(x.Score) : x.Index.CompareTo(y.Index)));
void Push(int left, int right)
{
if (left > right) return;
int best = BestIn(left, right);
ranges.Enqueue((best, left, right), (_scores[best], best));
}
Push(low, high - 1);
while (result.Count < k && ranges.TryDequeue(out var range, out _))
{
result.Add(_queries[range.Best]);
Push(range.Left, range.Best - 1); // split around the winner
Push(range.Best + 1, range.Right);
}
return result;
}
}Both structures must give the same answer as the obvious slow method. This test builds a catalogue of 20,000 synthetic queries from a small vocabulary (so they share prefixes the way real queries do) and checks 1,500 prefixes, including the empty prefix and prefixes that stop in the middle of a word, against a brute-force scan.
C#
using System.Diagnostics;
var random = new Random(5);
string[] syllables = { "ka", "to", "mi", "ra", "lo", "ne", "su", "pi", "da", "ve", "xo", "zu", "bre", "cla", "tri", "sto" };
var vocabulary = Enumerable.Range(0, 1_500)
.Select(_ => string.Concat(Enumerable.Range(0, random.Next(2, 4)).Select(__ => syllables[random.Next(syllables.Length)]))).ToList();
var catalog = new List<(string Query, long Score)>();
var seenQueries = new HashSet<string>();
while (catalog.Count < 20_000)
{
// words are drawn with a skew toward the front of the vocabulary, so a few words are in many queries
string query = string.Join(" ", Enumerable.Range(0, random.Next(1, 4)).Select(_ => vocabulary[(int)(vocabulary.Count * Math.Pow(random.NextDouble(), 2.5))]));
if (seenQueries.Add(query)) catalog.Add((query, 1 + (long)(100_000 / (1.0 + catalog.Count) * (0.5 + random.NextDouble()))));
}
var trie = new SuggestionTrie(k: 8);
foreach (var (query, score) in catalog) trie.Add(query, score);
var sortedIndex = new SortedSuggestions(catalog);
string[] BruteForce(string prefix) => catalog
.Where(c => c.Query.StartsWith(prefix, StringComparison.Ordinal))
.OrderByDescending(c => c.Score).ThenBy(c => c.Query, StringComparer.Ordinal)
.Take(8).Select(c => c.Query).ToArray();
bool agree = true;
for (int i = 0; i < 1_500; i++)
{
string whole = catalog[random.Next(catalog.Count)].Query;
string prefix = whole.Substring(0, random.Next(0, whole.Length + 1));
var expected = BruteForce(prefix);
agree &= trie.Suggest(prefix).SequenceEqual(expected) && sortedIndex.Suggest(prefix, 8).SequenceEqual(expected);
}
Debug.Assert(agree, "the trie and the sorted array both match a brute-force scan");
Debug.Assert(trie.Suggest("qqq").Count == 0 && sortedIndex.Suggest("qqq", 8).Count == 0, "an unknown prefix has no suggestions");
Debug.Assert(trie.NodeCount > 5 * catalog.Count, "the trie needs several nodes per query");
Debug.Assert(trie.StoredEntries > 7 * catalog.Count, "and stores each query in the top-k list of many ancestors, where the array stores it once");In this catalogue the trie holds about seven nodes and nearly ten stored list entries for every query, against one entry (and two tree slots) in the array. Real queries share more prefixes than these, so measure your own data. The shape holds: the trie spends memory to save query time, and the array does the opposite, which is why many systems pick the array or an FST for a very large index and the trie for a small, hot one.
In production, avoid one heap object per node. A trie with hundreds of millions of nodes spends its life in the garbage collector, so flatten it into arrays or an FST, serialise the result to an immutable file, memory-map or load it once, and swap it atomically. Immutable data needs no locks on the read path.
A daily build cannot show a breaking-news query at the moment it matters. Use two time scales.
- The base index is rebuilt daily or hourly from aggregated logs. Its score is a decayed popularity over a long window, so last month's fashion fades.
- The overlay is a small structure fed by the stream of searches. It holds queries that are suddenly frequent, with counts that decay in minutes. At request time the server merges the base list with the overlay's list for the same prefix, ordered by a blended score.
Decayed counts are cheap to keep. A counter stores a value and the time it was last updated; reading it multiplies by 0.5 for every half-life that has passed.
Heavy hitters. The stream has too many distinct queries to keep a counter for each. The Space-Saving algorithm tracks the most frequent ones with a fixed number of counters. When a new item arrives and the table is full, it replaces the item with the smallest count and inherits that count plus one, recording the inherited count as its possible error. Its guarantees: any item whose true frequency is more than N/m (N events, m counters) is always in the table, and every reported count is at least the true count and at most the true count plus its recorded error. (A Count-Min sketch is the other standard tool for this, and it can also estimate the count of any single item; see probabilistic data structures.)
C# · DecayedCounter, SpaceSaving, ZipfSampler
using System;
using System.Collections.Generic;
using System.Linq;
public sealed class DecayedCounter
{
private readonly double _halfLifeSeconds;
private double _value, _updatedAt;
public DecayedCounter(double halfLifeSeconds) { _halfLifeSeconds = halfLifeSeconds; }
public void Add(double nowSeconds, double weight = 1)
{
_value = ValueAt(nowSeconds) + weight;
_updatedAt = nowSeconds;
}
public double ValueAt(double nowSeconds) => _value * Math.Pow(0.5, (nowSeconds - _updatedAt) / _halfLifeSeconds);
}
public sealed class SpaceSaving
{
private readonly int _capacity;
private readonly Dictionary<string, (long Count, long Error)> _counters = new Dictionary<string, (long, long)>();
public SpaceSaving(int capacity) { _capacity = capacity; }
public void Add(string item)
{
if (_counters.TryGetValue(item, out var counter)) { _counters[item] = (counter.Count + 1, counter.Error); return; }
if (_counters.Count < _capacity) { _counters[item] = (1, 0); return; }
var smallest = _counters.MinBy(kv => kv.Value.Count); // a linear scan here; production keeps counters in a structure with O(1) updates
_counters.Remove(smallest.Key);
_counters[item] = (smallest.Value.Count + 1, smallest.Value.Count);
}
public IEnumerable<(string Item, long Count, long Error)> Entries() => _counters.Select(kv => (kv.Key, kv.Value.Count, kv.Value.Error));
}
public sealed class ZipfSampler
{
private readonly double[] _cumulative;
private readonly Random _random;
public ZipfSampler(int items, int seed)
{
_random = new Random(seed);
_cumulative = new double[items];
double total = 0;
for (int i = 0; i < items; i++) { total += 1.0 / (i + 1); _cumulative[i] = total; } // item i has weight 1 / (i + 1)
}
public int Next()
{
double u = _random.NextDouble() * _cumulative[_cumulative.Length - 1];
int low = 0, high = _cumulative.Length - 1;
while (low < high)
{
int middle = (low + high) / 2;
if (_cumulative[middle] < u) low = middle + 1; else high = middle;
}
return low;
}
}C# · A query nobody searched yesterday starts trending: 100 searches a second for three…
// A query nobody searched yesterday starts trending: 100 searches a second for three minutes. Half-life 10 minutes.
var storm = new DecayedCounter(halfLifeSeconds: 600);
double weatherBase = 900_000, trendingWeight = 100; // a popular query's base score, and how much an overlay count is worth
int enteredAt = -1;
for (int second = 0; second < 3_600; second++)
{
if (second < 180) for (int search = 0; search < 100; search++) storm.Add(second);
if (enteredAt < 0 && trendingWeight * storm.ValueAt(second) > weatherBase) enteredAt = second;
}
Debug.Assert(enteredAt >= 60 && enteredAt <= 120, "the trending query overtakes a popular one after about 90 seconds");
Debug.Assert(trendingWeight * storm.ValueAt(180) > 1_500_000, "it peaks when the burst ends");
Debug.Assert(trendingWeight * storm.ValueAt(3_600) < weatherBase / 10, "and an hour later it has faded out of the top");
// 300,000 searches over 50,000 distinct queries with a Zipf popularity; 500 counters.
var sampler = new ZipfSampler(items: 50_000, seed: 11);
var truth = new Dictionary<string, long>();
var summary = new SpaceSaving(capacity: 500);
const int events = 300_000;
for (int e = 0; e < events; e++)
{
string query = "q" + sampler.Next();
truth[query] = truth.GetValueOrDefault(query) + 1;
summary.Add(query);
}
var tracked = summary.Entries().ToDictionary(entry => entry.Item);
var heavy = truth.Where(kv => kv.Value > events / 500).Select(kv => kv.Key).ToList();
Debug.Assert(heavy.Count > 30 && heavy.All(tracked.ContainsKey), "every query above N/m is tracked");
Debug.Assert(tracked.Values.All(t => t.Count - t.Error <= truth.GetValueOrDefault(t.Item) && truth.GetValueOrDefault(t.Item) <= t.Count), "count - error <= truth <= count");
Debug.Assert(truth.OrderByDescending(kv => kv.Value).Take(20).All(kv => tracked.ContainsKey(kv.Key)), "so the true top 20 are all there");
Debug.Assert(tracked.Count == 500 && truth.Count > 20_000, "using 500 counters for more than 20,000 distinct queries");The trending query overtakes a popular one about 90 seconds into the burst and is gone within the hour; 500 counters followed more than 20,000 distinct queries and kept every query above N/m, all with bounded error. A Count-Min sketch is the usual alternative: it estimates the count of any item in fixed memory, always rounding up, and is paired with a small heap of candidates to find the top.
The merge at request time is small: look up the base list, look up the overlay's list for the same prefix, add the overlay's weighted decayed count to each candidate's base score, sort the at most 2k candidates, and return k. Overlay results are more exposed to manipulation than the base, so they carry a higher distinct-user threshold and a shorter cache lifetime.
Most of the saving is before the request reaches your servers.
- Debounce. Send a request only when the user has paused for 100 to 150 ms.
- Cancel and ignore stale responses. A slow answer for "sys" must not replace the answer for "syste". Number the requests and show only the newest response.
- Reuse earlier answers. If the server returned fewer than k suggestions for a prefix, it listed every match. Any longer prefix can then be answered by filtering that list on the client, with no request, and no match is missed. An empty answer is the same case: nothing beyond that prefix will match either.
- Cache at the edge. Key on the normalised prefix, the locale and the index version. Pick a time to live from how stale you can bear (30 to 60 seconds). Use jittered expiry and one in-flight refill per key, so a popular prefix does not stampede the origin when it expires.
C# · Debounce, PrefixCache, LruCache
using System;
using System.Collections.Generic;
using System.Linq;
public static class Debounce
{
/// <summary>The requests sent when the client waits `delayMs` after the last keystroke before it asks.</summary>
public static List<(int AtMs, string Prefix)> Requests(string typed, int[] keyTimesMs, int delayMs)
{
var requests = new List<(int AtMs, string Prefix)>();
for (int i = 0; i < typed.Length; i++)
{
int next = i + 1 < typed.Length ? keyTimesMs[i + 1] : int.MaxValue;
if (next - keyTimesMs[i] >= delayMs) requests.Add((keyTimesMs[i] + delayMs, typed.Substring(0, i + 1)));
}
return requests;
}
}
public sealed class PrefixCache
{
private readonly Dictionary<string, (IReadOnlyList<string> Items, bool Complete)> _byPrefix = new Dictionary<string, (IReadOnlyList<string>, bool)>();
private readonly int _limit;
public PrefixCache(int limit) { _limit = limit; }
/// <summary>Remembers a server answer. Fewer than `limit` items means the server listed every match.</summary>
public void Store(string prefix, IReadOnlyList<string> items) => _byPrefix[prefix] = (items, items.Count < _limit);
/// <summary>Answers from memory when this prefix, or a shorter one that listed every match, has been seen.</summary>
public bool TryAnswer(string prefix, out IReadOnlyList<string> items)
{
if (_byPrefix.TryGetValue(prefix, out var exact)) { items = exact.Items; return true; }
for (int length = prefix.Length - 1; length >= 0; length--)
{
if (_byPrefix.TryGetValue(prefix.Substring(0, length), out var shorter) && shorter.Complete)
{
items = shorter.Items.Where(s => s.StartsWith(prefix, StringComparison.Ordinal)).ToList();
return true;
}
}
items = Array.Empty<string>();
return false;
}
}
public sealed class LruCache
{
private readonly int _capacity;
private readonly Dictionary<string, LinkedListNode<string>> _nodes = new Dictionary<string, LinkedListNode<string>>();
private readonly LinkedList<string> _recent = new LinkedList<string>();
public LruCache(int capacity) { _capacity = Math.Max(1, capacity); }
/// <summary>Returns true on a hit. A miss inserts the key and evicts the least recently used one when full.</summary>
public bool Touch(string key)
{
if (_nodes.TryGetValue(key, out var node)) { _recent.Remove(node); _recent.AddFirst(node); return true; }
_nodes[key] = _recent.AddFirst(key);
if (_nodes.Count > _capacity) { _nodes.Remove(_recent.Last.Value); _recent.RemoveLast(); }
return false;
}
}C#
string typed = "system design";
var quickly = Enumerable.Range(0, typed.Length).Select(i => i * 90).ToArray(); // a key every 90 ms
var withPause = Enumerable.Range(0, typed.Length).Select(i => i * 90 + (i >= 4 ? 600 : 0)).ToArray(); // a 600 ms pause after "syst"
Debug.Assert(Debounce.Requests(typed, quickly, 150).Count == 1, "typed quickly: one request, for the whole phrase");
Debug.Assert(Debounce.Requests(typed, withPause, 150).Select(r => r.Prefix).SequenceEqual(new[] { "syst", "system design" }), "a pause sends the prefix so far");
Debug.Assert(Debounce.Requests(typed, quickly, 0).Count == typed.Length, "without debouncing, every keystroke is a request");
// Prefix reuse: type 300 queries one character at a time. The "server" is the trie above; compare the answers with and without reuse.
var typing = new Random(21);
int requestsWithout = 0, requestsWith = 0;
bool sameAnswers = true;
for (int t = 0; t < 300; t++)
{
string wanted = catalog[typing.Next(catalog.Count)].Query;
var remembered = new PrefixCache(limit: 8);
for (int length = 1; length <= wanted.Length; length++)
{
string prefix = wanted.Substring(0, length);
var fromServer = trie.Suggest(prefix);
requestsWithout++;
if (remembered.TryAnswer(prefix, out var local)) sameAnswers &= local.SequenceEqual(fromServer);
else { requestsWith++; remembered.Store(prefix, fromServer); }
}
}
Debug.Assert(sameAnswers, "answers filtered on the client are identical to the server's");
Debug.Assert(requestsWith < 0.6 * requestsWithout, "and about half of the per-keystroke requests are never sent");
// The edge cache: 150,000 searches with Zipf popularity, every prefix requested (the worst case), LRU caches of 1%, 5% and 20% of all prefixes.
var byPopularity = catalog.OrderByDescending(c => c.Score).Select(c => c.Query).ToArray();
var distinctPrefixes = new HashSet<string>(byPopularity.SelectMany(q => Enumerable.Range(1, q.Length).Select(n => q.Substring(0, n))));
var hitRatios = new List<double>();
double shortPrefixHitsAtOnePercent = 0;
foreach (double share in new[] { 0.01, 0.05, 0.20 })
{
var edge = new LruCache((int)(distinctPrefixes.Count * share));
var searches = new ZipfSampler(byPopularity.Length, seed: 33);
long hits = 0, total = 0, shortHits = 0, shortTotal = 0;
for (int s = 0; s < 150_000; s++)
{
string wanted = byPopularity[searches.Next()];
for (int length = 1; length <= wanted.Length; length++)
{
bool hit = edge.Touch(wanted.Substring(0, length));
total++; if (hit) hits++;
if (length <= 3) { shortTotal++; if (hit) shortHits++; }
}
}
hitRatios.Add((double)hits / total);
if (share == 0.01) shortPrefixHitsAtOnePercent = (double)shortHits / shortTotal;
}
Debug.Assert(hitRatios[0] > 0.45 && hitRatios[0] < 0.62, "a cache of 1% of the prefixes answers about half the requests");
Debug.Assert(hitRatios[1] > 0.65 && hitRatios[1] < 0.80, "5% answers about three quarters");
Debug.Assert(hitRatios[2] > 0.80 && hitRatios[2] < 0.92, "20% answers about 85%");
Debug.Assert(shortPrefixHitsAtOnePercent > 0.90, "and prefixes of up to three characters almost never miss");With about half of the keystroke requests answered by the client and between half and 85 percent of the rest answered by a cache of 1 to 20 percent of all prefixes, the origin sees a small fraction of the keystrokes. These numbers come from synthetic data with a Zipf curve, so use them as a method, not as a forecast: replay your own logs through the same two loops to size the cache.
The serving tier is stateless and replicated. Each server holds the whole index in memory, loaded from a versioned artifact, and answers from it. It reports healthy only after the load, so a new server does not take traffic cold. Scaling is adding replicas, and losing one is invisible.
The build is a pipeline with gates. Aggregate the search log into per-query statistics, filter, score, serialise the index, then validate before anything is published: the size is within bounds, the top suggestions for the most common prefixes overlap the previous version by a sensible margin, no blocked term is present, and sample queries return something. Publish to the object store, release to a small canary, compare its metrics (latency, the share of requests with no suggestions, the click-through rate on suggestions) with the live version, and then roll out. Rollback is a pointer swap to the previous artifact, not a rebuild.
If the index outgrows one machine, shard by a hash of the first two or three characters (not by alphabetical range, which is skewed) and replicate each shard. Better first steps are a higher threshold for entering the index, a compact structure such as an FST, and keeping only the head in memory and the tail on SSD behind a prefix filter. A cache in front absorbs most of the head anyway.
Latency budget. Client pause 100 to 150 ms (not user-visible latency); round trip 20 to 80 ms on a warm connection; edge hit a few milliseconds; origin parse, normalise, lookup and merge 1 to 3 ms. Time-out a request after a few hundred milliseconds and show nothing new: the box must never wait for suggestions, and a missing list is better than a late one.
- One normaliser, used by the build and the server. Fold case, normalise Unicode to a single form (NFKC is the usual choice), collapse whitespace and strip control characters; decide per locale whether accents are folded, since many people type without them. If the build and the server disagree, queries silently miss. Test the function against a file of tricky inputs, and ship it as shared code. Compose-aware input methods should not fire requests while a character is still being composed.
- Privacy by threshold. Suggest only queries searched by many distinct users, and drop anything shaped like personal data (emails, phone numbers, account numbers). A raw count would let one person's unusual search appear for others.
- Policy. Search engines remove predictions that violate published rules, such as violent, hateful or sexually explicit ones, and combine automated filters with human enforcement. Apply the policy at build time, and keep a serve-time blocklist that is consulted on the output path and can be updated in minutes, because a rebuild takes hours and a bad suggestion goes viral in minutes.
- Manipulation. Anyone can search a phrase a million times. Count distinct users, cap each user's contribution per query per day, watch growth rates, and treat the trending overlay as the exposed surface. Sensitive categories can need human review before a trending term is allowed.
- Typos. Treat fuzzy matching as a fallback for prefixes with few or no exact matches, within an edit distance of one or two. A Levenshtein automaton intersected with a trie or an FST does it efficiently, but the Lucene suggester developers reported the fuzzy suggester about ten times slower than the exact one, so budget for it.
- Measure quality. Offline: hit rate in the top k for held-out searches, mean reciprocal rank, the share of prefixes with no suggestion. Online: suggestion acceptance, keystrokes saved per search, latency. Roll each new index to a slice of traffic and compare.
| Case | What goes wrong | Response |
|---|---|---|
| The build produces a bad index | Everyone gets bad suggestions | Validation gates against the previous artifact, a canary, and a one-step rollback |
| An offensive or legal suggestion goes live | Reputation and legal harm | Serve-time blocklist applied on the output path, edge purge by prefix, policy review |
| An overlay entry is wrong or manipulated | The edge caches it for everyone | Short time to live on overlay-influenced results, higher distinct-user threshold, purge |
| A popular prefix expires in the CDN | A stampede on the origin | Jittered expiry, one refill per key, stale-while-revalidate |
| An answer arrives out of order | The list shows an older prefix | Number requests, show only the newest response, cancel in flight |
| The origin is slow or down | Typing feels laggy | A client timeout, show nothing new, serve stale from the edge; never block the input |
| The log pipeline lags | Trending stops and the base ages | The overlay is optional and the base still serves; alert on freshness lag |
| A larger artifact than usual | Memory pressure, restarts | A size gate in the build, staged rollout, memory headroom |
| The user's script differs from the locale | Poor suggestions | Detect the script of the prefix and route to the matching index |
| Personalised results cached publicly | One user's history leaks to another | Cache-Control: private for any response that depends on the user |
Interviewer follow-upL5Why a trie with top-k at each node rather than computing the top k on each request?How to answer
Computing it per request means scanning every query under the prefix, which for a short prefix is a large share of the index. Precomputing the top k at each node moves that work to build time and makes the lookup the length of the prefix plus k. The cost is memory and slow updates, which are acceptable because the index is rebuilt offline. If memory is the problem, store each query once in a sorted array and find the top k in the prefix's range with a segment tree and a priority queue.
Interviewer follow-upL5Should you shard the index?How to answer
Not first. It is gigabytes, not terabytes, and the load is reads, so replicate it and add replicas. Sharding by alphabetical range creates hot shards, so if it must be sharded, hash a short prefix and replicate each shard. A cache in front removes most of the head anyway.
Interviewer follow-upL6A news event makes a new phrase the most searched thing in the world within minutes. What happens?How to answer
The base index cannot know, so the stream feeds a trending overlay: a heavy-hitters summary and decayed counts. The server merges the overlay's list with the base list for the same prefix. The new phrase appears after the overlay's counts pass the threshold, about a minute and a half in the simulation. Results influenced by the overlay get a short cache time, and the overlay has a stricter abuse threshold because it is the easiest thing to manipulate.
Interviewer follow-upL6How do you add personalisation without ruining the cache?How to answer
Keep the shared answer cacheable and add the personal part as a small separate layer: the user's own recent searches, merged on the client or the server after the cached result arrives. Any response that depends on the user is Cache-Control: private. If personalisation is by segment (language, region, device), include the segment in the cache key and keep the number of segments small.
Interviewer follow-upL6How do you stop people from gaming it?How to answer
Count distinct users, not searches. Cap what one user, device or network can add to a query per day, watch for abnormal growth, and hold the overlay to a higher bar than the base. For sensitive categories require review before a trending term is shown. Keep a serve-time blocklist for what slips through, and log the evidence so a removal can be explained.
Interviewer follow-upL7The product wants typo tolerance.How to answer
Do exact prefix matching first and use fuzzy matching only when it returns few results. Limit the edit distance (one for short prefixes, two for longer ones), intersect a Levenshtein automaton with the trie or FST, or use a precomputed deletion index, and rank exact matches above corrected ones. It costs several times an exact lookup, so cap its share of traffic and cache its results, and keep the exact path unaffected if the fuzzy one is slow.
Interviewer follow-upL7How would you evaluate whether a new ranking is better?How to answer
Offline first: replay held-out searches and measure hit rate at k, mean reciprocal rank and the share with no suggestion, per locale and prefix length. Then online with an experiment on a slice of traffic: suggestion acceptance, keystrokes saved, abandonment and latency, with guardrails on blocked-term exposure. Because the output is cached, the experiment arm must be in the cache key or the arms will contaminate each other.
Interviewer follow-upL7Extend it to many languages, including ones without spaces.How to answer
Index per locale and route by the script of the prefix. For scripts without spaces, the prefix is a sequence of characters, so the structures are unchanged, but the lookup must happen after the input method commits a composition, and matching on the pronunciation form (such as a phonetic reading) often needs a second index that maps to the written form. Normalisation rules become per-script. The build, the cache keys and the abuse thresholds are all per locale, which multiplies the pipelines, so automate them.
- Clarify: what is completed, ranking signals, latency, freshness, typos, languages, and what must never appear.
- Estimate: a request per keystroke, the debounce factor, an index of gigabytes, and a network-dominated latency budget.
- Contract and model: a cacheable GET with a normalised prefix and a version, and a versioned immutable index artifact.
- Draw the two paths: build (logs, filters, index, validation, artifact) and serve (edge, replicated in-memory servers, overlay).
- Go deep on the structure: a trie with top-k against a sorted array with range top-k, and what each costs.
- Make it fresh: a base index, a decayed overlay, heavy hitters, and a blended score.
- Cut the load: debounce, cancel, prefix reuse and an edge cache sized from a Zipf curve.
- Name quality and abuse: one normaliser, thresholds, a serve-time blocklist, manipulation, and measurement.
Autocomplete is a lookup of the best few completions of a prefix over an immutable, replicated, in-memory index. A trie with top-k at each node gives the fastest lookup and a sorted array with range top-k gives the smallest memory, and both are built offline from filtered, thresholded logs and swapped in atomically. Freshness comes from a small overlay of decayed counts and a heavy-hitters summary merged at request time. Most of the load never reaches the origin: the client debounces and reuses earlier answers, and the edge caches popular prefixes. Quality is a normaliser shared by the build and the server, privacy thresholds, a serve-time blocklist and defences against manipulation.
Try answering out loud before you reveal each answer.
QuestionThe index is 25 GB and the load is a million requests a second. Why replicate instead of shard it?Reveal answer
The index fits in one server's memory and the load is read-only, so every replica can answer every request, and capacity is added by adding replicas. Sharding would add a routing step and create hot shards, because prefixes are far from uniform. Shard only when the index no longer fits, and then by a hash of a short prefix.
QuestionA client has the server's answer for "syst" with only three suggestions. What can it do for "syste", and why is that safe?Reveal answer
Filter the three suggestions locally, with no request. The server returned fewer than its limit, so it listed every match for "syst", and every match for "syste" is also a match for "syst". Nothing can be missed. If the server had returned its full limit of eight, the list could be truncated and the client would have to ask.
QuestionWhy does a trending query appear within minutes, and why is the overlay the part to defend against abuse?Reveal answer
The stream updates decayed counts and a small heavy-hitters table as searches arrive, and the server merges them with the base list, so a query overtakes a popular one once its recent rate is high enough (about 90 seconds in the simulation) and fades within the hour. The overlay is driven by recent, unfiltered volume, which is exactly what a coordinated burst of fake searches manipulates, so it needs a higher distinct-user threshold, per-user caps, a short cache time and a serve-time blocklist.
- Jakob Nielsen, Response Times: The 3 Important Limits (opens in a new tab), Nielsen Norman Group: why about 0.1 second is the threshold for a response to feel immediate.
- Ahmed Metwally, Divyakant Agrawal and Amr El Abbadi, Efficient Computation of Frequent and Top-k Elements in Data Streams (opens in a new tab), ICDT 2005 (extended in ACM TODS 31, 2006): the Space-Saving algorithm and its guarantees.
- Graham Cormode and S. Muthukrishnan, An improved data stream summary: the count-min sketch and its applications (opens in a new tab), Journal of Algorithms 55(1), 2005.
- Michael McCandless, Using Finite State Transducers in Lucene (opens in a new tab), 2010: FSTs as a compact in-memory structure for terms and suggestions.
- Robert Muir and Simon Willnauer, Query Suggestions with Lucene (opens in a new tab), Berlin Buzzwords 2013: Lucene's in-memory suggesters, including the cost of fuzzy suggestion.
- Google, How Google autocomplete predictions work (opens in a new tab): predictions as a reflection of real searches, freshness, and the policies for removing predictions.