Skip to content
RAG infrastructure on Kubernetes · Chapter 9 of 20 Day 8: Hybrid Search and Reranking

Day 8: Hybrid Search and Reranking

Goal: Put keyword search (BM25) next to vector search, run a reranker as a service of its own – and use the test bench to measure what both bring and what they cost · Duration: approx. 120 min · Prerequisite: Day 7

State before this chapter

# on rag1
kubectl -n rag get pod curl qdrant-0 embed-66bdc7c6c9-rqqpn

Read the name of the embedding pod beforehand with kubectl -n rag get pods; yours ends differently.

Expected: all three 1/1 Running. If curl shows Completed, recreate the pod as on Day 6, Drill 6, Step 1.

# on rag1
curl -s http://127.0.0.1:6333/collections/wissen -o sammlung.json
# on rag1
jq .result.payload_schema sammlung.json

Expected:

{
  "quelle": {
    "data_type": "keyword",
    "points": 173
  }
}

If curl does not answer, the port-forward to Qdrant is no longer running – restart it as on Day 4.

Introduction

Since Day 6, the question “Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?” (which pods are evicted first when a node runs out of memory?) has been looking for its card in vain. Day 7 showed that card size, overlap and heading change nothing about that. Two tools are almost always recommended in such cases: hybrid search – keywords in addition to vectors – and a reranker, which reads the hits once more and reorders them.

Today you build in both and let the test bench decide. The result is uncomfortable: one of the two tools makes the search worse for our questions. The other brings the memory-shortage card from position 25 to position 2 – and costs sixty times the time for it.

Today you learn:

  • how BM25 calculates and why it fails with German questions on English texts,
  • hybrid search in Qdrant with prefetch and Reciprocal Rank Fusion,
  • to run a reranker as a service of its own – with a memory limit, a batch limit and probes,
  • to measure the difference between “in the stack” and “at the front of the stack”,
  • to weigh hit rate against response time.

Background

The picture for today: subject catalogue and expert reader

The librarian from the last few days finds cards by the meaning of the question. Many libraries also have a subject catalogue: little cards, sorted alphabetically by words. Whoever looks for a rare word – a server name, an error number – is quick there. Whoever asks in different words or in a different language than the text finds nothing there, or the wrong thing.

And then there is the expert reader. He does not search for anything himself. He gets a stack of cards that the librarian has put in front of him, reads each one together with the question and puts them into a new order. He is thorough and slow – and he can only order what is on his table.

The terms

Term Meaning in the picture
BM25 ranking by shared words; rare words count more, long texts less subject catalogue
IDF inverse document frequency: the rarer a word in the collection, the higher its weight a subject heading with only one card
Hybrid search run vector search and BM25 separately and merge the rankings librarian and catalogue each put down a stack
Reciprocal Rank Fusion (RRF) merging method: per list, every card gets 1/(position + k) points, the points are added up whoever is high up in both stacks wins
Reranker (cross-encoder) model that reads question and card together and assigns a score expert reader
Candidates the cards the reranker gets to see the stack on the reader’s table
In the pool share of questions for which the right card is among the candidates the right card is on the table at all

The difference between embedding model and reranker is the core of the day. The embedding model reads question and card separately and compares two vectors. That is why all cards can be embedded once in advance, and the search takes milliseconds. The reranker reads every pair of question and card anew. That is more precise, but it is a model run of its own for every question and every candidate card.

Remember: The search decides what gets onto the table. The reranker only decides the order.

Drill 1: The subject catalogue

Where you are: on rag1.

What you have afterwards: a BM25 index over the card text in the collection wissen – and two queries that show what it can do and what it cannot.

Step 1 – the folder.

# on rag1
mkdir -p ~/kurs/08
# on rag1
cd ~/kurs/08

Step 2 – the index. Qdrant can put a full-text index on a payload field. With "scoring": true it calculates BM25 rankings over it. Since Day 6, the card text has been in the field text of every card – you do not need to load anything again.

# on rag1
nano index.json
~/kurs/08/index.json new file
{
  "field_name": "text",
  "field_schema": {
    "type": "text",
    "scoring": true
  }
}
Setting Value Meaning
field_name text the payload field that is indexed
type text full-text index: the text is split into words
scoring true also keep BM25 statistics so that results can be sorted by relevance
# on rag1
curl -s -X PUT "http://127.0.0.1:6333/collections/wissen/index?wait=true" -H "Content-Type: application/json" -d @index.json
  • -X PUT …/index: creates a payload index,
  • ?wait=true: only answers when the index is finished,
  • -d @index.json: sends the content of the file as the request.

Expected:

{"result":{"operation_id":27,"status":"completed"},"status":"ok","time":0.237979092}

Your operation_id will be different.

Step 3 – take a look.

# on rag1
curl -s http://127.0.0.1:6333/collections/wissen -o sammlung.json
# on rag1
jq .result.payload_schema sammlung.json

Expected:

{
  "quelle": {
    "data_type": "keyword",
    "points": 173
  },
  "text": {
    "data_type": "text",
    "params": {
      "type": "text",
      "tokenizer": "word",
      "scoring": {
        "type": "bm25"
      }
    },
    "points": 173
  }
}

What you see: Next to the index quelle from Day 6 there is now text over all 173 cards. The tokenizer word splits at spaces and punctuation and writes everything in lower case. You have not set a stemming filter or a stop-word list – “Pods” and “Pod” are two words, “der” and “ein” (German “the” and “a”) count too.

Step 4 – a query with the words of the documentation.

# on rag1
nano bm25-englisch.json
~/kurs/08/bm25-englisch.json new file
{
  "query": {"text": "evicted out of memory"},
  "using": "text",
  "limit": 5,
  "with_payload": ["quelle", "abschnitt"]
}
Setting Value Meaning
query.text evicted out of memory search text for BM25 – not a vector
using text the field whose full-text index is used
limit 5 the five best cards
with_payload quelle, abschnitt only the fields you need to place the hit
# on rag1
curl -s -X POST http://127.0.0.1:6333/collections/wissen/points/query -H "Content-Type: application/json" -d @bm25-englisch.json -o bm25.json
# on rag1
jq -c '.result.points[] | [.score, .payload.quelle, .payload.abschnitt]' bm25.json
  • .result.points[]: every card found, one by one,
  • [.score, …]: score, source and section as one line,
  • -c: compact, one card per line.

