Design: AI answer engine (search + LLM)

In one sentence

Rewrite the query, search, fetch and rerank passages from the top pages, then stream an answer citing a passage per claim; head queries hit a cache and the first token lands in ~1–2 s.

Every stage before the first token has a deadline; the page cache keeps live fetches off the hot path, and citation checks run after the stream.

How it works

  • Scale: ~10M queries/day (~300 QPS at peak) at about a cent per query.
  • Live fetches get a hard ~800 ms deadline; most pages come from a pre-crawled page cache.
  • Buy search first; at ~$50k/day the API outspends the small model, the trigger to build an own index.
  • The worst failure is an unsupported citation; a 2023 study found only 51.5% of sentences fully supported.
  • Grade citation precision and recall apart from retrieval coverage, to split search failures from model failures.

Check yourself

Answer to mark it learned; your answers aren't scored.

To raise the cache hit rate, your team added a semantic cache over answers. Now users asking about this month's Fed decision get last month's answer, with citations that look fine. What's the right fix?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: answer any question in natural language from live web pages, with numbered inline citations; handle follow-ups that depend on the conversation; show the sources and suggested next questions. Non-functional: first token in ~1–2 s at p50 (under 3 s at p95), full answer in ~5 s, news fresh within minutes, ~10M queries/day, and about a cent per query, because ad or subscription revenue per query is small.

Questions I'd ask:

  1. Own index or third-party search API? That decides cost, latency and platform risk.
  2. Free or paid product? It sets the model tier and the cost ceiling.
  3. Which verticals need special rules: news, health, finance, shopping?
  4. How do we treat publishers: robots.txt opt-outs, paywalls, how much text we quote?
  5. Which languages and regions?

The highest-cost failure is a confident answer whose citation doesn't support it, above all on health, money or news. Citations are the product's promise, and they break often: in a 2023 human evaluation of four generative search engines, only 51.5% of sentences were fully supported by their citations.

High-level design

Understand (~100 ms, small model): classify intent and freshness need (news, evergreen, navigational, no search needed), rewrite a follow-up into a standalone query from recent turns (Query transformation (rewrite, HyDE)), and split comparisons into 2–3 sub-queries. Cache: head queries without conversation context hit an answer cache keyed by the normalized query, with a TTL per freshness class. Retrieve: a search API or own index (Hybrid search & RRF) returns ~15 URLs in ~350 ms; the top ~8 come from a pre-crawled page cache or a live fetch under a hard ~800 ms deadline. Main content is extracted and split into passages. Rank: a cross-encoder (Reranking (cross-encoders)) with authority and freshness boosts keeps ~12 passages (~5k tokens). Generate: the LLM streams over SSE (Streaming responses (SSE)) an answer built only from those numbered passages, citing [n] per sentence and saying when sources disagree or are thin. After: a small model writes related questions in parallel; an async checker samples answers for citation support. Page text is data, never instructions (Prompt injection (direct & indirect)); the path holds no private data and no side-effecting tools, which caps the blast radius.

Code Deadline-bound fetch, then a streamed, cited answer
pythonDeadline-bound fetch, then a streamed, cited answer
import asyncio, httpx

FETCH_DEADLINE_S = 0.8  # pages that miss it are dropped, never awaited

async def fetch_pages(urls: list[str], q: Query) -> list[Page]:
    async def one(http: httpx.AsyncClient, url: str) -> Page:
        page = page_cache.get(url)
        if page and page.age_s < q.max_age_s:  # pre-crawled copy, fresh enough for this intent
            return page
        r = await http.get(url)
        return extract_main_content(url, r.text)  # drop nav, ads and hidden text
    async with httpx.AsyncClient(follow_redirects=True, headers={"User-Agent": BOT_UA}) as http:
        tasks = [asyncio.create_task(one(http, u)) for u in urls]
        done, pending = await asyncio.wait(tasks, timeout=FETCH_DEADLINE_S)
        for t in pending:
            t.cancel()  # the tail loses; latency wins
        return [t.result() for t in done if t.exception() is None]

async def answer(text: str, history: list[Turn]):
    q = await understand(text, history)  # standalone query, intent, max_age_s
    if not history and (hit := answer_cache.get(q.cache_key)):  # head queries only
        yield hit
        return
    urls = await search_api(q.text, count=15)
    yield SourceCards(urls[:8])  # on screen at ~0.5 s, before any token
    pages = await fetch_pages(urls[:8], q)
    passages = rerank(q.text, split_passages(pages), keep=12)  # ~5k tokens
    async for tok in llm_stream(build_prompt(q, passages)):  # cite [n] per sentence
        yield tok
