In this article, you'll learn how to make a multi-model inference serving platform on Kubernetes. You'll serve two models, one with one replica and another with two, on a total of 3 GPUs.

You'll use the Gateway API Inference Extension (GIE) to route traffic to those models based on metrics such as prefix cache affinity and user request for the selected model. You'll also configure pi as the client to test this setup end to end through one OpenAI-compatible endpoint.

One thing you need to remember before moving forward: no matter how powerful your GPUs are or the amount you've spent on the infrastructure to make this local AI Inference platform, if you go and tell your teams, "Hey everyone, you can now use the best open models with unlimited tokens. GLM 5.3-753B is available at example.com/v1/glm/53 and KIMI-k3-2.8T is available at example.com/v1/kimi/k3 and every model is at it's own endpoint.", they likely won't be happy.

Quite the opposite, in fact. People don't want to remember 10 different endpoints per model. They just want to select models using their harness with `/model` and get on with their tasks. This makes it harder to adopt an AI platform, and it's one of the things we'll fix in the article.

This article is for:

  • Platform engineers who are looking to build a local AI inference serving platform.
  • Anyone interested in prioritizing their local GPUs for inference and fallback to cloud when local GPUs aren't available.

What you'll get from this guide:

  • How to build and observe a multi-model inference platform on Kubernetes.
  • Terraform and Kubernetes artifacts to provision and destroy the setup on Google Cloud.
  • How to route LLM traffic to the correct model and pod replica based on different routing strategies.
  • Why regular Kubernetes Service load balancing fails for LLM inference traffic.
  • How to route your current conversation to correct pod that has your KV cache for faster decode and higher cache hit rate.

Every Kubernetes manifest used in the guide is available in the shkatara/kubernetes-llm-inference repository. The terraform scripts needed to provision and destroy the setup are available in the shkatara/kubernetes-llm-inference/terraform directory.

Clone the repo https://github.com/shkatara/kubernetes-llm-inference.git to inspect each manifest and apply them step by step. The end of the article covers common failure modes you'll almost certainly come up against on the first run.

Table of Contents

Prerequisites

Before following along, you'll need:

  • A Kubernetes cluster (1.31+) with at least three GPUs available. The demo works on GCP in an account with billing enabled.
  • The NVIDIA device plugin / GPU Operator installed, so nvidia.com/gpu shows up in node allocatable resources.
  • helm 3 and kubectl access to the cluster.
  • The pi agent harness installed on your machine (for the client section).
  • At least 16 GB of GPU memory per card. The examples load two models: Qwen2.5-3B and HuggingFaceTB/SmolLM2-1.7B in float16.
  • An OpenRouter API key (for the cloud fallback section when local GPU pools are down or saturated). If you don't have one, the LLM routing to different models running on Kubernetes still works. It's just the fallback that can't be used.

Why App-Level Routers Don't Work for Inference

When you start building a local AI inference platform, especially if your teammates or your users are already used to Claude or Cusror, the last thing you want to give them is different endpoints where different models are being served.

Developers won't like it if you tell them to use example.com/v1/qwen for using a Qwen model and example.com/v1/gemma for using a Gemma family model. They're set in their ways: they just open their harness and select a model using /model and carry on with their tasks.

When you have such a setup with different models at different endpoints, you might be tempted to write a custom router to send the requested model traffic to the right backends.

You may write a proxy, host it at llm.example.com, give this to your users, and tell them, "Hey, this is your one stop shop for every model. All models are available here at this URL. Just use /model in your harness and traffic goes to your model via this proxy."

What this proxy does in the end is interesting. It reads the model field from the request body, and forwards it to the right pod that holds that model. This does work for steering user traffic blindly to the model, but then two problems come up.

First, you'll need a way to keep the model replicas and proxy endpoints in sync for that model. Imagine you create 4 replica pods of a model, and the proxy only is updated to know about 1. The rest of the replicas are invisible to the proxy and so it gets no traffic.

It's the same as a hotel receptionist only knowing about 10 rooms, so they can reserve people in those 10 rooms. If you add 10 more rooms and don't tell the receptionist about them, they won't reserve those new rooms. They'd be empty. Similarly if you remove rooms and the receptionist isn't updated about it, they'd take more bookings than the rooms available.

So the sync between number of rooms (number of model pods) and the receptionist (the proxy) has to be real time.

Second, even if you could somehow keep the model replicas and proxy backends in sync, the routing problem is still there. The proxy will blindly (or at most round-robin) forward the traffic to the model replicas. It has no idea about queue depth, which replica contains the kv cache for the incoming request. It's routing, but not smart.

