Add a Reranker to Your RAG Pipeline

Vector search finds the roughly relevant, not the best. A cross-encoder reranker reorders your top candidates so the LLM reads the right passages first.

The right document is usually in there. That is the part that gets under your skin. You ask your RAG system a question, the answer comes back vague or slightly off, and when you dump the retrieved chunks to a log you find the passage that actually answers it sitting at position seven. Your vector search did find it. It just did not think it was the best match, so it never made the cut into the five chunks you handed the model.

This post is for engineers who already have retrieval working. You embed your documents, store the vectors, pull the top-k nearest neighbors, and stuff them into the prompt. You have hit the ceiling where answers plateau even though the right context is clearly being retrieved. A reranker is the cheapest fix for that exact problem. It is worth understanding why the first stage gets the order wrong before you bolt one on, because that tells you when it will help and when it will not.

Why the first stage ranks by a blunt signal

Almost every vector search runs on a bi-encoder. It takes a piece of text and turns it into one fixed-length vector. You run every chunk in your corpus through it once, ahead of time, and store the vectors in an index. At query time you encode the question the same way and look for the nearest vectors, usually by cosine similarity, over an approximate index like IVF so you are not comparing against millions of vectors one by one. The whole thing is fast because the expensive work, encoding the documents, already happened and the query side is a single forward pass plus a nearest-neighbor lookup.

The speed comes from a compression that also limits you. A whole passage, maybe a few hundred words, gets squeezed into one vector. The query gets squeezed into another. Then you compare the two summaries and never look at the original words again. That is enough to tell that a chunk is roughly on-topic. It is not enough to tell, among twenty roughly-on-topic chunks, which one contains the specific sentence that answers the question. The query and the document are encoded in separate rooms and only their summaries are ever in the same place.

So the first stage is good at recall and mediocre at precision. It reliably pulls the right passage into the top fifty. It is unreliable about putting it first. For plain search that is fine, because a human scans the list. For RAG it is not, because you are going to cut the list to a handful of chunks and the model reads whatever survives, in the order you give it.

Side-by-side of the two scoring architectures. On the left the bi-encoder sends query and passage through separate encoders into two vectors that are compared with cosine, with the passage vectors precomputed. On the right the cross-encoder feeds query and passage into one model together and emits a single relevance score, with a note that it cannot precompute and must run once per pair.

What a cross-encoder sees that a bi-encoder cannot

A cross-encoder does the thing a bi-encoder refuses to do: it puts the query and the passage into the model together, concatenated into one input, and lets attention run across both at once. The output is not an embedding. It is a single number: a relevance score for this query against this passage. Because the two texts share the same forward pass, the model can line up a phrase in the question with the exact span in the passage that matches it. That is the detail the bi-encoder threw away when it compressed each side into a vector.

This is not new. Nogueira and Cho showed back in 2019 that feeding a query and passage into BERT as a single sequence and training it to score relevance beat the previous state of the art on the MS MARCO passage ranking task by 27% relative MRR@10. The approach has been refined a lot since, but the shape is the same, and it is the shape every modern reranker still uses.

The accuracy has a price, and the price is why you cannot just use a cross-encoder for everything. There is nothing to precompute. The score depends on the query, so it cannot exist until the query arrives, which means one forward pass for every passage you want to score. Run that over a million-document corpus per query and you have built something unusably slow. A cross-encoder only makes sense over a list that something cheaper has already shortened.

The two-stage pattern

That constraint is the whole design. The bi-encoder is the first stage: it scans the entire corpus fast and returns a generous shortlist, maybe the top fifty, chosen for recall. The cross-encoder is the second stage: it scores each of those fifty against the query properly and sorts them, then you keep the top five. Cheap and wide, then expensive and precise. The slow model never touches more than the shortlist, so its cost stays bounded no matter how big the corpus gets.

Two ordered lists of the same six candidates. On the left, ranked by bi-encoder cosine similarity, the passage that answers the question sits at position six and a naive top-3 cut drops it. On the right, after the cross-encoder rerank, the same passage is at position one and survives the cut.

There is one rule that falls out of this and it catches people. The reranker can only reorder what the first stage handed it. If the passage you need is not in the top fifty, no amount of reranking will conjure it. It was never in the room. So the move when you add a reranker is to widen the first stage, not narrow it. If you were retrieving ten chunks and feeding all ten to the model, switch to retrieving forty or fifty, rerank those, and feed the top ten. You are spending a little more first-stage recall to give the precise stage something to work with.

Wiring it up in Python

The quickest way to try this is sentence-transformers, which ships a CrossEncoder class and a set of pretrained rerankers. A small MS MARCO model like ms-marco-MiniLM-L-6-v2 is a sane default to start from. It is tiny, fast on a GPU, and tolerable on CPU for modest shortlists.

from sentence_transformers import CrossEncoder

# Load once at startup and reuse the instance across requests.
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

