Skip to content
RAG infrastructure on Kubernetes · Chapter 11 of 20 Day 10: Load and Latency Budget

Day 10: Load and Latency Budget

Goal: Measure what happens to the answer service when many questions come in – which stage slows things down, how long users wait, when memory runs out – and set up the desk so that in a rush it honestly says “come back later” instead of making everyone wait · Duration: approx. 150 min · Prerequisite: Day 9

State before this chapter

# on rag1
kubectl -n rag get deployment

Expected:

NAME      READY   UP-TO-DATE   AVAILABLE   AGE
antwort   1/1     1            1           89m
embed     1/1     1            1           20h
llm       1/1     1            1           92m
rerank    0/0     0            0           161m

Your age will be different. Embedding service, language model and answer service are running, the reranker has been at zero replicas since Day 9. If llm or antwort is not at 1/1, apply the manifests from ~/kurs/09 once more.

# on rag1
kubectl -n rag get pod curl qdrant-0

Expected: both 1/1 Running.

Note on the numbers: The measurements in this chapter ran on a rag1 with 12 vCPU and 12 GB of memory. With the 4 vCPU from Day 0 everything works the same way, but reading the prompt takes about twice as long (on Day 9 around 40 instead of around 65 tokens per second here). The pattern – where things get tight and why – stays the same. How many cores your VM has is shown by nproc in Drill 1.

Introduction

On Day 9 you asked one question and measured to the second where the time goes. In operation a question rarely comes alone. Twenty people in the building read the same circular email, and five of them ask the assistant in the same minute. What happens then?

Today you learn:

  • to build a load test as a job that simulates several users and measures percentiles,
  • why the language model restarts after a few minutes without an error in the log – and how you find the reason,
  • why the waiting time grows linearly with every additional user while the throughput stays the same,
  • why a HorizontalPodAutoscaler on the answer service notices nothing,
  • what more parallelism and a second model replica on the same CPU bring – and what not,
  • how the answer service responds in a rush with 503 and Retry-After instead of making users wait for minutes.

At the end you can say a sentence about your lab such as: “With two simultaneous users the first word stays under 30 seconds, from the third on it does not.” That is a latency budget – and this is exactly the sentence operations teams want to hear before a service goes live.

Background

The picture for today: a rush at the desk

So far there was only ever one visitor at the information desk. Today there is a rush. A queue forms in front of the desk. The person at the desk serves one visitor after the other – she reads his cards, speaks her answer and takes the next one. Whoever stands at the back waits for everyone in front of him.

Four things happen at a full desk, and you measure all four today:

  1. The table fills up. The person at the desk leaves the stacks of cards of the last visitors lying on the table in case someone asks the same thing again. Nobody clears up. At some point the table collapses.
  2. The queue grows. With every visitor who arrives at the same time, the last one waits one answer longer. The person at the desk becomes neither faster nor slower – she manages the same number of answers per minute.
  3. The caretaker looks at the wrong place. He is supposed to open a second desk when it gets full. But he measures how busy the doorman at the entrance is – and the doorman is bored, because he only passes people on.
  4. The queue number. An honest desk only hands out as many queue numbers as it can handle in reasonable time. Whoever does not get one hears “please come back in half a minute” – instead of standing in the queue for a quarter of an hour and then leaving.

The terms

Term Meaning in the picture
Load test program that simulates several users and measures times test visitors with a stopwatch
Simultaneous users how many questions are open at the same time visitors in the queue
Throughput completed questions per minute answers per minute at the desk
Latency time from the question to the first word or to the whole answer waiting time of a visitor
p50, p95 median and 95th percentile: half or 95 of 100 questions were faster “most” and “almost all”
Latency budget promised upper limit, e.g. “first word under 30 s at p95” notice: “waiting time at most …”
Queue requests that have been accepted but not yet processed the queue
Prompt cache prompts that have been read, in the model’s memory stacks of cards on the table
OOMKilled the kernel ends a container that goes over its memory limit the table collapses
Parallelism (OLLAMA_NUM_PARALLEL) how many requests the model processes at the same time serving several visitors at once
HorizontalPodAutoscaler (HPA) increases the replicas of a deployment according to a metric, e.g. CPU caretaker who opens desks
Load shedding reject requests above a limit immediately instead of queuing them no more queue numbers
503 + Retry-After HTTP response “overloaded right now, try again in N seconds” “please come back later”

Remember: A desk with one person at it manages a fixed number of answers per minute. More visitors make the queue longer, not the desk faster.

Drill 1: The load test

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

What you have afterwards: a job that asks the answer service questions and prints percentiles, and a baseline – the times with a single user.

Why a job of its own. You could send ten questions at the same time by hand with curl. But then you measure on rag1, where the language model also computes, and your measurement steals computing time from the model. A job in the cluster goes through http://antwort.rag like any other user, the scheduler places it on the node with free CPU (in the lab rag2), and the result is in the log even if your SSH session drops.

Step 1 – how many cores. The number of cores determines how fast the model reads the prompt.

# on rag1
nproc

Expected:

12

Yours shows 4 here if you created rag1 as on Day 0. Then your reading times are about twice as long as in the book.

Step 2 – how full the nodes are.

# on rag1
kubectl top node

Expected:

NAME   CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)   
rag1   1367m        11%      3200Mi          25%         
rag2   395m         19%      616Mi           7%          

What you see: Both nodes have room to spare. This line is your starting point – if something gets slower later, you know it was not because of other services.

Step 3 – the folder for today.

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

Step 4 – the questions. Every load test needs new questions. You saw why on Day 9: a question whose prompt is still in the cache starts after less than a second – a load test with nothing but repetitions measures the cache, not the model. The file has 60 questions; every run today takes a different slice.

# on rag1
nano lastfragen.json
~/kurs/10/lastfragen.json new file
[
  {"id": "l01", "frage": "Wie groß darf ein Secret höchstens sein?"},
  {"id": "l02", "frage": "Wird eine als Volume eingehängte ConfigMap automatisch aktualisiert?"},
  {"id": "l03", "frage": "Wie verhindere ich, dass eine ConfigMap versehentlich geändert wird?"},
  {"id": "l04", "frage": "Was muss ein Pod erfüllen, damit er die QoS-Klasse Guaranteed bekommt?"},
  {"id": "l05", "frage": "Wozu dient eine Startup-Probe?"},
  {"id": "l06", "frage": "Wie lange wartet Kubernetes beim Beenden eines Pods, bevor es die Container hart beendet?"},
  {"id": "l07", "frage": "Welche Phasen kann ein Pod haben?"},
  {"id": "l08", "frage": "Wie halte ich Pods von einem bestimmten Node fern?"},
  {"id": "l09", "frage": "Was passiert mit den Pods, wenn ein Node nicht mehr erreichbar ist?"},
  {"id": "l10", "frage": "Wie hinterlege ich Zugangsdaten für eine private Container-Registry?"},
  {"id": "l11", "frage": "Der Drucker druckt nicht mehr. Was soll ich tun?"},
  {"id": "l12", "frage": "Wie komme ich von zu Hause ins Firmennetz?"},
  {"id": "l13", "frage": "Was bedeutet die Pod-Phase Pending?"},
  {"id": "l14", "frage": "Was ist der Unterschied zwischen Liveness- und Readiness-Probe?"},
  {"id": "l15", "frage": "Welche Arten von Secrets gibt es?"},
  {"id": "l16", "frage": "Wie lege ich ein Secret für Basic Authentication an?"},
  {"id": "l17", "frage": "Was ist eine Toleration?"},
  {"id": "l18", "frage": "Welche Effekte kann ein Taint haben?"},
  {"id": "l19", "frage": "Was bedeutet NoExecute bei einem Taint?"},
  {"id": "l20", "frage": "Wann bekommt ein Pod die QoS-Klasse BestEffort?"},
  {"id": "l21", "frage": "Wann ist ein Pod Burstable?"},
  {"id": "l22", "frage": "Wie kann ich ConfigMaps als Umgebungsvariablen nutzen?"},
  {"id": "l23", "frage": "Was passiert, wenn ein Container im Pod abstürzt?"},
  {"id": "l24", "frage": "Was ist ein Init-Container?"},
  {"id": "l25", "frage": "Wie werden Secrets im etcd gespeichert?"},
  {"id": "l26", "frage": "Kann ich ein Secret unveränderlich machen?"},
  {"id": "l27", "frage": "Was macht die restartPolicy eines Pods?"},
  {"id": "l28", "frage": "Wie beantrage ich Urlaub?"},
  {"id": "l29", "frage": "Wer genehmigt meinen Urlaubsantrag?"},
  {"id": "l30", "frage": "Wie starte ich den Druckdienst neu?"},
  {"id": "l31", "frage": "Wo bekomme ich das VPN-Profil?"},
  {"id": "l32", "frage": "Was ist ein ServiceAccount-Token-Secret?"},
  {"id": "l33", "frage": "Was ist die terminationGracePeriodSeconds?"},
  {"id": "l34", "frage": "Was passiert bei einer Eviction wegen Speichermangel?"},
  {"id": "l35", "frage": "Wie funktioniert Memory QoS mit cgroup v2?"},
  {"id": "l36", "frage": "Was ist ein Pod Disruption Budget?"},
  {"id": "l37", "frage": "Welche Bedingungen kann ein Pod haben?"},
  {"id": "l38", "frage": "Was ist der Unterschied zwischen Opaque und TLS-Secrets?"},
  {"id": "l39", "frage": "Wie lese ich eine ConfigMap in einem Pod als Datei ein?"},
  {"id": "l40", "frage": "Was bedeutet CrashLoopBackOff?"},
  {"id": "l41", "frage": "Wie lange bleibt ein Pod nach dem Beenden im Zustand Terminating?"},
  {"id": "l42", "frage": "Was ist ein Sidecar-Container?"},
  {"id": "l43", "frage": "Wie setze ich ein CPU-Limit für einen Container?"},
  {"id": "l44", "frage": "Was passiert, wenn ein Container sein Speicherlimit überschreitet?"},
  {"id": "l45", "frage": "Wie markiere ich einen Node als nicht planbar?"},
  {"id": "l46", "frage": "Welche Taints setzt Kubernetes automatisch?"},
  {"id": "l47", "frage": "Wie lange toleriert ein Pod standardmäßig einen nicht erreichbaren Node?"},
  {"id": "l48", "frage": "Was ist ein SSH-Auth-Secret?"},
  {"id": "l49", "frage": "Wie groß darf eine ConfigMap sein?"},
  {"id": "l50", "frage": "Kann ein Pod eine ConfigMap aus einem anderen Namespace nutzen?"},
  {"id": "l51", "frage": "Was ist ein Bootstrap-Token-Secret?"},
  {"id": "l52", "frage": "Wann wird eine Readiness-Probe ausgeführt?"},
  {"id": "l53", "frage": "Was bedeutet der Pod-Status Unknown?"},
  {"id": "l54", "frage": "Wie verteile ich Pods auf bestimmte Nodes?"},
  {"id": "l55", "frage": "Was passiert beim Löschen eines Secrets, das ein Pod nutzt?"},
  {"id": "l56", "frage": "Wie oft prüft das Kubelet eine Liveness-Probe?"},
  {"id": "l57", "frage": "Was ist ein Ephemeral Container?"},
  {"id": "l58", "frage": "Wie gebe ich eine ConfigMap als Kommandozeilenargument weiter?"},
  {"id": "l59", "frage": "Wer darf Secrets lesen?"},
  {"id": "l60", "frage": "Was bedeutet PreferNoSchedule?"}
]

