Skip to main content

Running CPU Inference and RAG on GKE: Autoscaling, Private Screening, and Recovery

Updated 12 min readMarkdown
Running CPU Inference and RAG on GKE: Autoscaling, Private Screening, and Recovery

In part 1, I built a private GKE platform using Terraform and Argo CD. I've now added a retrieval-augmented generation (RAG) assistant running entirely on CPU and tested how the platform handles scaling, overload, releases, and recovery. Every configuration change reached the cluster as a reviewed pull request.

Results at a glance

What I tested Result
Model server cold start, including a new node Ready in about 105 s, with the model file checksum-verified before the server starts
Release and Git-revert rollback under streaming load 177 and 203 requests, no stream cut by a rollout, about 4 min from merge to healthy
Autoscaling on queued and running requests Triggered by running requests above 1.5 per Pod: HPA decision 8 s after load rose, second replica serving at 39 s
Overload 116 of 158 requests refused with HTTP 429 in about 0.1 s; API memory flat at 55 MiB
Pod deletion, node drain, forced kill mid-stream Pod deletion and node drain completed without request errors; forced termination ended the partial answer with an explicit stalled state
Scaling metric lost, with the HPA fixed at 2 replicas HPA reported ScalingActive=False; the scaling alert's query matched
Model revision with a wrong checksum Refused at download; service restored 4 min after the git revert merged
Vector database deleted with its volume Restored with an identical ordered chunk-ID fingerprint over all 1,382 chunks
Model Armor screening Reached privately over Private Service Connect; about 0.25 s added to the first token; an injected instruction in a retrieved document dropped before the model saw it

The workload, and why CPU first

The assistant answers questions about the platform's own documentation. It has five parts:

  • llm-cpu: llama.cpp serving Qwen2.5-1.5B-Instruct, quantized to Q4_K_M.
  • embeddings: Hugging Face Text Embeddings Inference with bge-small-en-v1.5.
  • pgvector: PostgreSQL with the vector extension, as a StatefulSet.
  • ingest: a suspended CronJob that loads a 45-document corpus on demand.
  • rag-api: retrieval, prompting, and server-sent-event streaming behind the existing Gateway.

My project's GPU quota was zero, so I started on CPU. That still let me test dedicated node scheduling, verified model downloads, autoscaling, and recovery. With a 1.5B model on a 4-vCPU node and one request in flight, the median time to first token was about 15 seconds. That was enough to work through the platform changes before adding GPUs.

GKE routes requests through the Gateway to rag-api on the general pool. A dedicated CPU pool serves the language model, and rag-api reaches Model Armor through Private Service Connect

Where the inference workloads run

Inference got its own namespace, staging-inference, and its own node pool rather than sharing nodes with the web services:

  • A tainted node pool that scales from zero. n2d-standard-4 nodes with a workload-class=llm-cpu taint and label. I placed llm-cpu on the tainted inference pool. GKE system Pods also run there, while the embeddings server uses the general pool. Between sessions the inference pool is empty and costs nothing.
  • A separate Helm chart for model servers. A model server needs things a web service does not: a large download, a long startup, and hard inference limits. An init container downloads the model from a private bucket with the Pod's Workload Identity, checks its SHA-256 against a manifest pinned in Git, and refuses to start the server on a mismatch.
  • Admission policies for models. Kyverno requires model provenance (approved serving images, pinned model revisions) and inference bounds (context size, parallel slots, resource requests) on every model server.
  • Default-deny networking. Each model server admits only its listed callers and the Prometheus collectors. Model servers can resolve DNS, obtain credentials from the GKE metadata server, and download model files through the private Google APIs range, and nothing else, so a model server cannot reach the internet.

From an empty pool, a model server is ready in about 105 seconds: node creation, image pull, model download and verification, and model load.

Scaling on queued and running requests

CPU utilization is a poor scaling signal for LLM serving. A llama.cpp server with all its slots busy can sit at a stable CPU percentage while requests pile up in its queue.

