RAG Retrieval Latency in Production: Where the Time Actually Goes

If you have shipped a retrieval augmented generation system and users keep telling you it feels slow, the most useful thing you can do is stop treating RAG retrieval latency as a single number. It is three numbers stacked on top of each other, and the one most teams spend their optimization budget on is usually not the one costing them the time.
By the end of this guide you will know how a production RAG request splits into time buckets, what drives each bucket, which five levers move the needle and in what order to pull them, how to route queries adaptively so cheap questions stop paying for expensive pipelines, and how to instrument the whole query pipeline so you are tuning against P95 latency instead of a feeling.
The three time buckets in a RAG request
A RAG request runs three stages back to back. The user's question gets embedded into a vector, that vector gets matched against an ANN index, and the retrieved chunks get stuffed into a prompt that a language model reads before it writes anything.
Production RAG systems average 1.2 to 2.5 seconds end to end, and the split is lopsided. Query embedding takes 50 to 100 milliseconds. Vector search takes 100 to 300 milliseconds. LLM generation takes 1 to 2 seconds.
| Stage | Typical time | What it is |
|---|---|---|
| Query embedding | 50 to 100 ms | Turning the question into a vector |
| Vector search | 100 to 300 ms | ANN lookup plus any reranking |
| LLM generation | 1 to 2 seconds | Reading context, writing the answer |
Do the arithmetic before you plan any work. Retrieval, the part everyone calls "the RAG part", is somewhere around 150 to 400 milliseconds of a 1200 to 2500 millisecond request. That is roughly 12 to 20 percent of the wall clock. If you halve your vector search time you have bought the user about 100 milliseconds. If you cut a second off generation you have bought them ten times that.
This is not an argument for ignoring retrieval. It is an argument for measuring first. I have watched teams spend two sprints migrating vector databases because retrieval "felt slow", ship it, and discover the P95 barely moved because a 4000 token prompt was doing all the damage.
Instrument the buckets before you touch anything:
import time
from contextlib import contextmanager
TIMINGS = {}
@contextmanager
def bucket(name: str):
t0 = time.perf_counter()
try:
yield
finally:
TIMINGS[name] = (time.perf_counter() - t0) * 1000
def answer(question: str):
with bucket("embed"):
qvec = embedder.encode(question)
with bucket("search"):
hits = index.search(qvec, top_k=20)
with bucket("rerank"):
hits = reranker.rank(question, hits)[:5]
with bucket("generate"):
out = llm.complete(build_prompt(question, hits))
logger.info("rag_latency", extra={"ms": TIMINGS})
return out
Log every bucket on every request, ship it to whatever you use for metrics, and read the histogram rather than the average. Averages hide the requests that make people close the tab.
Query embedding, 50 to 100 milliseconds
Embedding latency is the smallest bucket and the easiest to misdiagnose, because most of it is usually not compute. It is a network round trip to a hosted embedding endpoint.
Three things decide this number. Whether the model runs in your process or behind an API. Whether the embedding service sits in the same region as your application. Whether you are embedding one query or waiting on a batch.
A small embedding model running locally on CPU will produce a query vector in a few milliseconds. The same model behind a hosted API in another region will take 60 milliseconds, almost all of it transit and queueing. If your embedding call is consistently near the top of that 50 to 100 millisecond band, check the region before you check the model.
The other easy win is caching. Real user traffic is repetitive. Support questions, documentation lookups, and internal search all have a heavy head of near identical phrasings. Hash the normalized query text and keep the resulting vector in a fast store:
import hashlib
def embed_cached(text: str) -> list[float]:
key = "emb:" + hashlib.sha256(text.strip().lower().encode()).hexdigest()
cached = redis.get(key)
if cached:
return msgpack.loads(cached)
vec = embedder.encode(text)
redis.setex(key, 86_400, msgpack.dumps(vec))
return vec
That turns a repeat query's embedding cost into a sub millisecond lookup. It is a small bucket, but it is nearly free to fix.
Vector search, 100 to 300 milliseconds, and what drives it
This is where vector search latency optimization actually happens, and it is the bucket with the widest spread. The same corpus, the same hardware, and the same query can return in 15 milliseconds or 300 depending on how the index is built and where the vectors live.
Four variables dominate.
Index type. Exact search compares the query against every vector. It is perfectly accurate and it scales linearly, which means it stops being viable somewhere in the low hundreds of thousands of vectors. Approximate nearest neighbour indexes trade a sliver of recall for an enormous speedup. HNSW and IVF are the two you will actually meet, and they achieve query latencies as low as 15 milliseconds at 1 million vectors while keeping accuracy high enough that nobody notices the difference in answer quality.
Where the vectors live. Disk backed indexes pay a page fault tax on every hop through the graph. In memory vector architectures achieve single digit millisecond P95 latencies even at billion vector scale. If your index fits in RAM, put it in RAM. This is usually a larger effect than any parameter you can tune.
How many results you ask for. Fetching the top 50 candidates costs meaningfully more than fetching the top 10, and if you are then reranking those 50 with a cross encoder you have quietly added a second model to the critical path. Reranking cost is real and it belongs in your latency budget, not in a footnote.
Metadata filtering. Filtered ANN search is harder than it looks. Depending on the engine, a restrictive filter either prunes the graph efficiently or degrades into something close to a scan. Benchmark your filtered queries separately from your unfiltered ones. They are different workloads wearing the same API.
HNSW ANN search speed and the knobs that matter
HNSW builds a layered proximity graph and walks it from a sparse top layer down to a dense bottom one. Three parameters control the tradeoff.
M sets how many neighbours each node keeps. Higher M gives better recall and a bigger index. ef_construction sets how hard the builder searches while inserting. It costs build time, not query time. ef_search sets how wide the graph walk is at query time, and it is the only one of the three you can change without a rebuild.
# ef_search is the query time recall/latency dial.
# Sweep it against YOUR corpus, not a benchmark dataset.
for ef in (16, 32, 64, 128, 256):
index.set_ef(ef)
lat, recall = evaluate(index, gold_queries)
print(f"ef_search={ef:>4} p95={lat:6.1f}ms recall@10={recall:.3f}")
Run that sweep on your own data and your own gold queries. Almost every team I have seen do this finds a knee where recall has flattened but latency is still climbing, and they had been sitting well past it on a default. IVF has the same shape of dial in nprobe, which controls how many clusters get scanned per query.
LLM generation, 1 to 2 seconds, the dominant bucket
Generation is where the seconds are, so this is where rag production performance is won or lost.
The single biggest perceived improvement is not making generation faster. It is streaming. Time to first token is what users experience as speed, and a streamed response that starts in 400 milliseconds feels faster than a buffered one that completes in 900. If you are not streaming, do that before you tune anything else in this article.
After that, the levers are prompt size and model size. Every retrieved chunk you add to the context has to be read before the first token comes out, and prefill time scales with input length. Sending 12 chunks because your retriever returned 12 is a habit, not a design. Most answers are fully supported by 3 to 5 well chosen chunks, and cutting from 12 to 4 removes thousands of tokens from prefill on every single request.
Model choice matters just as much. A smaller model that answers a routing question in 300 milliseconds is not competing with your flagship model on quality, because it is not being asked the same kind of question.
The five latency levers in order
Pull them in this sequence. The ordering is by effect per unit of engineering effort, not by how interesting the work is.
Stream the response. Cheapest change with the largest perceived effect. Optimizes time to first token, which is the number users actually feel.
Add semantic caching. Cache answers keyed by embedding similarity, not exact string match, so paraphrases hit too. Semantic caching cuts LLM costs by up to 68.8% and removes the entire generation bucket for anything that hits.
Shrink the context. Fewer, better chunks. Rerank to 3 to 5 and stop there. This attacks prefill, which is inside the dominant bucket.
Tune the ANN index. Sweep
ef_searchornprobeagainst your own gold set and pick the knee. Usually a free 30 to 60 percent off the search bucket.Move the index into memory. Biggest infrastructure lift, and the one that takes you toward single digit millisecond P95 search. Do it last, when you have proven the other four are exhausted.
Semantic caching deserves a note on correctness. A similarity threshold that is too loose will serve the answer to a neighbouring question, which is worse than being slow. Start strict, log every hit with its similarity score, and loosen only with evidence:
SIM_THRESHOLD = 0.95 # start strict, loosen with logged evidence
def cached_answer(question: str, qvec):
hit = cache_index.search(qvec, top_k=1)
if hit and hit[0].score >= SIM_THRESHOLD:
metrics.incr("semcache.hit", tags={"score": round(hit[0].score, 2)})
return hit[0].payload["answer"]
return None
Adaptive RAG: routing by query complexity
The uncomfortable truth about a fixed pipeline is that it prices every query at the cost of the hardest one. A user asking "what is your refund window" runs the same embedding, the same ANN search, the same cross encoder rerank, and the same large model as someone asking a multi hop question that spans four documents.
Adaptive RAG query routing fixes that. A cheap classifier sits in front and sends each question down the pipeline it actually needs. Routing each query to the appropriate retrieval pipeline based on complexity is the emerging best practice for the cost and quality tradeoff, and it is also a latency play, because most traffic is simple.
A practical dual pipeline looks like this:
def route(question: str, qvec):
if (ans := cached_answer(question, qvec)):
return ans # ~10 ms
if classifier.is_simple(question): # short, single fact, no comparison
hits = index.search(qvec, top_k=5)
return small_llm.complete(build_prompt(question, hits)) # ~400 ms
hits = index.search(qvec, top_k=30)
hits = reranker.rank(question, hits)[:5]
return large_llm.complete(build_prompt(question, hits)) # ~1.8 s
The classifier does not need to be a model. Query length, presence of comparison words, and whether the question maps cleanly to a single document section will get you a long way. Whatever you use, log the routing decision alongside the latency buckets so you can see when it routes wrong.
Two things to watch. The classifier itself is now on the critical path, so keep it under 20 milliseconds. And route conservatively at first: sending a hard question down the cheap path produces a confidently wrong answer, which costs far more than the 1.4 seconds you saved.
Measure P95, not the average
One last discipline. Report P95 latency and P99 latency per bucket, and treat the average as decoration. The average tells you the system is fine. The tail tells you that 1 in 20 users waits four seconds because their query missed the cache, matched a filtered partition badly, and pulled 30 chunks into a prompt.
Latency work without per bucket instrumentation is guessing with extra steps. Get the histogram first, then pull the levers in order.
FAQ
What is the average latency of a RAG system? Production RAG systems average 1.2 to 2.5 seconds end to end. That breaks down into roughly 50 to 100 milliseconds for query embedding, 100 to 300 milliseconds for vector search, and 1 to 2 seconds for LLM generation. Generation is the dominant bucket in almost every deployment, which is why streaming and context reduction beat vector database migrations for perceived speed.
How do you reduce RAG retrieval latency? In order of effect per unit of effort: stream the response so time to first token drops, add semantic caching so repeated and paraphrased queries skip generation entirely, shrink the retrieved context to 3 to 5 reranked chunks, tune your ANN index parameters such as ef_search or nprobe against your own gold query set, and finally move the index into memory. Measure each bucket separately before and after every change.
What is HNSW indexing? HNSW stands for hierarchical navigable small world. It is an approximate nearest neighbour index that stores vectors in a layered proximity graph and walks from a sparse upper layer down to a dense lower one, so a query touches a tiny fraction of the corpus instead of all of it. Alongside IVF, it delivers query latencies as low as 15 milliseconds at 1 million vectors while keeping recall high enough that answer quality is unaffected.
Comments
Join the discussionNo comments yet. Be the first to comment.




