Skip to content
RAG infrastructure on Kubernetes · Chapter 16 of 20 Day 15: Observing

Day 15: Observing

Goal: See the information desk in operation instead of guessing – collect metrics from Qdrant, PostgreSQL and the answer service in a small, self-operated Prometheus, measure the latency of every stage, count quality in operation and make an error visible that every status check misses · Duration: approx. 150 min · Prerequisite: Day 14

State before this chapter

First you check that all services from Day 14 are running.

# on rag1
kubectl -n rag get pods -o wide --field-selector=status.phase=Running
  • --field-selector=status.phase=Running – only running pods; finished jobs stay out.

Expected (cut off on the right):

NAME                       READY   STATUS    RESTARTS      AGE     IP           NODE
antwort-84cdcc9c7f-6xng2   1/1     Running   0             7h26m   10.42.0.76   rag1
antwort-84cdcc9c7f-crs4d   1/1     Running   0             7h26m   10.42.1.39   rag2
auswertung                 1/1     Running   0             7h25m   10.42.1.40   rag2
curl                       1/1     Running   0             7h28m   10.42.0.72   rag1
embed-66bdc7c6c9-rqqpn     1/1     Running   1 (16h ago)   33h     10.42.0.33   rag1
llm-579476976d-6rx9d       1/1     Running   0             13h     10.42.0.50   rag1
pg-1                       1/1     Running   1 (13h ago)   13h     10.42.1.3    rag2
qdrant-0                   1/1     Running   0             7h27m   10.42.1.36   rag2
qdrant-1                   1/1     Running   0             7h27m   10.42.0.75   rag1

How much the two nodes carry today is shown by the metrics-server that k3s brings along. You need this value later to measure the cost of observing.

# on rag1
kubectl top nodes

Expected:

NAME   CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)   
rag1   390m         3%       7166Mi          57%         
rag2   125m         6%       1198Mi          15%         

What you see: Nine pods 1/1 Running, among them auswertung and curl from Day 14. rag1 carries a good 7 GiB with the embedding service and the language model, rag2 a good 1 GiB. Your names, numbers and IP addresses differ.

Introduction

On Day 13 you built an error that no check reported: the sign pointed to the new cabinet, the answer service embedded with the old model – and the watch only counted 200. Every answer read “Dazu steht nichts im Handbuch.” (“Nothing about that in the handbook.”). You only found the error because you deliberately asked a question whose answer you knew.

In operation nobody asks that question. That is what metrics are for: numbers that every service continuously publishes about itself – how many questions, how many without a card, how long each stage took. A collector fetches them regularly, stores them as time series and checks rules. If something deviates, a rule fires – even if every request ends with 200.

Qdrant and the PostgreSQL operator already publish metrics. The answer service does not yet; you teach it to count. As the collector you take a single Prometheus pod with three files of configuration – no big package, no external service – and measure what it costs.

Today you learn:

  • to fetch and read the metrics of Qdrant with the read-only key,
  • to teach the answer service counters and histograms – without question text, users or addresses in the labels,
  • why a metric read through the Service shows only one pod,
  • to run Prometheus yourself with three files, find targets in the namespace and look through the fence from Day 14,
  • to measure the latency of every stage: sign, embedding, search, loading, reading the prompt and writing the answer of the language model,
  • to count quality in operation: share of “nothing in the handbook”, best score per question, discarded answers,
  • to write an alert rule that fires although every request returns 200,
  • what observing itself costs – in memory, CPU and time series.

Background

The picture for today: the library’s tally sheet

The library now has house rules. But whether it works well, nobody knows. Ask the librarian and she says: “Fine.” – just like the watch that only counts whether somebody stood at the counter.

From today on every station keeps a tally sheet:

  • The desk makes one tally mark per visitor in one of a few columns: “answer given”, “nothing in the handbook”, “answer held back”, “time exceeded”. For each station – reading the sign, translating the question, searching the cabinet, phrasing the answer – it drops a slip into a sorting tray by duration: up to 0.1 s, up to 0.5 s, up to 2.5 s and so on.
  • The stacks (Qdrant) and the archive (PostgreSQL) already keep their own lists: how many cards in the cabinet, how many requests, how many connections.
  • A caretaker walks through all rooms every 15 seconds, reads every list and writes the counts with the time into his book. He asks nobody, he just reads.
  • On his pinboard hang rules: “If more than half of the visitors leave without a card, tell somebody.”

The most important rule for the tally sheet: marks, no names. The list never says who asked or what. Otherwise the list would be a visitor log – and with every new question it would get a new column.

The terms

Term Meaning in the picture
metric a named number that a service publishes as text under /metrics one line of the tally sheet
label a key-value pair on a metric, e.g. ergebnis="keine_karte" the column the mark goes into
time series a metric with exactly one combination of labels, stored over time one column in the caretaker’s book
counter a number that only goes up (until the service restarts) tally marks
gauge a value that can go up and down the fill level of a shelf
histogram counts per boundary (le = less than or equal), plus sum and count the sorting trays by duration
scrape Prometheus fetches /metrics of a target the caretaker’s round
PromQL the query language of Prometheus, e.g. rate(), histogram_quantile() calculating in the caretaker’s book
alert rule a PromQL expression with threshold and duration (for) the rule on the pinboard
cardinality how many time series a metric creates how many columns the book has
The tally sheet: who counts, who collects, which rule fires – with the measurements from the lab

Remember: A status code says whether the desk answered – not whether the answer is any good. For that every station counts its own marks, and the caretaker does the maths. Names or questions never go into the marks.

Drill 1: What the stacks already count

Where you are: on rag1.

What you have afterwards: the metrics of Qdrant as a file, read and understood.

In this drill: Qdrant already keeps its tally sheet. You read it once by hand.

Step 1 – the folder for today.

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

Step 2 – without a key. Since Day 14 Qdrant demands a key for every request. Does that also apply to /metrics?

# on rag1
kubectl -n rag exec curl -- curl -s -o /dev/null \
  -w '%{http_code}\n' http://qdrant.rag:6333/metrics

Expected:

401

Yes. Whoever wants to observe Qdrant needs the read-only key – and, because of the fence, the label qdrant-zugang: "ja". The helper pod curl has both.

Step 3 – with the read-only key. The output is long; you write it to a file.

# on rag1
kubectl -n rag exec curl -- curl -s -K /schluessel/lesen.conf \
  http://qdrant.rag:6333/metrics > qdrant-metriken.txt
# on rag1
wc -l qdrant-metriken.txt

Expected:

274 qdrant-metriken.txt
# on rag1
grep -c '^# TYPE' qdrant-metriken.txt
  • -c – only count; ^# TYPE – lines that announce a metric.

Expected:

52

Step 4 – what a metric looks like. Every metric is preceded by two comment lines.

# on rag1
grep -B2 -m1 '^collection_points' qdrant-metriken.txt
  • -B2 – also print the two lines before,
  • -m1 – stop after the first match.

Expected:

# HELP collection_points approximate amount of points per collection
# TYPE collection_points gauge
collection_points{id="handbuch"} 4
Part Meaning
# HELP … description in words
# TYPE … gauge the kind: a value that can go up and down
collection_points the name of the metric
{id="handbuch"} a label: which collection
4 the value

Step 5 – stock and copies.

# on rag1
grep -E '^(app_info|collections_total|collection_points|collection_active_replicas_min)' qdrant-metriken.txt
  • -E – extended regular expression: four line beginnings, separated by |.

Expected:

app_info{name="qdrant",version="1.20.3"} 1
collections_total 7
collection_active_replicas_min 1
collection_points{id="handbuch"} 4
collection_points{id="wissen"} 174
collection_points{id="wissen-2000"} 0
collection_points{id="wissen-500"} 0
collection_points{id="wissen-ohne-kontext"} 0
collection_points{id="wissen-ohne-ueberlappung"} 0
collection_points{id="wissen-qwen3"} 175

What you see: Version, seven collections, 175 cards in wissen-qwen3 – the same numbers as on Day 14. The collections from Day 7 are empty on this pod; their only copy lives on the other peer. The Service qdrant sent you to one of the two pods. collection_active_replicas_min 1 means: at least one collection has only one active copy – the ones from Day 7, with replication_factor 1.

Step 6 – the requests.

# on rag1
grep -E '^rest_responses_(total|avg_duration_seconds)' qdrant-metriken.txt

Expected:

rest_responses_total{method="POST",endpoint="/collections/{collection_name}/points/count",status="200"} 14
rest_responses_total{method="POST",endpoint="/collections/{collection_name}/points",status="200"} 8
rest_responses_total{method="POST",endpoint="/collections/{collection_name}/points/query",status="200"} 123
rest_responses_total{method="POST",endpoint="/collections/{collection_name}/points/delete",status="403"} 1
rest_responses_avg_duration_seconds{method="POST",endpoint="/collections/{collection_name}/points/count",status="200"} 0.001248392822265625
rest_responses_avg_duration_seconds{method="POST",endpoint="/collections/{collection_name}/points",status="200"} 0.0014341875
rest_responses_avg_duration_seconds{method="POST",endpoint="/collections/{collection_name}/points/query",status="200"} 0.00442387646484375

What you see: 123 searches (points/query) at 4.4 milliseconds on average – and the one 403 from the challenge of Day 14, when you tried to delete with the read-only key. Look at the label endpoint: it says {collection_name}, not wissen-qwen3. Qdrant inserts the path as a pattern, not the real path. Otherwise every new collection – or every typo in a URL – would get its own time series.

Remember: A metric is one line of text: name, labels, value. Good labels have few, fixed values – a pattern instead of the real path. And /metrics is a door like any other: lock and fence apply here too.

Save your progress? Sign up for free

Drill 2: The desk learns to count

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

What you have afterwards: an answer service that publishes counters and histograms under /metrics – and the insight why you do not read them through the Service.

In this drill: from now on the desk keeps its tally sheet itself.

Step 1 – is there one already?

# on rag1
kubectl -n rag exec curl -- curl -s -o /dev/null \
  -w '%{http_code}\n' http://antwort.rag/metrics

Expected:

404

Step 2 – what should be counted. Before you write code, you fix the list. Every metric only gets labels with few, fixed values:

Metric Kind Labels what it counts
antwort_fragen_total counter ergebnis: antwort, keine_karte, verworfen, zeitueberschreitung, fehler, abgewiesen how each question ended (answer, no card, discarded, timeout, error, rejected)
antwort_stufe_sekunden histogram stufe: schild, embed, suche, rerank, llm_laden, llm_prompt, llm_antwort how long each stage took (sign, embed, search, rerank, LLM load, LLM prompt, LLM answer)
antwort_bester_score histogram – the score of the best card per question
antwort_token_total counter art: prompt, antwort tokens the language model read and wrote

What does not appear as a label: the question text, a user, an IP address, the tenant from the header X-Mandant. The first three are personal data or can be – the house rule of this project forbids them as labels. In this lab the caller sets the tenant itself (Day 14). Every freely chosen value would create a new time series: whoever sends a thousand different headers creates a thousand columns in the caretaker’s book.

The answer service does not measure the three times of the language model itself. Ollama delivers them with every answer, in nanoseconds: load_duration (loading the model), prompt_eval_duration (reading the prompt) and eval_duration (writing the answer), plus the number of tokens.

Step 3 – the answer service with a tally sheet. You take the code from Day 14.

# on rag1
cp ../14/antwort.py antwort.py
# on rag1
nano antwort.py
~/kurs/15/antwort.py changes in green
"""Antwortdienst: Frage einbetten, Karten suchen, mit Quellenangabe antworten, messen."""

import json
import os
import re
import signal
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
LLM = os.environ.get("LLM_URL", "http://llm.rag:11434")
RERANK = os.environ.get("RERANK_URL", "")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
LLM_MODELL = os.environ.get("LLM_MODELL", "qwen3:1.7b")
KARTEN = int(os.environ.get("KARTEN", "3"))
KANDIDATEN = int(os.environ.get("KANDIDATEN", "20"))
MINDEST = float(os.environ.get("MINDEST_SCORE", "0"))
LLM_TIMEOUT = float(os.environ.get("LLM_TIMEOUT", "120"))
MAX_TOKEN = int(os.environ.get("MAX_TOKEN", "300"))
PLAETZE = int(os.environ.get("PLAETZE", "0"))
SCHLUESSEL = os.environ.get("QDRANT_API_KEY", "")
ERLAUBT = os.environ.get("ERLAUBTE_DOMAINS", "firma.example,kubernetes.io").split(",")
ADRESSE = re.compile(r"https?://([\w.-]+)|[\w.+-]+@([\w-]+(?:\.[\w-]+)+)")
KEINE = "Dazu steht nichts im Handbuch."
THEKE = threading.BoundedSemaphore(PLAETZE) if PLAETZE else None
GRENZEN = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60)
SCORE_GRENZEN = (0.1, 0.2, 0.3, 0.4, 0.42, 0.5, 0.6, 0.7, 0.8)

ANWEISUNG = (
    "Du bist die IT-Auskunft einer Firma. Beantworte die Frage des Nutzers auf "
    "Deutsch, kurz, und nur mit dem Inhalt der Karten unten. Nenne hinter jeder "
    "Aussage die Nummer der Karte in eckigen Klammern, zum Beispiel [1]. Steht die "
    f"Antwort auf keiner Karte, antworte genau: {KEINE}\n\nKarten:\n"
)


