Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 1

Designing typeahead under 100 ms

Work through a typeahead design for a bookshop: estimate keystroke traffic, split a 100 ms latency budget, compare edge n-grams, the completion suggester and a precomputed top-k table, then size, cache and refresh the table safely.

Contentsand lesson path

What you will learn

  • Scale a search cluster with shards and replicas and serve typeahead within a latency budget.

01. The problem

An online bookshop wants suggestions under its search box: as a shopper types har, the box should offer harry potter and other popular searches that start with those letters. The target is that suggestions appear within 100 ms of the keystroke at the 99th percentile (p99), for shoppers in the region the service runs in. Suggestions are the same for everyone, come from past searches, and may be up to an hour old.

Every number below is an assumption to check against real logs, and each estimate gives a best, expected and worst case:

  • 4 million searches a day go through the box.
  • A shopper types 9 characters before choosing (6 to 14), and the busiest hour runs at 3 times the daily average (2.5 to 4).
  • After dropping rare queries, 5 million distinct queries are worth suggesting, and the box shows 8 of them.

02. Step 1: estimate the load and split the budget

Start with the worst simple design, one request per keystroke, because it gives an upper bound. The script also writes the latency budget down as numbers that must add up to 100, and sizes the table that step 3 builds.

Python 3.12 · typeahead_plan.py
"""Estimates for a bookshop typeahead. Every input is an assumption to check
against your own logs. Python 3.12, standard library only."""
import math

SEARCHES_PER_DAY = 4_000_000
CASES = {  # characters typed per search, peak-to-average ratio
    'best': (6, 2.5),
    'expected': (9, 3.0),
    'worst': (14, 4.0),
}
print('case      requests/day  average/s  peak/s')
for case, (chars, peak_ratio) in CASES.items():
    per_day = SEARCHES_PER_DAY * chars  # one request per keystroke, no debounce
    average = per_day / 86_400
    print(f'{case:<9} {per_day:>12,} {average:>10,.0f} {average * peak_ratio:>7,.0f}')

BUDGET_MS = {'browser: input event and render': 10, 'network round trip': 50,
             'load balancer and TLS': 5, 'suggestion service': 15, 'slack': 20}
print(f'latency budget, p99: {sum(BUDGET_MS.values())} ms in total')
for part, ms in BUDGET_MS.items():
    print(f'  {ms:>3} ms  {part}')

QUERIES = 5_000_000  # distinct queries kept after dropping rare ones
MAX_PREFIX = 12  # longer prefixes fall back to filtering the 12-character entry
TOP_K, ID_BYTES = 8, 4
entries = QUERIES * MAX_PREFIX  # upper bound: shared prefixes make it smaller
for overhead in (32, 48, 96):  # key bytes plus hash-table overhead per entry
    per_entry = TOP_K * ID_BYTES + overhead
    gib = entries * per_entry / 2**30
    print(f'{entries:,} entries x {per_entry} B = {math.ceil(gib * 10) / 10} GiB')
STRING_BYTES = 20 + 40  # average query text plus string overhead
text = QUERIES * STRING_BYTES / 2**30
lists = QUERIES * 50 * ID_BYTES / 2**30  # 50 ids on each 12-character prefix
print(f'plus {text:.1f} GiB of query text and at most {lists:.1f} GiB of 50-id lists')
Expected output (python3 typeahead_plan.py)
case      requests/day  average/s  peak/s
best        24,000,000        278     694
expected    36,000,000        417   1,250
worst       56,000,000        648   2,593
latency budget, p99: 100 ms in total
   10 ms  browser: input event and render
   50 ms  network round trip
    5 ms  load balancer and TLS
   15 ms  suggestion service
   20 ms  slack
60,000,000 entries x 64 B = 3.6 GiB
60,000,000 entries x 80 B = 4.5 GiB
60,000,000 entries x 128 B = 7.2 GiB
plus 0.3 GiB of query text and at most 0.9 GiB of 50-id lists

The expected peak is about 1,250 requests per second, and the worst case about 2,600. That is modest traffic; the hard part is the latency, not the volume.

