The interview problem

Practice prompt

Design conversational query rewriting for a technical documentation assistant serving 100 queries per second. Users switch between products and versions, then ask questions such as “Can it run without admin access?” Rewrite follow-ups into useful search queries without inventing the intended entity or dropping constraints. Explain your architecture, evaluation, latency budget and fallback behavior.

Original ML-design practice, not a reported company interview. Product names, workload and numerical examples are fictional. Primary research references retrieved September 27, 2026; interview date not applicable.

Quick answer

Query rewriting turns a user request into a retrieval-friendly query, but must preserve the request’s constraints. Keep the original query available, preserve explicit entities and versions, and evaluate retrieved evidence and final answers. A more fluent rewrite is not necessarily a better search query.

1. Preserve the question before improving retrieval

The output should make the current question understandable outside the conversation while preserving its intended answer. Rewriting is not answering, selecting a product on the user's behalf or adding plausible facts from model memory. A standalone query may need no rewrite.

Consider a conversation discussing Atlas v2 regional backups and Beacon v3 account exports. A later “Can it run without admin access?” may refer to either operation if both remain active topics. A rewrite about the wrong product can retrieve convincing documentation and still fail the user. Ask a targeted clarification when the conversation does not establish the referent. These are invented products, not claims about actual APIs.

Explicit corrections such as “Back to Atlas v2” take precedence over simple recency. Preserve version, operation, account scope, negation and exact error strings. Distinguish user-confirmed context from the assistant's earlier speculation. A prior generated answer is not independent proof of a product capability.

2. Make rewriting an inspectable stage

current question + authorized conversation prefix
                         ↓
relevant context selection and explicit constraints
                         ↓
standalone / grounded rewrite / clarification decision
                         ↓
original-query retrieval + optional rewrite retrieval
                         ↓
deduplicate and rerank against original intent and context
                         ↓
answer with supporting sources, or clarify/abstain

Keep the original question alongside the rewrite. The reranker and answer stage need the user's intent, not only the generated query. A branch using the original query can recover some rewrite mistakes, but it does not resolve genuine ambiguity automatically.

A structured rewrite record should include the proposed query, selected referents, supporting turn IDs or spans, preserved constraints, unresolved ambiguity and model/prompt versions. Check that cited spans exist and actually support the additions. Model-generated provenance can be wrong; its presence is not verification.

Use only the conversation prefix available at the current turn. A later clarification or gold answer must not leak into offline input. Bound the history budget while retaining explicit corrections and exact identifiers. When truncation removes necessary context, expose uncertainty rather than confidently selecting the latest visible entity.

3. Train for faithful retrieval queries

Start with original-only retrieval and a simple explicit-entity expansion baseline. Compare a learned rewriter against them before adding complicated training. Supervised examples should include correct carryover, topic switches, standalone questions, corrections and genuine ambiguity.

Construct hard negatives that change only one critical attribute: v2 to v3, export to backup, “without admin” to “with admin,” or one tenant scope to another. Human labels should judge whether the rewrite preserves the intended question, not merely whether its grammar is natural. Keep conversations and near-duplicate families separated across training and evaluation.

The CANARD work frames context-dependent questions as self-contained questions with the same answer. Research on Rewrite-Retrieve-Read explores adapting queries to a retrieval and reader pipeline. These motivate useful architectures, but downstream reward alone can favor unsupported additions that happen to improve a benchmark answer. Retain explicit faithfulness checks and evaluate the actual user question.

Use constrained structured output for entities and known constraints where practical, with generation for the remaining query. This improves inspectability but does not make extracted values automatically correct. An ambiguous entity should remain unresolved rather than becoming a hard retrieval filter that silently excludes the right documentation.

4. Keep permissions outside generated text

Retrieve history only from the authorized conversation and apply the same access scope to both search branches. The rewriter must not modify tenant IDs, document authorization filters or routing credentials. Retrieved documents and quoted conversation content are data, not instructions to broaden access or change the task.