Step 5 – the load test. A Python program, again with the standard library only. Every user is a thread that asks its questions one after the other – like a person who only types the next question after the answer. All users start at the same time.

# on rag1
nano last.py
~/kurs/10/last.py new file
"""Lastprobe: mehrere Nutzer stellen gleichzeitig Fragen an den Antwortdienst."""

import json
import os
import threading
import time
import urllib.error
import urllib.request

ZIEL = os.environ.get("ZIEL", "http://antwort.rag/frage")
NUTZER = int(os.environ.get("NUTZER", "1"))
FRAGEN_JE_NUTZER = int(os.environ.get("FRAGEN_JE_NUTZER", "3"))
AB = int(os.environ.get("AB", "0"))
FRAGEN = os.environ.get("FRAGEN", "/lastfragen/lastfragen.json")
TIMEOUT = float(os.environ.get("TIMEOUT", "300"))

ergebnisse = []
sperre = threading.Lock()


def fragen(text):
    """Eine Frage mit Streaming stellen; Zeit bis zum ersten Wort und bis zum Ende messen."""
    start = time.time()
    erstes, status, server = None, "abbruch", {}
    req = urllib.request.Request(
        ZIEL,
        data=json.dumps({"frage": text, "stream": True}).encode(),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT) as antwort:
            for roh in antwort:
                zeile = json.loads(roh)
                if "text" in zeile and erstes is None:
                    erstes = time.time() - start
                if "fehler" in zeile:
                    status = "fehler"
                if "antwort" in zeile:
                    status = "keine Karte"
                if "fertig" in zeile:
                    status, server = "ok", zeile["sekunden"]
    except urllib.error.HTTPError as fehler:
        status = f"http {fehler.code}"
    except TimeoutError:
        status = "timeout"
    return erstes, time.time() - start, status, server


def nutzer(nr, fragenliste, beginn):
    for i in range(FRAGEN_JE_NUTZER):
        text = fragenliste[(AB + nr * FRAGEN_JE_NUTZER + i) % len(fragenliste)]
        ab = time.time() - beginn
        erstes, gesamt, status, server = fragen(text)
        with sperre:
            ergebnisse.append((erstes, gesamt, status))
            print(
                f"n{nr} ab {ab:5.1f} s  erstes {erstes or 0:5.1f} s  gesamt {gesamt:5.1f} s"
                f"  suche {server.get('suche', '-')}  {status}  {text[:40]}",
                flush=True,
            )


def perzentil(werte, p):
    werte = sorted(werte)
    return werte[min(len(werte) - 1, round(p / 100 * (len(werte) - 1)))]


def main():
    with open(FRAGEN, encoding="utf-8") as datei:
        fragenliste = [f["frage"] for f in json.load(datei)]
    beginn = time.time()
    faeden = [
        threading.Thread(target=nutzer, args=(nr, fragenliste, beginn))
        for nr in range(NUTZER)
    ]
    for faden in faeden:
        faden.start()
    for faden in faeden:
        faden.join()
    dauer = time.time() - beginn
    gut = [e for e in ergebnisse if e[2] == "ok"]
    erstes = [e[0] for e in gut if e[0] is not None]
    gesamt = [e[1] for e in gut]
    zusammenfassung = {
        "nutzer": NUTZER,
        "fragen": len(ergebnisse),
        "ok": len(gut),
        "erstes_wort_p50": round(perzentil(erstes, 50), 1) if erstes else None,
        "erstes_wort_p95": round(perzentil(erstes, 95), 1) if erstes else None,
        "gesamt_p50": round(perzentil(gesamt, 50), 1) if gesamt else None,
        "gesamt_p95": round(perzentil(gesamt, 95), 1) if gesamt else None,
        "fragen_je_minute": round(len(gut) / dauer * 60, 1),
        "dauer_s": round(dauer, 1),
    }
    print(json.dumps(zusammenfassung), flush=True)


if __name__ == "__main__":
    main()

The parts:

Lines Part What it does
10–15 Switches target, number of users, questions per user, from which question, file, timeout
21–46 fragen() asks a question with "stream": true, measures the time to the first text line and to the end
36–41 Status ok only if the line fertig arrived; fehler for an error line; keine Karte (no card) for the score threshold
49–60 nutzer() one user: takes his questions from the list and prints a line after each one
51 Question selection user nr gets the questions from AB + nr × FRAGEN_JE_NUTZER on – no user asks what another one asks
63–65 perzentil() sorts the values and takes the one at position p %
68–95 main() starts all users, waits for them and prints the summary as JSON

Two decisions in the code matter for everything that follows:

  • Status abbruch (aborted) as the default. An answer only counts as ok if the final line fertig arrived. If the connection breaks off in the middle, it stays at abbruch. Without this default an aborted answer would be counted as a fast, good answer – and the percentiles would look better the worse things get.
  • Percentiles only over ok. Rejected and aborted questions are counted in fragen, but not in the times. That is why you must always read ok next to fragen.

Step 6 – code and questions into the cluster. As on Day 9, as ConfigMaps that the job mounts as files.

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

Expected:

configmap/last-code created
# on rag1
kubectl -n rag create configmap lastfragen --from-file=lastfragen.json

Expected:

configmap/lastfragen created

Step 7 – the job. One user, six questions, from question 0.

# on rag1
nano last-1.yaml
~/kurs/10/last-1.yaml new file
apiVersion: batch/v1
kind: Job
metadata:
  name: last-1
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: last
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/last.py"]
          env:
            - name: NUTZER
              value: "1"
            - name: FRAGEN_JE_NUTZER
              value: "6"
            - name: AB
              value: "0"
            - name: FRAGEN
              value: /lastfragen/lastfragen.json
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: lastfragen
              mountPath: /lastfragen
      volumes:
        - name: code
          configMap:
            name: last-code
        - name: lastfragen
          configMap:
            name: lastfragen
Setting Value Meaning
backoffLimit 0 if the job fails, do not restart it – a repeated load test would distort the measurement
ttlSecondsAfterFinished 86400 Kubernetes deletes the finished job after one day; until then you can read the log
NUTZER "1" one simultaneous user
FRAGEN_JE_NUTZER "6" six questions one after the other
AB "0" from the first question of the file (l01)
FRAGEN /lastfragen/lastfragen.json where the ConfigMap is mounted
requests.cpu 50m the load test almost only waits; it hardly needs any CPU

The job does not set the value ZIEL (target): the default in the code is http://antwort.rag/frage.

Step 8 – memory of the model before.

# on rag1
kubectl -n rag top pod -l app=llm

Expected:

NAME                  CPU(cores)   MEMORY(bytes)   
llm-bf5f4b584-9qxc2   1m           114Mi           

What you see: The model is idle and uses 114 MiB. The pod has just started; Ollama only loads the model itself with the first question. Remember the number, it plays the leading role in Drill 2.

Step 9 – start the load test.

# on rag1
kubectl apply -f last-1.yaml

Expected:

job.batch/last-1 created

Step 10 – wait until the job is finished. kubectl wait returns as soon as the condition is met and saves you from checking again and again.

# on rag1
kubectl -n rag wait --for=condition=Complete job/last-1 --timeout=900s
  • --for=condition=Complete – wait until the job reports the condition Complete,
  • --timeout=900s – give up after 15 minutes in case something hangs.

Expected (after just under two minutes):

job.batch/last-1 condition met

Step 11 – the result.

# on rag1
kubectl -n rag logs job/last-1

Expected (cut off on the right):

n0 ab   0.0 s  erstes  22.8 s  gesamt  25.0 s  suche 0.27  ok  Wie groß darf ein Secret höchstens sein?
n0 ab  25.0 s  erstes   8.7 s  gesamt  12.4 s  suche 0.62  ok  Wird eine als Volume eingehängte ConfigM
n0 ab  37.4 s  erstes   8.7 s  gesamt  19.8 s  suche 0.36  ok  Wie verhindere ich, dass eine ConfigMap 
n0 ab  57.2 s  erstes   6.9 s  gesamt  19.6 s  suche 0.4  ok  Was muss ein Pod erfüllen, damit er die 
n0 ab  76.8 s  erstes   6.4 s  gesamt  10.8 s  suche 0.45  ok  Wozu dient eine Startup-Probe?
n0 ab  87.6 s  erstes   9.4 s  gesamt  18.8 s  suche 0.31  ok  Wie lange wartet Kubernetes beim Beenden
{"nutzer": 1, "fragen": 6, "ok": 6, "erstes_wort_p50": 8.7, "erstes_wort_p95": 22.8, "gesamt_p50": 18.8, "gesamt_p95": 25.0, "fragen_je_minute": 3.4, "dauer_s": 106.4}

What you see:

Field Value Meaning
ab 0.0 … 87.6 s when the question was asked, counted from the start; a user only asks on after the answer
erstes 6.4 … 22.8 s time to the first word; the first question is slow because Ollama first loads the model into memory
suche 0.27 … 0.62 s embedding and Qdrant together – negligible compared with the model
erstes_wort_p50 8.7 s half of the questions had a first word after 8.7 s
erstes_wort_p95 22.8 s with six values, p95 is the largest – here the cold start
fragen_je_minute 3.4 the throughput with one user

This is your baseline: one user gets the first word after around 7 to 9 seconds and manages a good three questions per minute. The search costs less than a second – the time is in the model.

Step 12 – where in the model. As on Day 9, Ollama writes two lines into the log for every request: how long it read the prompt and how long it wrote the answer.