Sending the request to a GPU that doesn't have the KV Cache for your conversation is a hit to the time to first token, as the GPU on which this request lands on has to recalculate the entire prefill from scratch.

Also, you need to write everything yourself. Whether it's rate limiting, fallbacks if the model isn't available or overloaded, retries if a request fails, or anything else. Each of these lives in your proxy's codebase.

Where you wanted to build an AI inference platform, you ended up also managing a heavy router with a custom codebase.

The Gateway API Inference Extension (GIE) is the Kubernetes community's answer to both problems. It was designed by people from Google, Red Hat, and the vLLM and KServe communities specifically for inference traffic.

The Three Pieces: InferencePool, EPP, and Agentgateway

Our AI platform runs different pieces at different levels.

1. Agentgateway

This is the entrypoint for your LLM inference traffic. Think of this as something that sits on the edge of your cluster, exposes an OpenAI-compatible endpoint, and routes the traffic to the correct model and pod replica based on your routing logic. It can parse request bodies, route on the model field, count tokens, enforce token-based rate limits, run guardrails, and give you per-model observability.

2. InferencePool

This is a custom resource that groups model server pods into a single routable backend. You make one inferencepool for each model you'd like to serve. It uses labels and selectors on model pods to group them together. This is the answer to how many pods are used to serve a particular model. It's usually paired with an extension that makes routing decisions.

3. The Endpoint Picker (EPP)

This is that extension. You deploy one EPP per inferencepool. The EPP is the one that makes routing decision for that inferencepool across replicas. It watches the pods in the pool, scrapes their metrics such as queue depth, KV cache usage, and active requests, and for every incoming request picks the best pod.

Together the InferencePool and EPP form a single intelligent routable backend for a model.

Illustration of EPP and InferencePool working together

How a Request Flows Through the Stack

If you follow one request end to end, this is what it looks like:

  1. The client sends a request to the single OpenAI compatible endpoint at llm.example.com/v1/chat/completions with the model in the request body.
  2. The request is recieved by the Gateway. An existing prerouting policy from AgentGatewayPolicy is attached at the gateway that looks at the JSON request body, finds the value of model field, adds a new header to the request called x-model, and the request is moved onto the next step.
  3. After the request has moved on from the pre-routing phase and has the x-model header, where to forward that request (to which pod backend) is decided by the HTTProute. It selects the right pods that serves the model using the combination of two custom resource definitions: AgentGatewayBackend and InferencePool.
  4. Once the InferencePool is identified, the requested metadata is forwarded to the Endpoint Picker.
  5. Because the EPP is already scraping metrics for that selected inference pool, it can score pods based on the configuration given to it, aka what do you want to route on: prefix cache affinity, KV cache utilization, queue depth, and so on. Then it picks the right pod.
  6. The EPP returns back the best pod IP and port to the gateway using the x-gateway-destination-endpoint header.
  7. The gateway sends the request directly to the model pod IP and port.

Look at step 5. There's no Kubernetes Service load balancing involved in the flow anywhere. The EPP is the smart load balancer for the LLM traffic.

We aren't just routing blindly to the backend pods. We're routing to the best pod for the request based on the configuration given to it.

Request Flow Path

How the EPP Routes Traffic: Routing Strategies Explained

There are various reasons for how and why you might want to route the traffic in a certain way:

  1. You might want to route the traffic to the pod that's least used.
  2. You might want to route the traffic to the pod that already has your KV cache stored to reduce inter token latency.
  3. You might want to send traffic to pods that have the least queue depth.

You can mix and match based on your needs, and for that, there are several scoring strategies available.

1. Load-Aware Scheduling (queue-scorer and kv-cache-utilization-scorer)

If you're using vLLM, it exposes a lot of prometheus metrics such as the number of requests waiting, the number of running requests, and KV cache usage percentage.

The EPP scrapes these metrics and finds which pods are the most used. Pods that are busier or fuller are scored lower, spreading load to other replicas.

2. Prefix Cache Affinity (prefix-cache-scorer, Which We Care About)

For us, it matters that the request is served quickly. That means we want to avoid calculating the KV cache for every request. vLLM reuses its KV cache for prompts that share a token prefix, and if your conversation already cached the first 5k tokens on pod A, sending the next turn to pod B means recomputing all of it and re-prefilling. With this scoring strategy, we can try to send the request to the same pod A, if possible.