Expected:

[6.5530167,"k8s-taint-and-toleration.md","Taint based Evictions"]
[4.7593665,"k8s-taint-and-toleration.md","Concepts"]
[4.7173066,"k8s-pod-qos.md","Burstable"]
[4.496084,"k8s-taint-and-toleration.md","Concepts"]
[4.4565635,"k8s-pod-qos.md","Memory throttling"]

What you see: It finds where the words are – “Evictions” in the heading, “memory” in the QoS sections. The scores are not cosine values between 0 and 1, but BM25 sums without a fixed upper limit. The card “Quality of Service classes” that f01 is looking for is not among the first five: it says “evict” and “runs out of resources”, not “evicted” and “memory”. Without stemming, “evict” and “evicted” are two different words.

Step 5 – the same query with the German test question.

# on rag1
nano bm25-deutsch.json
~/kurs/08/bm25-deutsch.json new file
{
  "query": {"text": "Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?"},
  "using": "text",
  "limit": 5,
  "with_payload": ["quelle", "abschnitt"]
}
# on rag1
curl -s -X POST http://127.0.0.1:6333/collections/wissen/points/query -H "Content-Type: application/json" -d @bm25-deutsch.json -o bm25.json
# on rag1
jq -c '.result.points[] | [.score, .payload.quelle, .payload.abschnitt]' bm25.json

Expected:

[5.974007,"karte-vpn.txt","VPN-Zugang einrichten"]
[5.909961,"karte-druck.txt","Druckdienst neu starten"]
[3.7895288,"k8s-taint-and-toleration.md","Taint Nodes by Condition"]
[3.6869888,"k8s-pod-lifecycle.md","Pod behavior during kubelet restarts"]
[3.6823728,"k8s-taint-and-toleration.md","Concepts"]

What you see: Right at the top are the VPN card and the printer card – they have nothing to do with memory shortage. The question shares exactly one word with both: “der”. In a collection of five English pages and four German cards, “der” occurs only on these two cards – and rare words get a high weight in BM25. Short cards also count more than long ones. For BM25, “der” is a rare subject heading here.

Remember: BM25 knows words, not meaning. If users ask in a different language than the documents, the subject catalogue finds the filler words.

Save your progress? Sign up for free

Drill 2: Hybrid search on the test bench

Where you are: on rag1, in ~/kurs/08.

What you have afterwards: a test bench with switches for hybrid search and reranker – and the measurement of what hybrid search brings for the 13 test questions.

Step 1 – fetch the test bench from Day 7.

# on rag1
cp ../07/eval.py ../07/eval-job.yaml ../07/testfragen.json .

Step 2 – build in the switches.

# on rag1
nano eval.py
~/kurs/08/eval.py changes in green
"""Prüfstand: Testfragen stellen und messen, auf welchem Platz die erwartete Karte liegt."""

import json
import os
import time
import urllib.request

EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
FRAGEN = os.environ.get("FRAGEN", "/testfragen/testfragen.json")
SUCHE = os.environ.get("SUCHE", "dicht")
RERANK = os.environ.get("RERANK_URL", "")
KANDIDATEN = int(os.environ.get("KANDIDATEN", "20"))
K = 5


def anfrage(methode, url, daten):
    req = urllib.request.Request(
        url,
        data=json.dumps(daten).encode(),
        method=methode,
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=300) as antwort:
        return json.load(antwort)


def suchen(frage, vektor, limit):
    """Dichte Suche allein oder mit BM25, gemischt per Reciprocal Rank Fusion."""
    if SUCHE == "hybrid":
        koerper = {
            "prefetch": [
                {"query": vektor, "limit": KANDIDATEN},
                {"query": {"text": frage}, "using": "text", "limit": KANDIDATEN},
            ],
            "query": {"fusion": "rrf"},
        }
    else:
        koerper = {"query": vektor}
    koerper.update(limit=limit, with_payload=["quelle", "abschnitt", "text"])
    url = f"{QDRANT}/collections/{SAMMLUNG}/points/query"
    return anfrage("POST", url, koerper)["result"]["points"]


def neu_ordnen(frage, punkte):
    """Der Reranker liest Frage und Karte zusammen und vergibt eine neue Punktzahl."""
    urteile = anfrage(
        "POST",
        f"{RERANK}/rerank",
        {"query": frage, "texts": [p["payload"]["text"] for p in punkte]},
    )
    return [punkte[u["index"]] for u in urteile]


def rang(punkte, erwartet, tiefe=K):
    """Platz der ersten erwarteten Karte unter den ersten `tiefe`, sonst None."""
    for platz, punkt in enumerate(punkte[:tiefe], start=1):
        ort = {
            "quelle": punkt["payload"]["quelle"],
            "abschnitt": punkt["payload"]["abschnitt"],
        }
        if ort in erwartet:
            return platz
    return None


def main():
    with open(FRAGEN, encoding="utf-8") as datei:
        fragen = json.load(datei)
    plaetze, dauer, im_pool = [], [], 0
    for frage in fragen:
        start = time.time()
        vektor = anfrage(
            "POST", f"{EMBED}/api/embed", {"model": MODELL, "input": [frage["frage"]]}
        )["embeddings"][0]
        punkte = suchen(frage["frage"], vektor, KANDIDATEN if RERANK else K)
        vorher = rang(punkte, frage["erwartet"], len(punkte))
        im_pool += vorher is not None
        if RERANK:
            punkte = neu_ordnen(frage["frage"], punkte)
        dauer.append(time.time() - start)
        platz = rang(punkte, frage["erwartet"])
        plaetze.append(platz)
        weg = (
            f"{vorher or '-':>2} -> {platz or '-':<2}" if RERANK else f"{platz or '-'}"
        )
        print(
            f"{frage['id']:>4}  Platz {weg}  {dauer[-1]:5.1f} s  {frage['frage']}",
            flush=True,
        )
    n = len(plaetze)
    ergebnis = {
        "sammlung": SAMMLUNG,
        "suche": SUCHE,
        "rerank": bool(RERANK),
        "fragen": n,
        "treffer@1": round(sum(1 for p in plaetze if p and p <= 1) / n, 2),
        "treffer@3": round(sum(1 for p in plaetze if p and p <= 3) / n, 2),
        "treffer@5": round(sum(1 for p in plaetze if p) / n, 2),
        "mrr": round(sum(1 / p for p in plaetze if p) / n, 2),
        "im_pool": round(im_pool / n, 2),
        "sekunden_je_frage": round(sum(dauer) / n, 2),
    }
    print(json.dumps(ergebnis, ensure_ascii=False), flush=True)