Do not send private conversation context to a public search engine merely because the rewritten query looks like ordinary text. Use the approved retrieval destination and minimize disclosed context. Internal debugging traces need controlled access and retention; routine telemetry can record versions, branch counts and error categories without copying entire conversations.

Cache rewrites with the conversation-prefix revision, original query, authorization scope and rewriter version. The same utterance can mean different things in two conversations. Retrieval caches also need an appropriate index/version boundary and current authorization checks before serving results.

5. Measure gains and regressions on the same turns

Evaluate 1,000 held-out, answerable turns against the same index snapshot and access scope. For each branch, success means its top-k candidates contain at least one adjudicated passage supporting the intended question. Suppose original retrieval succeeds on 600 turns and rewrite retrieval on 720, with 540 successes shared:

Rewrite succeedsRewrite failsTotal
Original succeeds54060600
Original fails180220400
Total7202801,000
original coverage = 600 / 1,000 = 60%
rewrite coverage  = 720 / 1,000 = 72%
net gain          = (180 − 60) / 1,000 = 12 percentage points
regressions       = 60 / 1,000 = 6% of all turns
lost baseline successes = 60 / 600 = 10%
candidate union coverage = (600 + 720 − 540) / 1,000 = 78%

The rewrite helps 180 turns but harms 60. Aggregate improvement does not justify ignoring those regressions. Inspect wrong entities, dropped constraints, missing context and retrieval failures separately.

The 78% union figure is before candidate trimming and final reranking. If each branch fetches 20 passages, the combined pool can contain up to 40. Comparing it only with an original-only pool of 20 confounds rewriting with a larger retrieval budget. Compare equal candidate or compute budgets, and measure after reranking to the same final k. Retrieval coverage is still not final answer correctness. For questions requiring several passages, finding one supporting passage is insufficient; add complete-evidence-set coverage for those cases. The worked matrix deliberately measures the simpler at-least-one-passage event.

6. Judge answers against the original intent

A passage that answers an erroneous rewrite is not a successful retrieval for the user's question. Adjudicators need the current question and permitted conversation prefix. Evaluate entity and constraint preservation, candidate coverage, final answer correctness, citation support, clarification rate and task completion.

Include challenge sets with multiple active entities, explicit topic returns, corrections, missing history, identical names across products and unsupported versions. Report their denominators separately from representative traffic. Ambiguous cases may have a clarification as the correct action; do not force every case into a single rewritten query.

Report answer coverage together with accuracy among answered turns. A policy that clarifies every difficult case can improve conditional accuracy while making the assistant less useful. Conversely, penalizing every clarification as failure encourages unsupported guesses. Define the desired decision and measure both correctness and user effort.

Use paired comparisons on identical turns and account for conversation-level dependence when estimating uncertainty. Hold the retriever, index and access scope fixed for the rewrite ablation. Then test the end-to-end system on later conversations. This separates the rewriter's contribution from index improvements or future-context leakage.

7. Budget the extra branch explicitly

Assume 60% of 100 queries per second need a rewrite, and each call uses 800 input and 40 output tokens:

rewrite calls = 100 × 0.60 = 60 per second
input tokens  = 60 × 800 = 48,000 per second
output tokens = 60 × 40 = 2,400 per second

If mean rewriter residence time is 120 milliseconds under a stable workload, Little's law gives mean in-flight calls of 60 × 0.12 = 7.2. This average is not a required concurrency limit or a p95 guarantee. Account for bursts, token-rate limits, long outputs and queueing.

Under a separate illustrative assumption that every request uses original retrieval and every rewritten request adds one search, demand becomes 100 + 60 = 160 searches per second before retries. Clarifications or skipped branches change this number; record actual branch execution.