How Prefix Cache Affinity Keeps a Session on the Same GPU

An LLM is stateless during inference. Every single time we send a message in a chat or coding agent (pi), the client sends the entire conversation from the very beginning all over again:

  • Turn 1: [System Prompt + Question 1]
  • Turn 2: [System Prompt + Question 1 + Answer 1 + Question 2]
  • Turn 3: [System Prompt + Question 1 + Answer 1 + Question 2 + Answer 2 + Question 3]

There's a pattern: 95% of Turn 2 is identical at the start ("the prefix") to Turn 1. The prefix is simply the leading token sequence requests share. In our case it could be the System Prompt. In others, it could be system prompt + RAG context + user question. The prefix boundary is just the longest common leading sequence.

Reading that long prompt at the prefill stage and calculating the KV cache is heavy GPU math. So vLLM saves it in that GPU's memory. This is something very important you need to plan during the inference capacity planning phase.

While the model weights grow over time, this KV cache also grows with time based on the context window and the number of people using the model at once. This is stored in the GPUs memory.

To route the request to the same pod that has the KV cache stored, the EPP can use the prefix cache affinity scorer.

  1. Turn 1 arrives: Both GPU 1 and GPU 2 have nothing cached (score: 0 vs score: 0). EPP picks GPU 1, and remembers it in it's memory. Hash of [System Prompt + Question 1] is sent to GPU 1.
  1. Turn 2 arrives: The client sends [System Prompt + Question 1 + Answer 1 + Question 2] with zero session ID or cookie.
  2. EPP Hashes the prompt chunks. For this request that has the same system prompt + question 1, the EPP creates a hash of the request and sees which pods have the same hash in their KV cache. GPU #1 matches 96% of the chunks (prefix-cache-scorer = 0.96). GPU #2 matches 0% of the chunks (prefix-cache-scorer = 0.00).
  1. GPU #1 wins the score (0.96 vs 0.00), so EPP routes Turn 2 to GPU 1 again.

It makes a lot of sense to keep this prefix cache affinity in with the AgentGateway. If someone on your team uses the Gateway with a request that uses the same system prompt, there's a good chance that it'd be routed to the same pod that has the same hash for that prefix in the KV cache.

There are three caveats you should know:

  • This prefix cache affinity routing is best-effort at max. It's not a guarantee. You do this to reduce the time to first token. If the pod that has the cache is full or saturated, it makes more sense to send the request elsewhere, counting this as a cache miss rather thn an entire request failure.
  • The index lives in the EPP's memory. If the EPP pods are recreated, they do not have the idea of on which pod that cache prefix is stored.
  • Nothing outside the gateway should hit the model pods directly. Traffic that bypasses the EPP (a port-forward, a stray Service) desynchronizes the index.

How to Provision the Three-GPU Cluster with Terraform

Skip to the next section if you have a Kubernetes cluster with three GPUs and the NVIDIA GPU Operator installed in it. If not, we'll use terraform to create the infrastructure on Google Cloud Platform. Use the terraform setup in shkatara/kubernetes-llm-inference to spin up the three node and three GPU cluster in your GCP account.

The setup is interesting. Google Cloud limits how many GPUs you can ask for at one time in a project across every region in that project. And that limit is set to 1. Unless you've spent a good amount of money or the project is actively in use, Google Cloud won't let you have more than 1 GPU in any region in a project.

To solve this problem, we'll create three new projects with a billing account enabled. Each project gives us 1 spot VM with a GPU. To allow nodes to communicate with each other via private IPs in Kubernetes, we'll use VPC peering.

  • Project 1: one Spot n1-standard-8 VM (8 vCPU, 30 GB RAM, 100 GB SSD) with 1 x nvidia-tesla-t4 (16 GB VRAM), a static public IPv4 for the gateway, and the RKE2 control plane.
  • Project 2 and Project 3: one Spot n1-standard-4 VM in each project (4 vCPU, 15 GB RAM, 100 GB SSD, 1 x nvidia-tesla-t4), joined to Project 1's RKE2 server over private full-mesh VPC peering.
  • Locked-down firewall rules: The setup gets your public IPv4 and uses it to restrict access to SSH (22), Kubernetes API (6443), inference HTTP (80/443), and Grafana (3000) ingress to <your-ip>/32.
  • Total cost: across all three projects combined, the entire cluster costs roughly ~$0.85 USD per hour, or ~$20.50 USD per day if left running 24 hours. Leaving it running for two hours costs under $2.

