Skip to content

Part 5 · Blueprint 28

Search Engine & Real-Time Typeahead

15 min reading · Sources · Editorial review pending

A fast index can return stale or unauthorized candidates.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Indexes & Storage Engines: B-Trees vs. LSM Trees, Message Queues & Event Streams: Kafka vs. RabbitMQ, Database Sharding & Consistent Hashing.

Sixty-second mental model

Problem: A fast index can return stale or unauthorized candidates.

Use: Separate candidate retrieval from current result eligibility.

Design boundary: Support lexical search and ranked prefix suggestions as distinct query paths. A search index is a derived view whose document version and authorization scope must remain meaningful. Begin with a bounded corpus and explicit freshness target.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing search and typeahead. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one query means and which component owns the searchable document version.

Think of a book index with a ranked prefix directory. Separate the requester from searchable document version, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.

Architecture and worked reasoning

Design boundary: Support lexical search and ranked prefix suggestions as distinct query paths. A search index is a derived view whose document version and authorization scope must remain meaningful. Begin with a bounded corpus and explicit freshness target.

Responsibilities on the request path

Search and typeahead: responsibilities and request directionSupport lexical search and ranked prefix suggestions as distinct query paths. A search index is a derived view whose document version and authorization scope must remain meaningful. Begin with a bounded corpus and explicit freshness target.Document changesIndex builderSearch shardsQuery merger
Support lexical search and ranked prefix suggestions as distinct query paths. A search index is a derived view whose document version and authorization scope must remain meaningful. Begin with a bounded corpus and explicit freshness target.

Domain interface and access patterns

GET /search?q=...&cursor=... → authorized ranked documents; GET /suggest?prefix=... → bounded suggestions

source_documents(tenant_id, document_id, revision, state); index_generations(id, analyzer_version, source_boundary); postings(term, document_id, source_revision); prefix_candidates(prefix, candidate_id, rank_version). The index is derived and cannot independently restore revoked eligibility.

Workload and limiting resource

Hypothetical corpus has 10,000,000 documents with 100 distinct indexed terms each, producing up to 1,000,000,000 term-document associations before compression and other index structures. For a prefix candidate list of 1,000 items, returning ten suggestions requires ranking and eligibility work; a top-ten cache cannot guarantee ten authorized results if several are filtered later.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

Search and typeahead: mutation boundaryCommit a source revision and change identity. Then: Build postings/prefix structures with versioned analyzer rules. Then: Publish a coherent index generation and apply later changes by source revision.Step 1
Commit a source revision and change identity.
Step 2
Build postings/prefix structures with versioned analyzer rules.
Step 3
Publish a coherent index generation and apply later changes by source revision.
Commit a source revision and change identity. Then: Build postings/prefix structures with versioned analyzer rules. Then: Publish a coherent index generation and apply later changes by source revision.
  1. Commit a source revision and change identity.
  2. Build postings/prefix structures with versioned analyzer rules.
  3. Publish a coherent index generation and apply later changes by source revision.

Observation and recovery path

Search and typeahead: observation boundaryNormalize a query under the selected analyzer. Then: Search authorized partitions/candidates. Then: Merge top results with deterministic tie-breaking and current eligibility checks.Step 1
Normalize a query under the selected analyzer.
Step 2
Search authorized partitions/candidates.
Step 3
Merge top results with deterministic tie-breaking and current eligibility checks.
Normalize a query under the selected analyzer. Then: Search authorized partitions/candidates. Then: Merge top results with deterministic tie-breaking and current eligibility checks.
  1. Normalize a query under the selected analyzer.
  2. Search authorized partitions/candidates.
  3. Merge top results with deterministic tie-breaking and current eligibility checks.

Failure that changes the decision

Hypothetical scenario: A reindex built from an old snapshot swaps in after live updates. Define the snapshot boundary, retained change stream and catch-up point before replacing the active generation.

Attempt this decision before reading the explanation

Why not serve typeahead by scanning every document whose title contains the prefix?

That turns every keystroke into work proportional to a broad corpus. Use a prefix-oriented structure and bounded ranking path, while preserving update/version and permission semantics; the exact structure depends on corpus and ranking needs.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

Hypothetical scenario. Priya can search restricted supplier notes, but the public catalogue search box must not disclose those note titles in suggestions.

In short. Distinguish exact identity from tolerant discovery. Authorize suggestions and cached snippets before disclosure.

