LLM Serving on CPU-Only Kubernetes: How Prefix-Affinity Routing Cut Time to First Token 15x
TL;DR. I built an LLM serving stack on a single-node Minikube cluster with no GPU: llama.cpp serving a quantized Qwen 2.5 0.5B model, a FastAPI router with prefix-affinity and least-inflight routing, a Horizontal Pod Autoscaler, and Prometheus plus Grafana tracking LLM-specific metrics. A repeated prompt prefix dropped time to first token from 486 ms to 33 ms. The stack served 193 requests at up to 8 concurrent clients with zero errors, and the benchmarks showed exactly where it stops scaling.
- 15x faster TTFT on a warm prefix
- 85.7% affinity hit ratio, 100 mixed requests
- 0 errors across 193 requests
- 11 Grafana panels for LLM metrics
Why build this on a laptop?
Most local LLM setups are one terminal running one model. That works for a demo, but it skips everything that matters once real users show up: routing, health checks, autoscaling, and knowing why a request was slow. I wanted to practice those parts without renting GPUs, so I gave myself a hard limit: a 2015 MacBook Air with 4 CPU cores and 8 GB of RAM running Ubuntu 26.04.
The goal was a stack shaped like production AI infrastructure, small enough to run on that machine. Every component in it has a direct counterpart in a GPU cluster, which made the final step of the project, mapping it to vLLM, straightforward.
What I built
Requests enter through a Kubernetes NodePort Service, land on one of two router replicas, and are forwarded to a llama.cpp server holding the model. A separate monitoring namespace runs kube-prometheus-stack, which scrapes both the router and llama.cpp every 15 seconds.
- Inference: llama.cpp server, Qwen 2.5 0.5B Instruct in GGUF Q4_K_M (about 469 MB), 4 threads, 2,048-token context, one parallel slot, OpenAI-compatible API.
- Routing: a 147-line FastAPI app with SHA-256 prefix hashing, a bounded LRU affinity table and least-inflight fallback.
- Scaling: an HPA that grows the router tier from 2 to 6 pods at 60% average CPU.
- Observability: ServiceMonitors, Prometheus and an 11-panel Grafana dashboard covering TTFT, inter-token latency, tokens per second, queue length and KV cache reuse.
Step 1: The bug that blocked the cluster
The first minikube start failed before Kubernetes even came up:
hostname: error while loading shared libraries: ...cannot apply additional memory protection after relocation: Permission denied
The cause was the Snap package of Docker. Snap runs Docker under a strict AppArmor profile, and that profile blocks the mprotect calls nested containers need. Minikube's node is itself a container, so it hit the wall immediately. The fix was to remove Snap Docker completely and install docker-ce from Docker's apt repository:
sudo snap remove --purge docker# install docker-ce, docker-ce-cli and containerd.io from download.docker.comhash -r # make the shell forget the old /snap/bin/docker path
That last line matters. Without it, the shell keeps calling the deleted Snap binary and the error looks like it never went away.
Step 2: A cluster sized for 8 GB
With half the RAM going to the host and the browser, the cluster got 2 CPUs and 4 GB. The model directory is mounted into the node so the pod can read it from a hostPath volume, which avoids baking a 469 MB file into an image.
minikube start --driver=docker --container-runtime=containerd \ --cpus=2 --memory=4096mb --disk-size=30g \ --mount-string="$HOME/llm-minikube-lab/model:/models"
Step 3: The inference server
The model runs in the official ghcr.io/ggml-org/llama.cpp:server image. Two flags shape everything that follows: --parallel 1 gives the server a single decoding slot, and --metrics exposes a Prometheus endpoint with counters such as cached prompt tokens and deferred requests.
args: ["-m", "/models/model.gguf", "--host", "0.0.0.0", "--port", "8080", "-c", "2048", "-t", "4", "--parallel", "1", "--metrics"]resources: requests: { cpu: "1", memory: 1Gi } limits: { cpu: "4", memory: 4Gi }
Readiness and liveness probes hit /health, with a 20-second initial delay so Kubernetes does not send traffic while the model is still loading into memory.
Step 4: A router that keeps the KV cache warm
Before a model writes its first output token it has to process the whole prompt. That prefill work is stored in the KV cache. If the next request starts with the same system prompt and opening message, the server can reuse that cache and skip most of the prefill. The router’s job is to send matching prefixes to the same backend so the reuse can happen.
The core of the router is two small functions:
def prefix_key(body: dict) -> str: messages = body.get("messages", [])[:2] stable = json.dumps(messages, sort_keys=True, separators=(",", ":")) return hashlib.sha256(stable.encode()).hexdigest()
def choose_backend(key: str) -> str: now = time.time() existing = affinity.get(key) if existing and now - existing[1] < AFFINITY_TTL and existing[0] in BACKENDS: affinity.move_to_end(key) affinity_total.labels("hit").inc() return existing[0] affinity_total.labels("miss").inc() backend = min(BACKENDS, key=lambda item: inflight[item]) affinity[key] = (backend, now) affinity.move_to_end(key) while len(affinity) > AFFINITY_LIMIT: affinity.popitem(last=False) return backend
Three details make it safe to run for a long time. sort_keys=True makes the hash stable no matter how a client orders JSON fields. The table is an OrderedDict capped at 10,000 keys, so memory stays bounded. Entries expire after 10 minutes, so a backend that was replaced does not keep receiving traffic for old conversations.
The router ships as a non-root python:3.12-slim image (USER 65532), loaded straight into Minikube's image store, with /healthz for liveness and a /readyz check that only passes once a model backend answers.
Step 5: Metrics that describe an LLM, not a web server
Request count and latency tell you a request was slow. They do not tell you whether the time went to reading the prompt, generating tokens, or waiting in line. llama.cpp returns a timings block with every response, and the router turns it into Prometheus histograms:
Two ServiceMonitors tell the Prometheus Operator to scrape the router and llama.cpp. The dashboard is a ConfigMap labeled grafana_dashboard=1, so Grafana's sidecar imports it automatically and it survives a pod restart.
Step 6: Autoscaling the router tier
The HPA scales the router from 2 to 6 replicas when average CPU passes 60%. It scales up fast (up to 100% more pods every 30 seconds) and down slowly (at most half the pods per minute, after a 3-minute window), so a short lull does not remove capacity right before the next burst.
minReplicas: 2maxReplicas: 6metrics: - type: Resource resource: { name: cpu, target: { type: Utilization, averageUtilization: 60 } }
Results
Cold versus warm prefix
I sent the same prompt twice and read llama.cpp’s own timings. On the cold run the server evaluated all 36 prompt tokens. On the warm run it evaluated one token and reused 35 from the KV cache.
Generation speed stayed around 21 to 25 tokens per second in both runs. Prefix caching speeds up prefill, not decode, which is exactly what the split metrics are there to show.
Mixed-topic load
- 50 requests over 3 topics: 18.6 seconds, 100% HTTP 200, 78.7% affinity hit ratio.
- 100 requests over 5 topics (Kubernetes, databases, the Linux kernel, networking, AI/ML): 35.2 seconds, 85.7% affinity hit ratio.
- Running total: 193 requests with a 0.00% error rate. The two router pods used 15m and 14m of CPU, an even split.
Finding the capacity cliff
Then I pushed concurrency to 1, 2, 4 and 8 clients.
Nothing crashed, nothing leaked memory, and no request was dropped. But with --parallel 1, the server decodes one request at a time. Eight clients means seven waiting, so p95 latency grows in line with the queue while throughput cannot move.
What the numbers taught me
The bottleneck was never the router
This is the screenshot that changed how I think about the autoscaler:
The routers are almost idle, so a CPU-based HPA on the router tier will never fire while the model is saturated. Autoscaling works mechanically, but it is pointed at the wrong layer. The signal that matters is the backend queue length, which the stack already exports. The next version scales model replicas on llm_backend_queue_length through the custom metrics API (KEDA is the easiest path).
Sustained load tells a different story than bursts
Short bursts looked clean. The 16-minute run in the Grafana screenshot did not: generation speed slid from about 25 tokens per second toward single digits while TTFT and inter-token p95 climbed. Nothing failed, but the same request got slower the longer the box stayed busy. On a 2015 laptop holding 3.4 cores for minutes at a time, CPU throttling is the first suspect, and it is a good reminder that a benchmark is only as honest as its duration.
Affinity needs to agree across routers
Each router replica keeps its own affinity table in memory. With one model replica that does not matter, since every request goes to the same place. With several model replicas, two routers could send the same conversation to different backends and split its cache. The fix is to make the choice deterministic, for example consistent hashing on the prefix key, so every router reaches the same answer without sharing state.
How this maps to a GPU cluster
Every piece has a direct production counterpart:
- llama.cpp with one slot becomes vLLM with continuous batching, which fills the GPU with many requests at once instead of queuing them.
- KV cache reuse inside one server becomes PagedAttention with automatic prefix caching, plus LMCache to share KV blocks across nodes.
- A Python affinity table becomes cache-aware routing in the gateway, using the same prefix-hash idea.
- CPU-based HPA becomes scaling on queue depth or KV cache utilization.
The concurrency sweep above is the case for continuous batching in one chart. A flat throughput line under rising load is what a single slot looks like, and batching is what bends it upward.
Questions people ask about this setup
Can you run a production-like LLM stack without a GPU?
Yes, for learning and testing the platform around the model. A 0.5B model quantized to 4 bits runs at 20 to 28 tokens per second on 4 laptop cores. The routing, probes, autoscaling and monitoring behave the same way they would on GPUs.
What is time to first token and why track it separately?
TTFT is the time from sending a request to receiving the first output token. It is dominated by prompt processing, while inter-token latency is dominated by decoding. Tracking them separately tells you whether to fix caching and prompt length or decode speed.
Why hash only the first two messages?
The system prompt and first user message are the part most likely to repeat across requests and turns. Hashing the whole conversation would give every new turn a new key and the router would never get a hit.
Wrapping up
The most useful result of this project was not the 15x number. It was learning to read a serving system by its LLM metrics: TTFT told me caching worked, flat throughput told me the server was serialized, and kubectl top told me my autoscaler was watching the wrong pods. Those lessons carry directly to a GPU cluster.
If you are hiring for AI infrastructure, platform or MLOps roles, or want to compare notes on LLM serving, I would like to hear from you.
Yash Shah builds cloud, data and AI infrastructure. M.S. in Computer Science, previously at Zipline, now building LLM agents and data platforms at DataHub.
Portfolio· GitHub· LinkedIn