NOTE: Always make sure to do a Terraform destroy after you're done with the cluster. Provisioning the environment takes around 15 to 20 minutes. I made the mistake of moving away from the terminal during provisioning only to realize the cluster has been running for around 6 hours, which stacked up the bill higher than expected.

Once you're authenticated with gcloud, checkout the code and run Terraform. Be sure to replace the project ids with your own. Remember to wait for around 20 minutes for kubectl get nodes to show the nodes after provisioning is done.

git clone https://github.com/shkatara/kubernetes-llm-inference.git cd kubernetes-llm-inference gcloud auth application-default login cat > terraform.tfvars <<EOF project_id = "<gcp-project-1>" worker_project_ids = [ "<gcp-project-2>", "<gcp-project-3>", ] region = "asia-south1" zone = "asia-south1-a" spot = true openrouter_api_key = "sk-or-v1-..." EOF terraform init terraform apply 

Once the provisioning is complete, get the kubeconfig to your machine using the helper output:

eval "$(terraform output -raw kubeconfig_command)" export KUBECONFIG=$PWD/kubeconfig.yaml kubectl get nodes 

How to Install Agentgateway with Inference Extension Support

Once you have the Kubernetes cluster with nodes that have 3 GPUs in them, install the Kubernetes Gateway API CRDs and the Gateway API Inference Extension CRDs.

Install these before Agentgateway so the controller discovers GatewayClass and InferencePool when it starts:

kubectl apply --server-side -f \ https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.4.0/standard-install.yaml kubectl apply -f \ https://github.com/kubernetes-sigs/gateway-api-inference-extension/releases/download/v1.4.0/manifests.yaml 

Then install the Agentgateway CRDs and controller with inferenceExtension.enabled=true:

helm upgrade -i agentgateway-crds \ oci://cr.agentgateway.dev/charts/agentgateway-crds \ -n agentgateway-system --create-namespace \ --version v1.7.0 helm upgrade -i agentgateway \ oci://cr.agentgateway.dev/charts/agentgateway \ -n agentgateway-system --version v1.7.0 \ --set inferenceExtension.enabled=true \ --set monitoring.enabled=true \ --set monitoring.proxy.namespaceSelector.any=true 

Verify that the GatewayClass exists:

kubectl get gatewayclass agentgateway 

How to Serve Two Models Across Three GPUs with vLLM

We're using vLLM to serve the models. How to run and fine tune vLLM deployments is a big topic in itself and is beyond our scope for this article. We want to focus on the inference. We'll use kubernetes deployments here running the models with vLLM with the GPUs.

For the Qwen-2.5 model, we'll be running two replicas of it across two pods with GPUs. This will serve as our demo to show the prefix cache affinity routing.

For the SmolLM2.1 model, we'll only run one replica. This serves as our demo to show the multi-model routing with single gateway entrypoint.

Read k8s/deployment-vllm-qwen-3b.yaml and k8s/deployment-vllm-smollm2-1-7b.yaml in the repo, then apply both deployments:

kubectl apply -f k8s/deployment-vllm-qwen-3b.yaml kubectl apply -f k8s/deployment-vllm-smollm2-1-7b.yaml 

There are two details in those manifests that matter on T4 GPUs:

  • --enable-prefix-caching explicitly keeps automatic prefix caching enabled so prefix KV blocks are cached and reported in Prometheus metrics (vllm:prefix_cache_hits_total).
  • --served-model-name needs to match the name of the model in AgentgatewayBackend and the x-model header, and each pod asks for nvidia.com/gpu: "1" so Kubernetes schedules the three pods across the three physical T4 nodes automatically.

We already talked about routing being done by the EPP and not using any Kubernetes service in front of the pods running our models.

How to Deploy the Endpoint Picker

Now that we know what the endpoint picker does, let's deploy it.

Because one EPP handles one inferencepool, we will need two of them, one for the Qwen inferencepool and one for the SmolLM inference pool.

Inspect the files related to the EPP in the k8s directory. These files contain:

  • A configmap that defines the routing strategies and what weight each has for the routing.
  • RBAC configuration to allow the EPP to watch the pods and the InferencePools and coordination leases
  • A deployment and service for the EPP, per EPP.

Apply the plugin config, RBAC, and both EPP Deployments and Services:

kubectl apply -f k8s/configmap-epp-plugins.yaml kubectl apply -f k8s/rbac-epp.yaml kubectl apply -f k8s/deployment-epp-qwen-3b.yaml kubectl apply -f k8s/service-epp-qwen-3b.yaml kubectl apply -f k8s/deployment-epp-smollm2-1-7b.yaml kubectl apply -f k8s/service-epp-smollm2-1-7b.yaml 