def rerank(query: str, candidates: list[dict], top_n: int = 5) -> list[dict]:
    # `candidates` is whatever your vector store returned: each item has
    # at least an id and the chunk text. `predict` scores every pair in
    # one batched call, so pass the whole shortlist, not one at a time.
    pairs = [(query, c["text"]) for c in candidates]
    scores = reranker.predict(pairs)
    for c, score in zip(candidates, scores):
        c["rerank_score"] = float(score)
    candidates.sort(key=lambda c: c["rerank_score"], reverse=True)
    return candidates[:top_n]

Two things worth knowing. predict batches internally, so hand it the full shortlist in one call rather than looping. A loop throws away the batching and makes this several times slower. And the scores are pointwise: each is the model’s opinion of one query-passage pair on its own. They are comparable within a single query, which is all sorting needs, but they are not calibrated probabilities and they are not comparable across different queries. A score of 2.0 on one question and 2.0 on another do not mean the same thing. If you want a convenience method, reranker.rank(query, documents, top_k=5) does the pairing and sorting for you and returns the indices with scores.

Letting the datastore do it

If your retrieval already lives in OpenSearch, you can rerank inside the search request instead of round-tripping candidates back to your service. OpenSearch has a rerank processor that runs as a search response processor. It reorders the hits after the query returns them. The ml_opensearch type, available since 2.12, calls a cross-encoder model you have registered with the cluster; you attach the processor to a search pipeline and reference it per request.

PUT /_search/pipeline/rerank-pipeline
{
  "response_processors": [
    {
      "rerank": {
        "ml_opensearch": { "model_id": "<your-cross-encoder-model-id>" },
        "context": { "document_fields": ["chunk_text"] }
      }
    }
  ]
}

One caveat if you are running hybrid search: the rerank processor runs after the normalization processor that combines your lexical and vector scores, so it has the last word on the final order. That is usually what you want, since the cross-encoder is the better judge, but it means the carefully normalized hybrid score is no longer what decides the ranking. There is also a lighter by_field type, added in 2.18, that just reorders by a numeric field you already computed, which is handy when you score relevance somewhere else and only need OpenSearch to sort by it.

If you would rather not host a model at all, a hosted reranker fills the same slot. Cohere’s Rerank API takes a query and a list of documents and returns them ordered with relevance scores. Same second-stage contract, delivered as an HTTP call. You trade the operational weight of serving a cross-encoder for a per-request cost and a network hop, which is a reasonable trade when reranking is not your bottleneck and you do not want another model in your deployment.

Tradeoffs and the ways it goes wrong

The obvious cost is latency. You are adding a model pass over the shortlist to every query, and it lands on the critical path before the LLM can start. Keep the shortlist modest and make sure you are actually batching the pairs. Reranking fifty candidates is cheap; reranking five hundred is a different conversation. A small MiniLM cross-encoder on a GPU adds little, but the same model on CPU with a long shortlist can add real time, so size the shortlist to your hardware.

The failure mode that wastes the most time is the recall ceiling I mentioned. If reranking does not seem to help, the first suspect is not the reranker, it is the first stage: check whether the right passage is even in the shortlist before you blame the model that only reorders it. A quick way to catch this is to log, on a handful of known-answer questions, the rank of the correct chunk both before and after reranking. If it was never retrieved, widen recall; the reranker was never the problem.

Domain mismatch is the quieter one. The small MS MARCO rerankers were trained on web question-answering, and that is the flavor of relevance they know. Point one at a narrow domain (internal runbooks, legal text, machine logs) and it can underperform or occasionally rank worse than the plain vector order, because its notion of relevance was learned somewhere else. Rerankers do not always help, and the only way to know is to measure on your own eval set rather than trusting a leaderboard number. When a general model is not good enough, fine-tuning a cross-encoder on your own labeled pairs is the usual next step, but that is a project, not a config change, so reach for it only once you have confirmed the off-the-shelf model is the limit.

Where it fits, and where I have reached for it

A reranker is not the only thing you do to a shortlist, and the order of operations matters. My default is: retrieve wide for recall, rerank for precision, then, if your chunks are repetitive, run maximal marginal relevance over the reranked top to drop near-duplicates before they eat context budget, and keep grounded citations tied to whatever survives. Rerank first and dedupe second, not the other way around, so the diversity step is choosing among passages that are already the most relevant ones.

This was exactly the shape of problem behind Archi, the retrieval copilot I worked on for CMS operations at CERN. The questions were all over the map: a quick “what does this error code mean” next to a request that needed several runbooks and a configuration page pulled together. Vector search would reliably surface the roughly right documents and just as reliably get the order wrong, burying the one page that actually answered the question under five that merely shared vocabulary with it. A reranker was the cheapest precision win available: no new embedding model, no re-indexing, just a second pass over a shortlist I was already retrieving. It is the first thing I would try when a RAG system is retrieving the right thing and still answering the wrong one.


Image credit: diagrams by Muhammad Hassan Ahmed, released under CC0. No third-party images were used.