The budget explains why. The network round trip is an assumption for shoppers on broadband or 4G near the region, and it takes half of the 100 ms on its own. A round trip between the US and Europe is around 100 ms by itself (reference numbers), so for shoppers that far away no server is fast enough: serve them from a region or an edge location close to them. That leaves 15 ms at p99 for the suggestion service itself. A lookup in memory fits easily. A full search that fans out over many shards might fit on average and miss at p99. Keep the 20 ms of slack: it absorbs garbage-collection pauses, a quick retry inside the data centre and slow phones.

03. Step 2: choose how to find completions

There are three common designs, and the script below tries the first two in OpenSearch on six titles (start the node from lesson 01 first).

  • Edge n-grams. At index time, each word is also stored as its first 1, 2, 3 and more letters, so the prefix pot becomes an ordinary term. It finds word prefixes anywhere in a title, works with filters and normal relevance, and needs no extra pipeline. The costs: more terms in the index (a 7-letter word becomes 7 terms), and every keystroke is a full search across the shards.
  • The completion suggester. A completion field builds an in-memory structure (a finite-state transducer) that is fast for prefix lookups and supports weights. It matches only from the start of each input you give it.
  • A precomputed top-k table. A batch job reads the search logs, counts each query, and stores the best k completions for every prefix. A keystroke becomes one lookup in memory. It suggests what people search for, not what is in the catalogue, and it needs a pipeline to build and ship the table.
Python 3.12 · os_autocomplete.py
"""Edge n-grams and the completion suggester in OpenSearch.
Python 3.12, standard library only. Run it against an empty local node."""
import json
import os
import urllib.error
import urllib.request

OS = os.environ.get('OS_URL', 'http://localhost:9200')
TITLES = ['Harry Potter', 'Hamlet', 'Hard Times', 'Norwegian Wood', 'The Hobbit',
          'House of Leaves']


def call(method: str, path: str, body=None, ndjson: str | None = None):
    data = ndjson.encode() if ndjson else json.dumps(body).encode() if body else None
    req = urllib.request.Request(OS + path, data=data, method=method,
                                 headers={'Content-Type': 'application/json'})
    try:
        with urllib.request.urlopen(req) as resp:
            return json.load(resp)
    except urllib.error.HTTPError as err:
        return json.load(err)


GRAMS = {'type': 'edge_ngram', 'min_gram': 1, 'max_gram': 10}
tokens = call('POST', '/_analyze', {'tokenizer': 'standard', 'text': 'Harry Potter',
                                    'filter': ['lowercase', GRAMS]})
print('edge n-grams:', ' '.join(t['token'] for t in tokens['tokens']))

call('DELETE', '/books')
call('PUT', '/books', {
    'settings': {'number_of_shards': 1, 'number_of_replicas': 0, 'analysis': {
        'filter': {'grams': GRAMS},
        'analyzer': {'prefixes': {'tokenizer': 'standard',
                                  'filter': ['lowercase', 'grams']}}}},
    'mappings': {'properties': {
        'title': {'type': 'text', 'analyzer': 'prefixes',
                  'search_analyzer': 'standard'},
        'title_grams_both': {'type': 'text', 'analyzer': 'prefixes'},
        'suggest': {'type': 'completion'}}}})
lines = []
for i, title in enumerate(TITLES):
    doc = {'title': title, 'title_grams_both': title, 'suggest': title}
    lines += [json.dumps({'index': {'_id': str(i)}}), json.dumps(doc)]
call('POST', '/books/_bulk?refresh=true', ndjson='\n'.join(lines) + '\n')


def match(field: str, typed: str) -> list[str]:
    body = {'query': {'match': {field: typed}}, 'sort': ['_doc']}
    hits = call('POST', '/books/_search', body)['hits']['hits']
    return [h['_source']['title'] for h in hits]


def complete(typed: str) -> list[str]:
    body = {'suggest': {'s': {'prefix': typed, 'completion': {'field': 'suggest'}}}}
    options = call('POST', '/books/_search', body)['suggest']['s'][0]['options']
    return [o['text'] for o in options]