How to Define the InferencePools

We'll group the models and use them as a unit for routing the backend with the help of InferencePool. For each type of model you want to serve, you'll create a pool. We'll create two of them, each having different models. Think of this as your catalog of models that you want to serve.

Read the files for inferencepools in the k8s directory and apply them:

kubectl apply -f k8s/inferencepool-qwen-3b.yaml kubectl apply -f k8s/inferencepool-smollm2-1-7b.yaml 

Key fields in each InferencePool spec are:

  • selector.matchLabels picks the matching vLLM pods relevant to that InferencePool.
  • targetPorts is where the gateway sends inference traffic directly by pod IP and where the EPP scrapes vLLM /metrics.
  • endpointPickerRef names each pool's EPP Service on port 9002. failureMode: FailOpen means if the EPP is unreachable, the gateway forward the request to an endpoint of its own picking rather than failing the request.

At this point you have two pools, two EPPs, and no Services in front of the vLLM pods.

How to Expose One Endpoint with Body-Based Model Selection

Now the moment of truth. The last thing developers / teams want is to adopt a tooling that's hard. People are wired in with their own setups. We want to give them a unified endpoint for any model that teams want to consume.

Clients hit /v1/chat/completions exactly like OpenAI, and the model field in the JSON body decides everything.

Inspect the routing manifests in k8s/:

  1. gateway-inference.yaml: creates a Gateway that listens on http port 80. This is the entrypoint for all LLM traffic to the cluster.
  2. agentgatewaypolicy-extract-model.yaml: Creates a PreRouting policy and add it to the gateway. This lets the gateway look at incoming requests and evaluates the model field from body and writes it into an x-model request header before route matching runs. This is the place where we read what model the client wants to use.
  3. agentgatewaybackend-qwen-3b.yaml and agentgatewaybackend-smollm2-1-7b.yaml: Define an AgentgatewayBackend per model and point them at their respective inferencepools.
  4. httproute-models.yaml: Matches /v1 plus creates a mapping for the value of x-model header to a give AgentgatewayBackend. This is where we route the request to the correct InferencePool. Once the inferencepool is selected, the request metadata is sent to EPP to find the right backend pod for this request.

Apply the gateway, pre-routing policy, backends, and route:

kubectl apply -f k8s/gateway-inference.yaml kubectl apply -f k8s/agentgatewaypolicy-extract-model.yaml kubectl apply -f k8s/agentgatewaybackend-qwen-3b.yaml kubectl apply -f k8s/agentgatewaybackend-smollm2-1-7b.yaml kubectl apply -f k8s/httproute-models.yaml 

How to Fall Back to OpenRouter When Local GPUs Are Unavailable

Planned or unplanned, bad things can happen. Self-managed GPUs can go down, and the last thing you want teams to experience is an error like 503 Service Unavailable and the agents stop working.

Nodes drain for driver upgrades, vLLM pods crash on OOM, or every replica in a pool is saturated and shedding load. With a bare InferencePool, having zero ready pods means no requests can be served.

In case your local inferencepool isn't available for any reason, there's an option to failover to an external model provider. We'll use OpenRouter as our external model provider. We want to prioritize the use of our local models over external for all the right reasons and we can configure this priority in the AgentgatewayBackend.

In AgentgatewayBackend, under spec.ai.groups (priority groups), keep the local GPU InferencePool as Group 1 and OpenRouter model over HTTPS on openrouter.ai:443/api/v1/chat/completions) as Group 2.

When the local inferencepool isn't available for any reason within our defined threshold, it's evicted from the group and the request is then moved to Group 2.

This allows your user queries to still be served, at the cost of some latency and loss of context for the current request.

First, store your OpenRouter API key in Secret/openrouter-secret in the default namespace (Agentgateway reads the Authorization key and injects it as a Bearer token on outbound requests):

kubectl create secret generic openrouter-secret \ --namespace default \ --from-literal=Authorization="$OPENROUTER_API_KEY" 

Look at what happens on failover:

  • The client still sends "model": "qwen2.5-3b-instruct" to /v1/chat/completions. Nothing on the client changes.
  • While qwen2-5-3b-instruct has healthy GPU pods, Group 1 handles 100% of traffic, including EPP prefix-cache routing across the two T4 replicas.
  • When Group 1 is evicted, Group 2 rewrites the upstream model field to OpenRouter's slug (meta-llama/llama-3.2-3b-instruct), originates HTTPS with sni: openrouter.ai on /api/v1/chat/completions, and attaches openrouter-secret.