# on rag1
kubectl -n rag logs deployment/llm | grep 'eval time' | tail -4

Expected (the last two questions):

slot print_timing: id  0 | task 279 | prompt eval time =    5788.29 ms /   374 tokens (   15.48 ms per token,    64.61 tokens per second)
slot print_timing: id  0 | task 279 |        eval time =    4417.11 ms /    61 tokens (   73.62 ms per token,    13.58 tokens per second)
slot print_timing: id  0 | task 341 | prompt eval time =    8820.08 ms /   621 tokens (   14.20 ms per token,    70.41 tokens per second)
slot print_timing: id  0 | task 341 |        eval time =    9422.45 ms /    54 tokens (  177.78 ms per token,     5.62 tokens per second)

What you see: Reading manages 65 to 70 tokens per second; with a prompt of 374 to 621 tokens that is 6 to 9 seconds – exactly the time to the first word. Writing, at 5 to 14 tokens per second, is much slower, but the answers are short. id 0 means: there is exactly one seat at which the model works. That matters in Drill 4.

Step 13 – memory of the model afterwards.

# on rag1
kubectl -n rag top pod -l app=llm

Expected:

NAME                  CPU(cores)   MEMORY(bytes)   
llm-bf5f4b584-9qxc2   11150m       2314Mi          

What you see: Memory has risen from 114 to 2314 MiB. The loaded model with Ollama needs just under 2 GiB, plus a part that grows with every question – Drill 2 shows why. The CPU column still shows the last question: metrics-server averages over a few seconds and lags behind. 11150m means: while the model computes, it occupies almost all twelve cores.

Remember: First the baseline with one user, then load. Without the value “one user, 8.7 seconds” you cannot say later whether 40 seconds is a lot.

Save your progress? Sign up for free

Drill 2: The table fills up

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

What you have afterwards: a restart of the language model that you triggered yourself, and the command with which you find its reason.

What it is about. At the end of Drill 1 the model used 2314 MiB; the limit from Day 9 is 3 GiB (3072 MiB). Does the growth stop after a few questions? A longer test clarifies that: one user, twelve questions in a row. While it runs, you look at memory and prompt cache every half minute.

Step 1 – how large the cache may become. Ollama writes the limit into the log when it loads the model.

# on rag1
kubectl -n rag logs deployment/llm | grep 'size limit'

Expected:

srv    load_model: prompt cache is enabled, size limit: 8192 MiB

What you see: The prompt cache may grow to 8 GiB. The limit of the pod is 3 GiB. The two numbers know nothing about each other: Ollama does not ask how much memory Kubernetes allows it.

Step 2 – how full the table is now.

# on rag1
kubectl -n rag logs deployment/llm | grep 'cache state' | tail -1

Expected:

srv        update:  - cache state: 5 prompts, 332.648 MiB (limits: 8192.000 MiB, 4096 tokens, 74889 est)

What you see: After six questions there are five prompts with 333 MiB in the cache. That is around 66 MiB per prompt.

Step 3 – the long test. The file differs from last-1.yaml only in the name and in three values.

# on rag1
cp last-1.yaml last-lang.yaml
# on rag1
nano last-lang.yaml
~/kurs/10/last-lang.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: last-lang
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: last
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/last.py"]
          env:
            - name: NUTZER
              value: "1"
            - name: FRAGEN_JE_NUTZER
              value: "12"
            - name: AB
              value: "6"
            - name: FRAGEN
              value: /lastfragen/lastfragen.json
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: lastfragen
              mountPath: /lastfragen
      volumes:
        - name: code
          configMap:
            name: last-code
        - name: lastfragen
          configMap:
            name: lastfragen
Setting Value Meaning
name last-lang a new job; the old one stays with its log
FRAGEN_JE_NUTZER "12" twelve questions in a row
AB "6" from question l07 on – Drill 1 has already asked the first six
# on rag1
kubectl apply -f last-lang.yaml

Expected:

job.batch/last-lang created

Step 4 – watch. Run the next three commands every 20 to 30 seconds until something changes in the column RESTARTS. You do not need a loop for this – the up arrow key brings back the last command.

# on rag1
kubectl -n rag top pod -l app=llm
# on rag1
kubectl -n rag logs deployment/llm | grep 'cache state' | tail -1
# on rag1
kubectl -n rag get pod -l app=llm

Expected – this is how it looked in the lab (collected from the output of the three commands):

Time Memory (top) Cache (cache state) RESTARTS
14:13:48 2397 MiB 7 prompts, 494 MiB 0
14:14:16 2623 MiB 9 prompts, 641 MiB 0
14:14:44 2733 MiB 10 prompts, 750 MiB 0
14:15:11 2733 MiB 12 prompts, 882 MiB 0
14:15:39 2865 MiB 13 prompts, 953 MiB 0
14:16:06 2997 MiB 15 prompts, 1085 MiB 0
14:16:33 – – 1

The last line verbatim:

$ kubectl -n rag top pod -l app=llm
error: Metrics not available for pod rag/llm-bf5f4b584-9qxc2, age: 5m50.440871558s
$ kubectl -n rag logs deployment/llm | grep 'cache state' | tail -1
$ kubectl -n rag get pod -l app=llm
NAME                  READY   STATUS    RESTARTS      AGE
llm-bf5f4b584-9qxc2   1/1     Running   1 (17s ago)   5m51s

What you see: With every question a prompt lands on the table, a good 65 MiB each time. At just under 3000 MiB – the limit is 3072 – RESTARTS counts up to 1. The cache command no longer prints anything: the log now belongs to the new container, and it has not seen a question yet.

Step 5 – what the users noticed.

# on rag1
kubectl -n rag wait --for=condition=Complete job/last-lang --timeout=900s

Expected:

job.batch/last-lang condition met
# on rag1
kubectl -n rag logs job/last-lang

Expected (cut off on the right):

n0 ab   0.0 s  erstes  10.5 s  gesamt  12.5 s  suche 0.49  ok  Welche Phasen kann ein Pod haben?
n0 ab  12.5 s  erstes   9.0 s  gesamt  14.4 s  suche 0.32  ok  Wie halte ich Pods von einem bestimmten 
n0 ab  26.9 s  erstes   6.5 s  gesamt  10.6 s  suche 0.43  ok  Was passiert mit den Pods, wenn ein Node
n0 ab  37.5 s  erstes  12.0 s  gesamt  32.0 s  suche 0.36  ok  Wie hinterlege ich Zugangsdaten für eine
n0 ab  69.5 s  erstes   8.6 s  gesamt  19.0 s  suche 0.33  ok  Der Drucker druckt nicht mehr. Was soll 
n0 ab  88.5 s  erstes   6.1 s  gesamt  11.4 s  suche 0.52  ok  Wie komme ich von zu Hause ins Firmennet
n0 ab  99.9 s  erstes   7.1 s  gesamt  16.4 s  suche 0.35  ok  Was bedeutet die Pod-Phase Pending?
n0 ab 116.3 s  erstes   6.7 s  gesamt  20.3 s  suche 0.63  ok  Was ist der Unterschied zwischen Livenes
n0 ab 136.6 s  erstes   6.8 s  gesamt  14.8 s  suche 0.35  ok  Welche Arten von Secrets gibt es?
n0 ab 151.4 s  erstes  10.0 s  gesamt  20.1 s  suche 0.28  ok  Wie lege ich ein Secret für Basic Authen
n0 ab 171.5 s  erstes   0.0 s  gesamt   0.8 s  suche -  abbruch  Was ist eine Toleration?
n0 ab 172.3 s  erstes   0.0 s  gesamt   0.4 s  suche -  abbruch  Welche Effekte kann ein Taint haben?
{"nutzer": 1, "fragen": 12, "ok": 10, "erstes_wort_p50": 7.1, "erstes_wort_p95": 12.0, "gesamt_p50": 14.8, "gesamt_p95": 32.0, "fragen_je_minute": 3.5, "dauer_s": 172.6}

What you see: Ten questions went well, the eleventh and twelfth broke off after less than a second. The summary still looks friendly – p95 12.0 seconds – because aborted questions are not included in the percentiles. This shows why ok stands next to fragen: 10 of 12.

Step 6 – the reason. The model’s log shows no error; the process was ended from outside. Kubernetes knows the reason.

# on rag1
kubectl -n rag describe pod -l app=llm

Expected (excerpt – look for the section Last State):

    State:          Running
      Started:      Wed, 02 Dec 2026 14:16:19 +0000
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137
      Started:      Wed, 02 Dec 2026 14:10:45 +0000
      Finished:     Wed, 02 Dec 2026 14:16:18 +0000
    Ready:          True
    Restart Count:  1
    Limits:
      memory:  3Gi

What you see:

Line Value Meaning
Last State: Terminated – the previous container was ended
Reason OOMKilled the kernel ended it because it went over its memory limit
Exit Code 137 128 + 9: ended with signal 9 (SIGKILL) – the process could not write anything more into the log
Finished 14:16:18 matches the table from Step 4
Limits: memory 3Gi the limit the cache ran into

Step 7 – what the answer service got out of it.

# on rag1
kubectl -n rag logs deployment/antwort --tail=30

Expected (excerpt – look for the lines with /code/antwort.py):

  File "/code/antwort.py", line 156, in strom
    with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
         ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/code/antwort.py", line 38, in anfrage
    return urllib.request.urlopen(req, timeout=timeout)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^

and at the very bottom:

urllib.error.URLError: <urlopen error [Errno 111] Connection refused>
----------------------------------------

What you see: While the model was restarting, it refused connections. The answer service from Day 9 catches timeouts, but not a refused connection – it writes a traceback into the log and closes the connection without an error line. That is why the load test shows abbruch and not fehler. You fix this in Drill 6.

Remember: OOMKilled never appears in the container’s log, but in kubectl describe pod under Last State. A cache that knows its own limit but not that of the container grows until the kernel clears up.

Save your progress? Sign up for free

Drill 3: Limiting the table

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

What you have afterwards: a language model whose prompt cache grows to at most 256 MiB – and thus stays below the memory limit of the pod.

What it is about. Drill 2 showed: the cache may grow to 8192 MiB, the pod only to 3072 MiB. You have two options. Either you give the pod as much memory as the cache may grow to – 8 GiB for a model that itself needs just under 2 GiB. Or you tell the cache how large it may become. In the picture: not buying a bigger table, but deciding that at most three or four stacks of cards stay on it and the oldest one is cleared away.

Ollama passes settings that begin with LLAMA_ARG_ on to the built-in llama.cpp server. LLAMA_ARG_CACHE_RAM is the upper limit of the prompt cache in MiB.

