Sub topic 14
Cost, Latency and Query Drift
This chapter assumes you have read the earlier chapters on rewriting, multi-query expansion, reciprocal rank fusion, decomposition and the iterative retrieval loop. It also assumes you can read Python and know that every language model call costs money and time. Each technique so far improves recall. Each also adds work before the user sees a first word, and each can change the question in ways that hurt the answer. This chapter covers how to count that cost and how to limit the risk.
Where the extra cost comes from
A single-shot pipeline embeds the question, runs one search, and makes one generation call. Rewriting adds model calls before retrieval, more searches, and often more passages in the final prompt.
| Technique | Extra model calls | Extra searches | Latency pattern |
|---|---|---|---|
| Conversational condensing | 1 (skipped with no history) | 0 | Sequential, before search |
| Multi-query expansion | 1 | n more | One call, then searches can run in parallel |
| HyDE | 1, with a long output | 0 | Sequential. Output length dominates |
| Step-back | 1 | 1 more | One call, then two searches in parallel |
| Decomposition | 1 | one per sub-question | One call, then parallel searches. Larger final prompt |
| Iterative retrieval | up to `max_steps` | up to `max_steps` | Strictly sequential, because each step depends on the last |
Three costs add up:
- Token cost. Each rewriting call pays for its input and output tokens. Condensing sends the whole conversation, so it grows with the history. HyDE writes a paragraph, which costs more than a one-line query.
- Search cost. Each extra query is another embedding call and another index lookup. For a hosted vector database this may be billed per query.
- Generation cost. More retrieved passages mean a longer final prompt. Fusing five queries that each return five passages can push far more text into the context than one search would, unless you cut back to
top_kafterward.
Latency matters more to users than cost. Calls that depend on each other add up. Calls that are independent can overlap, so the wait is the slowest one.
Estimating worst-case latency
Before shipping an iterative loop, calculate its worst case. The loop from the earlier chapter stops on DONE or at max_steps. In the worst case it never says DONE.
def iterative_worst_case(max_steps: int, llm_seconds: float, search_seconds: float) -> float:
"""Each step is one search followed by one stopping-check call, run in sequence."""
return round(max_steps * (llm_seconds + search_seconds), 2)
# Assumed timings: 0.8 s per model call, 0.15 s per search.
print(iterative_worst_case(3, 0.8, 0.15)) # 2.85
print(iterative_worst_case(5, 0.8, 0.15)) # 4.75That time comes before the final generation call, which then runs on top of it. The timings above are assumptions, so replace them with p50 and p95 values measured on your own system. Plan the budget from the p95 number, because users notice slow answers.
Reducing latency
The main tool is parallelism for work that does not depend on earlier results. Multi-query variants and decomposed sub-questions fit this well, so run their searches together.
from concurrent.futures import ThreadPoolExecutor
from typing import Callable
def parallel_search(
queries: list[str],
search: Callable[[str, int], list[str]],
top_k: int = 5,
) -> list[list[str]]:
if not queries:
return []
with ThreadPoolExecutor(max_workers=len(queries)) as pool:
return list(pool.map(lambda q: search(q, top_k), queries))The returned lists keep the order of queries, so you can pass them straight to reciprocal_rank_fusion. Threads suit this work because search calls spend their time waiting on the network.
Other options, roughly in order of payoff:
- Skip rewriting when it is not needed. Condensing already returns the question unchanged when there is no history. A router, covered earlier, can send simple lookups straight to single-shot search.
- Use a small, fast model for rewriting. Producing a search query rarely needs the most capable model. Keep the strong model for the final answer.
- Cache. Identical questions, or identical rewrites, can reuse earlier results. Key the cache on the standalone question, not the raw follow-up, because "what about pricing?" means different things in different conversations.
- Cap output length. Ask for short queries and set a maximum token count on rewriting calls. For HyDE, request a short passage.
- Set a time limit with a fallback. If rewriting has not finished within your budget, run the original query. A plain answer on time is usually better than a better answer that arrives late.
Query drift
Query drift is when a rewritten query no longer asks what the user asked. It has three common forms.
- Dropped constraints. The user asks about "error E1042 in version 2.3". The model rewrites it as "how to fix export errors". The search now returns generic material, and the answer is confident and wrong for that version.
- Invented assumptions. The model adds details the user never gave, such as a product name or a time period. HyDE is especially exposed to this, because a hypothetical answer is partly made up and the search may match documents that agree with the invention.
- Wandering loops. In iterative retrieval, each new query is built from the previous passages. One off-topic passage can pull the next query away from the question, and the next away again.
Fusion can make drift worse. A document that appears in several drifted lists collects reciprocal rank score from each of them, so a popular but irrelevant document can outrank the one that matches the original question. This is why multi_query_search always searches the original question as well as the variants.
A simple drift guard
You cannot prove that a rewrite means the same thing, but you can cheaply catch the most damaging failure, which is losing exact identifiers. The guard below collects terms from the original question that must survive a rewrite: quoted phrases, tokens containing digits or underscores, and tokens with capital letters after the first character (such as OAuth). If any is missing from the rewrite, it returns the original.
import re
def protected_terms(text: str) -> set[str]:
quoted = re.findall(r'"([^"]+)"', text)
tokens = re.findall(r"[A-Za-z0-9_.\-]+", text)
special = [
t.strip(".-")
for t in tokens
if any(c.isdigit() or c == "_" for c in t) or any(c.isupper() for c in t[1:])
]
return {t.lower() for t in quoted + special if t}
def safe_rewrite(original: str, rewritten: str) -> str:
lowered = rewritten.lower()
missing = [t for t in protected_terms(original) if t not in lowered]
return original if missing else rewritten
question = "Why does error E1042 appear in v2.3?"
print(safe_rewrite(question, "Why does the export fail in a recent version?"))
print(safe_rewrite(question, "What causes error E1042 in v2.3 during export?"))The first call prints the original question, because e1042 and v2.3 are missing from the rewrite. The second prints the rewrite, because both identifiers are present.
For iterative loops, limit drift with structure:
- Keep a hard
max_steps, as in the earlier loop. - Put the original question in every stopping-check prompt, not only the latest query.
- Stop when a step adds no new passages. The loop already skips duplicates, so an empty addition signals a stall.
- Log every query the loop generates. Reading these logs is the quickest way to find drift in practice.
Deciding what is worth it
Link each technique to a measured failure, not to a feeling that it should help. The evaluation chapter showed how to compare a rewriting step against the baseline. For cost, extend that comparison with three numbers: the change in retrieval quality, the added p95 latency, and the added cost per request. A technique that gains two points of recall for one extra second on every request may be a poor trade for a chat product. It may be a good one for an offline research assistant.
Start with the cheapest option that addresses the failure you observed. Condensing fixes lost context. Multi-query with fusion fixes vocabulary mismatch. Decomposition and iteration are the most expensive, so use them only for questions that need them.
Do not let the iterative loop run without a step limit or a time limit in production. A model that never replies `DONE` turns every request into an unbounded chain of calls, and the bill and the wait grow with it.Exercise
A support chatbot uses multi-query expansion with 3 variants and an iterative loop with max_steps=4. A model call takes 0.7 s and a search takes 0.2 s. (a) What is the worst-case time spent on retrieval for a request that uses both, if the multi-query step runs first, its searches run in parallel, and the iterative loop then runs on the original question? (b) Name one change that lowers the worst case without removing either technique.
Show answer
(a) Multi-query: one model call (0.7 s), then 4 searches in parallel (the original plus 3 variants), costing about 0.2 s, so about 0.9 s. The loop: 4 steps of (0.2 + 0.7) = 3.6 s. Total is about 4.5 s before generation. (b) Any of these works: lower max_steps to 2 (the loop then takes 1.8 s), use a smaller faster model for the stopping check, or add a time limit that returns the passages found so far. Routing simple questions past the loop also lowers the average, though not the worst case.
Exercise
A rewrite of "Does the Pro_Plus tier support SSO?" is "Which plans include single sign-on?". Does the drift guard from this chapter accept the rewrite, and what does it return?
Show answer
It rejects the rewrite and returns the original question. Pro_Plus is a protected term, since it contains an underscore, and pro_plus does not appear in the rewrite. SSO is also protected, because it has capital letters after the first character, and it is missing too. Either missing term is enough to trigger the fallback.