The HPA scales llm-cpu on two Pod metrics scraped by Managed Service for Prometheus: requests waiting for a slot (llamacpp:requests_deferred, target 1 per Pod) and requests running (llamacpp:requests_processing, target 1.5 per Pod). The Custom Metrics Stackdriver Adapter exposes those series to the HPA.

In a warm scale-up test with four requests in flight, running requests crossed the HPA target. The HPA requested another replica after 8 seconds, and that replica was serving 31 seconds later.

I also compared fixed replica counts. One replica handling one request and two replicas handling two requests both had a median time to first token near 15 seconds. The prompt tokens split roughly 40/60 between the two Pods, showing that both were receiving work.

I also tested overload and loss of the scaling metrics:

  • Admission control is part of scaling. rag-api caps the work it queues per replica and refuses the rest with HTTP 429 and Retry-After. Under a flood of 15 concurrent clients, 116 of 158 requests were refused in about 0.1 s each, and rag-api's memory did not move.
  • A lost metric shows up as an HPA condition. With the HPA's bounds fixed at 2 replicas, I scaled the metrics adapter to zero: the HPA reported ScalingActive=False with FailedGetPodsMetric, and the scaling alert's query matched. When the adapter returned and the bounds went back to 1 to 2, the HPA scaled down within 12 seconds instead of waiting out its 5-minute window, because it had no recommendations from the outage to hold onto.

Releasing without cutting streams

Answers stream for tens of seconds, so a rolling update has to let in-flight streams finish. rag-api gets a preStop delay so the load balancer stops sending it new requests first, and a 150-second termination grace period so open streams complete.

Under continuous streaming load, a release and its Git-revert rollback each completed in about 4 minutes from merge to healthy, across 177 and 203 requests with no stream cut. One stream finished 30 seconds after its Pod began terminating, which is the drain doing its job. Five requests hit rag-api's first-token stall limit during those loads, one in the release run and four in the rollback run, all outside the rollout windows: on CPU, long prompts could wait longer than that limit for a free slot, which is why the first-token limit is now a separate 90-second setting.

Connecting to Model Armor privately

I wanted every question, every retrieved passage, and every answer screened for prompt injection and jailbreaks. I chose to call Model Armor from the workload rather than from the load balancer, because the load-balancer integration does not screen streamed responses and the workload is the only place that sees retrieved passages.

The three checks happen at different points. The question is screened alongside retrieval, before generation, so in blocking mode a flagged question is refused with HTTP 422 and nothing is generated. Passages are screened before they enter the prompt, so a flagged passage never reaches the model. The answer streams to the user as it is generated and is screened once it is complete: in blocking mode a flagged answer is replaced by a notice in the interface and in saved history. Answer screening therefore protects what is shown and kept afterward, not the tokens already streamed.

I initially configured a Model Armor template in Terraform, gave rag-api's Workload Identity principal the roles/modelarmor.user role, and allowed egress to the Google APIs range. When the lab came up, every check returned "unavailable" and rag-api served unscreened, as designed for a screening outage.

A test call from inside the Pod showed why: TLS verification failed. The platform's private DNS zone sends every *.googleapis.com name to private.googleapis.com, and that address does not serve the regional rep.googleapis.com hostnames that Model Armor templates require. The fix was a regional Private Service Connect endpoint for modelarmor.us-east4.rep.googleapis.com at a fixed internal address, a private DNS zone for that one hostname, and one extra NetworkPolicy egress rule. Cloud DNS answers from the most specific zone, so every other Google API kept its existing path. All three resources are created and destroyed with the lab, so they cost nothing between sessions.

After the endpoint merged, checks succeeded in 0.25 to 0.42 s from inside the Pod. Because the question is screened while retrieval runs, screening adds about 0.25 s to the time to first token at p50, under 2% of it. In blocking mode, Model Armor flagged the evaluation set's planted document, which tells "automated assistants" to switch off admission policies, and rag-api dropped that passage before the model saw it.

One more fix came out of this: the fallback had recorded that a check failed, not why. rag-api now logs the API method, error type, and HTTP status on every fallback, never the screened text.