show = lambda titles: ' | '.join(titles) or '(none)'
for typed in ('har', 'pot', 'wood'):
    print(f'edge n-grams {typed!r:<6} -> {show(match("title", typed))}')
both = match('title_grams_both', 'har')
print(f"grams at query  'har' -> {len(both)} of {len(TITLES)} titles,"
      f" starting {show(both[:3])}")
for typed in ('har', 'pot'):
    print(f'completion   {typed!r:<6} -> {show(complete(typed))}')
Expected output (python3 os_autocomplete.py, OpenSearch 2.19.4)
edge n-grams: h ha har harr harry p po pot pott potte potter
edge n-grams 'har'  -> Harry Potter | Hard Times
edge n-grams 'pot'  -> Harry Potter
edge n-grams 'wood' -> Norwegian Wood
grams at query  'har' -> 5 of 6 titles, starting Harry Potter | Hamlet | Hard Times
completion   'har'  -> Hard Times | Harry Potter
completion   'pot'  -> (none)

Edge n-grams found Harry Potter from pot and Norwegian Wood from wood, because every word was split into prefixes. The completion suggester found nothing for pot: Harry Potter does not start with it. The line in the middle is a classic mistake. When the same n-gram analyzer also runs on the query, har becomes h, ha and har, and 5 of the 6 titles match on the single letter h. The field must use the standard analyzer at search time, as the title mapping does.

For this bookshop, the budget points to the precomputed table for the box itself. Its 15 ms server share is easy to keep with one lookup, and popular searches are what shoppers expect to see. Edge n-grams stay useful on the results page, where a full search runs anyway.

04. Step 3: build, size and refresh the table

The script builds the table from a cleaned log of queries with the number of distinct users who searched each one. It keeps the top 3 for every prefix of up to 6 characters, to keep the output short (the real table keeps 8 for up to 12 characters). Longer input filters the candidates stored on its first 6 characters. The dictionary is a flat form of a trie (prefix tree) whose every node stores its top completions; a real trie, or the FST inside the completion suggester, shares common prefixes and needs less memory. Tries shows how to build one.

Python 3.12 · topk_prefix.py
"""Precompute the top completions for every prefix, then answer keystrokes with
one dictionary lookup. Python 3.12, standard library only."""
from collections import defaultdict

# Yesterday's search log after cleaning: query -> number of distinct users.
LOG = {
    'harry potter': 9_200, 'hobbit': 6_200, 'hunger games': 5_100,
    'hamlet': 2_400, 'hamilton': 1_900, 'harry potter cursed child': 1_800,
    'harry potter box set': 1_300, 'house of leaves': 900, 'history of rome': 700,
    'hard times': 300, 'haruki murakami': 2_100, 'harper lee': 1_100,
    'hartley lane 14 flat 2': 2,
}
MAX_PREFIX, TOP_K = 6, 3
MIN_USERS = 50  # drop rare queries: they leak private searches and add noise


def build(log: dict[str, int]) -> dict[str, list[str]]:
    table = defaultdict(list)
    for query, users in log.items():
        if users < MIN_USERS:
            continue
        for end in range(1, min(len(query), MAX_PREFIX) + 1):
            table[query[:end]].append(query)
    rank = lambda q: (-log[q], q)  # most users first, ties alphabetical
    # Keep extra candidates on the longest prefix so longer input can filter them.
    return {p: sorted(qs, key=rank)[:TOP_K if len(p) < MAX_PREFIX else 50]
            for p, qs in table.items()}


def suggest(table: dict[str, list[str]], typed: str) -> list[str]:
    typed = typed.lower()
    if len(typed) <= MAX_PREFIX:
        return table.get(typed, [])[:TOP_K]
    candidates = table.get(typed[:MAX_PREFIX], [])
    return [q for q in candidates if q.startswith(typed)][:TOP_K]


table = build(LOG)
kept = sum(users >= MIN_USERS for users in LOG.values())
print(f'{len(LOG)} queries, {kept} kept -> {len(table)} prefixes stored')
for typed in ('h', 'ha', 'har', 'harry p', 'harry potter b', 'zz'):
    print(f'{typed:>14} -> ' + (' | '.join(suggest(table, typed)) or '(none)'))

