Home / AI & GenAI

AI & GenAITroubleshootingAdvanced

Cross-encoder reranker adds seconds to RAG latency: candidate depth, passage truncation, batching and placement

Why a self-hosted cross-encoder reranker turns a 300 ms retrieval into a 3 second one, how to measure where the time goes, and the fixes that cut it without losing relevance.

Deepak Bhardwaj6 min read

Applies toSelf-hosted cross-encoder rerankers (bge-reranker, ms-marco MiniLM and similar) on Hugging Face TEI 1.x or sentence-transformers; Azure AI Search semantic ranker for comparison

You added a cross-encoder reranker to the RAG pipeline, answer quality improved, and p95 latency went from under a second to three or four. A cross-encoder is not a bigger embedding lookup: it runs a full transformer forward pass for every query and candidate pair, so its cost grows with candidates multiplied by tokens per pair. Most latency problems come from those two numbers, not from the model choice.

Symptoms

  • p95 time between "retrieval done" and "prompt built" is seconds, while vector search itself is tens of milliseconds.
  • Latency rises sharply with concurrency: fine at 2 users, poor at 20.
  • Long documents (PDF chunks, logs, tables) are slow; short FAQ queries are fast.
  • The reranker pod shows high GPU utilisation or, on CPU, all cores busy, while the LLM endpoint is idle.
  • After "fixing" latency with truncation, relevance dropped for some queries.

Where the cost comes from

Factor Effect on cost Typical mistake
Number of candidates Linear Reranking top 100 or 200 "to be safe"
Tokens per pair (query + passage) Linear to quadratic in attention Sending 1,000-token chunks to a model with a 512 limit
Batch packing Throughput Client sends candidates one request at a time
Concurrency vs replicas Queueing One reranker replica shared by query traffic and offline evals
Hardware Constant factor Large reranker on CPU

Checks

1. Time each stage separately

import time, statistics as st

def timed(fn, *a, **kw):
    t = time.perf_counter(); out = fn(*a, **kw)
    return out, (time.perf_counter() - t) * 1000

lat = {"search": [], "rerank": [], "llm": []}
for q in sample_queries:                    # 100+ real queries from logs
    cands, ms = timed(vector_search, q, k=100); lat["search"].append(ms)
    ranked, ms = timed(rerank, q, cands);       lat["rerank"].append(ms)
    _, ms = timed(generate, q, ranked[:8]);     lat["llm"].append(ms)

for k, v in lat.items():
    print(k, "p50", round(st.median(v)), "p95", round(st.quantiles(v, n=20)[18]))

If reranking is the largest number, keep going. If it is the LLM, look at prompt size and time to first token instead.

2. Measure tokens per pair

Count with the reranker's own tokenizer, not an LLM tokenizer:

from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("BAAI/bge-reranker-v2-m3")
lens = [len(tok(q, c["text"])["input_ids"]) for q in sample_queries[:20] for c in cands_for(q)]
print("p50", st.median(lens), "p95", st.quantiles(lens, n=20)[18], "max", max(lens))
print("model max:", tok.model_max_length)

If p95 is near the model's maximum, every pair costs the full sequence length. If it exceeds the maximum and truncation is off, requests fail or are rejected.

3. Check how the server is configured

curl -s http://reranker:8080/info | jq '{model_id, max_input_length, max_batch_tokens, max_client_batch_size}'
curl -s http://reranker:8080/metrics | grep -E '^te_(queue|batch|request)' | cut -d'{' -f1 | sort -u

Metric names vary by TEI version; look for queue size and batch size histograms. A growing queue with small batches means the client is sending tiny requests; a full batch with a growing queue means you need more capacity.

4. Check how the client calls it

Look for one HTTP call per candidate. That pattern is very common in hand-written pipelines and destroys batching.

Fixes

Rerank fewer candidates

Measure recall of the first stage at different depths before you choose. If the right chunk is in the vector search top 30 for 95% of your golden set, reranking 100 buys little.

def recall_at(k):
    hits = sum(1 for q, gold in golden if gold in [c["id"] for c in vector_search(q, k=k)])
    return hits / len(golden)

for k in (10, 20, 30, 50, 100):
    print(k, round(recall_at(k), 3))

Pick the smallest depth where recall flattens. Hybrid search (BM25 plus vectors) usually lets you go shallower, because the first stage is better. Azure AI Search's semantic ranker, for comparison, only reranks the top 50 results of the first stage.

Truncate passages deliberately

Send only the part of the chunk that matters, within a fixed token budget (256 to 512 is common), and send the full chunk to the LLM afterwards.

curl -s http://reranker:8080/rerank -H 'Content-Type: application/json' -d '{
  "query": "rotate the storage account key without downtime",
  "texts": ["...candidate 1...", "...candidate 2..."],
  "truncate": true,
  "raw_scores": false,
  "return_text": false
}' | jq '.[:5]'

Warning

Truncation from the right cuts the end of a passage. If your chunks put the useful content after a long header (page titles, breadcrumbs, table headers), strip the boilerplate first or relevance drops on exactly the documents people search for most. Re-run the golden set after any truncation change.

Batch every candidate into one request

One request per query, all candidates in texts, within --max-client-batch-size. Let the server pack batches across concurrent queries with --max-batch-tokens. Bigger values raise throughput and per-request latency; for an interactive service, raise it only while p95 improves.

Separate interactive and offline traffic

Evaluation runs and backfills send hundreds of rerank calls a second. Give them their own deployment so a nightly eval cannot add seconds to live queries.

kubectl -n rag get deploy -l component=reranker
kubectl -n rag scale deploy/reranker-online --replicas=3

Put the model on the right hardware

Small cross-encoders (MiniLM-class) can run acceptably on CPU at low volume. Larger multilingual rerankers need a GPU for interactive use at any real concurrency. A small GPU (an L4 or a MIG slice) is usually enough; reranking is short sequences, not long generation.

Use a cascade

For simple queries, skip the reranker when the first-stage score margin is large, or rerank only the top 20 with a small model and send the rest unchanged. Log which path each query took so you can compare quality.

Score thresholds after changing models

If you filter candidates by reranker score (for example "drop below 0.3"), changing the model or switching raw_scores invalidates the threshold. Raw logits and sigmoid outputs are on different scales, and different models are not calibrated to each other. Recompute thresholds from the golden set whenever the model, version or score mode changes.

Prevent it next time

  • Track reranker latency as its own span in traces, with candidate count and total tokens as attributes.
  • Keep a golden set and re-measure both recall and p95 latency for every change to depth, truncation or model.
  • Alert on reranker queue size and p95, not just on end-to-end latency.
  • Cap candidates and per-passage tokens in configuration, not in code scattered across services.
  • Load test the reranker at expected peak concurrency before launch, with realistic chunk lengths.