Step 1 – fetch the manifest from Day 9.

# on rag1
cp ~/kurs/09/llm.yaml llm.yaml

Step 2 – enter the limit.

# on rag1
nano llm.yaml
~/kurs/10/llm.yaml changes in green
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: llm-modell
  namespace: rag
spec:
  accessModes: ["ReadWriteOnce"]
  storageClassName: local-path
  resources:
    requests:
      storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: llm
  namespace: rag
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: llm
  template:
    metadata:
      labels:
        app: llm
    spec:
      nodeSelector:
        kubernetes.io/hostname: rag1
      containers:
        - name: ollama
          image: ollama/ollama:0.40.19
          env:
            - name: OLLAMA_KEEP_ALIVE
              value: "-1"
            - name: LLAMA_ARG_CACHE_RAM
              value: "256"
          ports:
            - containerPort: 11434
          resources:
            requests:
              cpu: 1500m
              memory: 2Gi
            limits:
              memory: 3Gi
          readinessProbe:
            httpGet:
              path: /api/version
              port: 11434
            periodSeconds: 5
          volumeMounts:
            - name: modell
              mountPath: /root/.ollama
      volumes:
        - name: modell
          persistentVolumeClaim:
            claimName: llm-modell
---
apiVersion: v1
kind: Service
metadata:
  name: llm
  namespace: rag
spec:
  selector:
    app: llm
  ports:
    - port: 11434
      targetPort: 11434
Setting Value Meaning
LLAMA_ARG_CACHE_RAM "256" the prompt cache grows to at most 256 MiB; the oldest entry goes first
limits.memory 3Gi stays as on Day 9 – model (a good 2 GiB) and cache (0.25 GiB) now fit in

256 MiB is enough for three to four prompts of the size from Drill 2 (around 66 MiB). That is enough for a follow-up question in the same conversation to still hit the cache.

Step 3 – apply.

# on rag1
kubectl apply -f llm.yaml

Expected:

persistentvolumeclaim/llm-modell unchanged
deployment.apps/llm configured
service/llm unchanged
# on rag1
kubectl -n rag rollout status deployment/llm --timeout=300s

Expected:

Waiting for deployment "llm" rollout to finish: 0 of 1 updated replicas are available...
deployment "llm" successfully rolled out

Step 4 – check the new limit. Ollama only writes the line size limit when it loads the model – that is, with the first question. Directly after the rollout the command therefore prints nothing. Run it again in Drill 4 after the first load test.

# on rag1
kubectl -n rag logs deployment/llm | grep 'size limit'

Expected (after the first question):

srv    load_model: prompt cache is enabled, size limit: 256 MiB

What you see: 256 MiB now instead of 8192. You read off how this works out under load at the end of Drill 4.

Remember: Every piece of software with its own cache has its own idea of how much memory it has. Set the cache’s limit below the container’s limit – not the other way round.

Save your progress? Sign up for free

Drill 4: The queue grows

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

What you have afterwards: measurements with two and four simultaneous users, a HorizontalPodAutoscaler that does nothing, and the explanation for it.

What it is about. With one user the first word came after 8.7 seconds (p50). What happens with two and with four users? And can Kubernetes counteract on its own? You try the second part with the tool that is meant for it: a HorizontalPodAutoscaler (HPA) on the answer service.

Step 1 – two users. Again a copy of the job file, this time four values change.

# on rag1
cp last-1.yaml last-2.yaml
# on rag1
nano last-2.yaml
~/kurs/10/last-2.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: last-2
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: last
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/last.py"]
          env:
            - name: NUTZER
              value: "2"
            - name: FRAGEN_JE_NUTZER
              value: "3"
            - name: AB
              value: "18"
            - name: FRAGEN
              value: /lastfragen/lastfragen.json
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: lastfragen
              mountPath: /lastfragen
      volumes:
        - name: code
          configMap:
            name: last-code
        - name: lastfragen
          configMap:
            name: lastfragen
Setting Value Meaning
name last-2 new job
NUTZER "2" two users ask at the same time
FRAGEN_JE_NUTZER "3" three questions each, six together – as many as in Drill 1
AB "18" from question l19 on; Drills 1 and 2 have already asked l01 to l18
# on rag1
kubectl apply -f last-2.yaml

Expected:

job.batch/last-2 created
# on rag1
kubectl -n rag wait --for=condition=Complete job/last-2 --timeout=900s

Expected (after around two minutes):

job.batch/last-2 condition met
# on rag1
kubectl -n rag logs job/last-2

Expected (cut off on the right):

n0 ab   0.0 s  erstes  19.5 s  gesamt  27.8 s  suche 0.21  ok  Was bedeutet NoExecute bei einem Taint?
n1 ab   0.0 s  erstes  39.0 s  gesamt  51.7 s  suche 0.56  ok  Wie kann ich ConfigMaps als Umgebungsvar
n0 ab  27.8 s  erstes  32.9 s  gesamt  40.5 s  suche 3.55  ok  Wann bekommt ein Pod die QoS-Klasse Best
n1 ab  51.7 s  erstes  24.9 s  gesamt  32.8 s  suche 3.28  ok  Was passiert, wenn ein Container im Pod 
n0 ab  68.3 s  erstes  24.9 s  gesamt  33.3 s  suche 2.46  ok  Wann ist ein Pod Burstable?
n1 ab  84.6 s  erstes  25.6 s  gesamt  31.5 s  suche 3.55  ok  Was ist ein Init-Container?
{"nutzer": 2, "fragen": 6, "ok": 6, "erstes_wort_p50": 24.9, "erstes_wort_p95": 39.0, "gesamt_p50": 32.8, "gesamt_p95": 51.7, "fragen_je_minute": 3.1, "dauer_s": 116.1}

What you see: The first two questions both start at 0.0 seconds. n0 gets the first word after 19.5 seconds, n1 only after 39.0 – n1 waited until n0 was finished. The median of the first word rises from 8.7 to 24.9 seconds, the throughput stays at a good three questions per minute. The search also gets slower (up to 3.55 instead of under 1 second): the embedding service computes on the same CPU as the model.

Step 2 – the caretaker. An HPA watches a metric and changes the number of replicas.

# on rag1
nano hpa.yaml
~/kurs/10/hpa.yaml new file
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: antwort
  namespace: rag
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: antwort
  minReplicas: 1
  maxReplicas: 4
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 50
Setting Value Meaning
scaleTargetRef Deployment antwort which deployment the HPA scales
minReplicas 1 never fewer than one replica
maxReplicas 4 never more than four
metrics[0].resource.name cpu it watches the CPU
averageUtilization 50 target: on average 50 % of the CPU request (requests.cpu) of each pod; above that it scales up

This is the HPA you see in every Kubernetes tutorial. You apply it and let four users come.

# on rag1
kubectl apply -f hpa.yaml

Expected:

horizontalpodautoscaler.autoscaling/antwort created

Step 3 – four users.

# on rag1
cp last-2.yaml last-4.yaml
# on rag1
nano last-4.yaml
~/kurs/10/last-4.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: last-4
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: last
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/last.py"]
          env:
            - name: NUTZER
              value: "4"
            - name: FRAGEN_JE_NUTZER
              value: "3"
            - name: AB
              value: "24"
            - name: FRAGEN
              value: /lastfragen/lastfragen.json
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: lastfragen
              mountPath: /lastfragen
      volumes:
        - name: code
          configMap:
            name: last-code
        - name: lastfragen
          configMap:
            name: lastfragen
Setting Value Meaning
name last-4 new job
NUTZER "4" four users at the same time, three questions each – twelve questions
AB "24" from question l25 on
# on rag1
kubectl apply -f last-4.yaml

Expected:

job.batch/last-4 created

Step 4 – look in the middle of the load. Wait about one minute so that metrics-server has values.

# on rag1
kubectl top pod -n rag

Expected (after a good minute; your names will be different):

NAME                       CPU(cores)   MEMORY(bytes)   
antwort-7fccd97f7d-tdsfg   3m           25Mi            
curl                       0m           0Mi             
embed-66bdc7c6c9-rqqpn     1732m        1536Mi          
last-4-wrrjk               1m           20Mi            
llm-579476976d-tfzfg       10151m       2170Mi          
pg-1                       22m          55Mi            
qdrant-0                   10m          63Mi            
# on rag1
kubectl -n rag get hpa antwort

Expected:

NAME      REFERENCE            TARGETS       MINPODS   MAXPODS   REPLICAS   AGE
antwort   Deployment/antwort   cpu: 3%/50%   1         4         1          77s

What you see:

Pod CPU Meaning
llm-… 10151m the model occupies around ten of the twelve cores – this is the bottleneck
embed-… 1732m the embedding service embeds the users’ questions
antwort-… 3m the answer service almost only waits – for Qdrant, for the model
HPA TARGETS 3%/50% 3 % of the request; far below the target, so no second replica

The caretaker is looking at the doorman. The doorman is bored while the queue behind him grows.

Step 5 – the result of the four users.

# on rag1
kubectl -n rag wait --for=condition=Complete job/last-4 --timeout=900s

Expected:

job.batch/last-4 condition met
# on rag1
kubectl -n rag logs job/last-4

Expected (cut off on the right):

n0 ab   0.0 s  erstes  14.1 s  gesamt  16.4 s  suche 0.45  ok  Wie werden Secrets im etcd gespeichert?
n1 ab   0.0 s  erstes  23.5 s  gesamt  30.3 s  suche 0.78  ok  Wie beantrage ich Urlaub?
n2 ab   0.0 s  erstes  39.5 s  gesamt  41.9 s  suche 4.69  ok  Wo bekomme ich das VPN-Profil?
n3 ab   0.0 s  erstes  53.0 s  gesamt  64.4 s  suche 8.32  ok  Was passiert bei einer Eviction wegen Sp
n0 ab  16.4 s  erstes  56.5 s  gesamt  67.9 s  suche 3.69  ok  Kann ich ein Secret unveränderlich mache
n1 ab  30.3 s  erstes   0.0 s  gesamt  63.6 s  suche -  fehler  Wer genehmigt meinen Urlaubsantrag?
n2 ab  41.9 s  erstes   0.0 s  gesamt  60.9 s  suche -  fehler  Was ist ein ServiceAccount-Token-Secret?
n2 ab 102.8 s  erstes   0.0 s  gesamt   4.9 s  suche -  keine Karte  Was ist die terminationGracePeriodSecond
n3 ab  64.4 s  erstes  51.1 s  gesamt  60.3 s  suche 0.41  ok  Wie funktioniert Memory QoS mit cgroup v
n0 ab  84.3 s  erstes  50.6 s  gesamt  60.9 s  suche 3.66  ok  Was macht die restartPolicy eines Pods?
n1 ab  94.0 s  erstes  58.7 s  gesamt  69.0 s  suche 4.8  ok  Wie starte ich den Druckdienst neu?
n3 ab 124.7 s  erstes  46.1 s  gesamt  55.1 s  suche 3.44  ok  Was ist ein Pod Disruption Budget?
{"nutzer": 4, "fragen": 12, "ok": 9, "erstes_wort_p50": 50.6, "erstes_wort_p95": 58.7, "gesamt_p50": 60.3, "gesamt_p95": 69.0, "fragen_je_minute": 3.0, "dauer_s": 179.9}