Hypothetical scenario. An internal catalogue supports product search and suggestions while a person types. Exact part identifiers should work, misspelled names should be useful, and restricted items must stay hidden. A new search engine responds quickly but ranks an obsolete product above the current one.

This case separates indexing, candidate generation, ranking, eligibility and presentation. Scope includes text search, exact identifiers, bounded prefix suggestions, index updates and evaluation. A public web crawler and model training are excluded. The design begins with the user's query contract rather than choosing a search product and adopting all its defaults.

Search is a derived view. Its latency and relevance are not enough if source versions and permissions are wrong. Decide what delay is acceptable for new items, updates, withdrawal and access changes; these transitions can require different treatment.

A prefix search for a typed fragment, an exact identifier lookup and a multiword topical query have different semantics. Applying fuzzy matching everywhere can turn a precise identifier into an unrelated near-match. Applying exact matching everywhere can make ordinary wording unhelpful.

Normalization also changes meaning. Case folding, punctuation handling, tokenization and language rules may be useful for names but harmful for identifiers where characters distinguish products. Preserve fields with their intended search behavior rather than putting everything into one analyzed string.

PostgreSQL’s pg_trgm documentation describes trigram similarity and index support for matching text. Such a matching mechanism supplies candidates; the product still decides whether an approximate spelling match is acceptable for a given query.

Ingestion preserves source identity, current version and visibility metadata. A transformation produces typed fields and searchable tokens under a named analyzer version. Updates and withdrawals carry ordered version evidence so retries do not restore obsolete state.

Keep an exact path for structured identifiers. A prefix index or suitable ordered dictionary can support suggestions; an inverted index can retrieve documents containing query terms. A ranking function orders the selected candidates under an explicit query interpretation.

Perform the required eligibility checks before returning titles, snippets or suggestions. A restricted name leaked through autocomplete is still a disclosure even if clicking it later produces an access error. Cache keys must preserve scope and relevant index versions.

Search is a projection of source records into a representation that supports specific query operations. PostgreSQL full-text and trigram matching are examples of concrete retrieval mechanisms; neither determines what an approximate match means to a customer. Separate exact product identity, tolerant spelling suggestions and ranked discovery so a missing identifier does not silently become a different confirmed item.

Suppose, hypothetically, fifty thousand users each make four search requests daily. The daily query count is 50,000 × 4 = 200,000. If the interface issues five suggestion requests while each search is typed, suggestions add 200,000 × 5 = 1,000,000 requests. The combined total is 1,200,000 requests per day before retries. These are illustrative interaction assumptions, not observed usage or a benchmark of any search engine.

A projection release should name the source revision, schema and analyzer settings that produced it. A new analyzer can change which terms are recognized; a new ranking policy can change the order even when the index bytes stay fixed. Evaluate the required query slices and record the selected release together, rather than referring to one timeless search index.

Suggestions need eligibility checks before text reaches the user. A result page that rejects a restricted document cannot undo a title already disclosed by an autocomplete cache. Carry the tenant and access context into every evidence-producing step, including suggestion generation and any shared cache. A current source permission decision must also have a defined relationship to a stale derived view.

Relevance and freshness need different evidence. Use known-item queries to check exact identity and representative discovery queries to compare ranking. Track publication and withdrawal separately so a useful mean score does not hide a source that was removed but remains suggestible. An opaque cursor should represent a defined ordering or result snapshot if the interface promises continuation across updates.

Hypothetical scenario. Choose 100,000 source records with an average of 20 indexed term occurrences. The logical occurrence count is 100,000 × 20 = 2,000,000. At a chosen eight bytes per occurrence record, raw payload is 16,000,000 bytes, or 16 MB. Dictionaries, positions, skip structures, stored fields, allocation and replication are excluded.

Suppose 1,000 people each type a five-character query, issuing one suggestion request after every character. That creates 1,000 × 5 = 5,000 requests. If a deliberate client policy emits only two requests for each completed typing sequence in this example, demand becomes 1,000 × 2 = 2,000. This is a constructed event schedule, not a universal reduction from a particular debounce duration.

For candidate evaluation, choose 40 candidates and a maximum returned page of ten. If eligibility removes 12,28 remain, so a full ten-item page is possible. If eligibility instead removes 35, only five remain. Filling the page requires another bounded candidate fetch or an explicit shorter result; the original candidate budget cannot guarantee ten.

