Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← AI system designAI guideAdvanced#system-design#search#rag#citations
Frame · ai-engineering / case-studies / 05-ai-answer-engine.mdGuide 096 / 103

Design an AI search and answer engine

An answer engine takes a question, searches the web (or its own index), reads the best sources, and writes a cited answer. Perplexity popularized the format, and Google, OpenAI and others now ship versions of it. The model is the visible part, but in my experience the quality is decided by retrieval. Perplexity's own public statements (via its search vendor Vespa) put it bluntly: they invest as much in retrieval as in models, and they want passages ranked at the finest granularity because models are brittle with noisy context.

Requirements

Functional

  • Users ask a question and get a streamed answer with inline numbered citations to sources.
  • Follow-up questions keep conversational context.
  • Modes: quick answer (a few seconds) and "pro" search that does more queries and reading.
  • Freshness: news and prices from today should be findable.

Non-functional

  • Time to first token of a few seconds even though retrieval happens first.
  • Citation accuracy: every cited claim must be supported by the cited source.
  • Cost per query bounded, since every query triggers search plus LLM calls.
  • Respect robots.txt and publisher terms; handle takedowns.

Scale estimates (assumptions)

QuantityAssumptionResult
Queries per day20Mabout 230/s average, 700/s peak
Sub-queries per question3about 2,100 search calls/s at peak
Pages fetched and read8 per questionabout 5,600 page reads/s at peak if not cached
Passages into the prompt15 x 200 tokensabout 3,000 tokens of context per answer
Own index1B pages, 20 passages each20B passages, which is why most teams start with a search API

The estimate tells you the build vs buy decision: crawling and indexing the web is a separate company-sized project. A realistic design uses third-party search APIs for breadth and an owned index for high-value, high-freshness verticals, then grows the owned index over time.

High-level architecture

Rendering diagram…

Request flow

Rendering diagram…

Components

ComponentResponsibilityNotes
Query plannerRewrite and decompose the question, detect intent and freshness needsSmall fast model; this step is latency-critical
Search fan-outQuery several backends in parallel with timeoutsMerge with reciprocal rank fusion; dedupe by canonical URL
Page fetcherDownload, render if needed, cacheRespect robots.txt; per-domain politeness; short TTL for news
ExtractorStrip boilerplate, keep headings, tables, datesBad extraction is a top cause of bad answers
Multi-stage rankerCheap scoring on many passages, expensive cross-encoder on fewPassage-level, not page-level
Answer modelSynthesize with inline citationsLarger model for pro mode
Citation verifierCheck claims against cited passageSmall NLI-style model or LLM judge, sampled or full
Owned indexHybrid retrieval with continuous updatesVespa, OpenSearch or Elasticsearch style engines

Data model

CREATE TABLE pages (
  url_canonical  TEXT PRIMARY KEY,
  domain         TEXT,
  fetched_at     TIMESTAMPTZ,
  published_at   TIMESTAMPTZ,
  content_hash   TEXT,
  quality_score  REAL,
  status         TEXT           -- ok | blocked | removed
);

CREATE TABLE passages (
  id             BIGINT PRIMARY KEY,
  url_canonical  TEXT,
  ordinal        INT,
  text           TEXT,
  embedding      VECTOR(768)
);

CREATE TABLE answers (
  id             UUID PRIMARY KEY,
  thread_id      UUID,
  question       TEXT,
  queries        JSONB,
  cited_passages BIGINT[],
  model          TEXT,
  latency_ms     INT,
  cost_usd       NUMERIC(10,5)
);

Storing exactly which passages were cited per answer is what makes evaluation, debugging and takedowns possible.

Deep dives

Query planning

The raw user question is often a bad search query. "Is it delayed?" as a follow-up needs the subject from history. The planner produces two to five search queries, flags whether recency matters (to set date filters and pick news sources), and chooses quick vs deep mode. Keep it to one small-model call with a structured JSON output; this sits directly on the TTFT path.

Multi-stage ranking

Ranking is a funnel:

  1. Retrieval: a few hundred candidates from BM25, vectors and external APIs.
  2. First-phase ranking: cheap features (BM25 score, vector similarity, domain quality, freshness) over passages.
  3. Second-phase ranking: a cross-encoder reranker over the top 50 passages.
  4. Diversity: cap passages per domain so one SEO farm does not dominate the context.

Vespa's write-ups on Perplexity describe exactly this layered approach: narrow cheaply, then apply richer neural models to the most promising results, all inside one engine to avoid network hops between a vector DB, keyword DB and model server.

Latency budget

A plausible budget for quick mode: planning 300 ms, parallel search 600 ms, fetch (mostly cache) 500 ms, ranking 200 ms, then first token. Streaming hides the rest. Tactics: start fetching pages as soon as the first search backend returns, use search snippets as early context when fetch is slow, and set hard timeouts so one slow site cannot block the answer. Show sources in the UI before the answer starts; it reads as progress.

Citations you can trust

Give each passage a short id in the prompt and instruct the model to cite after every claim. Then verify: for each sentence with a citation, check that the cited passage supports it. Unsupported sentences get dropped, re-cited, or flagged. This is also your best offline metric: citation precision (cited source supports claim) and recall (claims that need a source have one).

Freshness and caching

Cache at several levels: search results per normalized query (minutes for news, hours otherwise), fetched pages by URL with TTL based on how often the page changes, and passages by content hash. For the owned index, a freshness scheduler re-crawls pages based on observed change rate and query demand. Do not cache final answers for long; they depend on time and context.

Cost control

Every question costs search API calls, fetches and two or three LLM calls. Route simple factual questions to a small model, keep the answer context tight (15 good passages beat 50 mediocre ones), and reserve multi-step research for explicit pro mode with per-user quotas.

Trade-offs and pitfalls

  • Search API vs own index. APIs give breadth fast but limit ranking control and add per-call cost. Own index gives control and cost efficiency at scale but is a major investment.
  • Page-level vs passage-level context. Dumping whole pages wastes tokens and buries the relevant sentence. Passage ranking is worth the complexity.
  • Prompt injection from the web. Pages can contain hidden instructions. Treat fetched content as data, never give this pipeline action tools, and strip hidden text during extraction.
  • Source quality. SEO spam and AI-generated content farms are everywhere. Domain quality signals and per-domain caps help.
  • Publisher relations. Respect robots directives and provide attribution and takedown paths; this is legal and reputational risk, not just etiquette.
  • Over-citation. Ten citations on one sentence looks rigorous and helps no one. Limit citations per claim.

Checklist

  • Clear build vs buy decision for the search index, justified by the estimate.
  • Query planner rewrites, decomposes and detects freshness needs in one fast call.
  • Ranking is multi-stage and passage-level, with domain diversity.
  • Latency budget per stage with hard timeouts and parallel fetches.
  • Citations verified against passages, and citation precision tracked as a metric.
  • Multi-level caching with TTLs tuned for freshness.
  • Fetched content treated as untrusted; no action tools in this path.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.