class Messwerte:
    """Zähler und Histogramme im Textformat von Prometheus – ohne Fragetext."""

    def __init__(self):
        self.sperre = threading.Lock()
        self.fragen = {}
        self.token = {"prompt": 0, "antwort": 0}
        self.stufen = {}
        self.score = [0] * (len(SCORE_GRENZEN) + 1) + [0.0]

    def zaehlen(self, ergebnis):
        with self.sperre:
            self.fragen[ergebnis] = self.fragen.get(ergebnis, 0) + 1

    def stufe(self, name, sekunden):
        with self.sperre:
            eimer = self.stufen.setdefault(name, [0] * (len(GRENZEN) + 1) + [0.0])
            eimer[sum(sekunden > g for g in GRENZEN)] += 1
            eimer[-1] += sekunden

    def bester(self, score):
        with self.sperre:
            self.score[sum(score > g for g in SCORE_GRENZEN)] += 1
            self.score[-1] += score

    def llm(self, daten):
        """Zeiten und Token aus der Antwort von Ollama (Nanosekunden)."""
        self.stufe("llm_laden", daten.get("load_duration", 0) / 1e9)
        self.stufe("llm_prompt", daten.get("prompt_eval_duration", 0) / 1e9)
        self.stufe("llm_antwort", daten.get("eval_duration", 0) / 1e9)
        with self.sperre:
            self.token["prompt"] += daten.get("prompt_eval_count", 0)
            self.token["antwort"] += daten.get("eval_count", 0)

    def histogramm(self, name, label, grenzen, eimer):
        zeilen, summe = [], 0
        for grenze, anzahl in zip(list(grenzen) + ["+Inf"], eimer[:-1]):
            summe += anzahl
            zeilen.append(f'{name}_bucket{{{label}le="{grenze}"}} {summe}')
        klammer = f"{{{label.rstrip(',')}}}" if label else ""
        zeilen.append(f"{name}_sum{klammer} {eimer[-1]:.6f}")
        zeilen.append(f"{name}_count{klammer} {summe}")
        return zeilen

    def text(self):
        with self.sperre:
            zeilen = ["# TYPE antwort_fragen_total counter"]
            for ergebnis, anzahl in sorted(self.fragen.items()):
                zeilen.append(f'antwort_fragen_total{{ergebnis="{ergebnis}"}} {anzahl}')
            zeilen.append("# TYPE antwort_token_total counter")
            for art, anzahl in self.token.items():
                zeilen.append(f'antwort_token_total{{art="{art}"}} {anzahl}')
            zeilen.append("# TYPE antwort_stufe_sekunden histogram")
            for name, eimer in sorted(self.stufen.items()):
                zeilen += self.histogramm(
                    "antwort_stufe_sekunden", f'stufe="{name}",', GRENZEN, eimer
                )
            zeilen.append("# TYPE antwort_bester_score histogram")
            zeilen += self.histogramm(
                "antwort_bester_score", "", SCORE_GRENZEN, self.score
            )
        return "\n".join(zeilen) + "\n"


MESS = Messwerte()


def kopf(url):
    """Kopfzeilen; den Qdrant-Schlüssel bekommt nur Qdrant."""
    zeilen = {"Content-Type": "application/json"}
    if SCHLUESSEL and url.startswith(QDRANT):
        zeilen["api-key"] = SCHLUESSEL
    return zeilen


def anfrage(url, daten, timeout=30):
    req = urllib.request.Request(
        url, data=json.dumps(daten).encode(), headers=kopf(url)
    )
    return urllib.request.urlopen(req, timeout=timeout)


def lesen(url):
    """GET an Qdrant, Antwort als JSON."""
    with urllib.request.urlopen(
        urllib.request.Request(url, headers=kopf(url)), timeout=5
    ) as a:
        return json.load(a)


def fremde_adresse(text):
    """Erste Web- oder Mail-Adresse, deren Domain nicht auf der Liste steht."""
    for treffer in ADRESSE.finditer(text):
        domain = (treffer.group(1) or treffer.group(2)).lower().rstrip(".")
        if not any(domain == d or domain.endswith("." + d) for d in ERLAUBT):
            return domain
    return None


def schild():
    """Hinter dem Schild nachsehen: welche Collection, welches Modell, welche Schwelle."""
    name = SAMMLUNG
    for eintrag in lesen(f"{QDRANT}/aliases")["result"]["aliases"]:
        if eintrag["alias_name"] == SAMMLUNG:
            name = eintrag["collection_name"]
    config = lesen(f"{QDRANT}/collections/{name}")["result"]["config"]
    angaben = config.get("metadata") or {}
    return name, angaben.get("modell", MODELL), angaben.get("mindest_score", MINDEST)


def suchen(frage, mandant):
    """Frage einbetten, nur Karten des Mandanten und für alle holen, ggf. neu ordnen."""
    t = time.time()
    name, modell, mindest = schild()
    MESS.stufe("schild", time.time() - t)
    t = time.time()
    with anfrage(f"{EMBED}/api/embed", {"model": modell, "input": [frage]}) as a:
        vektor = json.load(a)["embeddings"][0]
    MESS.stufe("embed", time.time() - t)
    koerper = {
        "query": vektor,
        "limit": KANDIDATEN if RERANK else KARTEN,
        "with_payload": True,
        "filter": {"must": [{"key": "mandant", "match": {"any": [mandant, "alle"]}}]},
    }
    t = time.time()
    with anfrage(f"{QDRANT}/collections/{name}/points/query", koerper) as a:
        punkte = json.load(a)["result"]["points"]
    MESS.stufe("suche", time.time() - t)
    if RERANK and punkte:
        t = time.time()
        texte = [p["payload"]["text"] for p in punkte]
        with anfrage(f"{RERANK}/rerank", {"query": frage, "texts": texte}, 120) as a:
            punkte = [punkte[u["index"]] for u in json.load(a)]
        MESS.stufe("rerank", time.time() - t)
    return punkte[:KARTEN], name, mindest


def nachrichten(frage, punkte):
    """Anweisung und nummerierte Karten als System-, die Frage als Nutzernachricht."""
    karten = [
        f"[{nr}] {p['payload']['abschnitt']}\n{p['payload']['text']}\n"
        for nr, p in enumerate(punkte, start=1)
    ]
    return [
        {"role": "system", "content": ANWEISUNG + "\n".join(karten)},
        {"role": "user", "content": frage},
    ]