What you see: The four first questions get their first word after 14, 24, 40 and 53 seconds – a staircase, one step per user ahead of you. Two questions end after a good 60 seconds with fehler: that is LLM_TIMEOUT from Day 9. The answer service gives up if the model has not answered after one minute – even if the question was only standing in the queue. One question finds no card above the threshold; that has nothing to do with the load.

The three runs side by side:

Users ok / questions first word p50 first word p95 questions per minute
1 6 / 6 8.7 s 22.8 s (cold start) 3.4
2 6 / 6 24.9 s 39.0 s 3.1
4 9 / 12 50.6 s 58.7 s 3.0

The desk manages three questions per minute – no matter how many come. Every additional user lengthens the waiting time by one answer.

Step 6 – why the HPA did nothing.

# on rag1
kubectl -n rag describe hpa antwort

Expected (excerpt):

Metrics:                                               ( current / target )
  resource cpu on pods  (as a percentage of request):  4% (4m) / 50%
Min replicas:                                          1
Max replicas:                                          4
Deployment pods:                                       1 current / 1 desired
Conditions:
  Type            Status  Reason              Message
  ----            ------  ------              -------
  AbleToScale     True    ReadyForNewScale    recommended size matches current size
  ScalingActive   True    ValidMetricFound    the HPA was able to successfully calculate a replica count from cpu resource utilization (percentage of request)

What you see: The HPA works perfectly (ValidMetricFound) – it just has nothing to do. 4 millicores are 4 % of the request. Even if it scaled up: four answer services would all pass on to the same model. The queue would only stand in a different place.

Step 7 – where the queue really stands. The model has exactly one seat.

# on rag1
kubectl -n rag logs deployment/llm | grep n_seq_max

Expected:

llama_context: n_seq_max             = 1

What you see: n_seq_max = 1 – the model processes one sequence at a time. All other requests wait in Ollama. That is the queue in front of the desk.

Step 8 – and the table? The cache from Drill 3 under load:

# on rag1
kubectl -n rag logs deployment/llm | grep 'cache state' | tail -1

Expected:

srv        update:  - cache state: 3 prompts, 216.368 MiB (limits: 256.000 MiB, 4096 tokens, 4096 est)
# on rag1
kubectl -n rag top pod -l app=llm

Expected:

NAME                   CPU(cores)   MEMORY(bytes)   
llm-579476976d-tfzfg   11752m       2198Mi          

What you see: After 18 more questions there are only three prompts in the cache, 216 of 256 MiB. The memory of the pod stays at 2198 MiB – in Drill 2 it was almost 3000 after 15 questions. The table stays tidy.

Step 9 – dismiss the caretaker again. He does not help here; he should not cause confusion later.

# on rag1
kubectl -n rag delete -f hpa.yaml

Expected:

horizontalpodautoscaler.autoscaling "antwort" deleted from rag namespace

Remember: Scale the bottleneck, not the service that is easiest to scale. An HPA on CPU only sees who is computing – not who is waiting.

Save your progress? Sign up for free

Drill 5: More seats, more desks

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

What you have afterwards: two measurements that show what does not help on the same CPU – and why.

What it is about. If the model has only one seat, two ideas suggest themselves:

  1. More seats at the same desk. OLLAMA_NUM_PARALLEL=4 – the model serves four questions at the same time.
  2. A second desk. Two replicas of the model.

You try both. Both sound like more throughput. The measurement decides.

Part A: four seats

Step 1 – enter four seats.

# on rag1
nano llm.yaml
~/kurs/10/llm.yaml changes in green
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: llm-modell
  namespace: rag
spec:
  accessModes: ["ReadWriteOnce"]
  storageClassName: local-path
  resources:
    requests:
      storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: llm
  namespace: rag
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: llm
  template:
    metadata:
      labels:
        app: llm
    spec:
      nodeSelector:
        kubernetes.io/hostname: rag1
      containers:
        - name: ollama
          image: ollama/ollama:0.40.19
          env:
            - name: OLLAMA_KEEP_ALIVE
              value: "-1"
            - name: OLLAMA_NUM_PARALLEL
              value: "4"
            - name: LLAMA_ARG_CACHE_RAM
              value: "256"
          ports:
            - containerPort: 11434
          resources:
            requests:
              cpu: 1500m
              memory: 2Gi
            limits:
              memory: 3Gi
          readinessProbe:
            httpGet:
              path: /api/version
              port: 11434
            periodSeconds: 5
          volumeMounts:
            - name: modell
              mountPath: /root/.ollama
      volumes:
        - name: modell
          persistentVolumeClaim:
            claimName: llm-modell
---
apiVersion: v1
kind: Service
metadata:
  name: llm
  namespace: rag
spec:
  selector:
    app: llm
  ports:
    - port: 11434
      targetPort: 11434
Setting Value Meaning
OLLAMA_NUM_PARALLEL "4" up to four requests in the model at the same time
# on rag1
kubectl apply -f llm.yaml

Expected:

persistentvolumeclaim/llm-modell unchanged
deployment.apps/llm configured
service/llm unchanged
# on rag1
kubectl -n rag rollout status deployment/llm --timeout=300s

Expected (last line):

deployment "llm" successfully rolled out

Step 2 – four users.

# on rag1
cp last-4.yaml last-4p.yaml
# on rag1
nano last-4p.yaml
~/kurs/10/last-4p.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: last-4p
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: last
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/last.py"]
          env:
            - name: NUTZER
              value: "4"
            - name: FRAGEN_JE_NUTZER
              value: "3"
            - name: AB
              value: "36"
            - name: FRAGEN
              value: /lastfragen/lastfragen.json
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: lastfragen
              mountPath: /lastfragen
      volumes:
        - name: code
          configMap:
            name: last-code
        - name: lastfragen
          configMap:
            name: lastfragen
# on rag1
kubectl apply -f last-4p.yaml

Expected:

job.batch/last-4p created

Step 3 – check after a minute and a half.

# on rag1
kubectl -n rag get pod -l app=llm

Expected:

NAME                   READY   STATUS    RESTARTS      AGE
llm-68656ff484-dct9g   1/1     Running   1 (78s ago)   98s
# on rag1
kubectl -n rag describe pod -l app=llm

Expected (excerpt – look for the section Last State):

    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137
      Started:      Wed, 02 Dec 2026 14:26:07 +0000
      Finished:     Wed, 02 Dec 2026 14:26:26 +0000
    Ready:          True

What you see: OOMKilled again – this time just 19 seconds after the start, with the first four questions. Four seats means four simultaneous contexts in memory; with 3 GiB there is no room for that.

Step 4 – delete the aborted run. Its numbers measure the crash, not the four seats.

# on rag1
kubectl -n rag delete job last-4p

Expected:

job.batch "last-4p" deleted from rag namespace

Step 5 – more memory. So that the attempt is fair, the model gets 6 GiB.

# on rag1
nano llm.yaml
~/kurs/10/llm.yaml changes in green
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: llm-modell
  namespace: rag
spec:
  accessModes: ["ReadWriteOnce"]
  storageClassName: local-path
  resources:
    requests:
      storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: llm
  namespace: rag
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: llm
  template:
    metadata:
      labels:
        app: llm
    spec:
      nodeSelector:
        kubernetes.io/hostname: rag1
      containers:
        - name: ollama
          image: ollama/ollama:0.40.19
          env:
            - name: OLLAMA_KEEP_ALIVE
              value: "-1"
            - name: OLLAMA_NUM_PARALLEL
              value: "4"
            - name: LLAMA_ARG_CACHE_RAM
              value: "256"
          ports:
            - containerPort: 11434
          resources:
            requests:
              cpu: 1500m
              memory: 2Gi
            limits:
              memory: 6Gi
          readinessProbe:
            httpGet:
              path: /api/version
              port: 11434
            periodSeconds: 5
          volumeMounts:
            - name: modell
              mountPath: /root/.ollama
      volumes:
        - name: modell
          persistentVolumeClaim:
            claimName: llm-modell
---
apiVersion: v1
kind: Service
metadata:
  name: llm
  namespace: rag
spec:
  selector:
    app: llm
  ports:
    - port: 11434
      targetPort: 11434
# on rag1
kubectl apply -f llm.yaml
# on rag1
kubectl -n rag rollout status deployment/llm --timeout=300s

Expected (last line):

deployment "llm" successfully rolled out

Step 6 – four users once more.

# on rag1
kubectl apply -f last-4p.yaml
# on rag1
kubectl -n rag wait --for=condition=Complete job/last-4p --timeout=1200s

Expected:

job.batch/last-4p condition met
# on rag1
kubectl -n rag logs job/last-4p

Expected (cut off on the right):

