30–50% Recall Gains for Engineers: Query Rewriting in RAG

Query rewriting typically lifts retrieval recall and reduces hallucination for vague or conversational queries, but it adds latency and cost. Practitioner benchmarks show recall gains of 30–50% on vague queries when a small rewriter model generates two to three alternative queries. The trade-off is roughly 500 to 600 milliseconds of added latency and extra API spend. The rule of thumb: route only vague, pronoun-heavy, or conversational queries through a rewriter, and skip it for precise, keyword-style input.
TL;DR:
- Query rewriting boosts recall by 30 to 50 percent mainly for vague, pronoun-heavy, or conversational queries, but adds 500 to 600 milliseconds of latency per request.
- It is implemented as a front-end step transforming the user's raw input into better retrieval queries before document fetches, significantly improving retrieval accuracy.
- Rewriting techniques like contextualisation, multi-query expansion, decomposition, HyDE, and step-back prompting solve different retrieval issues with varying costs and effectiveness, with contextualisation being the most cost-effective.
- Routing logic should decide when to rewrite, typically on ambiguous or low-confidence queries, to avoid unnecessary latency on precise, keyword-based inputs.
- Progress in research includes trainable rewriters optimized with reader feedback and adaptive multi-query strategies based on query difficulty, which can be implemented with current tools.
Table of Contents
- What is query rewriting in a RAG pipeline?
- Why does query rewriting improve retrieval accuracy?
- Where does query rewriting sit in the RAG pipeline?
- Common query rewriting techniques and when to use each
- When should you skip query rewriting?
- How do you implement query rewriting step by step?
- How do you evaluate whether query rewriting is working?
- What are the common pitfalls in production?
- Real-studios: practitioner notes on query rewriting in RAG builds
- How do you handle ambiguous or unclear queries?
- What does query rewriting look like in practice?
- What's next in query rewriting research?
- How does query rewriting connect to retriever tuning and reader calibration?
- When we recommend rewriting in client projects
- Get query rewriting built into your RAG system properly
- Sources
- FAQ
What is query rewriting in a RAG pipeline?
Query rewriting is the step where a language model transforms a user's raw input into one or more queries better suited to a retriever, before any document is fetched. It happens upstream of retrieval, correcting the question rather than the search index or the ranking model that scores results afterwards.
The technique appears in several forms, each solving a slightly different problem:
- Single rewrite — resolves pronouns and vague phrasing into one self-contained query.
- Multi-query expansion — generates several variants of the same question to widen recall.
- HyDE (Hypothetical Document Embeddings) — asks the model to draft a plausible answer, then embeds that answer instead of the question.
- Decomposition — splits a compound question into separate sub-queries retrieved independently.
- Step-back prompting — generates a broader, more general query to pull in supporting context before answering the specific one.
This is a different lever from reranking or index tuning. A reranker reorders documents already retrieved; an index change alters what's stored or how it's chunked. Query rewriting fixes the input signal itself, before the retriever ever runs. The Rewrite‑Retrieve‑Read framework formalised this distinction, showing that a trainable rewriter, tuned with feedback from the reader model, consistently outperforms a fixed pipeline that never touches the query at all.
Why does query rewriting improve retrieval accuracy?
Retrieval fails in predictable ways. A user asks "what about the second one?" and the retriever has no idea what "the second one" refers to. A query like "pricing" is too generic to match anything specific. A multi-part question ("compare X and Y, then explain the difference") confuses a retriever built to match a single intent. Vocabulary mismatch, where the user's words don't overlap with the document's terminology, compounds all of it.
Practitioner benchmarks report 30 to 50% recall improvements on vague queries when a rewriter generates 2 to 3 alternative phrasings before retrieval, according to engineering write-ups on the rewrite loop. Answer correctness gains reported alongside these tests typically land in the 5 to 15% range.
Better retrieval reduces hallucination indirectly rather than directly. A language model asked to answer from five irrelevant chunks will often fabricate plausible-sounding content to fill the gap. Feed it the right chunks instead, and there's simply less need to guess. This is why the Rewrite‑Retrieve‑Read authors trained their rewriter against reader feedback: the goal was never a "nicer" query, it was fewer wrong answers downstream.
Where does query rewriting sit in the RAG pipeline?
Query rewriting sits at the very front of the pipeline, before any embedding or search call. The flow generally looks like this:
- Rewrite — the user's raw input (plus recent conversation turns) goes to a rewriter model, which returns one or more retrieval-ready queries.
- Retrieve — each rewritten query runs against the vector store or search index, often in parallel.
- Merge and deduplicate — results are combined by document ID, keeping the first-seen rank order to avoid double-counting overlapping hits.
- Read — the merged, deduplicated chunk set goes to the reader model, which generates the final answer.
Not every query needs this treatment. A routing classifier upfront can decide whether to rewrite at all, based on confidence thresholds, query length, or the presence of pronouns. Clear, well-formed queries can skip straight to retrieval, saving the round trip entirely.
Two operational patterns matter here. Synchronous rewriting blocks the response until the rewrite completes, which is simple but adds latency directly to the user-facing path. Asynchronous or speculative rewriting starts retrieval with the raw query while the rewrite runs in parallel, then swaps in the better result if it arrives in time and improves on the original. Backoff strategies matter too: if the rewriter call times out or errors, the pipeline should fall back to the raw query rather than fail the whole request.
Pro Tip: Log both the original and rewritten query on every request. When retrieval quality dips in production, this is the fastest way to spot whether the rewriter introduced the problem or masked one that was already there.
Common query rewriting techniques and when to use each
Each technique solves a distinct retrieval problem, and each carries a different cost profile.
- Contextualisation resolves pronouns and folds in recent conversation turns ("it", "that", "the second option"). This is the highest-leverage, lowest-cost technique, and for most conversational RAG systems it accounts for the majority of measurable gains, according to engineering guidance on query rewriting.
- Multi-query expansion generates 2 to 3 phrasings of the same question to catch documents that use different vocabulary. Practitioner rules of thumb suggest this range is the sweet spot; pushing past three or four variants raises latency and token cost with little extra recall.
- Decomposition splits a compound question into sub-questions, retrieving each independently before combining results at the reader stage. This matters most for comparison or multi-hop queries that no single retrieval pass can satisfy.
- HyDE asks the model to write a hypothetical answer first, then embeds that answer instead of the question. It works best on corpora where answers are phrased similarly to the documents themselves, such as technical documentation or FAQ-style content, and less well on short, fact-lookup queries where a hallucinated hypothetical can drift from the real answer.
- Step-back prompting generates a more general question to pull in background context before tackling the specific one. It suits domains where the specific answer only makes sense against broader context, such as legal or policy questions.
Pro Tip: If you only implement one technique, choose contextualisation. It's the cheapest to build, the easiest to evaluate, and it fixes the single most common failure mode in multi-turn RAG: the retriever never seeing what the user actually meant.
When should you skip query rewriting?
Rewriting isn't free, and applying it to every query is a common mistake. Use it when:
- The query is vague, short, or relies on pronouns from earlier turns.
- The user's intent spans multiple sub-questions in one message.
- The conversation has enough history that context resolution genuinely changes the meaning of the query.
Skip it when:
- The query is already a precise, structured, or keyword-style search (product codes, exact names, filters).
- Latency budgets are extremely tight and every millisecond in the request path is accounted for.
- The retriever already performs well on raw input, based on your evaluation data.
A lightweight classifier can automate this decision using signals like query length, punctuation patterns, presence of pronouns, or confidence scores from an intent detection model. Route uncertain or low-confidence cases through the rewriter and let everything else pass straight through to retrieval.
How do you implement query rewriting step by step?
Building this into a production RAG system follows a fairly consistent sequence, regardless of stack.
- Design the prompt template. Constrain the rewriter to return structured JSON containing 2 to 3 rewrites, built from the last 2 to 3 conversation turns (each truncated to avoid runaway context). A separate HyDE prompt variant asks for a short hypothetical answer instead of a rewritten question.
- Choose the model. Use a small, fast model for production rewrites. Engineering guidance from retrieval-focused documentation recommends reserving larger flagship models for research, ambiguous edge cases, or offline evaluation, not for every live request.
- Run retrieval in parallel. Fire each rewritten query against the retriever concurrently rather than sequentially, then merge results by document ID, preserving first-seen rank order to avoid re-ranking duplicates unfairly.
- Cache aggressively. Key the cache on the (query, context) tuple so repeated or near-identical questions in the same conversation state skip the rewrite call entirely.
- Instrument monitoring. Track recall, answer correctness, latency, and cost per thousand queries from day one, not after a problem surfaces.
- Roll out incrementally. Start with contextualisation only. Add multi-query expansion or HyDE once you have evaluation data showing where contextualisation alone falls short.
Cloudflare's AI Search documentation gives useful concrete examples of rephrasing informal input and injecting synonyms, worth reviewing when drafting your own prompt constraints.
Pro Tip: Constrain the rewriter's output schema tightly. An unconstrained rewrite prompt will occasionally produce three near-identical paraphrases instead of genuinely diverse queries, which burns latency and token budget for no recall gain.
How do you evaluate whether query rewriting is working?
Evaluation needs to happen end-to-end, not on the rewritten query in isolation. A rewrite that reads well to a human can still retrieve worse documents, so plausibility is a poor proxy according to guidance on query rewriting evaluation. Build a labelled set split between vague and already-clear queries, then measure with and without rewriting enabled.
| Metric | What it measures | Why it matters |
|---|---|---|
| Recall@k | Whether the correct document appears in the top k results | Direct measure of retrieval quality |
| NDCG@k | Ranking quality, weighting correct results higher up the list | Catches cases where the right document is buried |
| Answer correctness | Human labels or LLM-as-judge scoring of the final answer | Ties retrieval quality to actual output quality |
| latency | Worst-case response time under the rewrite step | Surfaces real user-facing cost |
| Cost | Token spend across rewrite and multi-query retrieval calls | Quantifies the operational trade-off |
Run A/B tests with enough volume to detect the expected lift; a 30 to 50% recall improvement on vague queries is large enough to show up with a modest sample, but near-zero lift on already-specific queries is the expected and correct result, not a failure. Watch for regressions specifically on clear, well-formed queries. If rewriting degrades performance there, it's a signal the rewriter is being applied too broadly rather than routed selectively.
What are the common pitfalls in production?
A handful of failure patterns show up repeatedly once rewriting hits real traffic.
- Over-aggressive rewriting drops specifics. A rewriter that "cleans up" a query can strip out exact numbers, dates, or product names. Constrain the prompt explicitly to preserve any figures or named entities present in the original.
- Hallucinated context creeps in. If the rewriter draws on conversation history too liberally, it can invent connections that were never stated. Limit the history window and instruct the model to use only explicit prior turns.
- Rewriter latency becomes the bottleneck. A slow rewrite call negates the retrieval gains. Use smaller models, cache by query and context, or route only ambiguous queries through the rewriter.
- Multi-turn sessions drift. Accumulated context across a long conversation can pull rewrites further and further from the user's actual current intent. Reset or cap the context window periodically.
Pro Tip: Add a simple guardrail: if the rewritten query is missing a number, date, or proper noun that appeared in the original, discard the rewrite and fall back to the raw query.
Real-studios: practitioner notes on query rewriting in RAG builds
Real-studios builds RAG systems, voice and chat agents, and search integrations for UK businesses, and query rewriting is a recurring decision point in nearly every engagement involving conversational retrieval.
- Delivery typically follows an audit, then a rapid MVP, then integration into existing systems, then ongoing support.
- GEO (Generative Engine Optimisation) work draws on the same retrieval logic: making sure AI engines surface the right content for a given query.
- Case studies and internal benchmark data are available on request for specific verticals.
- Recommendations are always grounded in measured recall and latency, not defaults.
How do you handle ambiguous or unclear queries?
Ambiguity in a user query typically falls into one of three categories, and each needs a slightly different rewriting response. Referential ambiguity ("what about that one?") needs contextualisation pulling in the last few conversation turns. Semantic ambiguity, where a word has multiple meanings depending on domain (does "python" mean the language or the animal?), needs either a clarifying question back to the user or a rewrite that includes domain context pulled from the system prompt. Scope ambiguity, where the query could reasonably mean several different things ("tell me about pricing" on a site with five products), often benefits from step-back prompting to surface the broader category first.
The mistake many teams make is treating every ambiguous query the same way, applying a single generic rewrite prompt regardless of the ambiguity type. A better pattern classifies the ambiguity first, even with a lightweight heuristic, then routes to the appropriate rewriting strategy. A query with a pronoun and no named entity goes to contextualisation. A short, single-word query goes to step-back or clarification. A query with "and" or "compare" goes to decomposition.
There's also a case for asking the user directly rather than guessing. If confidence in any rewrite remains low after context resolution, a short clarifying question ("did you mean the enterprise plan or the starter plan?") often produces better retrieval than a confident but wrong rewrite. This costs one extra conversational turn but avoids compounding an incorrect assumption through the entire retrieval and reading pipeline. Systems that never ask for clarification tend to silently degrade on the hardest 10 to 15% of queries, exactly the cases rewriting was meant to fix.