To make the cutover invisible to clients, we need policies to control the failure at different levels.

When the first request gets sent to the local inferencepool that's not available, the EPP returns a DirectResponse 503. Once this response is given, two polices do the following:

  1. pool-failover-health watches responses from the InferencePool. When the EPP returns 503 (zero ready GPU pods) or 429 (pool shedding load), consecutiveFailures: 1 immediately evicts Group 1 for 15s (with multiplicative backoff if it stays down).
  2. pool-failover-retry: The request that got a 503 or 429 response from EPP is replayed after 200ms on the same unavailable InferencePool. Because this is still already evicted for 15 seconds, the request is then sent to the fallback group 2 (OpenRouter).
kubectl apply -f k8s/agentgatewaypolicy-failover-health.yaml kubectl apply -f k8s/agentgatewaypolicy-failover-retry.yaml 

You can test the full failover and recovery loop in thirty seconds:

# 1. Simulate a GPU pool outage by scaling Qwen 3B to zero replicas kubectl scale deploy qwen2.5-3b-instruct --replicas=0 # 2. Send the exact same request, OpenRouter answers with meta-llama/llama-3.2-3b-instruct curl --retry 1 --retry-delay 1 --retry-all-errors -s http://<gateway-ip>/v1/chat/completions \ -H 'Content-Type: application/json' \ -d '{"model":"qwen2.5-3b-instruct","messages":[{"role":"user","content":"hi"}]}' \ | jq -r '.model' # Output: meta-llama/llama-3.2-3b-instruct # 3. Bring the local GPU replicas back kubectl scale deploy qwen2.5-3b-instruct --replicas=2 kubectl rollout status deploy/qwen2.5-3b-instruct 
Local Qwen 3B GPU pool scaled to zero replicas failing over automatically to OpenRouter meta-llama/llama-3.2-3b-instruct

Not just the logs but also in action. You can see this in the Pi session. It says 503 inference gateway: ServiceUnavailable, but the request didn't timeout or goes to a void. It's forwarded upstream to OpenRouter and we do get a response.

We can see, while actively using the model, that the request is being routed to OpenRouter after encountering an error from inference gateway. We get a 503, but then after a short delay, the request falls back to OpenRouter.

Fallback in Pi agent harness

Once the vLLM pods pass readiness and the eviction timer expires, Group 1 automatically rejoins at highest priority and subsequent requests return "qwen2.5-3b-instruct" from your local T4 GPUs again.

How to Connect the Pi Agent Harness to the Models

People have opinions, and they matter. Nobody on your team should be curling the gateway. Different people may prefer different harnesses: Claude Code, Codex, Antigravity, Pi, and so on. But here, we'll configure the open source Pi agent harness for our example. While the config snippets for each harness might differ, the idea is the same.

The Pi agent harness takes any OpenAI-compatible endpoint through ~/.pi/agent/models.json, so once it points at the gateway, agents get every model served by the cluster:

{ "providers": { "my-k8s-models": { "name": "Kubernetes Model Cluster", "baseUrl": "http://<GATEWAY_IP>/v1", "api": "openai-completions", "apiKey": "demo", "models": [ { "id": "qwen2.5-3b-instruct", "name": "Qwen2.5 3B (2x T4 pool)", "input": ["text"], "reasoning": false, "contextWindow": 8192, "maxTokens": 1024, "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } }, { "id": "smollm2-1.7b-instruct", "name": "SmolLM2 1.7B (1x T4 pool)", "input": ["text"], "reasoning": false, "contextWindow": 8192, "maxTokens": 1024, "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } } ], "compat": { "supportsDeveloperRole": false, "supportsReasoningEffort": false, "maxTokensField": "max_tokens" } } } } 

How to read this config:

  • baseUrl is the gateway, including /v1.
  • api: "openai-completions" matches what vLLM serves behind the gateway.
  • The model ids (qwen2.5-3b-instruct, smollm2-1.7b-instruct) match --served-model-name, x-model, and AgentgatewayBackend one-for-one.
  • apiKey uses environment interpolation. Agentgateway accepts any bearer token unless you configure auth policies, but the field is still required by Pi.
  • The compat flags turn off provider-specific fields that self-hosted OpenAI-compatible servers tend to reject.