n3 ab   0.0 s  erstes   0.0 s  gesamt  60.5 s  suche -  fehler  Welche Taints setzt Kubernetes automatis
n3 ab  60.6 s  erstes  16.8 s  gesamt  23.0 s  suche 3.07  ok  Wie lange toleriert ein Pod standardmäßi
n2 ab   0.0 s  erstes  35.2 s  gesamt  98.9 s  suche 7.93  ok  Wie setze ich ein CPU-Limit für einen Co
n1 ab   0.0 s  erstes  53.9 s  gesamt 110.5 s  suche 1.0  ok  Was bedeutet CrashLoopBackOff?
n3 ab  83.6 s  erstes  11.3 s  gesamt  40.0 s  suche 3.42  ok  Was ist ein SSH-Auth-Secret?
n1 ab 110.5 s  erstes  11.8 s  gesamt  16.4 s  suche 2.98  ok  Wie lange bleibt ein Pod nach dem Beende
n2 ab  98.9 s  erstes   6.2 s  gesamt  41.5 s  suche 2.82  ok  Was passiert, wenn ein Container sein Sp
n2 ab 140.4 s  erstes  10.2 s  gesamt  16.7 s  suche 2.8  ok  Wie markiere ich einen Node als nicht pl
n1 ab 126.9 s  erstes  10.8 s  gesamt  34.5 s  suche 2.9  ok  Was ist ein Sidecar-Container?
n0 ab   0.0 s  erstes  54.0 s  gesamt 162.2 s  suche 4.21  ok  Welche Bedingungen kann ein Pod haben?
n0 ab 162.2 s  erstes   8.2 s  gesamt  22.5 s  suche 0.33  ok  Was ist der Unterschied zwischen Opaque 
n0 ab 184.7 s  erstes   9.7 s  gesamt  29.0 s  suche 0.37  ok  Wie lese ich eine ConfigMap in einem Pod
{"nutzer": 4, "fragen": 12, "ok": 11, "erstes_wort_p50": 11.3, "erstes_wort_p95": 54.0, "gesamt_p50": 34.5, "gesamt_p95": 162.2, "fragen_je_minute": 3.1, "dauer_s": 213.8}
# on rag1
kubectl -n rag top pod -l app=llm

Expected:

NAME                  CPU(cores)   MEMORY(bytes)   
llm-9dc5d9b49-nfzsq   11807m       3538Mi          

What you see: Comparison with Drill 4, four users both times:

one seat (Drill 4) four seats, 6 GiB
ok / questions 9 / 12 11 / 12
first word p50 50.6 s 11.3 s
first word p95 58.7 s 54.0 s
whole answer p95 69.0 s 162.2 s
questions per minute 3.0 3.1
memory 2198 MiB 3538 MiB

The median of the first word is much better – whoever comes later often finds a free seat. But the first four questions share the cores: n0 waits 54 seconds for the first word and 162 seconds for the whole answer, n3 runs into the timeout. The throughput stays at three questions per minute, and the model needs 1.3 GiB more memory. Four seats distribute the same computing time differently – they do not create any new time.

Step 7 – back to one seat. In llm.yaml, remove the two lines OLLAMA_NUM_PARALLEL and set limits.memory back to 3Gi. The file is then exactly the one from Drill 3.

# on rag1
nano llm.yaml
# on rag1
kubectl apply -f llm.yaml
# on rag1
kubectl -n rag rollout status deployment/llm --timeout=300s

Expected (last line):

deployment "llm" successfully rolled out

Part B: two desks

Step 8 – two replicas.

# on rag1
kubectl -n rag scale deployment llm --replicas=2

Expected:

deployment.apps/llm scaled
# on rag1
kubectl -n rag rollout status deployment/llm --timeout=300s

Expected:

Waiting for deployment "llm" rollout to finish: 1 of 2 updated replicas are available...
deployment "llm" successfully rolled out

Step 9 – where they run.

# on rag1
kubectl -n rag get pods -l app=llm -o wide
  • -o wide – additional columns, among them NODE.

Expected (cut off on the right):

NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE
llm-579476976d-jkglp   1/1     Running   0          7s    10.42.0.47   rag1
llm-579476976d-zkqm6   1/1     Running   0          14s   10.42.0.46   rag1

What you see: Both on rag1 – since Day 9 the manifest has had nodeSelector: kubernetes.io/hostname: rag1, because the model lies on the disk there. Two desks, but one room with twelve cores.

Step 10 – two users.

# on rag1
cp last-2.yaml last-r2.yaml
# on rag1
nano last-r2.yaml
~/kurs/10/last-r2.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: last-r2
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: last
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/last.py"]
          env:
            - name: NUTZER
              value: "2"
            - name: FRAGEN_JE_NUTZER
              value: "2"
            - name: AB
              value: "56"
            - name: FRAGEN
              value: /lastfragen/lastfragen.json
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: lastfragen
              mountPath: /lastfragen
      volumes:
        - name: code
          configMap:
            name: last-code
        - name: lastfragen
          configMap:
            name: lastfragen
# on rag1
kubectl apply -f last-r2.yaml

Expected:

job.batch/last-r2 created

Step 11 – the CPU after two minutes.

# on rag1
kubectl -n rag top pod -l app=llm

Expected:

NAME                   CPU(cores)   MEMORY(bytes)   
llm-579476976d-jkglp   5884m        1979Mi          
llm-579476976d-zkqm6   5922m        1978Mi          

What you see: Each replica gets six cores. Twelve together – the same as one alone before.

Step 12 – the result. It takes over four minutes.

# on rag1
kubectl -n rag wait --for=condition=Complete job/last-r2 --timeout=1800s
# on rag1
kubectl -n rag logs job/last-r2

Expected (cut off on the right):

n0 ab   0.0 s  erstes   0.0 s  gesamt   0.6 s  suche -  keine Karte  Was ist ein Ephemeral Container?
n0 ab   0.6 s  erstes  35.3 s  gesamt 235.6 s  suche 2.95  ok  Wie gebe ich eine ConfigMap als Kommando
n1 ab   0.0 s  erstes  32.9 s  gesamt 242.1 s  suche 0.29  ok  Wer darf Secrets lesen?
n1 ab 242.1 s  erstes   6.6 s  gesamt  13.9 s  suche 0.24  ok  Was bedeutet PreferNoSchedule?
{"nutzer": 2, "fragen": 4, "ok": 3, "erstes_wort_p50": 32.9, "erstes_wort_p95": 35.3, "gesamt_p50": 235.6, "gesamt_p95": 242.1, "fragen_je_minute": 0.7, "dauer_s": 256.0}

What you see: Two answers that ran at the same time needed four minutes. The last question, alone, was finished after 14 seconds. The throughput falls from three to 0.7 questions per minute.

Step 13 – why. The model’s times, for each pod separately. Insert the names from Step 9.

# on rag1
kubectl -n rag logs pod/llm-579476976d-jkglp | grep 'eval time'

Expected:

slot print_timing: id  0 | task 0 | prompt eval time =   21180.95 ms /   723 tokens (   29.30 ms per token,    34.13 tokens per second)
slot print_timing: id  0 | task 0 |        eval time =  200325.76 ms /    73 tokens ( 2782.30 ms per token,     0.36 tokens per second)
slot print_timing: id  0 | task 75 | prompt eval time =    6097.94 ms /   498 tokens (   12.24 ms per token,    81.67 tokens per second)
slot print_timing: id  0 | task 75 |        eval time =    7347.48 ms /    66 tokens (  113.04 ms per token,     8.85 tokens per second)
# on rag1
kubectl -n rag logs pod/llm-579476976d-zkqm6 | grep 'eval time'

Expected:

slot print_timing: id  0 | task 0 | prompt eval time =   18515.32 ms /   620 tokens (   29.86 ms per token,    33.49 tokens per second)
slot print_timing: id  0 | task 0 |        eval time =  209152.40 ms /   149 tokens ( 1413.19 ms per token,     0.71 tokens per second)
# on rag1
kubectl -n rag logs pod/llm-579476976d-zkqm6 | grep -m1 'n_threads'
  • -m1 – stop after the first match.

Expected (cut off on the right):

cmn  common_param: system_info: n_threads = 12 (n_threads_batch = 12) / 12 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX2 = 1 |

What you see:

Measurement one replica (Drill 1) two replicas at the same time
Reading the prompt 65–70 tokens/s 33–34 tokens/s per replica
Writing the answer 5–14 tokens/s 0.36 and 0.71 tokens/s
Threads per replica 12 12 – 24 together on 12 cores

Reading is shared fairly: half the speed twice. Writing collapses – by more than a factor of ten. Each replica starts as many threads as the node has cores, and the two pods crowd each other out. As soon as the second answer was no longer running, the first replica wrote at 8.85 tokens per second again (task 75).

Step 14 – back to one replica.

# on rag1
kubectl -n rag scale deployment llm --replicas=1

Expected:

deployment.apps/llm scaled

Remember: A second desk only helps in a second room. Two replicas of a CPU model on the same node share the cores – and lose more by sharing than they gain. More replicas only pay off with more nodes or one GPU per replica.

Save your progress? Sign up for free

Drill 6: The queue number

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

What you have afterwards: an answer service that accepts at most two questions at the same time, rejects all further ones immediately with 503 and Retry-After: 30 – and that cleanly reports a refused connection to the model as an error.

What it is about. Drills 4 and 5 show the same thing: the desk manages around three questions per minute; more is not possible on this CPU. So all you can still decide is how it feels when more come. Without a limit everyone waits – and from the fourth user on, every question runs into the timeout of 60 seconds. With a limit the first two get an answer within their budget, the others hear immediately: “please come back in 30 seconds”.

This is called load shedding. The queue numbers are a threading.BoundedSemaphore with as many seats as PLAETZE (seats).

Step 1 – fetch the code from Day 9.

# on rag1
cp ~/kurs/09/antwort.py antwort.py

Step 2 – build in queue numbers and a clean error message.

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

import json
import os
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"))
KEINE = "Dazu steht nichts im Handbuch."
THEKE = threading.BoundedSemaphore(PLAETZE) if PLAETZE else None

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"
)


def anfrage(url, daten, timeout=30):
    req = urllib.request.Request(
        url,
        data=json.dumps(daten).encode(),
        headers={"Content-Type": "application/json"},
    )
    return urllib.request.urlopen(req, timeout=timeout)