if __name__ == "__main__":
    main()
Part What changes
SUCHE, RERANK_URL, KANDIDATEN three new switches: dicht (dense) or hybrid, the address of the reranker (empty = none), how many cards it sees
suchen (search) with hybrid, two prefetches – vector search and BM25 with KANDIDATEN cards each – and fusion: rrf on top; otherwise the vector search as before. text now comes along because the reranker has to read the card text
neu_ordnen (reorder) sends question and card texts to the reranker; the answer is a list of index and score, sorted in descending order
rang checks down to the depth tiefe – five for the metrics, all candidates for “in the pool”
main with a reranker fetches KANDIDATEN cards, otherwise five; measures the time per question including embedding and reranker; with a reranker shows “position before -> after”
im_pool, sekunden_je_frage two new metrics at the end

Without a reranker, the test bench fetches five cards as yesterday. Then im_pool is the same as treffer@5.

Step 3 – the new code into the cluster. A ConfigMap created from a file is not silently overwritten – delete it and create it again:

# on rag1
kubectl -n rag delete configmap eval-code
# on rag1
kubectl -n rag create configmap eval-code --from-file=eval.py

Step 4 – the baseline with the new code. The job eval from yesterday still exists, and a job cannot be restarted:

# on rag1
kubectl -n rag delete job eval
# on rag1
kubectl apply -f eval-job.yaml
# on rag1
kubectl -n rag wait --for=condition=Complete job/eval --timeout=600s
# on rag1
kubectl -n rag logs job/eval