# The next hourly rebuild includes a query that is suddenly popular.
fresh = build(LOG | {'hamnet': 8_000})
print(f"{'ha':>14} -> " + ' | '.join(suggest(fresh, 'ha')) + '  (after the rebuild)')
Expected output (python3 topk_prefix.py)
13 queries, 12 kept -> 41 prefixes stored
             h -> harry potter | hobbit | hunger games
            ha -> harry potter | hamlet | haruki murakami
           har -> harry potter | haruki murakami | harry potter cursed child
       harry p -> harry potter | harry potter cursed child | harry potter box set
harry potter b -> harry potter box set
            zz -> (none)
            ha -> harry potter | hamnet | hamlet  (after the rebuild)

Four decisions are visible here:

  • Privacy first. The query hartley lane 14 flat 2, an address typed by 2 people, never reaches the table, because only queries from at least MIN_USERS distinct users are suggested. Add a blocklist for offensive terms and a way to remove a suggestion within minutes.
  • Bounded prefixes. Capping stored prefixes at a fixed length bounds the table: harry potter b is answered by filtering the candidates of harry. The cost: a query that ranks below the kept candidates of the capped prefix can never be suggested for longer input. Choose the cap from the logs, from how often people type past it, or send longer input to a normal search.
  • Memory. The last four lines of step 1 give an upper bound: 5 million queries times 12 prefixes is at most 60 million entries, or 3.6 to 7.2 GiB depending on overhead, plus 0.3 GiB for the query text and at most 0.9 GiB for the longer candidate lists. Shared prefixes make the real figure smaller. Either way it fits in one server's memory, so each serving node holds the whole table and any node can answer any keystroke. Splitting the table by first letter would only make load uneven, because far more searches start with s than with x.
  • Freshness. The nightly table did not know hamnet; an hourly rebuild over a recent window put it second for ha. Build each version offline, ship it as one file, and let every node load it and switch over in one step, so that no node serves a half-built table.

Finally, cache what is shared. The browser keeps responses for the prefixes it has already asked about, which makes backspacing free. Responses are identical for everyone, so a CDN can cache short prefixes for a few minutes with Cache-Control: public, max-age=300; see Cache layers from HTTP to the database. If you later personalise suggestions, mark those responses private, so that they never enter a shared cache.

05. Check your understanding

Practice check · 3 questions

Typeahead design decisions

Three questions on prefix matching, freshness and privacy.

Q1. A bookshop's box uses the OpenSearch completion suggester with each book title as the only input. Shoppers who type 'kill' get no suggestion for 'To Kill a Mockingbird'. Why, and what fixes it?
Q2. Suggestions come from a top-k table rebuilt each night from yesterday's logs. A film release makes 'hamnet' the most searched query this morning, but the box shows 'hamlet' and 'hamilton' until tomorrow. Which change helps most?
Q3. A box built from raw search logs starts suggesting 'maria lopez 12 elm road' to other shoppers after one person searched for it. Which safeguard stops this kind of leak?
Practice only: not graded, not saved, not evidence.

06. Apply it

Add a search box to the product search design of this skill:

  1. Copy typeahead_plan.py and replace the inputs with numbers for your shop; keep a best, expected and worst case.
  2. Write a latency budget that adds up to your target, and name where users far from the region are served.
  3. Choose edge n-grams, the completion suggester or a precomputed table for the box, and give the one reason that decided it.
  4. Describe the build job: input logs, privacy threshold, blocklist, rebuild interval and how nodes switch to a new version.
  5. List what is cached in the browser and at the CDN, and for how long.

07. Review prompt

Without looking back, explain: how to estimate keystroke traffic and why the estimate is an upper bound; how a 100 ms budget splits and what it leaves for the server; the trade-offs of edge n-grams, the completion suggester and a precomputed table; why the table is copied to every node rather than split by letter; and how the table stays fresh and safe.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check