def suchen(frage):
    """Frage einbetten, Karten holen, auf Wunsch vom Reranker neu ordnen."""
    with anfrage(f"{EMBED}/api/embed", {"model": MODELL, "input": [frage]}) as a:
        vektor = json.load(a)["embeddings"][0]
    koerper = {
        "query": vektor,
        "limit": KANDIDATEN if RERANK else KARTEN,
        "with_payload": True,
    }
    with anfrage(f"{QDRANT}/collections/{SAMMLUNG}/points/query", koerper) as a:
        punkte = json.load(a)["result"]["points"]
    if RERANK and punkte:
        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)]
    return punkte[:KARTEN]


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 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"})
        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)
            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
        try:
            self.beantworten(frage, eingabe)
        finally:
            if THEKE:
                THEKE.release()

    def beantworten(self, frage, eingabe):
        """Suchen, Schwelle prüfen, dann ganz oder als Strom antworten."""
        start = time.time()
        punkte = suchen(frage)
        zeiten = {"suche": round(time.time() - start, 2)}
        bester = punkte[0]["score"] if punkte else 0.0
        if bester < MINDEST:
            print(f"keine Karte  bester {bester:.3f}  {frage}", flush=True)
            self.senden(200, {"antwort": KEINE, "quellen": [], "sekunden": zeiten})
            return
        quellen = [
            {
                "nr": nr,
                "quelle": p["payload"]["quelle"],
                "abschnitt": p["payload"]["abschnitt"],
                "score": round(p["score"], 3),
            }
            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:
                antwort = json.load(a)["message"]["content"].strip()
        except TimeoutError:
            print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s  {frage}", flush=True)
            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
            )
            self.senden(502, {"fehler": "Sprachmodell nicht erreichbar"})
            return
        zeiten["gesamt"] = round(time.time() - start, 2)
        print(f"antwort  {zeiten}  {frage}", flush=True)
        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})
        try:
            with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
                for roh in a:
                    stueck = json.loads(roh)["message"]["content"]
                    if stueck and "erstes_wort" not in zeiten:
                        zeiten["erstes_wort"] = round(time.time() - start, 2)
                    if stueck:
                        self.zeile({"text": stueck})
        except TimeoutError:
            print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s  {frage}", flush=True)
            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
            )
            self.zeile({"fehler": "Sprachmodell nicht erreichbar"})
            return
        zeiten["gesamt"] = round(time.time() - start, 2)
        print(f"strom  {zeiten}  {frage}", flush=True)
        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()

The changes:

Lines What Why
6, 26 threading and THEKE = threading.BoundedSemaphore(PLAETZE) the queue numbers (THEKE = desk); with PLAETZE=0 there is no limit, and the service behaves as on Day 9
24 PLAETZE from the environment the number is in the manifest, not in the code
104 THEKE.acquire(blocking=False) take a number without waiting; if none is free, False comes back
105–111 503 with Retry-After: 30 reject immediately, with a line in the log
112–116 try … finally: THEKE.release() the number is always given back – even if the answer ends with an error
118 beantworten() the previous rest of do_POST, moved unchanged into a method of its own
8, 158–163, 193–198 catch urllib.error.URLError a refused connection to the model becomes a 502 or an error line instead of a traceback (Drill 2, Step 7)

Step 3 – fetch the manifest from Day 9 and set PLAETZE.

# on rag1
cp ~/kurs/09/antwort.yaml antwort.yaml
# on rag1
nano antwort.yaml
~/kurs/10/antwort.yaml changes in green
apiVersion: apps/v1
kind: Deployment
metadata:
  name: antwort
  namespace: rag
spec:
  replicas: 1
  selector:
    matchLabels:
      app: antwort
  template:
    metadata:
      labels:
        app: antwort
    spec:
      containers:
        - name: antwort
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/antwort.py"]
          env:
            - name: SAMMLUNG
              value: wissen
            - name: KARTEN
              value: "3"
            - name: LLM_TIMEOUT
              value: "60"
            - name: MINDEST_SCORE
              value: "0.46"
            - name: RERANK_URL
              value: ""
            - name: PLAETZE
              value: "2"
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          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
Setting Value Meaning
PLAETZE "2" two questions at the same time: according to Drill 4, the first word stays under 40 seconds with two users, but not with four

Step 4 – swap the code. A ConfigMap cannot be overwritten with create; first delete it, then create it 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

Step 5 – apply the manifest. Because the environment of the pod changes (PLAETZE), Kubernetes starts a new pod, and it reads the new ConfigMap.

# 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 (last line):

deployment "antwort" successfully rolled out

Step 6 – four users at the desk with two numbers.

# on rag1
cp last-4.yaml last-theke.yaml
# on rag1
nano last-theke.yaml
~/kurs/10/last-theke.yaml changes in green
apiVersion: batch/v1
kind: Job
metadata:
  name: last-theke
  namespace: rag
spec:
  backoffLimit: 0
  ttlSecondsAfterFinished: 86400
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: last
          image: python:3.14.10-slim-trixie
          command: ["python", "/code/last.py"]
          env:
            - name: NUTZER
              value: "4"
            - name: FRAGEN_JE_NUTZER
              value: "3"
            - name: AB
              value: "48"
            - name: FRAGEN
              value: /lastfragen/lastfragen.json
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 64Mi
          volumeMounts:
            - name: code
              mountPath: /code
            - name: lastfragen
              mountPath: /lastfragen
      volumes:
        - name: code
          configMap:
            name: last-code
        - name: lastfragen
          configMap:
            name: lastfragen
# on rag1
kubectl apply -f last-theke.yaml

Expected:

job.batch/last-theke created
# on rag1
kubectl -n rag wait --for=condition=Complete job/last-theke --timeout=900s

Expected (after a good minute):

job.batch/last-theke condition met
# on rag1
kubectl -n rag logs job/last-theke

Expected (cut off on the right):

n3 ab   0.0 s  erstes   0.0 s  gesamt   0.2 s  suche -  http 503  Wie gebe ich eine ConfigMap als Kommando
n0 ab   0.0 s  erstes   0.0 s  gesamt   0.2 s  suche -  http 503  Wie groß darf eine ConfigMap sein?
n3 ab   0.2 s  erstes   0.0 s  gesamt   0.0 s  suche -  http 503  Wer darf Secrets lesen?
n0 ab   0.2 s  erstes   0.0 s  gesamt   0.0 s  suche -  http 503  Kann ein Pod eine ConfigMap aus einem an
n3 ab   0.2 s  erstes   0.0 s  gesamt   0.0 s  suche -  http 503  Was bedeutet PreferNoSchedule?
n0 ab   0.2 s  erstes   0.0 s  gesamt   0.0 s  suche -  http 503  Was ist ein Bootstrap-Token-Secret?
n1 ab   0.0 s  erstes   7.1 s  gesamt   9.6 s  suche 0.36  ok  Wann wird eine Readiness-Probe ausgeführ
n2 ab   0.0 s  erstes  16.2 s  gesamt  19.6 s  suche 1.3  ok  Was passiert beim Löschen eines Secrets,
n1 ab   9.6 s  erstes  18.5 s  gesamt  23.6 s  suche 0.38  ok  Was bedeutet der Pod-Status Unknown?
n2 ab  19.6 s  erstes  21.4 s  gesamt  29.0 s  suche 1.77  ok  Wie oft prüft das Kubelet eine Liveness-
n2 ab  48.6 s  erstes   0.0 s  gesamt   1.0 s  suche -  keine Karte  Was ist ein Ephemeral Container?
n1 ab  33.2 s  erstes  23.8 s  gesamt  34.4 s  suche 3.83  ok  Wie verteile ich Pods auf bestimmte Node
{"nutzer": 4, "fragen": 12, "ok": 5, "erstes_wort_p50": 18.5, "erstes_wort_p95": 23.8, "gesamt_p50": 23.6, "gesamt_p95": 34.4, "fragen_je_minute": 4.4, "dauer_s": 67.6}

What you see: n1 and n2 got the two numbers. Their first word came after at most 23.8 seconds – instead of 58.7 in Drill 4. n0 and n3 were turned away in 0.2 seconds, three times in a row: the load test asks on immediately after a rejection and does not respect Retry-After. A real client would wait 30 seconds.

No timeout, no abort. Five of twelve questions answered, six honestly rejected, one without a matching card.

Step 7 – the rejections in the log.

# on rag1
kubectl -n rag logs deployment/antwort | grep abgewiesen

Expected:

abgewiesen, 2 Plätze belegt  Wie gebe ich eine ConfigMap als Kommandozeilenargument weiter?
abgewiesen, 2 Plätze belegt  Wie groß darf eine ConfigMap sein?
abgewiesen, 2 Plätze belegt  Wer darf Secrets lesen?
abgewiesen, 2 Plätze belegt  Kann ein Pod eine ConfigMap aus einem anderen Namespace nutzen?
abgewiesen, 2 Plätze belegt  Was bedeutet PreferNoSchedule?
abgewiesen, 2 Plätze belegt  Was ist ein Bootstrap-Token-Secret?

What you see: Every rejection is in the log with its question. If you count these lines per hour, you know how often the desk was too small – that is the number with which you later justify a second machine.

Remember: If the desk cannot get faster, decide who waits. A fast rejection with Retry-After is better than a minute of waiting followed by a timeout.

If it does not work

Symptom Cause Fix
RESTARTS of the model rises after a few minutes of load, the log shows no error OOMKilled, the prompt cache grows beyond the limit (Drill 2) set LLAMA_ARG_CACHE_RAM (Drill 3); kubectl describe pod shows the reason under Last State
OOMKilled just a few seconds after the start of the load test OLLAMA_NUM_PARALLEL greater than 1 with a 3 GiB limit (Drill 5) remove the parallelism or raise the limit
grep 'size limit' prints nothing the model is not loaded yet; Ollama loads it with the first question ask a question first, then try again
error: Metrics not available for pod the pod has just restarted, metrics-server has no values yet wait a minute
Load test shows abbruch the connection to the answer service broke off without a final line, usually because the model restarted read kubectl -n rag logs deployment/antwort; with the code from Drill 6 it becomes fehler
fehler after a good 60 seconds LLM_TIMEOUT: the question stood in the queue too long fewer simultaneous users or set PLAETZE (Drill 6)

Save your progress? Sign up for free

Diagnosis task

The situation: A colleague wanted to “quickly free up some memory” and set the language model to zero replicas. Afterwards a user reports: the assistant shows nothing for a minute and then “Sprachmodell nicht erreichbar” (language model not reachable). Why does it take a minute until the error comes?

Recreate the situation:

# on rag1
kubectl -n rag scale deployment llm --replicas=0

Expected:

deployment.apps/llm scaled
# on rag1
kubectl -n rag wait --for=delete pod -l app=llm --timeout=120s
  • --for=delete – wait until the pod has disappeared.

Try it yourself first, then read on.

Solution.

Step 1 – reproduce the symptom. The question from Day 9, with headers (-i).

# on rag1
cp ~/kurs/09/f02.json .
# on rag1
date +%T
# on rag1
kubectl -n rag exec -i curl -- \
  curl -s -i -X POST http://antwort.rag/frage \
  -H 'Content-Type: application/json' -d @- < f02.json
# on rag1
date +%T

Expected (the output of curl):

HTTP/1.0 502 Bad Gateway
Server: BaseHTTP/0.6 Python/3.14.10
Date: Wed, 02 Dec 2026 16:19:22 GMT
Content-Type: application/json
Content-Length: 43

{"fehler": "Sprachmodell nicht erreichbar"}

What you see: The two date outputs are a good minute apart (in the lab 16:18:20 and 16:19:22). The answer is the new 502 from Drill 6 – without Drill 6 it would be an abort without a message.