A relevance case has four labeled relevant records. The returned top five include three of them. Precision is 3 ÷ 5 = 0.6 and recall is 3 ÷ 4 = 0.75 at that cutoff. These measures depend on the labels and query, not only the index algorithm.

A backlog of 60,000 updates with 6,000 successful updates per minute and 3,000 new updates per minute drains at 3,000 per minute, requiring 60,000 ÷ 3,000 = 20 minutes. A withdrawal contract that cannot tolerate that delay needs another serving-side protection or prioritized update path.

PostgreSQL’s pg_trgm documentation specifies trigram similarity operations and index support for approximate text matching. Use that concrete mechanism to distinguish candidate retrieval from the product’s interpretation of a query.

A ranking improvement can make popular queries better while damaging exact identifiers. Evaluate query families separately: known-item lookup, typo recovery, ambiguous names, rare terms and no-result behavior. Preserve the expected distinction between an exact match and a suggestion.

Layer 3 · Internals

Trade-offs and limits

ApproachProvidesRequires
Query-time candidate rankingCan use current signals without rebuilding every prefix result.Traversal and scoring consume work on each query.
Precomputed prefix candidatesReduces repeated lookup work for a selected ranking policy.Updates, eligibility holes and popularity shifts require refresh or fallback.

Recovery decision

Hypothetical scenario: A reindex built from an old snapshot swaps in after live updates. Define the snapshot boundary, retained change stream and catch-up point before replacing the active generation.

That turns every keystroke into work proportional to a broad corpus. Use a prefix-oriented structure and bounded ranking path, while preserving update/version and permission semantics; the exact structure depends on corpus and ranking needs.

Write your design before revealing the review

Why not serve typeahead by scanning every document whose title contains the prefix?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

That turns every keystroke into work proportional to a broad corpus. Use a prefix-oriented structure and bounded ranking path, while preserving update/version and permission semantics; the exact structure depends on corpus and ranking needs.

A reindex built from an old snapshot swaps in after live updates. Define the snapshot boundary, retained change stream and catch-up point before replacing the active generation.

Check your understanding

Why not serve typeahead by scanning every document whose title contains the prefix?

That turns every keystroke into work proportional to a broad corpus. Use a prefix-oriented structure and bounded ranking path, while preserving update/version and permission semantics; the exact structure depends on corpus and ranking needs.

How would you recover from this failure: A reindex built from an old snapshot swaps in after live updates. Define the snapshot boundary, retained change stream and catch-up point before replacing the active generation.

Start with the exact boundary that failed. Commit a source revision and change identity. Build postings/prefix structures with versioned analyzer rules. Publish a coherent index generation and apply later changes by source revision. Then recover evidence through the observation path: Normalize a query under the selected analyzer. Search authorized partitions/candidates. Merge top results with deterministic tie-breaking and current eligibility checks. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

Hypothetical corpus has 10,000,000 documents with 100 distinct indexed terms each, producing up to 1,000,000,000 term-document associations before compression and other index structures. For a prefix candidate list of 1,000 items, returning ten suggestions requires ranking and eligibility work; a top-ten cache cannot guarantee ten authorized results if several are filtered later. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Support lexical search and ranked prefix suggestions as distinct query paths. A search index is a derived view whose document version and authorization scope must remain meaningful. Begin with a bounded corpus and explicit freshness target.

Which component in this topology could be removed from a smaller first deployment?

Document changes, Index builder, Search shards, Query merger name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Commit a source revision and change identity.

What evidence must a caller have before relying on the observation path?

Normalize a query under the selected analyzer. Search authorized partitions/candidates. Merge top results with deterministic tie-breaking and current eligibility checks. That turns every keystroke into work proportional to a broad corpus. Use a prefix-oriented structure and bounded ranking path, while preserving update/version and permission semantics; the exact structure depends on corpus and ranking needs.

45-minute interview rubric

  1. 00–05: scope query and searchable document version.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw searchable document version, numbered writes and reads.
  4. 28–40: challenge recovery: Separate candidate retrieval from current result eligibility.
  5. 40–45: defend document_id placement, observations and remaining assumptions.

Go deeper

Decision log

Separate candidate retrieval from current result eligibility.

Preserve query identity and searchable document version ownership.

Revisit changed workload, observations or recovery objectives.