Latency Optimization

Find where the time goes and make each stage of the pipeline faster.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 20 · Lesson 5 of 9 · Advanced

Latency Optimization

Find where the time goes and make each stage of the pipeline faster.

Users judge an assistant by how quickly it starts answering. A RAG request passes through several stages (query processing, embedding, search, reranking, generation), and each adds time. This lesson shows how to measure where the time goes and the main techniques for reducing it, stage by stage.

Measure first

Never optimise blind. Time every stage of real requests, and look at percentiles (p50, p95), not just averages, because slow outliers are what users remember.

timing.py
import time
from contextlib import contextmanager

class Timer:
    def __init__(self):
        self.stages: dict[str, float] = {}

    @contextmanager
    def stage(self, name: str):
        start = time.perf_counter()
        try:
            yield
        finally:
            self.stages[name] = round((time.perf_counter() - start) * 1000, 1)

def answer_with_timing(question: str) -> dict:
    t = Timer()
    with t.stage("rewrite"):
        query = rewrite_query(question)
    with t.stage("retrieve"):
        candidates = retriever.search(query, k=40)
    with t.stage("rerank"):
        top = rerank(query, candidates, top_n=5)
    with t.stage("generate"):
        answer = generate(question, top)
    return {"answer": answer, "timings_ms": t.stages}

A typical unoptimised breakdown looks like this; your numbers will differ:

StageTypical timeMain levers
Query rewriting (LLM call)0.5–2 sSkip when not needed, low effort, run in parallel
Query embedding5–50 msKeep model loaded, GPU, cache
Vector + keyword search5–100 msIndex tuning, filters, co-location
Reranking50–500 msFewer candidates, smaller model, GPU
Generation, time to first token0.5–3 sShorter prompts, prompt caching, effort, streaming
Generation, full answer2–20 sShorter answers, streaming hides it

Generation: the biggest lever

  • Stream the answer. It does not shorten total time, but users see text within the time to first token (Streaming).
  • Lower the effort. Most RAG answers are reading comprehension, not deep reasoning; effort: "low" starts answering faster and uses fewer tokens.
  • Shorten the prompt. Fewer, reranked chunks mean less input to process.
  • Cache the stable prefix (system prompt, examples, conversation). Cached input is processed faster (Prompt Caching).
  • Ask for concise answers in the prompt. Output tokens are generated one at a time, so a 150-word answer finishes far sooner than a 600-word one.
  • Fast mode: Claude Opus 5.5 offers a premium-priced fast mode that generates output tokens faster, for latency-critical products.

Run independent steps in parallel

Many pipeline steps do not depend on each other: searching several indexes, running BM25 and vector search, or rewriting the query while the original query is already being searched. With asyncio, the total time becomes the slowest step instead of the sum.

import asyncio

async def parallel_retrieve(question: str) -> list:
    # Blocking (CPU or sync client) calls run in threads; await them together
    policy_task = asyncio.to_thread(policy_retriever.search, question, 20)
    manual_task = asyncio.to_thread(manual_retriever.search, question, 20)
    bm25_task = asyncio.to_thread(keyword_retriever.search, question, 20)
    policy, manuals, keywords = await asyncio.gather(policy_task, manual_task, bm25_task)
    return fuse([policy, manuals, keywords])          # e.g. reciprocal rank fusion

Skip work you do not need

  • Route simple questions past query rewriting, decomposition and self-correction (Query Routing). Each skipped LLM call saves a second or more.
  • Cache retrieval results and answers for frequent questions (Caching).
  • Short-circuit chit-chat ("thanks!") with no retrieval at all.

Retrieval and reranking

  • Keep embedding and reranking models loaded and warm; never load them per request.
  • Run them on a GPU, or use ONNX or quantised versions on CPU.
  • Rerank 20 to 40 candidates rather than 100; measure the recall cost of the smaller pool.
  • Tune ANN parameters (efSearch, nprobe) to your latency target (Index Types).
  • Place the API server, vector database and model endpoints in the same region to avoid network round trips.

Set a latency budget

Decide targets up front, for example "time to first token under 1.5 s at p95", and give each stage a share: 100 ms for retrieval, 200 ms for reranking, the rest for the model. Track the budget in monitoring, and test latency in CI alongside quality, so a slow change is caught before release.

Key takeaways

  • Time every stage and watch p95, not only averages.
  • Generation dominates: stream, lower effort, shorten prompts and answers, and cache prefixes.
  • Run independent retrieval steps in parallel and skip unnecessary LLM calls by routing.
  • Keep models warm and co-located, and enforce a latency budget per stage.