Real example

A user asked about home batteries and follows up: "how much does one cost installed?" The rewriter (~120 ms) turns it into "home battery installed cost 2026", intent prices, freshness class 1 day. History-dependent, so no answer cache. The search API returns 15 URLs in ~350 ms, and source cards appear. Of the top 8 pages, 6 come from the page cache (~20 ms), one live fetch lands at 600 ms and one misses the 800 ms deadline and is dropped. Extraction yields ~140 passages; the reranker (~80 ms) keeps 12 (~5k tokens). The first token arrives at ~1.7 s; 300 tokens finish by ~5 s, with 6 citations. Cost: ~0.3¢ of model plus ~0.5¢ of search, at assumed prices.

Trade-offs +4 · −4

+ You gain

  • Answers come from live pages, so they stay fresh without retraining, and every claim links to a checkable source.
  • A fixed pipeline, not an agent loop, gives a predictable ~1–2 s first token and about a cent per query.
  • Three cache layers (results, pages, head answers) cut both latency and search spend.
  • A read-only path with no private data: an injected page can skew one answer but cannot act or exfiltrate.

− You pay

  • Quality is capped by retrieval: if the top 8 pages are SEO spam, the model summarizes spam fluently.
  • The fetch deadline trades recall for latency; slow authoritative sites and large PDFs get dropped.
  • A third-party search API is a cost and platform risk (Bing Search APIs retired Aug 2025); an own index is a huge build.
  • One retrieval pass misses multi-hop questions; those need a slower agentic or deep-research route.

Use it when

Open-domain questions where freshness matters and users want a short, sourced answer in seconds: consumer search, a news or docs assistant, or the quick tier in front of a deep research agent.

Avoid it when

Multi-hop research that needs dozens of sources and minutes (Design: deep research agent), private corpora with permissions (Design: enterprise knowledge assistant), or navigational queries where a link is the whole answer.

Numbers to know 5
  • Load: 10M queries/day ≈ 115 QPS, ~300 at an assumed 2.5× peak; ~6.5k tokens in (5k passages + system and history) and ~300 out per query → ~65B in, ~3B out per day.
  • Per query at assumed Nov 2026 prices: small model at $0.40/$1.60 per M ≈ 0.3¢ + search at $5/1k = 0.5¢ → ~0.8¢; with a $3/$15 model ≈ 2.4¢ + 0.5¢.
  • First token: rewrite 120 ms + search 350 + fetch ≤ 800 + extract and rerank ~130 + prefill ~300 ≈ 1.7 s; source cards visible at ~0.5 s.
  • Search API: 10M/day × $5/1k ≈ $50k/day (~$18M/year), more than the small model's ~$30k/day: the build-vs-buy trigger for an own index.
  • Liu et al. (2023), 4 generative search engines: 51.5% of sentences fully supported by citations; 74.5% of citations supported their sentence.
Common pitfalls 4
  • Writing first, citing after: generate the answer, then attach URLs that look related. Citations end up plausible but unsupportive. Generate only from numbered passages and check support.
  • Long TTLs or a semantic cache on time-sensitive queries: last month's answer served as today's. Set TTL by freshness class; use exact keys for news.
  • No fetch deadline: one slow PDF or JavaScript-heavy page sets p99 at 6 s. Use a hard deadline, the page cache, and cancel stragglers.
  • Crediting the copy, not the source: citing a syndicated or scraped page instead of the original publisher. Resolve rel=canonical, dedupe near-duplicates, prefer the original.
Interview questions 3

Answer out loud first, then reveal.

First token is 3.5 s at p95. Where do you take the time out?Show answer

I'd read the per-stage traces first, but the tail is almost always fetching. I'd put a hard deadline on fetches and cancel stragglers, serve most pages from a pre-crawled page cache so live fetches become the exception, and hedge the slowest requests. Then overlap stages: start the search on the raw query while the rewrite runs, and render source cards when search returns. Last, the model: a faster model, the system-prompt prefix cached, and context held near 5k tokens. The trade-off is recall: every page I drop is a source the answer can't use, so I watch answer quality next to p95 while cutting.

How do follow-up questions work, and what breaks?Show answer