Users pick a model inside Pi with /model, or start Pi with --model and the name. Switching models mid-session is instant because it's just a different body field to the same gateway endpoint, but to a different pool. Because the routing is wired in the AgentGateway, you selecting a different model is automatically routed to the correct pool.

Once the config is in place, we can start Pi and see the models available.

Pi Harness Models

A nice property for agent workloads specifically is that agents make many sequential calls with long, growing prompts. That's exactly the workload prefix cache affinity was built for.

Repeated agent turns on qwen2.5-3b-instruct keep hitting whichever of the two T4 GPUs holds their warm KV cache without any special client configuration.

How to Test the Setup

Wait for the pods to come up, then grab <gateway-ip> from terraform output -raw public_ip (or kubectl get gateway inference-gateway), where ServiceLB exposes inference-gateway directly on port 80:

kubectl get pods -w 
curl http://<gateway-ip>/v1/chat/completions \ -H 'Content-Type: application/json' \ -d '{"model":"qwen2.5-3b-instruct","messages":[{"role":"user","content":"hi"}]}' 

Then switch the model field to smollm2-1.7b-instruct and confirm the second pool answers. Same URL, different model pool, different GPU.

Body-based model routing dispatching qwen2.5-3b-instruct and smollm2-1.7b-instruct across dedicated T4 GPU pods

How to Prove Session Affinity Works

Because the Qwen model is already running with two replicas on two t4 cards, you can verify prefix-based KV cache routing immediately without rescaling anything.

We'll tail the logs of two pods. One tail is for the decisions EPP makes and the second tail is for the requests being served by the pods.

On terminal A:

kubectl logs -f -l app=qwen2.5-3b-instruct --tail=-1 --prefix \ | grep -E "POST /v1|Prefix cache hit rate" 

And on terminal B:

kubectl logs -f deploy/epp-qwen2-5-3b-instruct | grep -E "Calculated score|Completed running picker|Request handled" 

Now run a Pi session against the Qwen model through the gateway.

Because Qwen runs multiple models, we can see the requests that have the same system prompt are served by the same pod. We already talked about this in the previous section.

A live Pi coding session sends the request to the gateway and EPP forwards the request to the same pod which increases the prefix_cache_hits_total Prometheus metric. The request goes here because the hash of the system prompt plus the request for Nth and N-1th turns are the same.

Three requests sent to the same pod

Deciding which pod gets the request is highly configurable. This is done by the configmap in EPP. You can decide what matters more for you and how to weight that decision.

Do you prefer spreading the load across all the pods for better utilization, or do you prefer the request going to the pod that has the most cache hit rate ? Or the one with the most free memory, or the one with the least queue depth?

Each scorer grades every GPU pod from 0 (worst) to 1 (best), multiplies that grade by its weight, and adds them up. For instance, imagine there are three scorers. Each scorer has a static weight and a dynamic score that's based on the metrics of that pod.

  • Queue depth (weight 2): both pods have empty queues, so both get 1.0 * 2 = 2 points.
  • KV memory free (weight 2): both pods have plenty of free KV memory, so both get 1.0 * 2 = 2 points.
  • Prefix cache match (weight 3): on Turn 2, pod xsk96 already holds 98.4% of the prompt in its KV cache (0.984375 * 3 = 2.95 points), while the cold pod cdbpf holds none of it (0 * 3 = 0 points).

Adding those up, the warm pod wins, so the EPP sends Turn 2 straight back to the same GPU pod, which for us is 10.42.2.252:8000.

This is also evident in Grafana. When you keep using the same model in a Pi session, the cache hits are high on the same model during that time by the Grafana dashboard. Check the Per-Pod Prefix Cache Hit Rate (%).

Grafana dashboard showing prefix cache hits for qwen2.5-3b-instruct

How to Monitor Routing, KV Cache, and GPUs with Prometheus and Grafana

In production, there are multiple layers to monitor to say your local AI Inference platform is healthy.

  • The GPU hardware with DCGM metrics
  • The layer that serves your model with vLLM metrics
  • The layer that makes routing decisions with EPP metrics
  • The last one that exposes your model as a single OpenAI-compatible endpoint with Agentgateway metrics

Install kube-prometheus-stack before agentgateway and gpu-operator so the ServiceMonitor and PodMonitor CRDs exist up front, and disable the default Helm-release label filter so Prometheus picks up monitors from every namespace:

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts helm repo update helm upgrade -i kube-prometheus-stack prometheus-community/kube-prometheus-stack \ -n monitoring --create-namespace \ --set alertmanager.enabled=false \ --set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false \ --set prometheus.prometheusSpec.podMonitorSelectorNilUsesHelmValues=false \ --set grafana.sidecar.dashboards.searchNamespace=ALL 