class Auskunft(BaseHTTPRequestHandler):
    def senden(self, status, daten):
        rumpf = json.dumps(daten, ensure_ascii=False).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(rumpf)))
        self.end_headers()
        self.wfile.write(rumpf)

    def text(self, rumpf):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain; version=0.0.4")
        self.send_header("Content-Length", str(len(rumpf)))
        self.end_headers()
        self.wfile.write(rumpf)

    def zeile(self, daten):
        self.wfile.write(json.dumps(daten, ensure_ascii=False).encode() + b"\n")
        self.wfile.flush()

    def do_GET(self):
        if self.path == "/health":
            self.senden(200, {"status": "ok"})
        elif self.path == "/metrics":
            self.text(MESS.text().encode())
        else:
            self.senden(404, {"fehler": "unbekannter Pfad"})

    def do_POST(self):
        if self.path != "/frage":
            self.senden(404, {"fehler": "unbekannter Pfad"})
            return
        laenge = int(self.headers.get("Content-Length", 0))
        eingabe = json.loads(self.rfile.read(laenge) or b"{}")
        frage = str(eingabe.get("frage", "")).strip()
        if not frage:
            self.senden(400, {"fehler": "frage fehlt"})
            return
        if THEKE and not THEKE.acquire(blocking=False):
            print(f"abgewiesen, {PLAETZE} Plätze belegt  {frage}", flush=True)
            MESS.zaehlen("abgewiesen")
            self.send_response(503)
            self.send_header("Retry-After", "30")
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(b'{"fehler": "zu viele Fragen gleichzeitig"}')
            return
        mandant = self.headers.get("X-Mandant", "alle")
        try:
            self.beantworten(frage, eingabe, mandant)
        except Exception:
            MESS.zaehlen("fehler")
            raise
        finally:
            if THEKE:
                THEKE.release()

    def beantworten(self, frage, eingabe, mandant):
        """Suchen, Schwelle prüfen, dann ganz oder als Strom antworten."""
        start = time.time()
        punkte, sammlung, mindest = suchen(frage, mandant)
        zeiten = {"suche": round(time.time() - start, 2)}
        bester = punkte[0]["score"] if punkte else 0.0
        MESS.bester(bester)
        if bester < mindest:
            print(f"keine Karte  bester {bester:.3f}  {sammlung}  {frage}", flush=True)
            MESS.zaehlen("keine_karte")
            self.senden(
                200,
                {
                    "antwort": KEINE,
                    "quellen": [],
                    "sammlung": sammlung,
                    "sekunden": zeiten,
                },
            )
            return
        quellen = [
            {
                "nr": nr,
                "quelle": p["payload"]["quelle"],
                "abschnitt": p["payload"]["abschnitt"],
                "score": round(p["score"], 3),
                "sammlung": sammlung,
            }
            for nr, p in enumerate(punkte, start=1)
        ]
        if eingabe.get("stream"):
            self.strom(frage, punkte, quellen, start, zeiten)
        else:
            self.ganz(frage, punkte, quellen, start, zeiten)

    def ganz(self, frage, punkte, quellen, start, zeiten):
        """Auf die ganze Antwort warten und sie in einem Stück senden."""
        koerper = {
            "model": LLM_MODELL,
            "messages": nachrichten(frage, punkte),
            "stream": False,
            "think": False,
            "options": {"num_predict": MAX_TOKEN, "temperature": 0},
        }
        try:
            with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
                daten = json.load(a)
            antwort = daten["message"]["content"].strip()
            MESS.llm(daten)
        except TimeoutError:
            print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s  {frage}", flush=True)
            MESS.zaehlen("zeitueberschreitung")
            self.senden(504, {"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
            return
        except urllib.error.URLError as fehler:
            print(
                f"Sprachmodell nicht erreichbar: {fehler.reason}  {frage}", flush=True
            )
            MESS.zaehlen("fehler")
            self.senden(502, {"fehler": "Sprachmodell nicht erreichbar"})
            return
        zeiten["gesamt"] = round(time.time() - start, 2)
        fremd = fremde_adresse(antwort)
        if fremd:
            print(f"verworfen  fremde Adresse {fremd}  {frage}", flush=True)
            MESS.zaehlen("verworfen")
            self.senden(200, {"antwort": KEINE, "quellen": [], "verworfen": fremd})
            return
        print(f"antwort  {zeiten}  {frage}", flush=True)
        MESS.zaehlen("antwort")
        self.senden(200, {"antwort": antwort, "quellen": quellen, "sekunden": zeiten})

    def strom(self, frage, punkte, quellen, start, zeiten):
        """Jedes Stück der Antwort sofort weiterreichen, eine JSON-Zeile je Stück."""
        koerper = {
            "model": LLM_MODELL,
            "messages": nachrichten(frage, punkte),
            "stream": True,
            "think": False,
            "options": {"num_predict": MAX_TOKEN, "temperature": 0},
        }
        self.send_response(200)
        self.send_header("Content-Type", "application/x-ndjson")
        self.end_headers()
        self.zeile({"quellen": quellen})
        bisher = ""
        try:
            with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
                for roh in a:
                    daten = json.loads(roh)
                    if daten.get("done"):
                        MESS.llm(daten)
                    stueck = daten["message"]["content"]
                    if stueck and "erstes_wort" not in zeiten:
                        zeiten["erstes_wort"] = round(time.time() - start, 2)
                    bisher += stueck
                    fremd = fremde_adresse(bisher)
                    if fremd:
                        print(f"verworfen  fremde Adresse {fremd}  {frage}", flush=True)
                        MESS.zaehlen("verworfen")
                        self.zeile({"fehler": "Antwort verworfen"})
                        return
                    if stueck:
                        self.zeile({"text": stueck})
        except TimeoutError:
            print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s  {frage}", flush=True)
            MESS.zaehlen("zeitueberschreitung")
            self.zeile({"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
            return
        except urllib.error.URLError as fehler:
            print(
                f"Sprachmodell nicht erreichbar: {fehler.reason}  {frage}", flush=True
            )
            MESS.zaehlen("fehler")
            self.zeile({"fehler": "Sprachmodell nicht erreichbar"})
            return
        zeiten["gesamt"] = round(time.time() - start, 2)
        print(f"strom  {zeiten}  {frage}", flush=True)
        MESS.zaehlen("antwort")
        self.zeile({"fertig": True, "sekunden": zeiten})

    def log_message(self, format, *args):
        pass


def beenden(signum, frame):
    """Auf SIGTERM von Kubernetes sofort und sauber enden."""
    print("SIGTERM erhalten, Antwortdienst endet", flush=True)
    raise SystemExit(0)


if __name__ == "__main__":
    signal.signal(signal.SIGTERM, beenden)
    print(
        f"Antwortdienst auf Port 8080, Sammlung {SAMMLUNG}, LLM {LLM_MODELL}",
        flush=True,
    )
    ThreadingHTTPServer(("", 8080), Auskunft).serve_forever()
Lines Content Meaning
31 GRENZEN the sorting trays for durations: from 5 milliseconds to 60 seconds
32 SCORE_GRENZEN the trays for the best score; 0.42 is the threshold from Day 13
42–103 class Messwerte the tally sheet: counters, histograms, a lock for simultaneous questions and the output in text format
59 sum(sekunden > g …) the tray: the number of boundaries that are smaller than the value
67–74 llm() the three times and the tokens from Ollama’s answer
76–84 histogramm() writes the trays cumulatively (le = up to and including), plus _sum and _count
154–176 MESS.stufe(…) time for sign, embedding, search and – if switched on – reranking
201–207, 215–216 text(), /metrics the new path delivers the tally sheet as text/plain
232, 242–244 abgewiesen, fehler a question that got no seat or failed with an exception
255, 258 bester, keine_karte the best score of every question; a mark if it is below the threshold
295–318 whole answer times of the language model and one mark each for zeitueberschreitung, fehler, verworfen, antwort
338–367 stream the same for the stream; Ollama sends the times in the last chunk (done)

The code adds no library – the text format is simple enough to write by hand. In larger services a Prometheus client library takes over.

Step 4 – swap the code and roll out again.

# on rag1
kubectl -n rag delete configmap antwort-code

Expected:

configmap "antwort-code" deleted from rag namespace
# on rag1
kubectl -n rag create configmap antwort-code --from-file=antwort.py

Expected:

configmap/antwort-code created
# on rag1
kubectl -n rag rollout restart deployment/antwort

Expected:

deployment.apps/antwort restarted
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120s

Expected (last line, after 23 seconds in the lab):

deployment "antwort" successfully rolled out

Step 5 – two questions. One with an answer, one without. The question files come from Day 14.

# on rag1
cp ../14/backup.json .
# on rag1
cp ../14/gehalt.json .
# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < backup.json > backup.json.antwort
# on rag1
jq '{antwort, sekunden}' backup.json.antwort

Expected:

{
  "antwort": "Das Backup wiederherstellen kann mit `restic restore latest --include /pfad/zur/datei` erfolgen. [1]",
  "sekunden": {
    "suche": 0.68,
    "gesamt": 5.4
  }
}
# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- \
  < gehalt.json > gehalt.json.antwort
# on rag1
jq '{antwort, sekunden}' gehalt.json.antwort

Expected:

{
  "antwort": "Dazu steht nichts im Handbuch.",
  "sekunden": {
    "suche": 0.75
  }
}

Before you read the tally sheet – your prediction: You query /metrics twice through the Service antwort. Do you see two questions both times?

Step 6 – read the tally sheet. grep -v _bucket hides the many tray lines.

# on rag1
kubectl -n rag exec curl -- curl -s http://antwort.rag/metrics > antwort-metriken-1.txt
# on rag1
grep -v _bucket antwort-metriken-1.txt
  • -v – show lines that do not match.

Expected:

# TYPE antwort_fragen_total counter
# TYPE antwort_token_total counter
antwort_token_total{art="prompt"} 0
antwort_token_total{art="antwort"} 0
# TYPE antwort_stufe_sekunden histogram
# TYPE antwort_bester_score histogram
antwort_bester_score_sum 0.000000
antwort_bester_score_count 0
# on rag1
kubectl -n rag exec curl -- curl -s http://antwort.rag/metrics > antwort-metriken-2.txt
# on rag1
grep -v _bucket antwort-metriken-2.txt

Expected:

# TYPE antwort_fragen_total counter
antwort_fragen_total{ergebnis="antwort"} 1
antwort_fragen_total{ergebnis="keine_karte"} 1
# TYPE antwort_token_total counter
antwort_token_total{art="prompt"} 285
antwort_token_total{art="antwort"} 29
# TYPE antwort_stufe_sekunden histogram
antwort_stufe_sekunden_sum{stufe="embed"} 1.294030
antwort_stufe_sekunden_count{stufe="embed"} 2
antwort_stufe_sekunden_sum{stufe="llm_antwort"} 3.845703
antwort_stufe_sekunden_count{stufe="llm_antwort"} 1
antwort_stufe_sekunden_sum{stufe="llm_laden"} 0.013299
antwort_stufe_sekunden_count{stufe="llm_laden"} 1
antwort_stufe_sekunden_sum{stufe="llm_prompt"} 0.486682
antwort_stufe_sekunden_count{stufe="llm_prompt"} 1
antwort_stufe_sekunden_sum{stufe="schild"} 0.100436
antwort_stufe_sekunden_count{stufe="schild"} 2
antwort_stufe_sekunden_sum{stufe="suche"} 0.034913
antwort_stufe_sekunden_count{stufe="suche"} 2
# TYPE antwort_bester_score histogram
antwort_bester_score_sum 0.804179
antwort_bester_score_count 2

What you see: The first query landed on the pod that had not received a question yet – all zero. The second on the pod that answered both questions: one answer, one without a card, two embeddings, one call of the language model. The distribution already shows: 3.8 seconds writing the answer, 0.49 seconds reading the prompt, on average 0.65 seconds embedding, 0.02 seconds search.

Resolving your prediction: No. Every pod keeps its own tally sheet, and the Service sends each query to some pod. Whoever reads metrics through the Service sees chance. The caretaker has to visit every pod individually – Prometheus does that in Drill 3.

Step 7 – a histogram.

# on rag1
grep 'stufe="embed"' antwort-metriken-2.txt

Expected:

antwort_stufe_sekunden_bucket{stufe="embed",le="0.005"} 0
antwort_stufe_sekunden_bucket{stufe="embed",le="0.01"} 0
antwort_stufe_sekunden_bucket{stufe="embed",le="0.025"} 0
antwort_stufe_sekunden_bucket{stufe="embed",le="0.05"} 0
antwort_stufe_sekunden_bucket{stufe="embed",le="0.1"} 0
antwort_stufe_sekunden_bucket{stufe="embed",le="0.25"} 0
antwort_stufe_sekunden_bucket{stufe="embed",le="0.5"} 0
antwort_stufe_sekunden_bucket{stufe="embed",le="1"} 2
antwort_stufe_sekunden_bucket{stufe="embed",le="2.5"} 2
antwort_stufe_sekunden_bucket{stufe="embed",le="5"} 2
antwort_stufe_sekunden_bucket{stufe="embed",le="10"} 2
antwort_stufe_sekunden_bucket{stufe="embed",le="30"} 2
antwort_stufe_sekunden_bucket{stufe="embed",le="60"} 2
antwort_stufe_sekunden_bucket{stufe="embed",le="+Inf"} 2
antwort_stufe_sekunden_sum{stufe="embed"} 1.294030
antwort_stufe_sekunden_count{stufe="embed"} 2

What you see: Up to 0.5 seconds no embedding, up to 1 second both. The numbers are cumulative: every tray contains all smaller ones. From these trays Prometheus later calculates percentiles – without storing every single duration.

Remember: The desk counts in a few fixed columns and drops durations into trays. Every pod has its own list; through the Service you only see one of them by chance.

Save your progress? Sign up for free

Drill 3: The caretaker

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

What you have afterwards: a Prometheus pod on rag2 that reads every pod of the answer service, Qdrant and PostgreSQL every 15 seconds – and a rule in the fence from Day 14 that allows exactly that.

In this drill: you hire the caretaker. He needs three things: the right to see the pods in the namespace, a list of where to read, and a badge for the doors.

Step 1 – the right to see pods. Prometheus asks the Kubernetes API which pods exist – that way it also finds new pods after a rollout. It gets its own ServiceAccount and a Role that only applies in the namespace rag and may only read pods.

# on rag1
nano prometheus-rechte.yaml
~/kurs/15/prometheus-rechte.yaml new file
apiVersion: v1
kind: ServiceAccount
metadata:
  name: prometheus
  namespace: rag
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: prometheus
  namespace: rag
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: prometheus
  namespace: rag
subjects:
  - kind: ServiceAccount
    name: prometheus
    namespace: rag
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: prometheus
Lines Content Meaning
1–5 ServiceAccount the identity of the Prometheus pod
7–15 Role only pods, only get, list, watch, only in the namespace rag
17–29 RoleBinding connects both

A ClusterRole would be more convenient – then Prometheus would see every pod in the cluster. It only needs this namespace.

# on rag1
kubectl apply -f prometheus-rechte.yaml

Expected:

serviceaccount/prometheus created
role.rbac.authorization.k8s.io/prometheus created
rolebinding.rbac.authorization.k8s.io/prometheus created

Step 2 – the list of rounds.

# on rag1
nano prometheus.yml
~/kurs/15/prometheus.yml new file
global:
  scrape_interval: 15s
  evaluation_interval: 15s
rule_files:
  - /etc/prometheus/regeln.yml
scrape_configs:
  - job_name: antwort
    kubernetes_sd_configs:
      - role: pod
        namespaces:
          names: [rag]
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_label_app, __meta_kubernetes_pod_container_port_number]
        regex: antwort;8080
        action: keep
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: instance
  - job_name: qdrant
    authorization:
      credentials_file: /schluessel/lesen
    kubernetes_sd_configs:
      - role: pod
        namespaces:
          names: [rag]
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name, __meta_kubernetes_pod_container_port_number]
        regex: qdrant;6333
        action: keep
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: instance
  - job_name: pg
    kubernetes_sd_configs:
      - role: pod
        namespaces:
          names: [rag]
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_label_cnpg_io_cluster, __meta_kubernetes_pod_container_port_number]
        regex: pg;9187
        action: keep
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: instance
Lines Content Meaning
2 scrape_interval: 15s read every 15 seconds
3 evaluation_interval: 15s check the rules every 15 seconds
4–5 rule_files the rules on the pinboard (step 3)
8–11 kubernetes_sd_configs find targets through the Kubernetes API: every pod with every container port in the namespace rag
13–15 keep only keep pods with label app=antwort and port 8080
16–17 instance the target is named like the pod – not like its IP address
19–20 authorization for Qdrant send the read-only key as Authorization: Bearer …; the file comes from the Secret
26–28 keep the Qdrant pods, only port 6333 (not gRPC 6334, not peers 6335)
37–39 keep the pods of the cluster pg, only port 9187 – there CloudNativePG publishes its metrics

Without the selection by port every pod would get several targets – Qdrant for example three, one for each of its ports.

Step 3 – the rules on the pinboard. Three rules; what they mean you measure in Drills 5 and 6.

# on rag1
nano regeln.yml
~/kurs/15/regeln.yml new file
groups:
  - name: auskunft
    rules:
      - alert: AuskunftFindetNichts
        expr: sum(rate(antwort_fragen_total{ergebnis="keine_karte"}[2m])) / sum(rate(antwort_fragen_total[2m])) > 0.5
        for: 1m
        annotations:
          zusammenfassung: Mehr als die Hälfte der Fragen endet ohne Karte.
      - alert: AuskunftVerwirft
        expr: sum(increase(antwort_fragen_total{ergebnis="verworfen"}[10m])) > 0
        annotations:
          zusammenfassung: Die Ausgaberegel hat Antworten verworfen.
      - alert: ZielNichtErreichbar
        expr: up == 0
        for: 1m
        annotations:
          zusammenfassung: Prometheus erreicht ein Ziel nicht.
Lines Content Meaning
4–8 AuskunftFindetNichts share of questions without a card in the last 2 minutes above 50 %, and that for 1 minute
9–12 AuskunftVerwirft at least one answer discarded in the last 10 minutes (output rule from Day 14)
13–17 ZielNichtErreichbar a target has not answered for 1 minute (up is 0)
# on rag1
kubectl -n rag create configmap prometheus \
  --from-file=prometheus.yml --from-file=regeln.yml

Expected:

configmap/prometheus created

Step 4 – the Prometheus pod.

# on rag1
nano prometheus.yaml
~/kurs/15/prometheus.yaml new file
apiVersion: apps/v1
kind: Deployment
metadata:
  name: prometheus
  namespace: rag
spec:
  replicas: 1
  selector:
    matchLabels:
      app: prometheus
  template:
    metadata:
      labels:
        app: prometheus
        qdrant-zugang: "ja"
    spec:
      serviceAccountName: prometheus
      nodeSelector:
        kubernetes.io/hostname: rag2
      containers:
        - name: prometheus
          image: prom/prometheus:v3.16.0
          args:
            - --config.file=/etc/prometheus/prometheus.yml
            - --storage.tsdb.path=/prometheus
            - --storage.tsdb.retention.time=2d
            - --web.enable-lifecycle
          ports:
            - containerPort: 9090
          resources:
            requests:
              cpu: 50m
              memory: 128Mi
            limits:
              memory: 512Mi
          volumeMounts:
            - name: config
              mountPath: /etc/prometheus
            - name: schluessel
              mountPath: /schluessel
              readOnly: true
            - name: daten
              mountPath: /prometheus
      volumes:
        - name: config
          configMap:
            name: prometheus
        - name: schluessel
          secret:
            secretName: qdrant-schluessel
            items:
              - key: lesen
                path: lesen
        - name: daten
          emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  name: prometheus
  namespace: rag
spec:
  selector:
    app: prometheus
  ports:
    - port: 9090
Lines Content Meaning
15 qdrant-zugang: "ja" the badge for the fence around Qdrant
17 serviceAccountName the rights from step 1
19 rag2 not on rag1, where the embedding service and the language model compute
22 prom/prometheus:v3.16.0 the official image, for amd64 and arm64
26 retention.time=2d keep data for two days
27 web.enable-lifecycle reload the configuration with POST /-/reload (challenge)
31–35 resources 128 MiB requested, at most 512 MiB
36–55 volumeMounts, volumes configuration from the ConfigMap, read-only key as file /schluessel/lesen, data in emptyDir

emptyDir means: if the pod restarts, the collected time series are gone. That is enough for a lab; in operation a PersistentVolume belongs here.

# on rag1
kubectl apply -f prometheus.yaml

Expected:

deployment.apps/prometheus created
service/prometheus created
# on rag1
kubectl -n rag rollout status deployment/prometheus --timeout=180s

Expected (last line):

deployment "prometheus" successfully rolled out

In the lab the image was already on rag2 (from the author’s exploration); for you the first start takes a little longer.

Before you look at the targets – your prediction: Prometheus looks for two answer service pods, two Qdrant pods and one PostgreSQL pod. Does it reach all five?

Step 5 – the targets. A good 20 seconds after the start you ask the Prometheus API how the targets are doing.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/targets > ziele.json
# on rag1
jq -c '.data.activeTargets[] | {job: .labels.job, instance: .labels.instance, health, lastError}' ziele.json
  • .data.activeTargets[] – every target found,
  • {job: …, instance: …, health, lastError} – only these four fields, one line per target (-c).

Expected:

{"job":"antwort","instance":"antwort-74f68864c8-c2dtl","health":"up","lastError":""}
{"job":"antwort","instance":"antwort-74f68864c8-crhs6","health":"up","lastError":""}
{"job":"pg","instance":"pg-1","health":"down","lastError":"Get \"http://10.42.1.3:9187/metrics\": dial tcp 10.42.1.3:9187: connect: connection refused"}
{"job":"qdrant","instance":"qdrant-0","health":"up","lastError":""}
{"job":"qdrant","instance":"qdrant-1","health":"up","lastError":""}

What you see: Both answer service pods and both Qdrant pods up – key and label work. PostgreSQL down with connection refused: that is the signature of the fence from Day 14. pg-zaun allows port 5432 and the operator on 8000 – port 9187 it allows to nobody.

The same information exists as a metric: for every target Prometheus writes up – 1 or 0. You put the query into a file; curl sends it with --data-urlencode query@- from standard input.

# on rag1
nano up.promql
~/kurs/15/up.promql new file
up
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < up.promql > up.json
  • /api/v1/query – one query at the current point in time,
  • --data-urlencode query@- – read the parameter query from standard input and encode it for the URL.
# on rag1
jq -c '.data.result[] | {job: .metric.job, instance: .metric.instance, wert: .value[1]}' up.json

Expected:

{"job":"qdrant","instance":"qdrant-0","wert":"1"}
{"job":"antwort","instance":"antwort-74f68864c8-c2dtl","wert":"1"}
{"job":"qdrant","instance":"qdrant-1","wert":"1"}
{"job":"antwort","instance":"antwort-74f68864c8-crhs6","wert":"1"}
{"job":"pg","instance":"pg-1","wert":"0"}

Step 6 – a door in the fence. You add a fourth rule to pg-zaun: pods with app: prometheus may use port 9187. Only this port – Prometheus still cannot reach the database on 5432.

# on rag1
cp ../14/pg-zaun.yaml pg-zaun.yaml
# on rag1
nano pg-zaun.yaml
~/kurs/15/pg-zaun.yaml changes in green
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: pg-zaun
  namespace: rag
spec:
  podSelector:
    matchLabels:
      cnpg.io/cluster: pg
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              pg-zugang: "ja"
      ports:
        - port: 5432
    - from:
        - podSelector:
            matchLabels:
              cnpg.io/cluster: pg
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: cnpg-system
      ports:
        - port: 8000
        - port: 5432
    - from:
        - podSelector:
            matchLabels:
              app: prometheus
      ports:
        - port: 9187
# on rag1
kubectl apply -f pg-zaun.yaml

Expected:

networkpolicy.networking.k8s.io/pg-zaun configured

Step 7 – after the next round. Prometheus only tries again at the next scrape. In the lab the target was still down 10 seconds after the apply and up after 20 seconds – repeat the command until up appears.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/targets > ziele.json
# on rag1
jq -c '.data.activeTargets[] | {job: .labels.job, instance: .labels.instance, health, lastError}' ziele.json

Expected:

{"job":"antwort","instance":"antwort-74f68864c8-c2dtl","health":"up","lastError":""}
{"job":"antwort","instance":"antwort-74f68864c8-crhs6","health":"up","lastError":""}
{"job":"pg","instance":"pg-1","health":"up","lastError":""}
{"job":"qdrant","instance":"qdrant-0","health":"up","lastError":""}
{"job":"qdrant","instance":"qdrant-1","health":"up","lastError":""}

Step 8 – what the archive counts. Short queries you write directly into the command.

# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode 'query=cnpg_collector_up' > pg-up.json
# on rag1
jq -c '.data.result[] | {instance: .metric.instance, wert: .value[1]}' pg-up.json

Expected:

{"instance":"pg-1","wert":"1"}
# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode 'query=cnpg_pg_database_size_bytes' > pg-groesse.json
# on rag1
jq -c '.data.result[] | {datname: .metric.datname, wert: .value[1]}' pg-groesse.json

Expected:

{"datname":"postgres","wert":"8099519"}
{"datname":"rag","wert":"8451775"}
{"datname":"template1","wert":"8181439"}
# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode 'query=cnpg_backends_total' > pg-verbindungen.json
# on rag1
jq -c '.data.result[] | {datname: .metric.datname, usename: .metric.usename, state: .metric.state, wert: .value[1]}' pg-verbindungen.json

Expected:

{"datname":"rag","usename":"cnpg_metrics_exporter","state":"active","wert":"1"}

What you see: The exporter is running, the database rag is a good 8 MB in size, and the only open connection is that of the exporter itself – auswertung from Day 14 only logs in for the duration of a psql call. Note the label usename: it contains the name of the database role. That is harmless here (leser, rag). If every employee got their own role, personal names would end up in the metrics – then this label has to go or be aggregated.

Resolving your prediction: Four out of five. The fence also kept the caretaker away from the archive until he got his own door – only for port 9187.

Remember: The caretaker finds the pods himself and visits each one individually. He needs the same badges and keys as anybody else – observing is no reason to open fence and lock, only a door for exactly the one port.

Save your progress? Sign up for free

Drill 4: Where the time goes

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

What you have afterwards: mean duration and 95th percentile of every stage under steady load – measured by Prometheus, not by hand.

In this drill: a visitor asks eight questions in turn, again and again. After a few minutes you read in the caretaker’s book how long each station takes.

Step 1 – the visitor’s questions. Eight questions from the load questions of Day 10 and the cards of the practice company, among them one about which there is nothing in the handbook (the laptop).

# on rag1
nano fragen.txt
~/kurs/15/fragen.txt new file
Wie komme ich von zu Hause ins Firmennetz?
Der Drucker druckt nicht mehr. Was soll ich tun?
Wie beantrage ich Urlaub?
Wie groß darf ein Secret höchstens sein?
Was ist eine Toleration?
Wie bekomme ich einen neuen Laptop?
Wozu dient eine Startup-Probe?
Wie stelle ich ein Backup wieder her?
# on rag1
kubectl -n rag create configmap besucher-fragen --from-file=fragen.txt

Expected:

configmap/besucher-fragen created

Step 2 – the visitor. A pod with curl that asks the questions in order, waits 3 seconds and starts over. The loop runs in the pod; you do not type it.

# on rag1
nano besucher.yaml
~/kurs/15/besucher.yaml new file
apiVersion: v1
kind: Pod
metadata:
  name: besucher
  namespace: rag
spec:
  nodeSelector:
    kubernetes.io/hostname: rag2
  terminationGracePeriodSeconds: 0
  containers:
    - name: besucher
      image: curlimages/curl:8.17.0
      command: ["sh", "-c"]
      args:
        - |
          while true; do
            while read -r frage; do
              s=$(curl -s -o /dev/null -m 90 -w '%{http_code}' \
                -H 'Content-Type: application/json' \
                -d "{\"frage\": \"$frage\"}" http://antwort.rag/frage)
              echo "$(date +%T) $s"
              sleep 3
            done < /fragen/fragen.txt
          done
      resources:
        requests:
          cpu: 10m
          memory: 16Mi
        limits:
          memory: 32Mi
      volumeMounts:
        - name: fragen
          mountPath: /fragen
  volumes:
    - name: fragen
      configMap:
        name: besucher-fragen
Lines Content Meaning
7–8 rag2 not on the node of the language model
16–24 loop send every line of the file as a question, wait at most 90 seconds, pause 3 seconds
21 echo "$(date +%T) $s" only time and status go into the log – not the question
31–37 volume the questions from the ConfigMap
# on rag1
kubectl apply -f besucher.yaml

Expected:

pod/besucher created
# on rag1
kubectl -n rag wait --for=condition=Ready pod/besucher --timeout=120s

Expected:

pod/besucher condition met

Let the visitor ask for a good four minutes. In the lab it ran from 06:17:21; the queries below are from 06:21:38.

# on rag1
kubectl -n rag logs besucher --tail=8

Expected (your times differ):

06:20:05 200
06:20:23 200
06:20:27 200
06:20:42 200
06:20:54 200
06:21:07 200
06:21:19 200
06:21:33 200

Step 3 – the mean duration per stage. Sum and count of a histogram give a mean: increase of the sum divided by increase of the count, over the last 5 minutes, across both pods.

# on rag1
nano stufen-mittel.promql
~/kurs/15/stufen-mittel.promql new file
sum by (stufe) (rate(antwort_stufe_sekunden_sum[5m])) / sum by (stufe) (rate(antwort_stufe_sekunden_count[5m]))
Part Meaning
rate(…_sum[5m]) seconds per second added in the last 5 minutes
rate(…_count[5m]) measurements per second in the same time
sum by (stufe) add up both pods, separated by stage
/ divided: seconds per measurement
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < stufen-mittel.promql > stufen-mittel.json
# on rag1
jq -c '.data.result[] | {stufe: .metric.stufe, sekunden: .value[1]}' stufen-mittel.json

Expected:

{"stufe":"embed","sekunden":"0.37876584702184024"}
{"stufe":"llm_antwort","sekunden":"6.6985723719261"}
{"stufe":"llm_laden","sekunden":"0.005476244602717517"}
{"stufe":"llm_prompt","sekunden":"4.109311878385215"}
{"stufe":"schild","sekunden":"0.017511651044769386"}
{"stufe":"suche","sekunden":"0.02513427966964362"}

Step 4 – the 95th percentile. The mean hides the slow questions. histogram_quantile estimates from the trays below which duration 95 % of the measurements lie.

# on rag1
nano stufen-p95.promql
~/kurs/15/stufen-p95.promql new file
histogram_quantile(0.95, sum by (stufe, le) (rate(antwort_stufe_sekunden_bucket[5m])))
  • rate(…_bucket[5m]) – how fast each tray filled up in the last 5 minutes,
  • sum by (stufe, le) – both pods together, separated by stage and tray,
  • histogram_quantile(0.95, …) – the boundary below which 95 % lie; estimated within a tray.
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < stufen-p95.promql > stufen-p95.json
# on rag1
jq -c '.data.result[] | {stufe: .metric.stufe, sekunden: .value[1]}' stufen-p95.json

Expected:

{"stufe":"embed","sekunden":"0.9362040698899343"}
{"stufe":"llm_antwort","sekunden":"15.24716971403317"}
{"stufe":"llm_laden","sekunden":"0.01577127420605145"}
{"stufe":"llm_prompt","sekunden":"9.363446409051157"}
{"stufe":"schild","sekunden":"0.024442560458652222"}
{"stufe":"suche","sekunden":"0.05330605043540658"}

What you see:

Stage Mean 95 % Interpretation
schild 0.018 s 0.024 s two small GET requests to Qdrant (alias, metadata)
embed 0.38 s 0.94 s embedding the question – noticeable, but small
suche 0.025 s 0.053 s Qdrant with filter – negligible
llm_laden 0.005 s 0.016 s the model is loaded; only after a pause would this be expensive
llm_prompt 4.1 s 9.4 s the language model reads instruction and three cards
llm_antwort 6.7 s 15.2 s the language model writes the answer

A good 95 % of the time goes to the language model – Day 10 showed that too. What is new is the split: almost 40 % of it is not spent writing, but reading the prompt. Three cards with up to 1000 characters are hundreds of tokens, and on the CPU every token costs time. Whoever wants to save here passes fewer or shorter cards – not a faster embedding. Rerank is missing from the list: it has been switched off since Day 10 (RERANK_URL empty), so there is no measurement. The values above 10 seconds are rough: the tray reaches from 10 to 30 seconds, and histogram_quantile estimates linearly within it.

Step 5 – tokens per second. How fast does the language model write?

# on rag1
nano token-je-sekunde.promql
~/kurs/15/token-je-sekunde.promql new file
sum(rate(antwort_token_total{art="antwort"}[5m])) / sum(rate(antwort_stufe_sekunden_sum{stufe="llm_antwort"}[5m]))
  • numerator: written tokens per second,
  • denominator: seconds in the stage llm_antwort per second – together: tokens per second of writing time.
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < token-je-sekunde.promql > token.json
# on rag1
jq -c '.data.result[] | .value[1]' token.json

Expected:

"9.092987139355257"

Around 9 tokens per second – in the range you saw on Day 14 without load (10.3 to 13.8).

Step 6 – the searches from Qdrant’s point of view. Qdrant counts what arrives.

# on rag1
nano qdrant-anfragen.promql
~/kurs/15/qdrant-anfragen.promql new file
sum by (endpoint) (increase(rest_responses_total[5m]))
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < qdrant-anfragen.promql > qdrant-anfragen.json
# on rag1
jq -c '.data.result[] | {endpoint: .metric.endpoint, anzahl: .value[1]}' qdrant-anfragen.json

Expected:

{"endpoint":"/collections/{collection_name}/points","anzahl":"0"}
{"endpoint":"/collections/{collection_name}/points/count","anzahl":"0"}
{"endpoint":"/collections/{collection_name}/points/query","anzahl":"21.052631578947366"}
{"endpoint":"/collections/{collection_name}/points/delete","anzahl":"0"}

What you see: A good 21 searches in 5 minutes – one per question. The odd number is not an error: increase() has values 15 seconds apart and extrapolates to the whole window.

Step 7 – what the caretaker costs.

# on rag1
kubectl top pod -n rag

Expected:

NAME                          CPU(cores)   MEMORY(bytes)   
antwort-74f68864c8-c2dtl      3m           18Mi            
antwort-74f68864c8-crhs6      3m           18Mi            
auswertung                    0m           0Mi             
besucher                      2m           0Mi             
curl                          0m           0Mi             
embed-66bdc7c6c9-rqqpn        333m         2666Mi          
llm-579476976d-6rx9d          7141m        2235Mi          
pg-1                          19m          74Mi            
prometheus-69c6d5f589-v7zgx   15m          29Mi            
qdrant-0                      23m          108Mi           
qdrant-1                      23m          323Mi           

What you see: Prometheus needs 15 millicores and 29 MiB – less memory than one answer service pod. The language model computes with a good 7 cores. The tally sheet did not make the answer service pod measurably bigger (18 MiB, on Day 14 it was 17 MiB).

Remember: Measure first, then optimise: the stages you think of first – embedding and search – together cost less than half a second. The language model needs almost as long for reading as for writing.

Save your progress? Sign up for free

Drill 5: Quality in operation

Where you are: on rag1, in ~/kurs/15. The visitor keeps asking.

What you have afterwards: the numbers that say whether the information desk is any good – and the normal value against which you recognise deviations.

In this drill: not how fast, but how good. Three numbers: how did the questions end? How many without a card? How well did the best card fit?

Step 1 – how the questions ended.

# on rag1
nano ergebnisse.promql
~/kurs/15/ergebnisse.promql new file
sum by (ergebnis) (increase(antwort_fragen_total[5m]))
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < ergebnisse.promql > ergebnisse.json
# on rag1
jq -c '.data.result[] | {ergebnis: .metric.ergebnis, anzahl: .value[1]}' ergebnisse.json

Expected:

{"ergebnis":"antwort","anzahl":"18.244004385964914"}
{"ergebnis":"keine_karte","anzahl":"2.1052631578947367"}

And what the visitor saw itself:

# on rag1
kubectl -n rag logs besucher | grep -c ' 200$'
  • -c – only count; ' 200$' – lines ending in 200.

Expected:

20
# on rag1
kubectl -n rag logs besucher | grep -c -v ' 200$'

Expected:

0

What you see: The visitor saw 200 20 times, no error. Prometheus saw the same questions in more detail: a good 18 with an answer, a good 2 without a card. No verworfen, no zeitueberschreitung – results that never occurred do not have a time series yet.

Step 2 – the share without a card. This is the expression of the first alert rule, without the threshold.

# on rag1
nano anteil-keine.promql
~/kurs/15/anteil-keine.promql new file
sum(rate(antwort_fragen_total{ergebnis="keine_karte"}[2m])) / sum(rate(antwort_fragen_total[2m]))
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < anteil-keine.promql > anteil-keine.json
# on rag1
jq -c '.data.result[] | .value[1]' anteil-keine.json

Expected:

"0.125"

12.5 % – exactly one in eight questions: the laptop. That is the normal value of this information desk with this visitor. The alert rule is set at 50 %.

Step 3 – how well did the best card fit?

# on rag1
nano score-verteilung.promql
~/kurs/15/score-verteilung.promql new file
sum by (le) (increase(antwort_bester_score_bucket[5m]))
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < score-verteilung.promql > score-verteilung.json
# on rag1
jq -c '.data.result[] | {le: .metric.le, anzahl: .value[1]}' score-verteilung.json

Expected:

{"le":"0.1","anzahl":"0"}
{"le":"0.2","anzahl":"0"}
{"le":"0.3","anzahl":"0"}
{"le":"0.4","anzahl":"2.1052631578947367"}
{"le":"0.42","anzahl":"2.1052631578947367"}
{"le":"0.5","anzahl":"7.292161403508771"}
{"le":"0.6","anzahl":"20.633203508771928"}
{"le":"0.7","anzahl":"20.633203508771928"}
{"le":"0.8","anzahl":"20.633203508771928"}
{"le":"+Inf","anzahl":"20.633203508771928"}

What you see:

Tray Count (cumulative) Interpretation
up to 0.3 0 no question missed completely
up to 0.4 a good 2 the laptop questions – below the threshold 0.42
0.42 to 0.5 a good 5 (7.3 − 2.1) just above the threshold; this is where the shaky answers live
0.5 to 0.6 a good 13 safely above the threshold
above 0.6 0 –

A good quarter of the questions landed just above the threshold. If the distribution slides to the left – for example because cards are missing or a model does not fit – they are the first to fall below 0.42.

Step 4 – the pinboard.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/alerts > alarme.json
# on rag1
jq -c '.data.alerts[] | {alarm: .labels.alertname, state, wert: .value}' alarme.json

Expected: no output – no alert, not even ZielNichtErreichbar any more, since the fence has the door for port 9187.

Remember: Quality in operation means: the same numbers every day. Only when you know the normal value – here 12.5 % without a card, best scores around 0.5 – do you recognise the deviation.

Save your progress? Sign up for free

Drill 6: All 200, nothing found

Where you are: on rag1, in ~/kurs/15. The visitor keeps asking.

What you have afterwards: the error from Day 13 once more – this time reported by an alert rule, although every request ends with 200.

In this drill: a colleague wants to readjust the threshold on wissen, the way back from Day 13. He takes the file schild-wissen.json from Day 13 – and sends it to the wrong collection.

Step 1 – the colleague’s file.

# on rag1
cat ../13/schild-wissen.json

Expected:

{
  "metadata": {
    "modell": "bge-m3",
    "mindest_score": 0.46
  }
}

Model and threshold of wissen. Since Day 13 the answer service reads both from the metadata of the collection behind the sign for every question.

Step 2 – the mistake. Changing metadata is a writing request; the colleague has the full key.

# on rag1
date -u +%T

Expected:

06:22:18
# on rag1
kubectl -n rag exec -i curl -- curl -s -K /schluessel/voll.conf -X PATCH \
  http://qdrant.rag:6333/collections/wissen-qwen3 \
  -H 'Content-Type: application/json' -d @- < ../13/schild-wissen.json

Expected:

{"result":true,"status":"ok","time":0.107986722}

Before you check – your prediction: What does the visitor see? What does the watch from Day 13 see, which only counts the status code? And what does Prometheus see?

Step 3 – what the visitor sees. A good minute later:

# on rag1
kubectl -n rag logs besucher --since=60s
  • --since=60s – only the lines of the last minute.

Expected:

06:22:37 200
06:22:40 200
06:22:44 200
06:22:47 200
06:22:50 200
06:22:54 200
06:22:57 200
06:23:01 200
06:23:04 200
06:23:08 200
06:23:11 200
06:23:15 200
06:23:18 200
06:23:21 200
06:23:25 200
06:23:28 200
06:23:31 200

What you see: Only 200 – and the questions come faster than before, every 3 to 4 seconds instead of every 12 to 18. Whoever only looks at errors and response time sees an information desk running better than ever.

Step 4 – what the answer service says.

# on rag1
kubectl -n rag logs -l app=antwort --prefix --since=60s

Expected (excerpt – the first five lines):

[pod/antwort-74f68864c8-c2dtl/antwort] keine Karte  bester 0.076  wissen-qwen3  Wozu dient eine Startup-Probe?
[pod/antwort-74f68864c8-c2dtl/antwort] keine Karte  bester 0.058  wissen-qwen3  Der Drucker druckt nicht mehr. Was soll ich tun?
[pod/antwort-74f68864c8-c2dtl/antwort] keine Karte  bester 0.071  wissen-qwen3  Wie beantrage ich Urlaub?
[pod/antwort-74f68864c8-c2dtl/antwort] keine Karte  bester 0.052  wissen-qwen3  Was ist eine Toleration?
[pod/antwort-74f68864c8-c2dtl/antwort] keine Karte  bester 0.076  wissen-qwen3  Wozu dient eine Startup-Probe?

Every question ends without a card, best scores around 0.05 – as on Day 13, Drill 6. The log shows it, but only to whoever looks into it. And it contains the question text: logs are not a tally sheet; their own rules apply (who reads along, how long they are kept).

Step 5 – what Prometheus sees.

# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < anteil-keine.promql > anteil-keine.json
# on rag1
jq -c '.data.result[] | .value[1]' anteil-keine.json

Expected:

"0.9036907510014658"
# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/alerts > alarme.json
# on rag1
jq -c '.data.alerts[] | {alarm: .labels.alertname, state, activeAt, wert: .value}' alarme.json

Expected:

{"alarm":"AuskunftFindetNichts","state":"pending","activeAt":"2026-12-03T06:22:56.898659708Z","wert":"8.573027686433933e-01"}

What you see: 90 % without a card instead of 12.5 %. The rule AuskunftFindetNichts has been pending since 06:22:56 – 38 seconds after the mistake the share was above 50 %. Because the rule has for: 1m, it waits a minute to see whether it stays that way.

Step 6 – one minute later.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/alerts > alarme.json
# on rag1
jq -c '.data.alerts[] | {alarm: .labels.alertname, state, activeAt, wert: .value}' alarme.json

Expected:

{"alarm":"AuskunftFindetNichts","state":"firing","activeAt":"2026-12-03T06:22:56.898659708Z","wert":"1e+00"}

firing, value 1: in the last two minutes no question ended with an answer any more. Here an Alertmanager would send a message – in this course the pinboard is enough.

# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < score-verteilung.promql > score-verteilung.json
# on rag1
jq -c '.data.result[] | {le: .metric.le, anzahl: .value[1]}' score-verteilung.json

Expected:

{"le":"0.1","anzahl":"35.90213333333333"}
{"le":"0.2","anzahl":"35.90213333333333"}
{"le":"0.3","anzahl":"36.633305263157894"}
{"le":"0.4","anzahl":"38.73856842105263"}
{"le":"0.42","anzahl":"38.73856842105263"}
{"le":"0.5","anzahl":"42.10526315789473"}
{"le":"0.6","anzahl":"48.421052631578945"}
{"le":"0.7","anzahl":"48.421052631578945"}
{"le":"0.8","anzahl":"48.421052631578945"}
{"le":"+Inf","anzahl":"48.421052631578945"}

What you see: A good 36 of the 48 questions of the last 5 minutes had a best card below 0.1 – before, not a single one. The distribution has tipped to the left. That is the signature of a wrong model: the question is embedded differently from the cards, and nothing fits any more.

And the latency? Looks splendid:

# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < stufen-mittel.promql > stufen-mittel.json
# on rag1
jq -c '.data.result[] | {stufe: .metric.stufe, sekunden: .value[1]}' stufen-mittel.json

Expected:

{"stufe":"embed","sekunden":"0.34008041304347825"}
{"stufe":"llm_antwort","sekunden":"6.364581454545456"}
{"stufe":"llm_laden","sekunden":"0.005689090909090909"}
{"stufe":"llm_prompt","sekunden":"5.06514090909091"}
{"stufe":"schild","sekunden":"0.016286847826086956"}
{"stufe":"suche","sekunden":"0.021217282608695653"}

Embedding and search as before; the times of the language model only come from the first minutes of the window – since the mistake it is not asked at all. A latency dashboard would stay green.

Step 7 – the cause. What is in the metadata behind the sign?

# on rag1
kubectl -n rag exec curl -- curl -s -K /schluessel/lesen.conf \
  http://qdrant.rag:6333/collections/wissen-qwen3 > qwen3.json
# on rag1
jq '.result.config.metadata' qwen3.json

Expected:

{
  "modell": "bge-m3",
  "mindest_score": 0.46
}

Step 8 – back. The right file from Day 13.

# on rag1
cp ../13/schild-qwen3.json .
# on rag1
date -u +%T

Expected:

06:24:28
# on rag1
kubectl -n rag exec -i curl -- curl -s -K /schluessel/voll.conf -X PATCH \
  http://qdrant.rag:6333/collections/wissen-qwen3 \
  -H 'Content-Type: application/json' -d @- < schild-qwen3.json

Expected:

{"result":true,"status":"ok","time":0.15918337}

Step 9 – the pinboard clears. Just under two minutes later – that is how far back the window [2m] of the rule reaches:

# on rag1
kubectl -n rag logs -l app=antwort --prefix --tail=2

Expected:

[pod/antwort-74f68864c8-c2dtl/antwort] antwort  {'suche': 0.44, 'gesamt': 9.54}  Wie beantrage ich Urlaub?
[pod/antwort-74f68864c8-c2dtl/antwort] keine Karte  bester 0.332  wissen-qwen3  Wie bekomme ich einen neuen Laptop?
[pod/antwort-74f68864c8-crhs6/antwort] antwort  {'suche': 0.26, 'gesamt': 12.32}  Wie groß darf ein Secret höchstens sein?
[pod/antwort-74f68864c8-crhs6/antwort] antwort  {'suche': 0.21, 'gesamt': 13.16}  Was ist eine Toleration?
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < anteil-keine.promql > anteil-keine.json
# on rag1
jq -c '.data.result[] | .value[1]' anteil-keine.json

Expected:

"0.4545454545454546"
# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/alerts > alarme.json
# on rag1
jq -c '.data.alerts[] | {alarm: .labels.alertname, state, activeAt, wert: .value}' alarme.json

Expected: no output – the alert is gone.

What you see: Answers come again, the laptop remains the one question without a card (best score 0.332 instead of 0.05). At 45 % the share of the last two minutes is below the threshold – the window still contains questions from the time of the mistake. The alert withdrew without you doing anything.

Remember: The watch counts whether the desk answers; the tally sheet counts what it answers. The error from Day 13 delivered 100 % 200 and faster answers – it only became visible in the share of “nothing in the handbook” and in the score distribution tipped to the left.

Save your progress? Sign up for free

If it does not work

Symptom Cause Solution
/metrics of Qdrant returns 401 or nothing no key, or the pod lacks the label qdrant-zugang: "ja" (fence from Day 14) send the read-only key, set the label in the pod template
target pg is down, connection refused the fence pg-zaun does not let port 9187 through add a rule for app: prometheus on port 9187 (Drill 3), wait 15 to 30 seconds
/metrics of the answer service shows only zeros the request landed on the other pod Prometheus asks both pods; by hand, ask via the pod name
query returns "result":[] metric not scraped yet or name/label mistyped check up, wait one scrape round (15 s), look up the name in /metrics
odd numbers like 21.05 with increase() Prometheus extrapolates the intervals to the window not an error; take a longer window for whole numbers
curl ends with exit code 52 right after a rollout the request hit the pod that is just being terminated wait a few seconds, repeat the request
new file in the ConfigMap, but Prometheus uses the old one the volume is only updated after up to a minute look into the pod (grep), only then /-/reload
alert rule stays silent although the case occurred the counter only appeared with the event (value 1), increase() sees no increase create all label values with 0 at start (diagnosis task)

Diagnosis task: The silent alert

Where you are: on rag1, in ~/kurs/15. The visitor keeps asking.

Starting point. IT adds a new card to the handbook: where to download the new VPN client – from the vendor. The next morning a colleague reports: “The information desk says there is nothing about it in the handbook.” The pinboard is empty, although AuskunftVerwirft is supposed to report exactly this case. Find out why the answer is held back and why the alert stays silent.

Step 1 – the new card. You take over the handbook from Day 14 and add the card.

# on rag1
cp -r ../14/korpus .
# on rag1
nano korpus/karte-vpn-client.txt
~/kurs/15/korpus/karte-vpn-client.txt new file
VPN-Client aktualisieren: Die neue Version des VPN-Clients lädst du unter https://download.vpn-hersteller.example/client herunter. Installiere sie über die alte Version; dein Profil firma.ovpn bleibt erhalten.

Recreate the ConfigMap and run the ingest job from Day 14 once more – it has the label qdrant-zugang: "ja" and the full key, and it only embeds new cards.

# on rag1
kubectl -n rag delete configmap korpus

Expected:

configmap "korpus" deleted from rag namespace
# on rag1
kubectl -n rag create configmap korpus --from-file=korpus/

Expected:

configmap/korpus created
# on rag1
kubectl -n rag delete job ingest-qwen3

Expected:

job.batch "ingest-qwen3" deleted from rag namespace
# on rag1
kubectl apply -f ../14/ingest-qwen3.yaml

Expected:

job.batch/ingest-qwen3 created
# on rag1
kubectl -n rag wait --for=condition=Complete job/ingest-qwen3 --timeout=600s

Expected:

job.batch/ingest-qwen3 condition met
# on rag1
kubectl -n rag logs job/ingest-qwen3 --tail=4

Expected:

karte-vpn.txt: 1 Karten, 0 neu, 0 gelöscht
nachtrag-wartung.txt: 1 Karten, 0 neu, 0 gelöscht
personal-gehaltsbaender.txt: 1 Karten, 0 neu, 0 gelöscht
{"dokumente": 13, "karten": 176, "neu": 1, "unveraendert": 175, "geloescht": 0, "gesperrt": 1, "sekunden": 3.7}

176 cards, one new. You leave the jobs ingest and eval from Days 7 and 13 alone: they have neither the label nor the key and have not been able to reach Qdrant since Day 14.

Step 2 – the colleague’s question.

# on rag1
nano vpn-client.json
~/kurs/15/vpn-client.json new file
{"frage": "Wo lade ich den neuen VPN-Client herunter?"}
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- < vpn-client.json > vpn-client.json.antwort
# on rag1
jq . vpn-client.json.antwort

Expected:

{
  "antwort": "Dazu steht nichts im Handbuch.",
  "quellen": [],
  "verworfen": "download.vpn-hersteller.example"
}

Before you read on – your prediction: The colleague is right. Is there an alert on the pinboard now?

Try it yourself first. The solution follows.

Solution

Step 3 – the pinboard.

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/alerts > alarme.json
# on rag1
jq -c '.data.alerts[] | {alarm: .labels.alertname, state, activeAt, wert: .value}' alarme.json

Expected: no output – 20 seconds after the question, so after at least one scrape round.

Step 4 – the log. What did the answer service decide?

# on rag1
kubectl -n rag logs -l app=antwort --prefix --since=3m

Expected (excerpt – look for the line with verworfen):

[pod/antwort-74f68864c8-c2dtl/antwort] verworfen  fremde Adresse download.vpn-hersteller.example  Wo lade ich den neuen VPN-Client herunter?

The output rule from Day 14 held back the answer: it contained an address outside ERLAUBTE_DOMAINS. The rule did what it was built for – the card is new, the list is not.

Step 5 – the time series itself. Why did AuskunftVerwirft not fire? Instead of the rule you query the raw values of the last 5 minutes. The range [5m] after the metric delivers every scraped value, not only the last one.

# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode 'query=antwort_fragen_total{ergebnis="verworfen"}[5m]' > verworfen-roh.json
# on rag1
jq -c '.data.result[] | {instance: .metric.instance, werte: [.values[][1]]}' verworfen-roh.json
  • .values[][1] – from every value pair [time, value] only the value,
  • [ … ] around it – all values into one list.

Expected:

{"instance":"antwort-74f68864c8-c2dtl","werte":["1","1","1"]}

What you see: The time series only exists since the discarded question, and it starts at 1. increase() measures the increase between the values in the window: 1, 1, 1 – no increase, so 0. The value before the event is missing because the answer service only creates the counter verworfen at the first discard.

Step 6 – first help the colleague. The vendor site is wanted, so the domain belongs on the list. You take over the file from Day 14:

# on rag1
cp ../14/antwort.yaml .
# on rag1
nano antwort.yaml
~/kurs/15/antwort.yaml changes in green
apiVersion: apps/v1
kind: Deployment
metadata:
  name: antwort
  namespace: rag
spec:
  replicas: 2
  selector:
    matchLabels:
      app: antwort
  template:
    metadata:
      labels:
        app: antwort
        qdrant-zugang: "ja"
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: antwort
          matchLabelKeys:
            - pod-template-hash
      containers:
        - name: antwort
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/antwort.py"]
          env:
            - name: SAMMLUNG
              value: auskunft
            - name: KARTEN
              value: "3"
            - name: LLM_TIMEOUT
              value: "60"
            - name: MINDEST_SCORE
              value: "0.46"
            - name: RERANK_URL
              value: ""
            - name: PLAETZE
              value: "2"
            - name: ERLAUBTE_DOMAINS
              value: firma.example,kubernetes.io,vpn-hersteller.example
            - name: QDRANT_API_KEY
              valueFrom:
                secretKeyRef:
                  name: qdrant-schluessel
                  key: lesen
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          lifecycle:
            preStop:
              sleep:
                seconds: 5
          readinessProbe:
            httpGet:
              path: /health
              port: 8080
          volumeMounts:
            - name: code
              mountPath: /code
      volumes:
        - name: code
          configMap:
            name: antwort-code
---
apiVersion: v1
kind: Service
metadata:
  name: antwort
  namespace: rag
spec:
  selector:
    app: antwort
  ports:
    - port: 80
      targetPort: 8080
# on rag1
kubectl apply -f antwort.yaml

Expected:

deployment.apps/antwort configured
service/antwort unchanged
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120s

Expected (excerpt – the last line):

deployment "antwort" successfully rolled out
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- < vpn-client.json > vpn-client.json.antwort

Expected (in the lab on the first attempt right after the rollout):

command terminated with exit code 52

52 means “empty reply from server” for curl: the request hit the old pod that was just being terminated. Wait a moment and send the same command again:

# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- < vpn-client.json > vpn-client.json.antwort
# on rag1
jq '{antwort, quellen}' vpn-client.json.antwort

Expected:

{
  "antwort": "Die neue Version des VPN-Clients lädst du unter https://download.vpn-hersteller.example/client herunter. [1]",
  "quellen": [
    {
      "nr": 1,
      "quelle": "karte-vpn-client.txt",
      "abschnitt": "VPN-Client aktualisieren",
      "score": 0.705,
      "sammlung": "wissen-qwen3"
    },
    {
      "nr": 2,
      "quelle": "karte-vpn.txt",
      "abschnitt": "VPN-Zugang einrichten",
      "score": 0.597,
      "sammlung": "wissen-qwen3"
    },
    {
      "nr": 3,
      "quelle": "karte-druck.txt",
      "abschnitt": "Druckdienst neu starten",
      "score": 0.338,
      "sammlung": "wissen-qwen3"
    }
  ]
}

The colleague gets the answer, with address and source.

Step 7 – then repair the tally sheet. Every column has to be there from the start, with 0. In the answer service these are two places: a list of all results and the start of the counters.

# on rag1
nano antwort.py
~/kurs/15/antwort.py changes in green
"""Antwortdienst: Frage einbetten, Karten suchen, mit Quellenangabe antworten, messen."""

import json
import os
import re
import signal
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
LLM = os.environ.get("LLM_URL", "http://llm.rag:11434")
RERANK = os.environ.get("RERANK_URL", "")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
LLM_MODELL = os.environ.get("LLM_MODELL", "qwen3:1.7b")
KARTEN = int(os.environ.get("KARTEN", "3"))
KANDIDATEN = int(os.environ.get("KANDIDATEN", "20"))
MINDEST = float(os.environ.get("MINDEST_SCORE", "0"))
LLM_TIMEOUT = float(os.environ.get("LLM_TIMEOUT", "120"))
MAX_TOKEN = int(os.environ.get("MAX_TOKEN", "300"))
PLAETZE = int(os.environ.get("PLAETZE", "0"))
SCHLUESSEL = os.environ.get("QDRANT_API_KEY", "")
ERLAUBT = os.environ.get("ERLAUBTE_DOMAINS", "firma.example,kubernetes.io").split(",")
ADRESSE = re.compile(r"https?://([\w.-]+)|[\w.+-]+@([\w-]+(?:\.[\w-]+)+)")
KEINE = "Dazu steht nichts im Handbuch."
THEKE = threading.BoundedSemaphore(PLAETZE) if PLAETZE else None
GRENZEN = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60)
SCORE_GRENZEN = (0.1, 0.2, 0.3, 0.4, 0.42, 0.5, 0.6, 0.7, 0.8)
ERGEBNISSE = (
    "antwort",
    "keine_karte",
    "verworfen",
    "zeitueberschreitung",
    "fehler",
    "abgewiesen",
)

ANWEISUNG = (
    "Du bist die IT-Auskunft einer Firma. Beantworte die Frage des Nutzers auf "
    "Deutsch, kurz, und nur mit dem Inhalt der Karten unten. Nenne hinter jeder "
    "Aussage die Nummer der Karte in eckigen Klammern, zum Beispiel [1]. Steht die "
    f"Antwort auf keiner Karte, antworte genau: {KEINE}\n\nKarten:\n"
)


class Messwerte:
    """Zähler und Histogramme im Textformat von Prometheus – ohne Fragetext."""

    def __init__(self):
        self.sperre = threading.Lock()
        self.fragen = dict.fromkeys(ERGEBNISSE, 0)
        self.token = {"prompt": 0, "antwort": 0}
        self.stufen = {}
        self.score = [0] * (len(SCORE_GRENZEN) + 1) + [0.0]

    def zaehlen(self, ergebnis):
        with self.sperre:
            self.fragen[ergebnis] = self.fragen.get(ergebnis, 0) + 1

    def stufe(self, name, sekunden):
        with self.sperre:
            eimer = self.stufen.setdefault(name, [0] * (len(GRENZEN) + 1) + [0.0])
            eimer[sum(sekunden > g for g in GRENZEN)] += 1
            eimer[-1] += sekunden

    def bester(self, score):
        with self.sperre:
            self.score[sum(score > g for g in SCORE_GRENZEN)] += 1
            self.score[-1] += score

    def llm(self, daten):
        """Zeiten und Token aus der Antwort von Ollama (Nanosekunden)."""
        self.stufe("llm_laden", daten.get("load_duration", 0) / 1e9)
        self.stufe("llm_prompt", daten.get("prompt_eval_duration", 0) / 1e9)
        self.stufe("llm_antwort", daten.get("eval_duration", 0) / 1e9)
        with self.sperre:
            self.token["prompt"] += daten.get("prompt_eval_count", 0)
            self.token["antwort"] += daten.get("eval_count", 0)

    def histogramm(self, name, label, grenzen, eimer):
        zeilen, summe = [], 0
        for grenze, anzahl in zip(list(grenzen) + ["+Inf"], eimer[:-1]):
            summe += anzahl
            zeilen.append(f'{name}_bucket{{{label}le="{grenze}"}} {summe}')
        klammer = f"{{{label.rstrip(',')}}}" if label else ""
        zeilen.append(f"{name}_sum{klammer} {eimer[-1]:.6f}")
        zeilen.append(f"{name}_count{klammer} {summe}")
        return zeilen

    def text(self):
        with self.sperre:
            zeilen = ["# TYPE antwort_fragen_total counter"]
            for ergebnis, anzahl in sorted(self.fragen.items()):
                zeilen.append(f'antwort_fragen_total{{ergebnis="{ergebnis}"}} {anzahl}')
            zeilen.append("# TYPE antwort_token_total counter")
            for art, anzahl in self.token.items():
                zeilen.append(f'antwort_token_total{{art="{art}"}} {anzahl}')
            zeilen.append("# TYPE antwort_stufe_sekunden histogram")
            for name, eimer in sorted(self.stufen.items()):
                zeilen += self.histogramm(
                    "antwort_stufe_sekunden", f'stufe="{name}",', GRENZEN, eimer
                )
            zeilen.append("# TYPE antwort_bester_score histogram")
            zeilen += self.histogramm(
                "antwort_bester_score", "", SCORE_GRENZEN, self.score
            )
        return "\n".join(zeilen) + "\n"


MESS = Messwerte()


def kopf(url):
    """Kopfzeilen; den Qdrant-Schlüssel bekommt nur Qdrant."""
    zeilen = {"Content-Type": "application/json"}
    if SCHLUESSEL and url.startswith(QDRANT):
        zeilen["api-key"] = SCHLUESSEL
    return zeilen


def anfrage(url, daten, timeout=30):
    req = urllib.request.Request(
        url, data=json.dumps(daten).encode(), headers=kopf(url)
    )
    return urllib.request.urlopen(req, timeout=timeout)


def lesen(url):
    """GET an Qdrant, Antwort als JSON."""
    with urllib.request.urlopen(
        urllib.request.Request(url, headers=kopf(url)), timeout=5
    ) as a:
        return json.load(a)


def fremde_adresse(text):
    """Erste Web- oder Mail-Adresse, deren Domain nicht auf der Liste steht."""
    for treffer in ADRESSE.finditer(text):
        domain = (treffer.group(1) or treffer.group(2)).lower().rstrip(".")
        if not any(domain == d or domain.endswith("." + d) for d in ERLAUBT):
            return domain
    return None


def schild():
    """Hinter dem Schild nachsehen: welche Collection, welches Modell, welche Schwelle."""
    name = SAMMLUNG
    for eintrag in lesen(f"{QDRANT}/aliases")["result"]["aliases"]:
        if eintrag["alias_name"] == SAMMLUNG:
            name = eintrag["collection_name"]
    config = lesen(f"{QDRANT}/collections/{name}")["result"]["config"]
    angaben = config.get("metadata") or {}
    return name, angaben.get("modell", MODELL), angaben.get("mindest_score", MINDEST)


def suchen(frage, mandant):
    """Frage einbetten, nur Karten des Mandanten und für alle holen, ggf. neu ordnen."""
    t = time.time()
    name, modell, mindest = schild()
    MESS.stufe("schild", time.time() - t)
    t = time.time()
    with anfrage(f"{EMBED}/api/embed", {"model": modell, "input": [frage]}) as a:
        vektor = json.load(a)["embeddings"][0]
    MESS.stufe("embed", time.time() - t)
    koerper = {
        "query": vektor,
        "limit": KANDIDATEN if RERANK else KARTEN,
        "with_payload": True,
        "filter": {"must": [{"key": "mandant", "match": {"any": [mandant, "alle"]}}]},
    }
    t = time.time()
    with anfrage(f"{QDRANT}/collections/{name}/points/query", koerper) as a:
        punkte = json.load(a)["result"]["points"]
    MESS.stufe("suche", time.time() - t)
    if RERANK and punkte:
        t = time.time()
        texte = [p["payload"]["text"] for p in punkte]
        with anfrage(f"{RERANK}/rerank", {"query": frage, "texts": texte}, 120) as a:
            punkte = [punkte[u["index"]] for u in json.load(a)]
        MESS.stufe("rerank", time.time() - t)
    return punkte[:KARTEN], name, mindest


def nachrichten(frage, punkte):
    """Anweisung und nummerierte Karten als System-, die Frage als Nutzernachricht."""
    karten = [
        f"[{nr}] {p['payload']['abschnitt']}\n{p['payload']['text']}\n"
        for nr, p in enumerate(punkte, start=1)
    ]
    return [
        {"role": "system", "content": ANWEISUNG + "\n".join(karten)},
        {"role": "user", "content": frage},
    ]


class Auskunft(BaseHTTPRequestHandler):
    def senden(self, status, daten):
        rumpf = json.dumps(daten, ensure_ascii=False).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(rumpf)))
        self.end_headers()
        self.wfile.write(rumpf)

    def text(self, rumpf):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain; version=0.0.4")
        self.send_header("Content-Length", str(len(rumpf)))
        self.end_headers()
        self.wfile.write(rumpf)

    def zeile(self, daten):
        self.wfile.write(json.dumps(daten, ensure_ascii=False).encode() + b"\n")
        self.wfile.flush()

    def do_GET(self):
        if self.path == "/health":
            self.senden(200, {"status": "ok"})
        elif self.path == "/metrics":
            self.text(MESS.text().encode())
        else:
            self.senden(404, {"fehler": "unbekannter Pfad"})

    def do_POST(self):
        if self.path != "/frage":
            self.senden(404, {"fehler": "unbekannter Pfad"})
            return
        laenge = int(self.headers.get("Content-Length", 0))
        eingabe = json.loads(self.rfile.read(laenge) or b"{}")
        frage = str(eingabe.get("frage", "")).strip()
        if not frage:
            self.senden(400, {"fehler": "frage fehlt"})
            return
        if THEKE and not THEKE.acquire(blocking=False):
            print(f"abgewiesen, {PLAETZE} Plätze belegt  {frage}", flush=True)
            MESS.zaehlen("abgewiesen")
            self.send_response(503)
            self.send_header("Retry-After", "30")
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(b'{"fehler": "zu viele Fragen gleichzeitig"}')
            return
        mandant = self.headers.get("X-Mandant", "alle")
        try:
            self.beantworten(frage, eingabe, mandant)
        except Exception:
            MESS.zaehlen("fehler")
            raise
        finally:
            if THEKE:
                THEKE.release()

    def beantworten(self, frage, eingabe, mandant):
        """Suchen, Schwelle prüfen, dann ganz oder als Strom antworten."""
        start = time.time()
        punkte, sammlung, mindest = suchen(frage, mandant)
        zeiten = {"suche": round(time.time() - start, 2)}
        bester = punkte[0]["score"] if punkte else 0.0
        MESS.bester(bester)
        if bester < mindest:
            print(f"keine Karte  bester {bester:.3f}  {sammlung}  {frage}", flush=True)
            MESS.zaehlen("keine_karte")
            self.senden(
                200,
                {
                    "antwort": KEINE,
                    "quellen": [],
                    "sammlung": sammlung,
                    "sekunden": zeiten,
                },
            )
            return
        quellen = [
            {
                "nr": nr,
                "quelle": p["payload"]["quelle"],
                "abschnitt": p["payload"]["abschnitt"],
                "score": round(p["score"], 3),
                "sammlung": sammlung,
            }
            for nr, p in enumerate(punkte, start=1)
        ]
        if eingabe.get("stream"):
            self.strom(frage, punkte, quellen, start, zeiten)
        else:
            self.ganz(frage, punkte, quellen, start, zeiten)

    def ganz(self, frage, punkte, quellen, start, zeiten):
        """Auf die ganze Antwort warten und sie in einem Stück senden."""
        koerper = {
            "model": LLM_MODELL,
            "messages": nachrichten(frage, punkte),
            "stream": False,
            "think": False,
            "options": {"num_predict": MAX_TOKEN, "temperature": 0},
        }
        try:
            with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
                daten = json.load(a)
            antwort = daten["message"]["content"].strip()
            MESS.llm(daten)
        except TimeoutError:
            print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s  {frage}", flush=True)
            MESS.zaehlen("zeitueberschreitung")
            self.senden(504, {"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
            return
        except urllib.error.URLError as fehler:
            print(
                f"Sprachmodell nicht erreichbar: {fehler.reason}  {frage}", flush=True
            )
            MESS.zaehlen("fehler")
            self.senden(502, {"fehler": "Sprachmodell nicht erreichbar"})
            return
        zeiten["gesamt"] = round(time.time() - start, 2)
        fremd = fremde_adresse(antwort)
        if fremd:
            print(f"verworfen  fremde Adresse {fremd}  {frage}", flush=True)
            MESS.zaehlen("verworfen")
            self.senden(200, {"antwort": KEINE, "quellen": [], "verworfen": fremd})
            return
        print(f"antwort  {zeiten}  {frage}", flush=True)
        MESS.zaehlen("antwort")
        self.senden(200, {"antwort": antwort, "quellen": quellen, "sekunden": zeiten})

    def strom(self, frage, punkte, quellen, start, zeiten):
        """Jedes Stück der Antwort sofort weiterreichen, eine JSON-Zeile je Stück."""
        koerper = {
            "model": LLM_MODELL,
            "messages": nachrichten(frage, punkte),
            "stream": True,
            "think": False,
            "options": {"num_predict": MAX_TOKEN, "temperature": 0},
        }
        self.send_response(200)
        self.send_header("Content-Type", "application/x-ndjson")
        self.end_headers()
        self.zeile({"quellen": quellen})
        bisher = ""
        try:
            with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
                for roh in a:
                    daten = json.loads(roh)
                    if daten.get("done"):
                        MESS.llm(daten)
                    stueck = daten["message"]["content"]
                    if stueck and "erstes_wort" not in zeiten:
                        zeiten["erstes_wort"] = round(time.time() - start, 2)
                    bisher += stueck
                    fremd = fremde_adresse(bisher)
                    if fremd:
                        print(f"verworfen  fremde Adresse {fremd}  {frage}", flush=True)
                        MESS.zaehlen("verworfen")
                        self.zeile({"fehler": "Antwort verworfen"})
                        return
                    if stueck:
                        self.zeile({"text": stueck})
        except TimeoutError:
            print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s  {frage}", flush=True)
            MESS.zaehlen("zeitueberschreitung")
            self.zeile({"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
            return
        except urllib.error.URLError as fehler:
            print(
                f"Sprachmodell nicht erreichbar: {fehler.reason}  {frage}", flush=True
            )
            MESS.zaehlen("fehler")
            self.zeile({"fehler": "Sprachmodell nicht erreichbar"})
            return
        zeiten["gesamt"] = round(time.time() - start, 2)
        print(f"strom  {zeiten}  {frage}", flush=True)
        MESS.zaehlen("antwort")
        self.zeile({"fertig": True, "sekunden": zeiten})

    def log_message(self, format, *args):
        pass


def beenden(signum, frame):
    """Auf SIGTERM von Kubernetes sofort und sauber enden."""
    print("SIGTERM erhalten, Antwortdienst endet", flush=True)
    raise SystemExit(0)


if __name__ == "__main__":
    signal.signal(signal.SIGTERM, beenden)
    print(
        f"Antwortdienst auf Port 8080, Sammlung {SAMMLUNG}, LLM {LLM_MODELL}",
        flush=True,
    )
    ThreadingHTTPServer(("", 8080), Auskunft).serve_forever()
Lines Content Meaning
33–40 ERGEBNISSE all six results the service knows – a fixed, small list
55 dict.fromkeys(ERGEBNISSE, 0) every counter starts at 0, not only at the first event

A fixed list also means: no label value comes from outside. The same rule that keeps question text and users out of the labels also keeps the cardinality small.

# on rag1
kubectl -n rag delete configmap antwort-code

Expected:

configmap "antwort-code" deleted from rag namespace
# on rag1
kubectl -n rag create configmap antwort-code --from-file=antwort.py

Expected:

configmap/antwort-code created
# on rag1
kubectl -n rag rollout restart deployment/antwort

Expected:

deployment.apps/antwort restarted
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120s

Expected (excerpt – the last line):

deployment "antwort" successfully rolled out
# on rag1
kubectl -n rag exec curl -- curl -s http://antwort.rag/metrics > antwort-metriken-3.txt
# on rag1
grep antwort_fragen_total antwort-metriken-3.txt

Expected:

# TYPE antwort_fragen_total counter
antwort_fragen_total{ergebnis="abgewiesen"} 0
antwort_fragen_total{ergebnis="antwort"} 0
antwort_fragen_total{ergebnis="fehler"} 0
antwort_fragen_total{ergebnis="keine_karte"} 0
antwort_fragen_total{ergebnis="verworfen"} 0
antwort_fragen_total{ergebnis="zeitueberschreitung"} 0

All six columns, all at 0 – right after the start, before the first question arrived.

Step 8 – the counter-check. Only a real discard proves whether the alert fires now. You briefly take back the permission by applying the file from Day 14:

# on rag1
kubectl apply -f ../14/antwort.yaml

Expected:

deployment.apps/antwort configured
service/antwort unchanged
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120s

Expected (excerpt – the last line):

deployment "antwort" successfully rolled out
# on rag1
date -u +%T

Expected:

06:30:11
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- < vpn-client.json > vpn-client.json.antwort
# on rag1
jq . vpn-client.json.antwort

Expected:

{
  "antwort": "Dazu steht nichts im Handbuch.",
  "quellen": [],
  "verworfen": "download.vpn-hersteller.example"
}

Just under a minute later the raw values – this time over 2 minutes:

# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode 'query=antwort_fragen_total{ergebnis="verworfen"}[2m]' > verworfen-roh.json
# on rag1
jq -c '.data.result[] | {instance: .metric.instance, werte: [.values[][1]]}' verworfen-roh.json

Expected:

{"instance":"antwort-54d5786864-nq9lh","werte":["0","0","0"]}
{"instance":"antwort-54d5786864-wwl5f","werte":["0","0","0","0"]}
{"instance":"antwort-6776b54dcf-v4wvz","werte":["0","1","1","1"]}
{"instance":"antwort-6776b54dcf-ztj4d","werte":["0","0","0","0","0"]}
# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/alerts > alarme.json
# on rag1
jq -c '.data.alerts[] | {alarm: .labels.alertname, state, activeAt, wert: .value}' alarme.json

Expected:

{"alarm":"AuskunftVerwirft","state":"firing","activeAt":"2026-12-03T06:30:41.898659708Z","wert":"1.2822333333333333e+00"}

What you see: Four pods in two minutes – two from the restart, two from the rollout – each with its own time series starting at 0. At v4wvz it jumps from 0 to 1, and exactly this jump is what increase() sees. The rule has no for:, so it goes to firing at once. The value 1.28 instead of 1 is the extrapolation again.

Step 9 – the permission back.

# on rag1
kubectl apply -f antwort.yaml

Expected:

deployment.apps/antwort configured
service/antwort unchanged
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120s

Expected (excerpt – the last line):

deployment "antwort" successfully rolled out

Remember: A counter that did not exist before the event has no increase. Whoever wants to alert on rare events creates every column of the tally sheet with 0 at start – and tries the rule once for real.

Challenge: What the caretaker writes down

Observing costs time series, and every time series costs memory. Find out which target delivers the most time series and which metric has the lion’s share there. Throw it away if you do not need it – without restarting Prometheus – and measure what it brings.

The author’s solution.

Step 1 – time series per target. {__name__=~".+"} selects every time series, count by (job) counts them per job.

# on rag1
nano serien.promql
~/kurs/15/serien.promql new file
count by (job) ({__name__=~".+"})
# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < serien.promql > serien.json
# on rag1
jq -c '.data.result[] | {job: .metric.job, serien: .value[1]}' serien.json

Expected:

{"job":"qdrant","serien":"393"}
{"job":"pg","serien":"478"}
{"job":"antwort","serien":"292"}
{"job":null,"serien":"2"}

PostgreSQL delivers the most time series. The two without a job are the results of the alert rules (ALERTS, ALERTS_FOR_STATE). For antwort the time series of the pods replaced in the diagnosis task are still counted.

Step 2 – the biggest metrics in the job pg. topk(3, …) keeps the three largest values.

# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode 'query=topk(3, count by (__name__) ({job="pg"}))' > pg-gross.json
# on rag1
jq -c '.data.result[] | {metrik: .metric.__name__, serien: .value[1]}' pg-gross.json

Expected:

{"metrik":"cnpg_pg_settings_setting","serien":"284"}
{"metrik":"cnpg_collector_pg_wal","serien":"8"}
{"metrik":"cnpg_pg_stat_database_blk_read_time","serien":"5"}

What you see: 284 of the 478 time series are cnpg_pg_settings_setting – one per PostgreSQL setting. Settings hardly ever change; nobody in the course queries them.

Step 3 – memory before. How many time series Prometheus currently holds in memory is in the TSDB statistics.

# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/status/tsdb > tsdb.json
# on rag1
jq -c '.data.headStats' tsdb.json

Expected:

{"numSeries":2024,"numLabelPairs":582,"chunkCount":2024,"minTime":1796278599444,"maxTime":1796279523626}

2024 time series in the head – more than the good 1100 from step 1, because the series of replaced pods are still in it.

# on rag1
kubectl top pod -n rag prometheus-69c6d5f589-v7zgx

You read the pod name from kubectl -n rag get pods.

Expected:

NAME                          CPU(cores)   MEMORY(bytes)   
prometheus-69c6d5f589-v7zgx   16m          31Mi            

Step 4 – throw away the metric. metric_relabel_configs acts after scraping and before storing: whatever matches action: drop there never ends up in the database.

# on rag1
nano prometheus.yml
~/kurs/15/prometheus.yml changes in green
global:
  scrape_interval: 15s
  evaluation_interval: 15s
rule_files:
  - /etc/prometheus/regeln.yml
scrape_configs:
  - job_name: antwort
    kubernetes_sd_configs:
      - role: pod
        namespaces:
          names: [rag]
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_label_app, __meta_kubernetes_pod_container_port_number]
        regex: antwort;8080
        action: keep
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: instance
  - job_name: qdrant
    authorization:
      credentials_file: /schluessel/lesen
    kubernetes_sd_configs:
      - role: pod
        namespaces:
          names: [rag]
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name, __meta_kubernetes_pod_container_port_number]
        regex: qdrant;6333
        action: keep
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: instance
  - job_name: pg
    kubernetes_sd_configs:
      - role: pod
        namespaces:
          names: [rag]
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_label_cnpg_io_cluster, __meta_kubernetes_pod_container_port_number]
        regex: pg;9187
        action: keep
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: instance
    metric_relabel_configs:
      - source_labels: [__name__]
        regex: cnpg_pg_settings_setting
        action: drop
  • source_labels: [__name__] – the name of the metric,
  • regex: cnpg_pg_settings_setting – exactly this one,
  • action: drop – do not store.
# on rag1
kubectl -n rag delete configmap prometheus

Expected:

configmap "prometheus" deleted from rag namespace
# on rag1
kubectl -n rag create configmap prometheus --from-file=prometheus.yml --from-file=regeln.yml

Expected:

configmap/prometheus created

Step 5 – wait until the file is in the pod. The kubelet does not update the volume of a ConfigMap at once, but at its next sync – that can take up to a minute. Check first, then reload. In the lab the file was there 71 seconds later:

# on rag1
kubectl -n rag exec deploy/prometheus -- grep -c cnpg_pg_settings_setting /etc/prometheus/prometheus.yml
  • deploy/prometheus – any pod of the Deployment, here the only one,
  • grep -c – counts the lines with the name; 0 would mean: still the old file.

Expected:

1

Step 6 – reload. Because Prometheus runs with --web.enable-lifecycle, a POST to /-/reload loads the configuration without the pod restarting and losing the data in the emptyDir.

# on rag1
kubectl -n rag exec curl -- curl -s -X POST http://prometheus.rag:9090/-/reload

Expected: no output.

Prometheus itself shows whether the new configuration applies:

# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/status/config > konfig.json
# on rag1
jq -r '.data.yaml' konfig.json > konfig.yml
  • -r – output the text without quotes, so that a readable YAML file results.
# on rag1
grep -A4 metric_relabel_configs konfig.yml
  • -A4 – the matching line and the 4 lines after it.

Expected:

  metric_relabel_configs:
  - source_labels: [__name__]
    separator: ;
    regex: cnpg_pg_settings_setting
    replacement: $1

Prometheus took over the rule and added default values (separator, replacement).

Step 7 – count right afterwards. 21 seconds after the reload:

# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < serien.promql > serien.json
# on rag1
jq -c '.data.result[] | {job: .metric.job, serien: .value[1]}' serien.json

Expected:

{"job":"qdrant","serien":"393"}
{"job":"pg","serien":"478"}
{"job":null,"serien":"2"}
{"job":"antwort","serien":"242"}

Before you read on – your prediction: Still 478 for pg. Did the rule not work?

Prometheus keeps two numbers of its own for every target: how many values it scraped and how many it stored after the metric_relabel_configs.

# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode 'query=scrape_samples_scraped{job="pg"}' > pg-geholt.json
# on rag1
jq -c '.data.result[] | .value[1]' pg-geholt.json

Expected:

"473"
# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode 'query=scrape_samples_post_metric_relabeling{job="pg"}' > pg-proben.json
# on rag1
jq -c '.data.result[] | .value[1]' pg-proben.json

Expected:

"189"

What you see: The rule works: 473 scraped, 189 stored – 284 fewer. The count still shows 478 because a query looks back up to 5 minutes to see whether a time series still has a value. On reload Prometheus starts the scrape round anew and writes no end marker for the dropped series; they only disappear once their last value is older than 5 minutes.

Step 8 – five minutes later.

# on rag1
kubectl -n rag exec -i curl -- curl -s http://prometheus.rag:9090/api/v1/query \
  --data-urlencode query@- < serien.promql > serien.json
# on rag1
jq -c '.data.result[] | {job: .metric.job, serien: .value[1]}' serien.json

Expected:

{"job":"qdrant","serien":"393"}
{"job":"pg","serien":"194"}
{"job":null,"serien":"2"}
{"job":"antwort","serien":"242"}
# on rag1
kubectl -n rag exec curl -- curl -s http://prometheus.rag:9090/api/v1/status/tsdb > tsdb.json
# on rag1
jq -c '.data.headStats' tsdb.json

Expected:

{"numSeries":2072,"numLabelPairs":582,"chunkCount":2072,"minTime":1796278599444,"maxTime":1796279876898}
# on rag1
kubectl top pod -n rag prometheus-69c6d5f589-v7zgx

Expected:

NAME                          CPU(cores)   MEMORY(bytes)   
prometheus-69c6d5f589-v7zgx   17m          32Mi            

What you see:

Number before after Interpretation
time series pg in queries 478 194 189 stored values plus 5 numbers that Prometheus creates for every target itself (up, scrape_*)
numSeries in the head 2024 2072 the head keeps old series until it writes them into a block – according to the Prometheus docs about every two hours
memory 31 MiB 32 MiB not measurable in this small lab; with a hundred PostgreSQL clusters it would be 28,400 series fewer

The saving is small here, the method is not: first count who delivers the most, then throw away selectively.

Save your progress? Sign up for free

Checkpoint

All pods are running, plus prometheus and the visitor:

# on rag1
kubectl -n rag get pods --field-selector=status.phase=Running

Expected:

NAME                          READY   STATUS    RESTARTS      AGE
antwort-54d5786864-7fhh6      1/1     Running   0             7m
antwort-54d5786864-zt6q8      1/1     Running   0             6m48s
auswertung                    1/1     Running   0             7h48m
besucher                      1/1     Running   0             20m
curl                          1/1     Running   0             7h51m
embed-66bdc7c6c9-rqqpn        1/1     Running   1 (17h ago)   34h
llm-579476976d-6rx9d          1/1     Running   0             14h
pg-1                          1/1     Running   1 (13h ago)   13h
prometheus-69c6d5f589-v7zgx   1/1     Running   0             21m
qdrant-0                      1/1     Running   0             7h50m
qdrant-1                      1/1     Running   0             7h50m

Five targets, all up:

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/targets > ziele.json
# on rag1
jq -c '.data.activeTargets[] | {job: .labels.job, instance: .labels.instance, health}' ziele.json

Expected:

{"job":"antwort","instance":"antwort-54d5786864-7fhh6","health":"up"}
{"job":"antwort","instance":"antwort-54d5786864-zt6q8","health":"up"}
{"job":"pg","instance":"pg-1","health":"up"}
{"job":"qdrant","instance":"qdrant-0","health":"up"}
{"job":"qdrant","instance":"qdrant-1","health":"up"}

Three rules, all without errors:

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/rules > regeln.json
# on rag1
jq -c '.data.groups[].rules[] | {name, health, state}' regeln.json

Expected:

{"name":"AuskunftFindetNichts","health":"ok","state":"inactive"}
{"name":"AuskunftVerwirft","health":"ok","state":"firing"}
{"name":"ZielNichtErreichbar","health":"ok","state":"inactive"}

health: ok means: the expression can be evaluated. AuskunftVerwirft is still firing because the rule looks back 10 minutes and the counter-check of the diagnosis task ran at 06:30:11.

After the 10 minutes have passed you ask the pinboard again:

# on rag1
kubectl -n rag exec curl -- \
  curl -s http://prometheus.rag:9090/api/v1/alerts > alarme.json
# on rag1
jq -c '.data.alerts[] | {alarm: .labels.alertname, state}' alarme.json

Expected: no output – at 06:41:21 the pinboard was empty.

What the visitor saw:

# on rag1
kubectl -n rag logs besucher | grep -c ' 200$'

Expected:

116
# on rag1
kubectl -n rag logs besucher | grep -c -v ' 200$'

Expected:

2

116 times 200 in a good 20 minutes, twice something else. In the lab the author did not look at the two lines before deleting; they fall into the time of the four rollouts of the diagnosis task (compare exit code 52). Look at them with kubectl -n rag logs besucher | grep -v ' 200$' before you delete the visitor.

The visitor keeps the language model busy all the time. For Day 16 you clear it away:

# on rag1
kubectl -n rag delete pod besucher

Expected:

pod "besucher" deleted from rag namespace

The information desk answers:

# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- < ../14/backup.json > backup.json.antwort
# on rag1
jq '{antwort, sekunden}' backup.json.antwort

Expected:

{
  "antwort": "Ein Backup wiederherstellen: Die Sicherungen laufen jede Nacht um 2 Uhr auf den Server sich01. Eine einzelne Datei stellst du mit restic restore latest --include /pfad/zur/datei wieder her. [1]",
  "sekunden": {
    "suche": 0.22,
    "gesamt": 7.89
  }
}

What observing costs:

# on rag1
kubectl top pod -n rag

Expected:

NAME                          CPU(cores)   MEMORY(bytes)   
antwort-54d5786864-7fhh6      3m           18Mi            
antwort-54d5786864-zt6q8      1m           18Mi            
auswertung                    0m           0Mi             
curl                          18m          3Mi             
embed-66bdc7c6c9-rqqpn        379m         2667Mi          
llm-579476976d-6rx9d          8295m        2225Mi          
pg-1                          29m          73Mi            
prometheus-69c6d5f589-v7zgx   16m          32Mi            
qdrant-0                      27m          109Mi           
qdrant-1                      22m          324Mi           

What you see: Prometheus after a good 20 minutes with five targets: 16 millicores, 32 MiB. The language model is still computing the last question. Prometheus stays in place for Day 16.

Test yourself

  1. Why does curl http://antwort.rag/metrics sometimes show only zeros although the service has answered questions?
  2. You want to know which department asks how often. Why does the header X-Mandant still not belong on antwort_fragen_total as a label?
  3. The information desk needs around 11 seconds on average. Where do you start to make it faster – and where not?
  4. After a change the visitor gets only 200, and the answers come faster than before. How do you recognise that something is broken anyway?
  5. Why did AuskunftVerwirft stay silent in the diagnosis task although an answer was discarded?
  6. The challenge threw away 284 time series per scrape. Why did the count right afterwards still show 478?

Answers:

  1. Every pod keeps its own tally sheet in memory. The Service sends the request to one pod; if that was the pod that had not received a question yet, it shows zeros. That is why Prometheus asks every pod individually and adds them up with sum.
  2. The value comes from the client and can be chosen freely: every new value creates new time series, a script with random values bloats Prometheus. On top of that comes data protection: whatever is stored as a label appears in every query and every dashboard. Label values therefore only come from a fixed list in the code.
  3. At the language model: llm_prompt (4.1 s) and llm_antwort (6.7 s) make up a good 95 %. Fewer or shorter cards reduce the reading time, shorter answers the writing time. Optimising embedding (0.38 s) and search (0.025 s) would bring almost nothing.
  4. By the share of “no card” (from 12.5 % to 90 %) and by the score distribution tipping to the left (36 of 48 questions below 0.1). The information desk only gets faster because the language model is not asked at all any more.
  5. The counter verworfen only appeared with the first discard and started at 1. increase() measures the increase between the values in the window; 1, 1, 1 is no increase. Only since all results are created with 0 at start does the rule see the jump from 0 to 1.
  6. On reloading the configuration Prometheus restarts the scrape loops and sets no end marker for the dropped series. They are therefore still counted as long as a query looks back – 5 minutes. Right after the reload scrape_samples_post_metric_relabeling already showed that only 189 of 473 values were being stored.

Interview note

“How do you monitor a RAG application in operation?” – On three levels. First the building blocks: Qdrant and CloudNativePG ship Prometheus metrics; for Qdrant /metrics needs an API key, for CNPG the NetworkPolicy has to open port 9187. Second the latency per stage as a histogram. In our CPU setup a good 95 % went to the language model, almost 40 % of that to reading the prompt – the measurement showed that less context brings more than a faster embedding. Third the quality: result counters with fixed label values (answer, no card, discarded, timeout), the best retrieval score per request as a histogram, and alert rules on top. The most important case: a wrong embedding model delivers 100 % HTTP 200, only the share of “no card” jumps from 12.5 % to 90 % – only a metric sees that. Question text, user IDs and IP addresses never go into labels; I create counters with 0 at start, otherwise increase() does not see the first event.

Enterprise note

In operation Prometheus does not run as a single pod with emptyDir: data lives on a PersistentVolume, often with two replicas and long-term storage (Thanos, Mimir, VictoriaMetrics). The Prometheus Operator or kube-prometheus-stack replaces the hand-made pod discovery with ServiceMonitor and PodMonitor; CloudNativePG brings an option for that. Alerts go to an Alertmanager that groups, silences and forwards to on-call, chat or ticket; for the error from Drill 6 a runbook belongs in the annotation. Grafana shows the same queries as a dashboard – with its own login and its own permissions, because metrics also allow conclusions. Expensive queries like histogram_quantile over many pods are precomputed as recording rules. For quality many teams additionally rely on samples: a share of the questions with answers is stored and rated by humans – with consent, deletion period and separate from the metrics. Logs with question text are personal data and need the same rules.

Summary

  • Qdrant delivers 52 metrics under /metrics, but only with a key; the paths are templates ({collection_name}), so that the number of time series stays small.
  • The answer service now counts itself: results, duration of each stage, tokens, best score – in the Prometheus text format, without a library, without question text, users or addresses in the labels. Each pod counts on its own.
  • One Prometheus pod with three files of configuration finds the pods in the namespace by itself. It cost 15 to 16 millicores and 29 to 32 MiB. For PostgreSQL it needed a door in the fence on port 9187.
  • Latency: sign 0.018 s, embedding 0.38 s, search 0.025 s, language model reading 4.1 s and writing 6.7 s on average; 9.1 tokens per second. Rerank is off and has no measurement.
  • Quality in normal operation: 12.5 % without a card, best scores mostly between 0.42 and 0.6, no discarded answer.
  • The wrong model from Day 13 delivered only 200 and faster answers. The rule AuskunftFindetNichts was pending 38 seconds later, firing a minute after that, and disappeared by itself after the correction.
  • A counter without a start value makes an alert rule blind; with all results at 0, AuskunftVerwirft fired at once.
  • One line of metric_relabel_configs threw away 284 of 473 PostgreSQL values per scrape – settings that never change.

Commands at a glance

Command what it does important options
curl -H 'Authorization: Bearer <key>' …:6333/metrics metrics of Qdrant with key -K <file>
curl …/metrics + grep '^# TYPE' which metrics a service publishes -c to count
kubectl create configmap <name> --from-file=<file> configuration as ConfigMap --from-file several times
curl …:9090/api/v1/targets targets of Prometheus with state and error –
curl …:9090/api/v1/query --data-urlencode query@- PromQL query from a file query=… directly
rate(x_total[5m]), increase(x_total[5m]) increase per second / in the window window ≥ 4 × scrape
sum by (label) (…) add up across pods, separated by label without
histogram_quantile(0.95, sum by (le) (rate(x_bucket[5m]))) 95th percentile from a histogram le must stay
x_total[5m] raw values in the window –
curl …:9090/api/v1/alerts, …/api/v1/rules alerts and rules with state –
curl -X POST …:9090/-/reload reload the configuration needs --web.enable-lifecycle
curl …:9090/api/v1/status/tsdb number of time series in memory –
kubectl logs <pod> --since=60s only the last minute --prefix, -l
kubectl top pod -n <ns> CPU and memory per pod --containers

Contents

More