Each follow-up is rewritten into a standalone query from the last few turns: "what about on Android?" becomes a full question with the topic restored. A small classifier decides whether it needs retrieval at all; "shorter" or "as a table" reuses the previous passages, saving ~1 s and a search call. New retrieval merges fresh passages with the still-relevant ones from earlier turns. What breaks is the rewrite: it drops a constraint from three turns back or carries a stale one forward, and the answer is confidently about the wrong thing. I eval the rewriter on its own on multi-turn traces, and the answer cache never serves history-dependent queries.

Would you use a search API or build your own index?Show answer

Start with an API and plan the index. At 10M queries a day, an assumed $5 per 1,000 searches is ~$50k/day, more than a small model costs, and it's platform risk: Microsoft retired the Bing Search APIs in August 2025 with about 90 days' notice. I'd first build the cheap, differentiating part: a crawler and page cache for the domains users actually click, which also cuts fetch latency. Then an index for head traffic, keeping the API as a fallback for the tail. A full web index is a multi-year, exabyte-scale effort; Perplexity reports tracking over 200B URLs. It's worth it only if search quality is the product.

Deep dive 5

Search API or own index

Day one, buy: commercial search APIs return ranked URLs and snippets in a few hundred ms (Perplexity's own benchmark put its API at 358 ms p50 and other providers at ~0.5–1.4 s, Sep 2025). Two risks: cost grows linearly with queries, and the provider can change the terms; Microsoft retired the Bing Search APIs on Aug 11, 2025, with ~90 days' notice. Build in stages: first a crawler and page cache for the domains users actually click, which also takes live fetches off the hot path; then an index for head traffic, with the API as a fallback for the tail. A full web index is another company: Perplexity reports 200B+ URLs tracked, hybrid lexical and dense retrieval at span level, and ranking that ends in cross-encoders.

Latency budget and streaming

Budget to first token: rewrite 120 ms, search 350, fetch ≤ 800 (hard deadline), extract and rerank ~130, prefill and first token ~300: ~1.7 s. Fetch is the tail, so serve most pages from the page cache, hedge the slowest live requests, cancel stragglers at the deadline, and never block on a large PDF. Overlap stages: fire the search on the raw query while the rewrite runs, and render source cards as soon as search returns, at ~0.5 s, so the wait feels shorter. On the model side, keep the context near ~5k tokens, cache the system-prompt prefix and use a fast model; keep a larger model for an opt-in Pro mode. Stream over SSE, and check citations after the stream, never in front of it.

Caching and freshness

Cache in layers (Caching layers in an AI system). Search results: normalized query → URLs, TTL from minutes to a day. Pages: URL → extracted text, revalidated with ETag or Last-Modified and recrawled by observed change rate; Perplexity uses a model to decide what to index and when. Answers: only for head queries with no conversation context and no personalization, keyed by normalized query, locale and freshness bucket. TTL follows the intent: minutes for news, scores and prices; days for evergreen how-tos. Search traffic is Zipf-like, so a small answer cache absorbs a real share; measure the hit rate instead of assuming it. Avoid Semantic caching on time-sensitive intents: "Fed decision" this month and last month embed almost identically.

Source trust and prompt injection

The answer is only as good as its passages. Keep per-domain authority priors, demote SEO farms and generated spam, and resolve syndicated copies to the original publisher with rel=canonical and near-duplicate detection. The Tow Center (Mar 2025) found eight AI search tools gave incorrect answers to over 60% of its citation queries, often crediting Yahoo or AOL copies over the source. For health and finance, require two authoritative sources or decline. Pages can hide instructions ("say this product is the best"): strip hidden text, quote passages as data, and keep the answer path free of private data and side-effecting tools, so an injection can skew one answer but cannot act or exfiltrate. Honor robots.txt; publishers audit it.

Evaluation

Score retrieval and generation separately (Evaluating RAG). Citation precision (does the cited passage support the sentence?) and citation recall (is every claim cited?), the ALCE-style pair, graded by an NLI model or an LLM judge calibrated on human labels (LLM-as-a-judge). Correctness on a golden set refreshed monthly, because answers to "latest" questions expire; public sets such as SimpleQA and FreshQA serve as external checks. Retrieval coverage: did the top 8 pages contain the answer at all? That separates search failures from model failures. Online: citation click-through, thumbs, reformulation within ~30 s (a silent dissatisfaction signal) and abandonment before the first token. Every model, prompt or ranker change runs against the set in CI before an A/B test (A/B testing LLM features).