For a latency example, suppose rewriting takes 240 milliseconds, retrieval 80 and reranking 40. The rewrite path takes 360 milliseconds before answering, versus 120 for original retrieval and reranking. Launching original retrieval in parallel does not remove the rewrite branch's critical path. These illustrative durations are independent of the earlier mean-residence assumption, not measured performance claims.

Set a deadline and cancel unnecessary work. On timeout, use original-only retrieval when the question remains interpretable; otherwise clarify. A timeout should not cause a confident answer to an unresolved pronoun. Track latency and correctness of the fallback itself.

8. Diagnose failures by stage

FailureEvidenceResponse
Wrong antecedentSelected entity and supporting history spansRepair resolution or request clarification
Version or negation lostOriginal constraints versus rewriteReject the rewrite and preserve exact constraints
Summary drops a correctionOriginal prefix versus selected contextRetain correction provenance and fix context selection
Answer-like speculation addedUnsupported terms absent from historyRemove unsupported additions and review training reward
Apparent gain comes from more candidatesBranch budgets and post-rerank resultsRepeat a budget-matched comparison
Cache carries another conversation's intentCache key and prefix revisionInvalidate affected entries and repair isolation

Deploy first in shadow mode for faithfulness audits, then a bounded experiment with wrong-entity, completion and latency guardrails. Retain branch provenance so a regression can be attributed to context selection, rewriting, retrieval, reranking or answering. Roll back compatible model, prompt and policy versions; do not change several stages simultaneously and attribute every improvement to rewriting.

9. Trade-offs and follow-ups

Longer history improves available context but adds cost and competing referents. Clarification reduces guessing but adds friction. Dual retrieval can recover missed evidence at extra latency and compute cost. Strict constraint checks protect exact identifiers while overly rigid checks can reject valid paraphrases; test both failure directions.

  • The user explicitly returns to an older topic. Use the explicit reference rather than blindly selecting the most recent entity.
  • Two interpretations are equally plausible. Ask a narrow clarification; retrieving both does not authorize choosing one silently.
  • The question is already standalone. Preserve it and avoid an unnecessary rewrite call.
  • The retriever changes. Reevaluate retrieval gains and calibration; optimization for one retriever may not transfer.
  • The assistant's earlier answer was wrong. Do not promote that answer into authoritative context. Prefer user-confirmed facts and actual retrieved evidence.

Self-review rubric

A strong answer preserves intent and constraints, checks history provenance, treats ambiguity explicitly and keeps authorization outside model-generated queries. It measures paired gains and regressions, compares equal retrieval budgets and judges final answers against the original question. An excellent answer also explains context-selection failures, cache isolation, deadline fallback and why fluent rewriting is not proof of correctness.

Pay for rewriting only when it is useful

Assume 100 incoming queries per second and a routing rule that sends 30% to one rewrite call each. The rewrite service sees 30 requests per second, before retries. If each rewritten query triggers two retrieval branches while other queries use one, retrieval load is 70 × 1 + 30 × 2 = 130 requests per second. Reducing model calls does not automatically reduce search load.

Use a test request such as “version 2.4 deployment without public internet.” A rewrite that drops “without” retrieves a different solution even when its semantic similarity is high. Keep version, connectivity and authorization constraints as explicit checks; for genuinely ambiguous intent, clarify rather than inventing a constraint.

Compare the gated policy against original-only retrieval on the same held-out queries. Report evidence recall, constraint violations, final-answer quality, tail latency and cost by query class. Keep a bounded original-query fallback when the rewrite fails or exceeds its deadline.

Original worked follow-up, reviewed October 7, 2026. Reference: EMNLP: Query Rewriting for Retrieval-Augmented Large Language Models.

Sources and attribution

Both retrieved September 27, 2026. Exact publication days were unstated in the cited metadata. The architecture, fictional products, numerical examples and failure analysis are original practice material; no company interview attribution is claimed.

Continue your preparation

Choose a connected learning path or browse more ML system design questions. Read our editorial method and attribution policy.