Failure testing

Configuration faults arrived the same way a real change would: a pull request that Argo CD applied from Git, then a pull request that undid it, with no manual edits for self-heal to fight. That covered the metrics adapter, the embeddings NetworkPolicy, and the bad model revision below. Disruptions that are not configuration, deleting Pods, draining a node, and force-killing Pods, were run with kubectl under load.

Fault Outcome
One of two model Pods deleted under load The stopping Pod finished its streams; replacement ready in 47 s; 0 errors
Inference node drained under load The PodDisruptionBudget allowed it; one replica served everything; 0 errors
Both model Pods force-killed mid-stream The silent connection hit rag-api's stall limit; the stream ended as stalled and the UI kept the partial answer; Pods back in 31 s
rag-api cut off from the embeddings server by NetworkPolicy HTTP 503 with a clear retrieval error after 5 s; rag-api stayed ready, so the Gateway kept routing to it
Metrics adapter scaled to zero With bounds fixed at 2, the HPA reported FailedGetPodsMetric; the alert query matched

The bad model revision

The most useful test was a model revision whose manifest pinned the wrong SHA-256. CI checks that the chart values and the model manifest agree, so a consistent-but-wrong pair passes; only the download check against the real file can catch it. It did: the init container downloaded the 1.12 GB file in about 14 s, logged the expected and actual hashes, and refused to start the server.

The surprise was the rollout. The chart used maxSurge: 0, maxUnavailable: 1, chosen so a release never asks for an extra node. At one replica, that meant Kubernetes stopped the only good Pod before the new one proved itself, and the model was offline for 10 minutes until the git revert landed and the known-good Pod was ready, 4 minutes after the revert merged.

The fix is now in the chart: maxSurge: 1, maxUnavailable: 0, so a replacement Pod must be ready before an existing replica is removed, and the inference pool's node cap rose from 2 to 3 to leave room for the surge Pod. Chart validation passes; the next lab session validates the surge rollout live.

Restoring pgvector after deleting its volume

pgvector holds the corpus embeddings and saved conversations. I exported the database (2.8 MB in 3 s), deleted the StatefulSet and its volume, and let Argo CD recreate both, which took 36 seconds. The restore took 3 s, and the ordered chunk-ID fingerprint matched the original exactly, with all 45 documents present.

The first restore attempt stopped at schema "rag" already exists, because the database's init script creates the schema on every fresh volume. The runbook's restore command already used --clean --if-exists; it now explains why, and adds the fingerprint check before and after.

Observability and teardown

I added a 14-panel dashboard covering request outcomes, latency, inference capacity, and Model Armor checks, plus six PromQL alert policies. The dashboard and alerts are created and destroyed with the lab. I also corrected the alert labels so notification emails identify the affected resource.

Teardown is part of the design: the lab exists only during a session and is removed afterward, verified by an empty resource inventory and an unchanged Terraform plan. Two teardown details were fixed this time. Model Armor's Private Service Connect endpoint creates its own forwarding rule, which the load-balancer wait loop now skips because Terraform removes it next. And GKE recreates leftover network endpoint groups while the cluster still runs, so they are now deleted after the cluster is gone, followed by one more apply.

Scope

GPU serving is next. Further work covers answer quality on the small CPU model and live validation of the surge rollout. The linked evidence reports contain the full results and links to the raw measurements.

Links:

Validating the entire operational surface on CPU first—checksum-verified model downloads, Git-revert rollbacks under active SSE streams, HPA scaling on in-flight requests, and Private Service Connect screening—is a smart way to de-risk a cluster before paying for GPU nodes. Proving that 116 of 158 overload requests fail fast with HTTP 429 in 0.1 s while API memory stays flat at 55 MiB is much more valuable than synthetic happy-path benchmarks.

Verifying vector store recovery with an ordered chunk-ID fingerprint across all 1,382 chunks is a neat touch too. Too many teams test database backups without checking that the rebuilt index actually matches the pre-disaster corpus.