What does query rewriting look like in practice?
The clearest demonstration of rewriting's impact comes from the Rewrite‑Retrieve‑Read study, which tested both a fixed rewriter and a trainable one against a standard retrieve-then-read baseline across open-domain and multiple-choice question answering tasks. Both rewriter variants improved downstream performance consistently, and the trainable version, tuned using feedback from the reader model itself, outperformed the fixed prompt-based rewriter. That's a meaningful distinction for teams weighing whether to invest in fine-tuning: a static rewrite prompt gets you most of the way, but closing the loop with reader feedback captures additional gains a static prompt can't reach.
On the engineering side, benchmarks from production rewrite implementations show the pattern holding at smaller scale too: a small rewriter model generating 2 to 3 query variants, run in parallel against the retriever, lifted recall by 30 to 50% specifically on the vague-query subset of their test data, while leaving performance on already-clear queries essentially unchanged. That last detail matters as much as the headline number. It confirms rewriting is a targeted fix for a specific failure mode, not a universal upgrade, which is exactly why routing logic deciding when to rewrite carries as much weight as the rewriting technique itself.
What's next in query rewriting research?
Recent work is pushing past static, prompt-only rewriting toward rewriters trained end-to-end with the retriever and reader as a single feedback loop, rather than treating rewriting as an isolated preprocessing step. The trainable rewriter variant in the Rewrite‑Retrieve‑Read framework is an early example: instead of hand-crafting a rewrite prompt and hoping it helps, the rewriter is optimised directly against reader accuracy, closing the loop between what gets rewritten and what actually improves the final answer.
A second direction is adaptive multi-query strategies that vary the number of rewrites based on query difficulty rather than using a fixed count for every request. Instead of always generating three rewrites, a difficulty classifier decides whether one rewrite suffices or whether a harder, more ambiguous query warrants deeper expansion or decomposition. This directly addresses the diminishing-returns problem practitioners report when pushing past 2 to 3 rewrites indiscriminately.
A third area worth watching is corpus-aware rewriting, where the rewriter has some signal about the shape of the underlying documents (FAQ-style, narrative, tabular, code) and adjusts its strategy accordingly. HyDE's effectiveness already depends heavily on whether the corpus resembles the hypothetical answers the technique generates. Extending that awareness to other techniques, so the system picks contextualisation, decomposition, or HyDE based on document shape rather than a one-size-fits-all default, is a natural next step for teams running heterogeneous knowledge bases.
None of this requires waiting for research to mature before shipping. The trainable-rewriter pattern and adaptive rewrite counts are both implementable today with existing tooling; they simply require the evaluation infrastructure described earlier to measure whether the added complexity earns its keep.