Step 2 – what the answer service experienced.

# on rag1
kubectl -n rag logs deployment/antwort --tail=2

Expected (the last line):

Sprachmodell nicht erreichbar: timed out  Wie groß darf ein Secret höchstens sein?

What you see: timed out – not Connection refused as in Drill 2. The answer service waited 60 seconds for a connection that never came about (LLM_TIMEOUT).

Step 3 – does the service have a target at all?

# on rag1
kubectl -n rag get endpointslices -l kubernetes.io/service-name=llm
  • -l kubernetes.io/service-name=llm – only the EndpointSlices that belong to the service llm.

Expected:

NAME        ADDRESSTYPE   PORTS     ENDPOINTS   AGE
llm-2x2w9   IPv4          <unset>   <unset>     3h41m

What you see: ENDPOINTS <unset> – there is no pod behind the service. The service itself still exists and has its cluster IP; so the name llm.rag resolves.

Step 4 – how this feels from the outside. A direct call with a short timeout:

# on rag1
kubectl -n rag exec curl -- \
  curl -s -m 10 -o /dev/null -w '%{http_code} %{time_total}\n' \
  http://llm.rag:11434/api/version
Setting Value Meaning
-m 10 give up after 10 seconds
-o /dev/null discard the content of the response
-w '%{http_code} %{time_total}\n' print only status code and total time

Expected:

000 10.002565
command terminated with exit code 28

What you see: No status code (000), given up after exactly 10 seconds; exit code 28 means “timeout” for curl. The connection is not refused – it simply stays unanswered.

Step 5 – for the curious: why not refused immediately? For a service without endpoints, kube-proxy creates a rule that is supposed to reject connections immediately.

# on rag1
sudo iptables-save | grep 'rag/llm'

Expected:

-A KUBE-SERVICES -d 10.43.181.13/32 -p tcp -m comment --comment "rag/llm has no endpoints" -m tcp --dport 11434 -j REJECT --reject-with icmp-port-unreachable
# on rag1
sudo iptables -t filter -L KUBE-SERVICES -v -n
  • -t filter – the table filter,
  • -L KUBE-SERVICES – show only this chain,
  • -v -n – with packet counters, addresses as numbers.

Expected (excerpt – look for the line with rag/llm):

    0     0 REJECT     6    --  *      *       0.0.0.0/0            10.43.181.13         /* rag/llm has no endpoints */ tcp dpt:11434 reject-with icmp-port-unreachable

What you see: The rule is there, but after the attempt from Step 4 its counter is still at 0 packets. In this k3s lab the packet from the pod does not reach the rule, so nobody sends the rejection back, and the caller waits until its timeout. So do not rely on a missing target being noticed quickly.

Step 6 – fix it.

# on rag1
kubectl -n rag scale deployment llm --replicas=1
# on rag1
kubectl -n rag rollout status deployment/llm --timeout=300s

Expected (last line):

deployment "llm" successfully rolled out
# on rag1
kubectl -n rag exec curl -- \
  curl -s -m 10 -o /dev/null -w '%{http_code} %{time_total}\n' \
  http://llm.rag:11434/api/version

Expected:

200 0.007240

The cause: The service llm had no endpoints. Connections to it are not refused in this cluster but go nowhere. The answer service therefore waits the full 60 seconds from LLM_TIMEOUT before it reports “not reachable”.

What you take away from it: LLM_TIMEOUT is one number for two things – how long the model may compute and how long a dead service holds the user up. Whoever promises a latency budget needs a separate, short limit (a few seconds) for establishing the connection and a long one for the answer.

Challenge

Write down your latency budget – a sentence you can give to an operations team. Use only the JSON lines of your own runs (kubectl -n rag logs job/<name> --tail=1) and put them side by side in a table: users, ok/fragen, erstes_wort_p95, fragen_je_minute.

The author’s solution (with the numbers from the lab, 12 vCPU):

Run Users ok / questions first word p95 questions per minute
last-1 1 6 / 6 22.8 s (cold start) 3.4
last-2 2 6 / 6 39.0 s 3.1
last-4 4 9 / 12 58.7 s 3.0
last-theke 4, two seats 5 / 12, 6 rejected 23.8 s 4.4

“A rag1 with 12 vCPU manages around three questions per minute. With PLAETZE=2, accepted questions get the first word under 25 seconds at p95; from the third simultaneous user on, requests are rejected immediately with 503.”

The 4.4 questions per minute in the last run are not a gain: the load test only counts accepted questions, and the run was shorter. With your 4 vCPU all times are longer; the sentence still has the same form.

Save your progress? Sign up for free

Checkpoint

# on rag1
kubectl -n rag get deployment llm antwort

Expected:

NAME      READY   UP-TO-DATE   AVAILABLE   AGE
llm       1/1     1            1           118m
antwort   1/1     1            1           116m
# on rag1
kubectl -n rag logs deployment/llm | grep 'size limit'

Expected:

srv    load_model: prompt cache is enabled, size limit: 256 MiB

If the command prints nothing, the model has not received a question since its last restart – ask one.

# on rag1
kubectl -n rag exec curl -- curl -s -i http://antwort.rag/health

Expected:

HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.10
Date: Wed, 02 Dec 2026 14:37:49 GMT
Content-Type: application/json
Content-Length: 16

{"status": "ok"}
# on rag1
kubectl top pod -n rag

Expected (roughly – the names are different):

NAME                       CPU(cores)   MEMORY(bytes)   
antwort-7974d4c4c6-6cnnj   8m           18Mi            
curl                       0m           0Mi             
embed-66bdc7c6c9-rqqpn     1070m        1535Mi          
llm-579476976d-jkglp       11145m       2186Mi          
pg-1                       18m          55Mi            
qdrant-0                   10m          63Mi            

One replica llm with memory well below 3 GiB, an answer service with PLAETZE=2, no HPA.

Test yourself

  1. The load test reports erstes_wort_p95: 12.0 – and yet the run was bad. How do you recognise that?
  2. The language model restarts under load, and there is no error in the container’s log. Where do you find the reason?
  3. Why did the HPA on the answer service not scale up in Drill 4, although users waited for a minute?
  4. OLLAMA_NUM_PARALLEL=4 lowered the median of the first word from 50.6 to 11.3 seconds. Why is that still not a solution for more users?
  5. What happens if you start a second replica of the CPU model on the same node?
  6. Why is a rejection with 503 and Retry-After better for the user than an accepted question?

Answers:

  1. By ok next to fragen: in Drill 2 it was 10 of 12. Aborted questions are not included in the percentiles – the more abort, the better the times look.
  2. In kubectl describe pod under Last State: Reason: OOMKilled, Exit Code: 137. The kernel ends the process with SIGKILL; the process cannot write anything more into its own log.
  3. It measures the CPU of the answer service (3–4 % of the request). The answer service only waits; the bottleneck is the model. And more answer services would pass on to the same model.
  4. The throughput stays at three questions per minute. The computing time is only distributed differently: the first questions get slower (p95 of the whole answer 162 instead of 69 seconds), and the model needs 1.3 GiB more memory.
  5. Both start as many threads as the node has cores and crowd each other out. In the lab, writing fell from 5–14 to under 1 token per second, and the throughput from three to 0.7 questions per minute.
  6. He knows where he stands after 0.2 seconds instead of after 60, and the accepted questions stay within budget. Without a limit everyone waits and many run into the timeout.

Interview note

“How do you test whether an LLM service is enough for N users?” – With a load test in the cluster, not on the laptop: first a baseline with one user, then two, four. You measure the time to the first token and to the end as p50/p95, the throughput and – importantly – the ratio of successful to asked questions, because aborts make the percentiles look better. With CPU inference the throughput stays constant, and the latency grows linearly with the number of simultaneous users. The remedies are load shedding with 503/Retry-After in the application and more hardware, not more replicas on the same node. A CPU HPA on the frontend is a typical mistake, because the frontend is I/O-bound.

Enterprise note

In larger environments, load shedding is often handled by a gateway in front of the model (concurrency limits per tenant, queues with priorities). Scaling follows a metric that sees the bottleneck – such as the length of the queue in the inference server or the number of running requests, via KEDA or an HPA with custom metrics, not the CPU of the frontend. Different numbers apply to GPU inference: servers such as vLLM batch many requests (continuous batching), and there the throughput rises with parallelism – until the GPU memory for the KV cache is full. The principle “cache limit below container limit” applies there just the same. Latency budgets are set as SLOs in operation, e.g. “p95 time to first token under 3 seconds”, with an alerting rule on them.

Summary

  • A load test as a job measures p50/p95 of the first word and of the whole answer, the throughput and ok next to fragen.
  • Ollama’s prompt cache was allowed to grow to 8 GiB, the pod only to 3 GiB – OOMKilled after 15 questions. LLAMA_ARG_CACHE_RAM=256 keeps it small.
  • On CPU the model manages around three questions per minute, no matter how many users come; the waiting time grows with every additional one.
  • An HPA on the CPU of the answer service notices none of this.
  • More parallelism distributes the same computing time differently and costs memory; two replicas on the same CPU are much slower than one.
  • Load shedding with PLAETZE, 503 and Retry-After keeps accepted questions within budget.
  • In this cluster, a service without endpoints makes callers wait until the timeout.

Commands at a glance

Command What it does Important options
nproc number of cores –
kubectl top node · kubectl top pod -n <ns> CPU and memory, averaged by metrics-server -l label filter
kubectl -n <ns> wait --for=condition=Complete job/<name> wait until a job is finished --timeout=
kubectl -n <ns> wait --for=delete pod -l <label> wait until pods have disappeared --timeout=
kubectl -n <ns> logs job/<name> log of a job --tail=
kubectl -n <ns> describe pod -l <label> state, Last State, reason for the last end –
kubectl -n <ns> get hpa <name> · describe hpa <name> target, current value, conditions of the HPA –
kubectl -n <ns> scale deployment <name> --replicas=<n> set the number of replicas –
kubectl -n <ns> get pods -o wide pods with node and IP –
kubectl -n <ns> get endpointslices -l kubernetes.io/service-name=<svc> which pods stand behind a service –
kubectl -n <ns> delete configmap <name> · create configmap <name> --from-file=<file> replace a ConfigMap –
curl -s -m <s> -o /dev/null -w '%{http_code} %{time_total}\n' <url> measure reachability and time -m timeout, -w output format
sudo iptables -t filter -L <chain> -v -n rules of a chain with counters -v counters, -n numeric

Contents

More