With these settings, Agentgateway automatically creates its ServiceMonitor, proxy PodMonitor, and a pre-built Grafana dashboard.

Inspect the monitoring, dashboard, and Grafana Gateway manifests in k8s/:

  • podmonitor-vllm.yaml and servicemonitor-epp.yaml: These monitor vllm pods and EPP service.
  • configmap-grafana-dashboard-llm.yaml: provisions a custom LLM Inference & GPU Routing dashboard. This dashboard covers time to first token and cloud fallbacks. EPP prefix-indexer hit ratio and queue depth. Per pod vLLM KV prefix cache hits and physical t4 gpu usage and VRAM.
  • gateway-grafana.yaml and httproute-grafana.yaml: These lets you expose the Grafana service using a dedicated gateway for querying.

Apply the monitors, dashboard, and Grafana Gateway:

kubectl apply -f k8s/podmonitor-vllm.yaml kubectl apply -f k8s/servicemonitor-epp.yaml kubectl apply -f k8s/configmap-grafana-dashboard-llm.yaml kubectl apply -f k8s/gateway-grafana.yaml kubectl apply -f k8s/httproute-grafana.yaml 

Fetch the generated admin password and open http://<gateway-ip>:3000 (under Dashboards, open LLM Inference & GPU Routing and Agentgateway):

kubectl -n monitoring get secret kube-prometheus-stack-grafana \ -o jsonpath='{.data.admin-password}' | base64 -d && echo 
Custom LLM Inference and GPU Routing Grafana dashboard showing agentgateway failover, EPP prefix indexer hit ratio, vLLM per-pod prefix cache hits, and NVIDIA DCGM T4 GPU telemetry

The bundled Agentgateway dashboard also tracks gateway memory, CPU, request rates by HTTP status (200 Upstream vs 503 DirectResponse during simulated outages), and token consumption per model:

Bundled Agentgateway Grafana dashboard showing request status breakdown and LLM token consumption

These are some of the important metrics you'll want to observe and alert at across each layer. Here are the highest-signal metrics to watch across each layer:

Gateway:

  • agentgateway_gen_ai_client_token_usage: This metric is a histogram and includes important information about the request and the response from the LLM, such as whether the metric is a request or response, the model that was used for request and response. When local GPUs serve traffic, both labels read either Qwen or SmolLM and during an OpenRouter failover, the response model flips to meta-llama/llama-3.2-3b-instruct.
  • agentgateway_gen_ai_server_time_to_first_token: Time to first token for client-facing streaming. This drops with higher cache hits on Turn 2+ when prefix affinity hits a warm GPU.
  • agentgateway_gen_ai_server_time_per_output_token and agentgateway_requests_total: This shows the inter token latency and gateway request/error rates. This is useful to alert on high latency. This is something that makes your users feel that the inference is slow.

EPP:

  • inference_extension_prefix_indexer_hit_ratio and inference_extension_prefix_indexer_hit_bytes: This shows how much of each incoming prompt matched cached prefix blocks in the EPP's in-memory index. You usually want a higher hit ratio and higher bytes as an indication of good prefix cache hits.
  • inference_pool_average_kv_cache_utilization, inference_pool_average_queue_size, inference_pool_per_pod_queue_size, and inference_pool_ready_pods: live pool saturation and replica health per InferencePool.

Model Server:

  • vllm:prefix_cache_hits_total / vllm:prefix_cache_queries_total: This shows the per-replica KV prefix cache hit rate, which climbs on the warm replica while the other replica stays flat.
  • vllm:kv_cache_usage_perc, vllm:num_requests_running, and vllm:num_requests_waiting: per-pod KV memory fill and queue depth.

GPU Hardware:

  • DCGM_FI_DEV_GPU_UTIL and DCGM_FI_DEV_FB_USED: Physical T4 compute % and VRAM consumption across all three cards. The DGCM exporter collects hardware related metrics including the temperature of the GPU. Higher temperatures means throttling and lower performance.

Common Issues and How to Solve Them

1. GPU pods stuck in Pending (or GCP rejects VM creation).

If your pod requests a GPU and that GPU isn't available, the pod stays pending. If the VM creation is rejected, it's probably because the quota for GPUs in your project across all regions is...