How does query rewriting connect to retriever tuning and reader calibration?
Query rewriting doesn't operate in isolation from the rest of the RAG stack, and treating it as a standalone fix while ignoring the retriever and reader leaves gains on the table. A retriever that's been fine-tuned on domain-specific query-document pairs will respond differently to rewritten queries than an off-the-shelf embedding model, sometimes needing fewer rewrite variants because the embedding space already captures domain vocabulary that a generic model would miss.
Reader calibration matters just as much. A reader model that's poorly calibrated, confidently generating answers from weak or irrelevant context, will mask retrieval improvements because it produces plausible-sounding output regardless of whether the retrieved chunks actually support it. Pairing query rewriting with reader-side techniques such as citation grounding or confidence scoring makes retrieval gains visible in the final answer quality metric rather than absorbed into an already-confident model.
The trainable rewriter approach in the Rewrite‑Retrieve‑Read framework is itself an integration point: rather than tuning the rewriter against a generic objective, it's trained using feedback from the reader's actual performance, which means rewriter improvements and reader behaviour move together rather than being optimised separately. Teams running mature RAG systems increasingly treat rewriting, retrieval, and reading as one pipeline to evaluate jointly rather than three separate components each optimised in isolation. This is more engineering overhead upfront, but it avoids the common failure where a query rewriting win on paper produces no measurable improvement in the answers users actually see.
When we recommend rewriting in client projects
Real-studios doesn't default to query rewriting on every RAG build. It's the right fix when conversational, multi-turn queries are common and evaluation data shows a real recall gap on vague inputs, not as a blanket addition. Stakeholder buy-in usually hinges on latency budgets and, where customer conversation history is involved, clear data retention and GDPR boundaries agreed before any context window gets built.
— Oded
Get query rewriting built into your RAG system properly
An alternative to hiring a full-time ML team for query rewriting and RAG optimisation is to work with consultancies offering rapid demos, defined pricing, and ongoing support once the system is live. Rather than spending weeks tuning rewrite prompts and routing logic from scratch, a Rapid MVP gets a working prototype of your rewriter, retriever, and reader pipeline in front of you fast, so you can test recall gains on your own queries before committing to a full build.
For teams with an existing knowledge base or CRM that needs connecting to a RAG pipeline, AI Integrations & Enablement handles the data-plumbing side. And if visibility inside AI-driven search results matters as much as the retrieval accuracy itself, Real-studios' full services range covers GEO alongside agent development. Interested parties can request a working demonstration built around their own data to evaluate potential solutions.
Sources
- Query Rewriting for Retrieval-Augmented Large Language Models (EMNLP 2023)
- Query rewriting in RAG with LLMs: the rewrite loop
FAQ
What is query rewriting?
Query rewriting is the step in a retrieval pipeline where a language model transforms a user's raw input into one or more queries better suited to a retriever, typically resolving pronouns, vague phrasing, or compound intent before any document is fetched.
How can you improve the accuracy of RAG?
Query rewriting is one of the most reliable levers: routing vague or conversational queries through a rewriter before retrieval has shown recall improvements of 30 to 50% on that query subset, alongside gains in NDCG and answer correctness when measured end-to-end.
What is query expansion in information retrieval?
Query expansion generates multiple variants of the same query, typically 2 to 3, to widen the set of documents a retriever can match, catching relevant results that use different vocabulary from the original question.
Does query rewriting always improve retrieval?
No. Rewriting mainly helps vague, pronoun-heavy, or conversational queries; on already-specific, well-formed queries it typically adds latency with little or no recall gain, which is why routing logic matters as much as the rewriting technique itself.
Can Real-studios help implement query rewriting in an existing RAG system?
Yes. Real-studios builds and integrates query rewriting, retrieval, and reader pipelines as part of its AI Agents and integration services, typically starting with a rapid MVP to validate recall gains before a full rollout.