Expected (in the lab after 9 seconds):

 f01  Platz -    0.4 s  Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?
 f02  Platz 1    0.2 s  Wie groß darf ein Secret höchstens sein?
 f03  Platz 1    0.4 s  Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?
 f04  Platz 1    0.3 s  Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?
 f05  Platz 1    0.3 s  Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?
 f06  Platz 1    0.2 s  Wozu dient eine Startup-Probe?
 f07  Platz 3    0.3 s  Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
 f08  Platz 1    0.1 s  Welche Phasen kann ein Pod haben?
 f09  Platz -    0.2 s  Wie halte ich Pods von einem bestimmten Node fern?
 f10  Platz -    0.3 s  Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
 f11  Platz 1    0.2 s  Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
 f12  Platz 1    0.3 s  Der Drucker druckt nicht mehr. Was soll ich tun?
 f13  Platz 1    0.2 s  Wie komme ich von zu Hause ins Firmennetz?
{"sammlung": "wissen", "suche": "dicht", "rerank": false, "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.77, "treffer@5": 0.77, "mrr": 0.72, "im_pool": 0.77, "sekunden_je_frage": 0.25}

What you see: The same positions and metrics as on Day 7 – the rebuild has shifted nothing. What is new is the time: a quarter of a second per question, most of it for embedding the question.

Step 5 – a job for hybrid search.

# on rag1
cp eval-job.yaml eval-hybrid.yaml
# on rag1
nano eval-hybrid.yaml
~/kurs/08/eval-hybrid.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: eval-hybrid
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: eval
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/eval.py"]
          env:
            - name: SAMMLUNG
              value: wissen
            - name: SUCHE
              value: hybrid
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: testfragen
              mountPath: /testfragen
      volumes:
        - name: code
          configMap:
            name: eval-code
        - name: testfragen
          configMap:
            name: testfragen
# on rag1
kubectl apply -f eval-hybrid.yaml
# on rag1
kubectl -n rag wait --for=condition=Complete job/eval-hybrid --timeout=600s
# on rag1
kubectl -n rag logs job/eval-hybrid

Expected:

 f01  Platz -    0.5 s  Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?
 f02  Platz 1    0.2 s  Wie groß darf ein Secret höchstens sein?
 f03  Platz 1    0.2 s  Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?
 f04  Platz 1    0.3 s  Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?
 f05  Platz 1    0.2 s  Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?
 f06  Platz 1    0.2 s  Wozu dient eine Startup-Probe?
 f07  Platz -    0.3 s  Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
 f08  Platz 1    0.2 s  Welche Phasen kann ein Pod haben?
 f09  Platz 4    0.2 s  Wie halte ich Pods von einem bestimmten Node fern?
 f10  Platz -    0.2 s  Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
 f11  Platz 1    0.2 s  Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
 f12  Platz 1    0.2 s  Der Drucker druckt nicht mehr. Was soll ich tun?
 f13  Platz 2    0.2 s  Wie komme ich von zu Hause ins Firmennetz?
{"sammlung": "wissen", "suche": "hybrid", "rerank": false, "fragen": 13, "treffer@1": 0.62, "treffer@3": 0.69, "treffer@5": 0.77, "mrr": 0.67, "im_pool": 0.77, "sekunden_je_frage": 0.24}
Question dense hybrid what happened
f07 3 – drops out of the first five
f09 – 4 won: the taint section moves into the first five
f13 1 2 the VPN card slips back one position
Total hits@3 0.77, MRR 0.72 hits@3 0.69, MRR 0.67 worse

What you see: Hybrid search wins one question and loses two positions elsewhere. On balance, hits@3 and MRR drop. That is the subject catalogue from Drill 1: with German questions on mostly English texts, BM25 mainly delivers filler-word hits, and RRF mixes them in with equal weight.

Step 6 – a run that ends differently. In the lab, a second run of the same job put f02 in position 2 instead of position 1 – hits@1 0.54 instead of 0.62. Why? Look at what BM25 alone delivers for f02:

# on rag1
nano bm25-f02.json
~/kurs/08/bm25-f02.json new file
{
  "query": {"text": "Wie groß darf ein Secret höchstens sein?"},
  "using": "text",
  "limit": 3,
  "with_payload": ["quelle", "abschnitt"]
}
# on rag1
curl -s -X POST http://127.0.0.1:6333/collections/wissen/points/query -H "Content-Type: application/json" -d @bm25-f02.json -o bm25.json
# on rag1
jq -c '.result.points[] | [.score, .payload.quelle, .payload.abschnitt]' bm25.json

Expected:

[6.9571533,"karte-urlaub.txt","Urlaub beantragen"]
[2.9813926,"k8s-secret.md","Opaque Secrets"]
[2.8146358,"k8s-secret.md","Editing a Secret"]

What you see: For the question about the size of a Secret, BM25 delivers the leave card in position 1 – by a wide margin. The card ends with “… unter Abwesenheiten ein.”, and the word “ein” occurs in no other card of the collection. The vector search has “Size limit” in position 1. RRF gives every card, per list, 1/(position + 1) points (Qdrant calculates with k = 2 and counts positions from 0): position 1 brings ½. The leave card gets ½ from BM25, “Size limit” ½ from the vector search – a tie. Which of the two comes first is then not determined.

Remember: A mixture is only as good as its worst ingredient. And with RRF, positions decide, not distances – a filler-word hit in position 1 weighs as much as a real hit in position 1.

Save your progress? Sign up for free

Drill 3: The expert reader as a service

Where you are: on rag1, in ~/kurs/08.

What you have afterwards: a reranker service rerank in the namespace rag that runs on rag1 and is reachable at http://rerank.rag.

Why this model. The server is Text Embeddings Inference (TEI) from Hugging Face – a program that offers embedding and reranker models over HTTP, with an image of its own for CPUs. As the model you use cross-encoder/mmarco-mMiniLMv2-L12-H384-v1: multilingual, 118 million parameters, Apache 2.0 licence, with ready-made ONNX files for the CPU. In the lab, the better-known BAAI/bge-reranker-v2-m3 with 568 million parameters ran first. With the default settings it was killed with OOMKilled during warm-up despite a 4 GiB limit. With smaller batches it ran, but on two cores it needed 229 seconds for a single question with 20 candidates. For a lab without a GPU, the small model is the honest choice.

Step 1 – the manifest.

# on rag1
nano rerank.yaml
~/kurs/08/rerank.yaml new file
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: rerank-modell
  namespace: rag
spec:
  accessModes: ["ReadWriteOnce"]
  storageClassName: local-path
  resources:
    requests:
      storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rerank
  namespace: rag
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: rerank
  template:
    metadata:
      labels:
        app: rerank
    spec:
      nodeSelector:
        kubernetes.io/hostname: rag1
      containers:
        - name: rerank
          image: ghcr.io/huggingface/text-embeddings-inference:cpu-1.9.4
          args:
            - --model-id=cross-encoder/mmarco-mMiniLMv2-L12-H384-v1
            - --revision=1427fd652930e4ba29e8149678df786c240d8825
            - --port=8080
            - --max-batch-tokens=2048
          ports:
            - containerPort: 8080
          volumeMounts:
            - name: modell
              mountPath: /data
          resources:
            requests:
              cpu: "1"
              memory: 1Gi
            limits:
              cpu: "2"
              memory: 2Gi
          startupProbe:
            httpGet:
              path: /health
              port: 8080
            periodSeconds: 10
            failureThreshold: 60
          readinessProbe:
            httpGet:
              path: /health
              port: 8080
      volumes:
        - name: modell
          persistentVolumeClaim:
            claimName: rerank-modell
---
apiVersion: v1
kind: Service
metadata:
  name: rerank
  namespace: rag
spec:
  selector:
    app: rerank
  ports:
    - port: 80
      targetPort: 8080
Setting Value Meaning
PVC rerank-modell 5 GiB, local-path the model is downloaded once and survives restarts – like the model volume of the embedding service on Day 3
strategy: Recreate – first stop the old pod, then start the new one; an RWO volume cannot be attached to two pods
nodeSelector rag1 rag1 has four cores, rag2 only two – and Qdrant and PostgreSQL already run on rag2
image …:cpu-1.9.4 TEI image for CPUs, pinned version
--model-id, --revision model and commit the revision fixes the exact state of the model; without it, TEI loads the latest one
--max-batch-tokens 2048 the model computes at most this many tokens at once – limits memory during warm-up and under load
requests / limits 1–2 cores, 1–2 GiB measured in the lab: around 300 MiB when idle; with a 1 GiB limit the container was killed with OOMKilled during warm-up
startupProbe up to 60 × 10 s time for the first download of the model
readinessProbe /health the service only gets requests once TEI answers
Service rerank port 80 → 8080 address in the cluster: http://rerank.rag

Step 2 – apply.

# on rag1
kubectl apply -f rerank.yaml

Expected:

persistentvolumeclaim/rerank-modell created
deployment.apps/rerank created
service/rerank created
# on rag1
kubectl -n rag rollout status deployment/rerank --timeout=600s

Expected (in the lab after 76 seconds, most of it the download):

Waiting for deployment "rerank" rollout to finish: 0 of 1 updated replicas are available...
deployment "rerank" successfully rolled out
# on rag1
kubectl -n rag logs deployment/rerank --tail=3

Expected (excerpt – the last line, without colour codes):

2026-12-02T11:30:44.673771Z  INFO text_embeddings_router::http::server: router/src/http/server.rs:1879: Ready

Step 3 – how much it needs.

# on rag1
kubectl top pod -n rag

Expected:

NAME                     CPU(cores)   MEMORY(bytes)   
curl                     0m           0Mi             
embed-66bdc7c6c9-rqqpn   1m           1381Mi          
pg-1                     20m          55Mi            
qdrant-0                 8m           63Mi            
rerank-7d88b8858-862xc   418m         305Mi           

What you see: The reranker takes up 305 MiB – a quarter of the embedding service. The 418 millicores are still from the warm-up. Without requests the value drops – after the big run in Drill 5 it was at 40 millicores in the lab one minute later.

Step 4 – a test by hand. Three texts, one of which matches the question:

# on rag1
nano rerank-probe.json
~/kurs/08/rerank-probe.json new file
{
  "query": "Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?",
  "texts": [
    "The Pod phase is a simple, high-level summary of where the Pod is in its lifecycle.",
    "Kubernetes uses QoS classes to decide which Pods to evict when a Node runs out of resources.",
    "Druckdienst neu starten: Melde dich am Druckserver druck02 an."
  ]
}

The helper pod curl does not have the file. You send it in through standard input:

# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://rerank.rag/rerank -H "Content-Type: application/json" -d @- < rerank-probe.json
Setting Meaning
exec -i pass rag1’s standard input through to the command in the pod
-d @- read the request body from standard input
< rerank-probe.json the file on rag1 is this standard input
/rerank TEI’s endpoint for rerankers: question plus a list of texts

Expected:

[{"index":1,"score":0.806005},{"index":0,"score":0.0036397323},{"index":2,"score":0.0007380989}]

What you see: The reranker has re-sorted the three texts. index points to the position in your list: the QoS sentence (index 1) gets 0.81, the pod phase 0.004, the printer card almost nothing. It has connected the German question with the English sentence, although no word is the same except “Pods” and “Node”.

Step 5 – how long it takes.

# on rag1
kubectl -n rag exec -i curl -- curl -s -o /dev/null -w "%{time_total}\n" -X POST http://rerank.rag/rerank -H "Content-Type: application/json" -d @- < rerank-probe.json
  • -o /dev/null: throw the response away,
  • -w "%{time_total}\n": print only the total duration in seconds.

Expected:

0.245275

What you see: A quarter of a second for three short sentences. Real cards are up to 1000 characters long, and the test bench sends 20 of them. What that costs is measured in Drill 4.

Remember: A reranker is a service of its own with its own model, its own memory and its own latency. It needs to be planned like the embedding service – not dropped into the answer service “just like that” as a library.

Save your progress? Sign up for free

Drill 4: The expert reader on the test bench

Where you are: on rag1, in ~/kurs/08.

What you have afterwards: two measurements with a reranker – after vector search and after hybrid search.

Step 1 – a job with a reranker.

# on rag1
cp eval-job.yaml eval-rerank.yaml
# on rag1
nano eval-rerank.yaml
~/kurs/08/eval-rerank.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: eval-rerank
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: eval
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/eval.py"]
          env:
            - name: SAMMLUNG
              value: wissen
            - name: RERANK_URL
              value: http://rerank.rag
            - name: KANDIDATEN
              value: "20"
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: testfragen
              mountPath: /testfragen
      volumes:
        - name: code
          configMap:
            name: eval-code
        - name: testfragen
          configMap:
            name: testfragen
Setting Value Meaning
RERANK_URL http://rerank.rag the service from Drill 3
KANDIDATEN "20" the vector search fetches 20 cards, the reranker orders them, the first five are counted

Values of environment variables are always strings in Kubernetes – hence "20" in quotation marks.

# on rag1
kubectl apply -f eval-rerank.yaml
# on rag1
kubectl -n rag wait --for=condition=Complete job/eval-rerank --timeout=900s
# on rag1
kubectl -n rag logs job/eval-rerank

Expected (in the lab after 70 seconds):

 f01  Platz  - -> -     5.4 s  Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?
 f02  Platz  1 -> 1     5.0 s  Wie groß darf ein Secret höchstens sein?
 f03  Platz  1 -> 1     4.8 s  Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?
 f04  Platz  1 -> 1     4.8 s  Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?
 f05  Platz  1 -> 1     4.6 s  Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?
 f06  Platz  1 -> 1     4.7 s  Wozu dient eine Startup-Probe?
 f07  Platz  3 -> 5     5.8 s  Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
 f08  Platz  1 -> 2     4.7 s  Welche Phasen kann ein Pod haben?
 f09  Platz  6 -> 5     5.3 s  Wie halte ich Pods von einem bestimmten Node fern?
 f10  Platz  9 -> 1     5.3 s  Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
 f11  Platz  1 -> 1     4.8 s  Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
 f12  Platz  1 -> 1     5.6 s  Der Drucker druckt nicht mehr. Was soll ich tun?
 f13  Platz  1 -> 1     4.6 s  Wie komme ich von zu Hause ins Firmennetz?
{"sammlung": "wissen", "suche": "dicht", "rerank": true, "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.77, "treffer@5": 0.92, "mrr": 0.76, "im_pool": 0.92, "sekunden_je_frage": 5.04}

Read every line as “position with vector search -> position after the reranker”:

Question before after Meaning
f10 9 1 the reader brings the right card from ninth place right to the front
f09 6 5 just makes it into the first five
f07, f08 3, 1 5, 2 lost: the reader puts other cards in front
f01 – – the right card is not among the 20 candidates
im_pool 0.92 for 12 of 13 questions the right card was on the table
sekunden_je_frage 5.04 twenty times as long as without a reranker (0.25 s)

What you see: The reranker brings two questions into the first five (hits@5 0.77 → 0.92), but also moves two right cards further back. hits@1 and hits@3 stay the same, MRR rises slightly (0.72 → 0.76). And it cannot save f01: what is not on the table, the reader cannot put at the front.

Step 2 – hybrid search plus reranker. Perhaps BM25 brings the f01 card onto the table:

# on rag1
cp eval-rerank.yaml eval-hybrid-rerank.yaml
# on rag1
nano eval-hybrid-rerank.yaml
~/kurs/08/eval-hybrid-rerank.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: eval-hybrid-rerank
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: eval
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/eval.py"]
          env:
            - name: SAMMLUNG
              value: wissen
            - name: SUCHE
              value: hybrid
            - name: RERANK_URL
              value: http://rerank.rag
            - name: KANDIDATEN
              value: "20"
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: testfragen
              mountPath: /testfragen
      volumes:
        - name: code
          configMap:
            name: eval-code
        - name: testfragen
          configMap:
            name: testfragen
# on rag1
kubectl apply -f eval-hybrid-rerank.yaml
# on rag1
kubectl -n rag wait --for=condition=Complete job/eval-hybrid-rerank --timeout=900s
# on rag1
kubectl -n rag logs job/eval-hybrid-rerank

Expected:

 f01  Platz  - -> -     5.3 s  Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?
 f02  Platz  2 -> 1     4.7 s  Wie groß darf ein Secret höchstens sein?
 f03  Platz  1 -> 1     5.4 s  Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?
 f04  Platz  1 -> 1     5.6 s  Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?
 f05  Platz  1 -> 1     5.0 s  Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?
 f06  Platz  1 -> 1     4.0 s  Wozu dient eine Startup-Probe?
 f07  Platz  9 -> 5     5.5 s  Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
 f08  Platz  1 -> 2     4.6 s  Welche Phasen kann ein Pod haben?
 f09  Platz  4 -> -     5.4 s  Wie halte ich Pods von einem bestimmten Node fern?
 f10  Platz 13 -> 1     5.2 s  Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
 f11  Platz  1 -> 1     5.1 s  Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
 f12  Platz  1 -> 1     5.5 s  Der Drucker druckt nicht mehr. Was soll ich tun?
 f13  Platz  2 -> 1     5.1 s  Wie komme ich von zu Hause ins Firmennetz?
{"sammlung": "wissen", "suche": "hybrid", "rerank": true, "fragen": 13, "treffer@1": 0.69, "treffer@3": 0.77, "treffer@5": 0.85, "mrr": 0.75, "im_pool": 0.92, "sekunden_je_frage": 5.11}
Question before (hybrid) after Meaning
f10 13 1 right to the front again
f02, f13 2, 2 1, 1 the reader clears away BM25’s filler-word hits
f09 4 – lost: dropped out of the first five
f01 – – BM25 does not get the card among the 20 candidates either

What you see: The reranker repairs much of what BM25 spoiled – hits@1 rises from 0.62 to 0.69. It does not get better than “vector search plus reranker” (hits@5 0.85 instead of 0.92, MRR 0.75 instead of 0.76). And im_pool stays at 0.92: even with BM25, the f01 card is not on the table.

Remember: If the reranker does not save a question, check im_pool first. If the right card is not among the candidates, no better reader helps – only a bigger stack or a better search.

Save your progress? Sign up for free

Drill 5: A bigger stack

Where you are: on rag1, in ~/kurs/08.

What you have afterwards: a reranker that accepts 50 candidates and stays in the service under load – and the measurement of whether f01 gets onto the table that way.

Step 1 – 50 candidates.

# on rag1
cp eval-rerank.yaml eval-rerank-50.yaml
# on rag1
nano eval-rerank-50.yaml
~/kurs/08/eval-rerank-50.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: eval-rerank-50
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: eval
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/eval.py"]
          env:
            - name: SAMMLUNG
              value: wissen
            - name: RERANK_URL
              value: http://rerank.rag
            - name: KANDIDATEN
              value: "50"
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: testfragen
              mountPath: /testfragen
      volumes:
        - name: code
          configMap:
            name: eval-code
        - name: testfragen
          configMap:
            name: testfragen
# on rag1
kubectl apply -f eval-rerank-50.yaml
# on rag1
kubectl -n rag wait --for=condition=Failed job/eval-rerank-50 --timeout=300s

This time you wait for Failed – the job fails immediately.

Expected:

job.batch/eval-rerank-50 condition met

Step 2 – why.

# on rag1
kubectl -n rag logs job/eval-rerank-50 --tail=1

Expected:

urllib.error.HTTPError: HTTP Error 422: Unprocessable Entity

422 means: the request is formally correct, but the server rejects its content. The server states the reason, not the client:

# on rag1
kubectl -n rag logs deployment/rerank --tail=1

Expected (without colour codes):

2026-12-02T11:33:20.577523Z ERROR rerank: text_embeddings_router::http::server: router/src/http/server.rs:384: batch size 50 > maximum allowed batch size 32

What you see: TEI accepts at most 32 texts in one request. That is a protective limit against clients that block the service with a giant request – and a number that appears in none of the test bench’s error messages. With a service you run yourself, looking into the server log is part of the first step.

Step 3 – two changes to the reranker. The first raises the limit. The second comes from a lab run in which the service vanished in the middle of the test bench: after eight questions the test bench reported Connection timed out, and the events showed:

Warning   Unhealthy   pod/rerank-…   Readiness probe failed: Get "http://10.42.0.17:8080/health": context deadline exceeded (Client.Timeout exceeded while awaiting headers)

TEI queries the model itself on /health. If it is busy computing a large batch, the answer only comes afterwards – in the lab later than after one second. That is how long the readiness probe waits by default. After three missed answers, Kubernetes takes the pod out of the service, and the next request goes nowhere – although the service was only busy.

# on rag1
nano rerank.yaml
~/kurs/08/rerank.yaml changes in green
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: rerank-modell
  namespace: rag
spec:
  accessModes: ["ReadWriteOnce"]
  storageClassName: local-path
  resources:
    requests:
      storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rerank
  namespace: rag
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: rerank
  template:
    metadata:
      labels:
        app: rerank
    spec:
      nodeSelector:
        kubernetes.io/hostname: rag1
      containers:
        - name: rerank
          image: ghcr.io/huggingface/text-embeddings-inference:cpu-1.9.4
          args:
            - --model-id=cross-encoder/mmarco-mMiniLMv2-L12-H384-v1
            - --revision=1427fd652930e4ba29e8149678df786c240d8825
            - --port=8080
            - --max-batch-tokens=2048
            - --max-client-batch-size=64
          ports:
            - containerPort: 8080
          volumeMounts:
            - name: modell
              mountPath: /data
          resources:
            requests:
              cpu: "1"
              memory: 1Gi
            limits:
              cpu: "2"
              memory: 2Gi
          startupProbe:
            httpGet:
              path: /health
              port: 8080
            periodSeconds: 10
            failureThreshold: 60
          readinessProbe:
            httpGet:
              path: /health
              port: 8080
            timeoutSeconds: 30
      volumes:
        - name: modell
          persistentVolumeClaim:
            claimName: rerank-modell
---
apiVersion: v1
kind: Service
metadata:
  name: rerank
  namespace: rag
spec:
  selector:
    app: rerank
  ports:
    - port: 80
      targetPort: 8080
Setting Value Meaning
--max-client-batch-size 64 up to 64 texts per request
timeoutSeconds 30 the readiness probe waits up to 30 seconds for /health – longer than a full batch takes
# on rag1
kubectl apply -f rerank.yaml
# on rag1
kubectl -n rag rollout status deployment/rerank --timeout=600s

Expected (excerpt – the last line, in the lab after 11 seconds, the model is already in the volume):

deployment "rerank" successfully rolled out

Step 4 – the run with 50 candidates.

# on rag1
kubectl -n rag delete job eval-rerank-50
# on rag1
kubectl apply -f eval-rerank-50.yaml
# on rag1
kubectl -n rag wait --for=condition=Complete job/eval-rerank-50 --timeout=1200s
# on rag1
kubectl -n rag logs job/eval-rerank-50

Expected (in the lab after 3 minutes 31 seconds):

 f01  Platz 25 -> 2    16.3 s  Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?
 f02  Platz  1 -> 1    14.6 s  Wie groß darf ein Secret höchstens sein?
 f03  Platz  1 -> 1    15.2 s  Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?
 f04  Platz  1 -> 1    18.7 s  Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?
 f05  Platz  1 -> 1    15.6 s  Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?
 f06  Platz  1 -> 1    14.7 s  Wozu dient eine Startup-Probe?
 f07  Platz  3 -> -    16.1 s  Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?
 f08  Platz  1 -> 2    13.6 s  Welche Phasen kann ein Pod haben?
 f09  Platz  6 -> 3    15.4 s  Wie halte ich Pods von einem bestimmten Node fern?
 f10  Platz  9 -> 1    16.2 s  Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?
 f11  Platz  1 -> 1    14.9 s  Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
 f12  Platz  1 -> 3    17.2 s  Der Drucker druckt nicht mehr. Was soll ich tun?
 f13  Platz  1 -> 1    17.4 s  Wie komme ich von zu Hause ins Firmennetz?
{"sammlung": "wissen", "suche": "dicht", "rerank": true, "fragen": 13, "treffer@1": 0.62, "treffer@3": 0.92, "treffer@5": 0.92, "mrr": 0.74, "im_pool": 1.0, "sekunden_je_frage": 15.85}
Question before after Meaning
f01 25 2 the memory-shortage card is found – with vector search it was in position 25
f09 6 3 further to the front than with 20 candidates
f10 9 1 as with 20 candidates
f07 3 – lost: more candidates also means more cards that push in front
f12 1 3 the printer card slips back
im_pool 1.0 all 13 right cards are on the table
sekunden_je_frage 15.85 60 times as long as without reranker

What you see: Since Day 6 you have been looking for the card for f01 – now it is in position 2. It was never gone, but was in position 25: the vector search found it, just not far enough to the front. hits@3 rises to 0.92, the best value of the day. At the same time, hits@1 drops to 0.62, and every question takes almost 16 seconds.

Step 5 – what the reader needs for this. Directly after the run:

# on rag1
kubectl top pod -n rag

Expected:

NAME                      CPU(cores)   MEMORY(bytes)   
curl                      0m           0Mi             
embed-66bdc7c6c9-rqqpn    97m          1381Mi          
pg-1                      26m          55Mi            
qdrant-0                  8m           64Mi            
rerank-557b8c4b6d-gcc4v   1965m        898Mi           

What you see: The reranker is at its CPU limit of two cores and takes up 898 MiB – three times as much as freshly started. It does not give the memory back afterwards: one minute later, kubectl top showed 40 millicores in the lab, but still 898 MiB. That is why 1 GiB is not enough as a limit. More candidates cost time and memory, and on the node on which the embedding service also computes.

Remember: The number of candidates is the lever between hit rate and response time. More candidates bring more right cards onto the table – and cost every single card for every question.

Save your progress? Sign up for free

Drill 6: The bill

Where you are: on rag1, in ~/kurs/08.

What you have afterwards: all variants of the day in one table – and a reasoned decision about which of them the answer service gets on Day 9.

Step 1 – the run times at a glance.

# on rag1
kubectl -n rag get jobs

Expected (excerpt – today’s jobs; the ingest jobs from Days 6 and 7 are listed below them):

NAME                       STATUS     COMPLETIONS   DURATION   AGE
eval                       Complete   1/1           8s         8m55s
eval-hybrid                Complete   1/1           7s         8m45s
eval-hybrid-rerank         Complete   1/1           71s        6m4s
eval-rerank                Complete   1/1           70s        7m16s
eval-rerank-50             Complete   1/1           3m31s      4m31s

What you see: The column DURATION is the time for all 13 questions. Without a reranker under ten seconds, with 20 candidates a good minute, with 50 three and a half minutes.

Step 2 – the table. Collect the last lines of the five runs:

Variant H@1 H@3 H@5 MRR Pool s/question
Vector 0.69 0.77 0.77 0.72 0.77 0.25
hybrid 0.62 0.69 0.77 0.67 0.77 0.24
Vector + R. 20 0.69 0.77 0.92 0.76 0.92 5.04
hybrid + R. 20 0.69 0.77 0.85 0.75 0.92 5.11
Vector + R. 50 0.62 0.92 0.92 0.74 1.00 15.85

H@1, H@3, H@5 are hits@1, hits@3, hits@5; “Pool” is im_pool, “R. 20” means reranker with 20 candidates.

Step 3 – decide. Three questions help:

  1. Which metric counts? On Day 9 the language model gets the first three cards. So hits@3 counts more than hits@1.
  2. What may it cost? An answer that only begins after 16 seconds of search is too slow for an information service – and the language model then still needs its own time.
  3. How certain is the difference? Between “Vector” and “Vector + reranker, 50” there are two questions at hits@3. On Day 7 you learned how little that carries with 13 questions.

For this lab the decision goes like this: hybrid search is dropped – it makes every metric worse except the time. The reranker stays as a switch in the answer service, switched off by default. On Day 10 you measure how much time the overall budget leaves for it. On a GPU or with fewer, shorter candidates the bill looks different – that is why it is a switch and not a constant.

Remember: An improvement is only one if it is worth its price. Write both into the same table: hit rate and time.

If it does not work

  • The reranker restarts, kubectl -n rag describe pod -l app=rerank shows Reason: OOMKilled: the memory limit is not enough for the warm-up. In the lab this happened with 1 GiB. Set the limit to 2 GiB, or lower --max-batch-tokens.
  • The test bench aborts with HTTP Error 422: Unprocessable Entity: more candidates than --max-client-batch-size allows (default 32). The server log states the number (batch size 50 > maximum allowed batch size 32).
  • The test bench aborts in the middle of the run with Connection timed out, and the events show Readiness probe failed: … context deadline exceeded: the busy reranker answers /health too late, and Kubernetes takes it out of the service. Increase timeoutSeconds of the readiness probe.
  • curl on /collections/wissen/points/query with "using": "text" reports an error: the full-text index is missing or was created without "scoring": true. Repeat Drill 1, Steps 2 and 3.

Save your progress? Sign up for free

Diagnosis task

A colleague installed the reranker on a new cluster. The test bench with 20 candidates runs, the one with 50 only reports after the first question:

urllib.error.HTTPError: HTTP Error 422: Unprocessable Entity

She suspects an error in eval.py, “because 422 is a client error”. You have five minutes.

Solution: The code is the same for 20 and 50 candidates – only the number of texts per request differs. The server states the reason for a rejection, so read the reranker’s log: kubectl -n rag logs deployment/rerank --tail=1 shows batch size 50 > maximum allowed batch size 32. Remedy: --max-client-batch-size=64 in the deployment (Drill 5, Step 3) – or split the candidates in the test bench into batches of at most 32. With the second solution you have to merge the scores of the batches yourself; they are comparable because every pair of question and card is scored on its own.

Challenge

Find the smallest number of candidates at which f01 gets onto the table. The vector search has the card in position 25 – so 25 candidates should be enough. Create eval-rerank-30.yaml, measure hits@3 and seconds per question and enter the row in the table from Drill 6. Is the point between 20 and 50 closer to the hit rate of 50 or to the time of 20?

Save your progress? Sign up for free

Checkpoint

# on rag1
kubectl -n rag get deployment rerank

Expected:

NAME     READY   UP-TO-DATE   AVAILABLE   AGE
rerank   1/1     1            1           9m31s

Your age will be different.

# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://rerank.rag/rerank -H "Content-Type: application/json" -d @- < rerank-probe.json

Expected: three entries, the first with "index":1 and the highest score.

# on rag1
curl -s http://127.0.0.1:6333/collections/wissen -o sammlung.json
# on rag1
jq -c '.result.payload_schema | keys' sammlung.json

Expected:

["quelle","text"]

Test yourself

  1. Why does BM25 find the VPN card and the printer card for the German question about memory shortage?
  2. How does Reciprocal Rank Fusion calculate, and why can a filler-word card end up level with the right card?
  3. How does a reranker differ from an embedding model – and why is it slower as a result?
  4. The reranker does not bring f01 to the front with 20 candidates, but it does with 50. What does im_pool say about this?
  5. Why did Kubernetes take the reranker out of the service under load although it was running?
  6. hits@3 rises from 0.77 to 0.92 with 50 candidates. Why is the reranker nevertheless off by default in the lab?

Answers:

  1. The question shares only the word “der” with both cards. In the mostly English collection, “der” is rare, and rare words get a high weight in BM25; short cards also count more.
  2. Every card gets points per list according to its position (in Qdrant ½ for position 1, ⅓ for position 2 …), the points are added up. Distances do not count. If the filler-word card is in position 1 for BM25 and the right one in position 1 for the vector search, both have ½.
  3. The embedding model reads question and card separately; the cards are embedded once in advance. The reranker reads every pair of question and card together – a model run of its own for every question and every candidate card.
  4. With 20 candidates, im_pool is 0.92 – for one question, f01, the right card is not on the table (it is in position 25 with vector search). With 50, im_pool is 1.0, and the reranker can bring it to position 2.
  5. The readiness probe waited one second for /health. In the middle of a large batch TEI answered later; after three failures the pod counted as not ready, and the service no longer sent requests to it.
  6. A question then takes almost 16 seconds instead of a quarter of a second, the gain is two of 13 questions, and hits@1 drops. Whether it pays off is decided by the latency budget (Day 10), not by the hit rate alone.

Interview note

“Would you use hybrid search and a reranker?” – Not across the board. You measure both against a gold standard. An example from the lab is convincing: with German questions on English documents, BM25 brought the wrong cards to the front via filler words, and hybrid search was worse than pure vector search. The reranker brought a card from position 25 to position 2 – but only with 50 candidates and 16 seconds per question on the CPU. The decisive metric here: is the right card among the candidates at all?

Enterprise note

In production, the reranker almost always runs on a GPU, where 50 candidates take milliseconds instead of seconds. Teams still limit the candidates and cut off long cards, because the computing time grows with the number of candidates and the text length. Hybrid search pays off above all where users search for exact identifiers – article numbers, error codes, host names – and ask in the same language as the documents. Multilingual collections get one full-text index per language, with a stop-word list and stemming. And as on Day 7: every one of these decisions goes through the test bench in CI.

Summary

You put a BM25 index over the card text and saw that it finds words, not meaning: the German test question brought the VPN card and the printer card because it shares the word “der” with them. The hybrid search with Reciprocal Rank Fusion lowered hits@3 from 0.77 to 0.69. After that you ran a reranker as a service of its own and met three real operational limits along the way: memory during warm-up, the batch limit of 32 texts and a readiness probe that takes a busy service for dead. With 20 candidates, hits@5 rose to 0.92, and f01 stayed lost – the card was not on the table. With 50 candidates it came from position 25 to position 2, and hits@3 reached 0.92 – for 15.85 seconds per question. On Day 9 you build the answer service, with the reranker as a switch.

Commands at a glance

Command What it does Parameters
curl -s -X PUT "…/collections/wissen/index?wait=true" -d @index.json create a full-text index with BM25 field_name, type: text, scoring: true
curl -s -X POST …/points/query -d @bm25-englisch.json BM25 search over the card text query.text, using: text, limit
jq -c '.result.points[] \| [.score, .payload.quelle, .payload.abschnitt]' hits as one line each -c
kubectl apply -f rerank.yaml create or change the reranker service –
kubectl -n rag rollout status deployment/rerank wait until the reranker is ready --timeout
kubectl -n rag exec -i curl -- curl … -d @- < rerank-probe.json send a file from rag1 to a service in the cluster -i, -d @-
kubectl -n rag wait --for=condition=Failed job/<name> wait for a job to fail --timeout
kubectl -n rag logs deployment/rerank --tail=1 last line in the server log --tail
kubectl top pod -n rag CPU and memory per pod -n
kubectl -n rag get jobs run time of all test bench runs –

Contents

More