Build an LLM gateway on Civo that routes between relaxAI and your own GPU
Route every request through one endpoint that sends private traffic to your own GPU and bursts to relaxAI, with automatic fallback and per-request cost tracking.
Written by
Software Engineer at GoCardless
Written by
Software Engineer at GoCardless
You hardcode a model provider’s endpoint into your first service. When another service needs the same model, you add the endpoint there too. Six services later, that address is scattered across your code.
If the provider goes down, all six services fail. There’s no central way to reroute traffic, so you update and redeploy each service. Even without an outage, you face the same work when routing cheaper requests to a smaller model or keeping sensitive traffic on a private backend. Routing logic ends up repeated in every app.
A gateway brings that logic into one place. Services send requests to a single endpoint, and the gateway forwards each request to its configured backend. Switching models or adding a fallback means updating one configuration file rather than every service.
In this tutorial, you’ll build that gateway with LiteLLM on Civo Kubernetes. It connects relaxAI for hosted requests and a self-hosted model running on one NVIDIA L40S for private traffic. The gateway handles routing, failover, and per-request cost tracking.
What you'll build
You'll set up a Civo Kubernetes cluster with a LiteLLM gateway connecting two model backends. Applications use a single endpoint, with the gateway handling routing and fallback.
The setup has four parts:
- The gateway: A CPU-only LiteLLM Deployment exposing an OpenAI-compatible endpoint through a Civo LoadBalancer.
- Two backends: relaxAI for hosted inference and a self-hosted vLLM model on a single NVIDIA L40S for private inference.
- Fallback routing: If the private model goes down, LiteLLM redirects requests to relaxAI without requiring application changes.
- Cost tracking: Response headers report per-request costs, allowing you to compare hosted and private calls.
Once deployed, you'll test routing to both backends, take the private model offline to verify fallback, and compare the costs reported for each path.
Prerequisites
Before you begin, make sure your Civo account is ready, you have a relaxAI key, and the required tools are installed.
Account
- A Civo account with access to Kubernetes and GPU (L40S) nodes.
- A relaxAI API key, created from your relaxAI account. API access requires the relaxAI Plus plan; follow Create API Key to generate one.
Local tools
- Civo CLI for provisioning the cluster and GPU node pool
- kubectl for communicating with the cluster
- Helm for installing the NVIDIA GPU Operator
Tested versions
Secrets
The gateway needs two secrets: your relaxAI API key and a master key you generate to protect its endpoint. Keep both in a local .env file outside version control, then create a Kubernetes Secret from that file so the credentials reach the cluster without being committed.
Add your relaxAI key to .env:
echo "RELAX_API_KEY=<paste-your-key>" >> .env
Generate the master key and add it too:
echo "LITELLM_MASTER_KEY=sk-$(openssl rand -hex 16)" >> .env
Check that the file holds both entries:
cut -d= -f1 .env
The output shows RELAX_API_KEY and LITELLM_MASTER_KEY.
Project structure
llm-gateway/├── .env # relaxAI key + gateway master key└── kubernetes/├── namespace.yaml # the gateway namespace├── deployment-model.yaml # self-hosted vLLM model + Service├── litellm-configmap.yaml # model_list, fallbacks, cost tracking└── litellm-deployment.yaml # LiteLLM proxy + LoadBalancer Service
With your Civo account ready, tools installed, and both keys saved in .env, you can begin.
How it fits together
Three things sit between your app and an answer: the gateway and the two backends it chooses from. Here's what each one does and how a single request moves through them.

The setup has three components:
- The gateway: A LiteLLM proxy that routes requests based on the model name in model_list and applies configured fallback rules when a backend fails. It runs on CPU without hosting a model.
- The hosted backend: relaxAI, accessed through its public API and billed per token.
- The private backend: A vLLM server running Qwen3-8B on a Civo L40S GPU inside the Kubernetes cluster.
When an application sends a request, LiteLLM matches the requested model name to its configured backend and forwards the call. If the private model becomes unavailable, the configured fallback redirects the request to relaxAI. The gateway also provides token usage and per-request cost information.
The infrastructure is straightforward: a small CPU node runs LiteLLM and the Kubernetes system pods, while the L40S handles private inference. A LoadBalancer exposes the gateway, and relaxAI adds usage-based charges without requiring another GPU node.
Creating the cluster
Create a Kubernetes cluster with two node pools: a small CPU node for system workloads and LiteLLM, and an L40S GPU node for vLLM. This keeps the GPU dedicated to model inference while the gateway runs on cheaper CPU resources.
Get your API key from the Civo dashboard by following Retrieve and Reset Your Civo API Key.
Authenticate the Civo CLI and set your region:
civo apikey save my-key YOUR_CIVO_API_KEYcivo apikey use my-keycivo region use NYC1
Create the cluster with a single small CPU node:
civo kubernetes create llm-gateway \--size g4s.kube.medium \--nodes 1 \--region NYC1 \--wait
The --wait flag holds the terminal until the control plane is ready, which takes about 90 seconds. Then add the L40S GPU node pool:
civo kubernetes node-pool create llm-gateway \--size an.g1.l40s.kube.x1 \--nodes 1 \--region NYC1
Once the GPU node joins, save the kubeconfig so kubectl can access the cluster:
civo kubernetes config llm-gateway --region NYC1 --save
Verify both nodes are ready:
kubectl get nodes
Both the small CPU node and the L40S GPU node must show Ready before moving on.

Two nodes in Ready state
Install the NVIDIA GPU operator
The cluster is ready, but Kubernetes still needs the NVIDIA GPU Operator to expose the GPU as a schedulable nvidia.com/gpu resource. Install the Operator with the toolkit disabled, since Civo’s GPU image already includes the NVIDIA Container Toolkit.
Add the NVIDIA Helm repository:
helm repo add nvidia https://helm.ngc.nvidia.com/nvidiahelm repo update
Install the Operator:
helm upgrade --install gpu-operator \-n gpu-operator --create-namespace \nvidia/gpu-operator \--version 25.10.1 \--set driver.enabled=true \--set toolkit.enabled=false \--set devicePlugin.enabled=true \--set gfd.enabled=true \--set operator.defaultRuntime=containerd \--set validator.cuda.runtimeClassName=nvidia
A STATUS: deployed message means the install succeeded. The Operator then brings up several pods on the GPU node; the driver loads first, and the other components restart around it, so give it a few minutes to settle:
kubectl get pods -n gpu-operator -w
Wait until the driver, device plugin, and validators are all Running or Completed.

gpu-operator pods Running/Completed
Confirm the GPU is now visible to Kubernetes:
kubectl get nodes -o custom-columns="NAME:.metadata.name,GPU:.status.allocatable.nvidia\.com/gpu"
The L40S node reports GPU = 1: one physical card, one schedulable unit. That single GPU is all the self-hosted model needs.

node showing nvidia.com/gpu = 1
With the cluster running and the GPU available, you’re ready to deploy the self-hosted model that forms the gateway’s private path.
Deploying the self-hosted model
Qwen3-8B runs on a single L40S GPU through vLLM, which LiteLLM accesses via an internal Kubernetes Service and an OpenAI-compatible API. At startup, vLLM downloads the Apache-2.0-licensed model from Hugging Face without an access token.
First, create a namespace for the gateway resources. Save it as kubernetes/namespace.yaml:
apiVersion: v1kind: Namespacemetadata:name: llm-gateway
Apply it so the namespace exists before anything is deployed into it:
kubectl apply -f kubernetes/namespace.yaml
With the namespace created, define the vLLM Deployment and its Service, which provides a stable internal address for the model.
Save the manifest as kubernetes/deployment-model.yaml:
apiVersion: apps/v1kind: Deploymentmetadata:name: qwen3-8bnamespace: llm-gatewaylabels:app: qwen3-8bspec:replicas: 1selector:matchLabels:app: qwen3-8btemplate:metadata:labels:app: qwen3-8bspec:containers:- name: vllmimage: vllm/vllm-openai:v0.33.0args:- "--model"- "Qwen/Qwen3-8B"- "--port"- "8000"- "--gpu-memory-utilization"- "0.90"- "--max-model-len"- "8192"ports:- containerPort: 8000resources:limits:nvidia.com/gpu: 1volumeMounts:- name: cachemountPath: /root/.cache/huggingface- name: shmmountPath: /dev/shmreadinessProbe:httpGet:path: /healthport: 8000initialDelaySeconds: 120periodSeconds: 10livenessProbe:httpGet:path: /healthport: 8000initialDelaySeconds: 600periodSeconds: 15volumes:- name: cacheemptyDir: {}- name: shmemptyDir:medium: MemorysizeLimit: 4Gi---apiVersion: v1kind: Servicemetadata:name: qwen3-8bnamespace: llm-gatewayspec:selector:app: qwen3-8bports:- port: 8000targetPort: 8000
Three settings matter: nvidia.com/gpu: 1 allocates the L40S, while --gpu-memory-utilization 0.90 sets vLLM’s GPU memory target to 90%. The livenessProbe waits ten minutes before its first check, giving the model time to download and load without restarting the pod.
Apply the manifest to create the Deployment and its Service:
kubectl apply -f kubernetes/deployment-model.yaml
On first start, vLLM downloads the Qwen3-8B weights from Hugging Face, so the pod takes a few minutes to become ready. Watch its progress:
kubectl get pods -n llm-gateway -w
Keep an eye on the READY column specifically. The pod will sit at 0/1 while the model loads, then flip to 1/1 Running once vLLM has finished and its health check passes.

qwen3-8b pod at 1/1 Running
Verify the model answers
The model is accessible only within the cluster at qwen3-8b:8000. To verify it, run a temporary pod and use curl to check which model the server is serving:
kubectl run curl-test -n llm-gateway --rm -it --restart=Never --image=curlimages/curl:8.11.1 -- \curl -s http://qwen3-8b:8000/v1/models
The response lists Qwen/Qwen3-8B. The server is up, and the model is loaded.

Response listing Qwen/Qwen3-8B
Listing the model proves the server is running, but not that it can actually generate. Send a real chat completion to confirm it responds:
kubectl run curl-test -n llm-gateway --rm -it --restart=Never --image=curlimages/curl:8.11.1 -- \curl -s http://qwen3-8b:8000/v1/chat/completions \-H "Content-Type: application/json" \-d '{"model":"Qwen/Qwen3-8B","messages":[{"role":"user","content":"In one sentence, what is Kubernetes?"}]}'
A normal chat completion comes back. The private backend is serving requests.
Qwen3 includes its reasoning in a <think>…</think> block before the final answer, which is why the response is longer than one sentence.

Chat completion response from the in-cluster model
The gateway will use this internal Service address to reach the private model:
http://qwen3-8b.llm-gateway.svc.cluster.local:8000/v1
Configuring the LiteLLM gateway
Configure LiteLLM routing and fallback with three Kubernetes resources: a Secret for credentials, a ConfigMap for routing rules, and a Deployment that exposes the gateway through a LoadBalancer.
Create the secret
LiteLLM uses the relaxAI API key and a master key to protect its endpoint. You stored both in .env earlier.
Create a Kubernetes Secret from that file to supply the credentials without adding them to a manifest:
kubectl create secret generic litellm-secret -n llm-gateway --from-env-file=.env
Verify that the Secret contains both entries:
kubectl get secret litellm-secret -n llm-gateway -o jsonpath='{.data}' | grep -o '"[A-Z_]*":'
The output shows RELAX_API_KEY and LITELLM_MASTER_KEY, which are the two names the gateway config will reference.
Write the routing config
The LiteLLM configuration registers both backends in model_list, defines fallback behavior in router_settings, and sets the gateway's master key.
Save it as kubernetes/litellm-configmap.yaml:
apiVersion: v1kind: ConfigMapmetadata:name: litellm-confignamespace: llm-gatewaydata:config.yaml: |model_list:- model_name: private-qwenlitellm_params:model: hosted_vllm/Qwen/Qwen3-8Bapi_base: http://qwen3-8b.llm-gateway.svc.cluster.local:8000/v1api_key: "none"input_cost_per_token: 0output_cost_per_token: 0- model_name: hosted-relaxlitellm_params:model: openai/DeepSeek-V41-Flashapi_base: https://api.relax.ai/v1api_key: os.environ/RELAX_API_KEYinput_cost_per_token: 0.00000018output_cost_per_token: 0.00000072litellm_settings:drop_params: truerouter_settings:fallbacks: [{"private-qwen": ["hosted-relax"]}]num_retries: 2general_settings:master_key: os.environ/LITELLM_MASTER_KEY
Each model_list entry links a gateway model name to its backend. private-qwen connects to the internal vLLM Service through hosted_vllm/, while hosted-relax uses openai/ and credentials from the Secret to access relaxAI.
LiteLLM estimates per-request costs from the configured rates. Private inference has a zero per-token rate because the GPU is billed hourly, while relaxAI charges per token. Keep the hosted rates aligned with the model’s current pricing.
The fallback rule redirects failed private-qwen requests to hosted-relax, with two retries configured. Since fallback traffic leaves the private cluster, use this rule only for workloads approved for hosted processing.
Apply the ConfigMap:
kubectl apply -f kubernetes/litellm-configmap.yaml
Deploy the proxy
With the Secret and configuration ready, create the LiteLLM deployment. The manifest runs a single CPU pod, mounts the configuration, loads credentials from the Secret, and exposes the gateway through a Civo LoadBalancer.
Save it as kubernetes/litellm-deployment.yaml:
apiVersion: apps/v1kind: Deploymentmetadata:name: litellmnamespace: llm-gatewaylabels:app: litellmspec:replicas: 1selector:matchLabels:app: litellmtemplate:metadata:labels:app: litellmspec:affinity:nodeAffinity:requiredDuringSchedulingIgnoredDuringExecution:nodeSelectorTerms:- matchExpressions:- key: nvidia.com/gpu.presentoperator: DoesNotExistcontainers:- name: litellmimage: ghcr.io/berriai/litellm:v1.99.1args:- "--config"- "/app/config.yaml"- "--port"- "4000"ports:- containerPort: 4000envFrom:- secretRef:name: litellm-secretvolumeMounts:- name: configmountPath: /app/config.yamlsubPath: config.yamlreadinessProbe:httpGet:path: /health/readinessport: 4000initialDelaySeconds: 15periodSeconds: 10livenessProbe:httpGet:path: /health/livelinessport: 4000initialDelaySeconds: 30periodSeconds: 15volumes:- name: configconfigMap:name: litellm-config---apiVersion: v1kind: Servicemetadata:name: litellmnamespace: llm-gatewayspec:type: LoadBalancerselector:app: litellmports:- port: 4000targetPort: 4000
envFrom loads both keys from the Secret as environment variables, allowing the os.environ/... references to resolve. The subPath mount places the configuration at /app/config.yaml, where LiteLLM reads it on startup. The affinity rule keeps the gateway off any node the GPU Operator has labelled as having a GPU. It runs on the CPU node instead, so it stays up, and can still fall back to relaxAI, even if the GPU node goes down.
Apply the Deployment and its Service:
kubectl apply -f kubernetes/litellm-deployment.yaml
Unlike the model, the gateway has nothing to download, so it comes up quickly. Watch for it to reach 1/1 Running:
kubectl get pods -n llm-gateway -w
The litellm pod should reach 1/1 Running within a minute. If it keeps restarting, check the pod logs for a configuration error or missing key.

litellm gateway pod at 1/1 Running
Check that the gateway landed on the CPU node and the model on the L40S:
kubectl get pods -n llm-gateway -o widekubectl get nodes -L nvidia.com/gpu.present
The second command marks the L40S node with true in the GPU.PRESENT column. In the first, qwen3-8b should sit on that node and litellm on the other one.
Verify the endpoint
The LoadBalancer gives the gateway a public address. Civo takes a minute or two to assign it, so watch for the external IP to appear:
kubectl get svc litellm -n llm-gateway -w
Wait until the EXTERNAL-IP column shows an address instead of <pending>, then press Ctrl+C.

litellm service with an assigned EXTERNAL-IP
Save the address and the master key into shell variables so the next commands are easy to read. The IP comes from the Service, and the key comes from your .env:
GW=$(kubectl get svc litellm -n llm-gateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}')KEY=$(grep '^LITELLM_MASTER_KEY=' .env | cut -d= -f2-)
Keep this terminal open, as the remaining commands use both variables. If you switch terminals, set them again with the commands above.
Now ask the gateway which models it serves. Unlike the earlier backend checks, this request goes through LiteLLM and requires the master key:
curl -s "http://$GW:4000/v1/models" -H "Authorization: Bearer $KEY"
The response lists both private-qwen and hosted-relax. Two backends, one endpoint, one key: the gateway is up and presenting both paths through a single address.

Listing both aliases
With the gateway running and both backends registered, the next section sends real requests to each one and watches the gateway route them.
Routing to each backend
You registered both models with the gateway. Send a request to each to confirm LiteLLM routes traffic correctly.
Start with private-qwen, which forwards the request to the self-hosted model on the L40S:
curl -s "http://$GW:4000/v1/chat/completions" \-H "Authorization: Bearer $KEY" \-H "Content-Type: application/json" \-d '{"model":"private-qwen","messages":[{"role":"user","content":"In one sentence, what is Kubernetes?"}]}'
The answer comes back with "model": "private-qwen", so the gateway routed it to the private backend. The response also carries a vLLM system_fingerprint, a further sign it came from your own pod rather than anywhere else.
Now the hosted path. The command is identical except for the model name: this one names hosted-relax, so the gateway sends it out to relaxAI instead:
curl -s "http://$GW:4000/v1/chat/completions" \-H "Authorization: Bearer $KEY" \-H "Content-Type: application/json" \-d '{"model":"hosted-relax","messages":[{"role":"user","content":"In one sentence, what is Kubernetes?"}]}'
This answer comes back with "model": "hosted-relax", served by relaxAI across the public internet. Nothing about the request changed except the model name in the body, yet the two calls landed on entirely different backends.
Both backends now respond through the same endpoint and API key, with the requested model determining the route. To change a backend, you edit the gateway config.
Next, take the private backend offline to verify that automatic fallback keeps requests working.
Watching a backend fail, and the fallback catches it
You configured LiteLLM to redirect failed private-qwen requests to hosted-relax. To test this, take the private model offline to check whether relaxAI handles the request.
Scale the model Deployment to zero replicas:
kubectl scale deployment qwen3-8b -n llm-gateway --replicas=0
Check that the pod has terminated:
kubectl get pods -n llm-gateway -w
Wait until qwen3-8b disappears from the list, leaving the LiteLLM gateway running.

qwen3-8b terminating, with LiteLLM still running
With the private backend offline, send another request to private-qwen:
curl -s "http://$GW:4000/v1/chat/completions" \-H "Authorization: Bearer $KEY" \-H "Content-Type: application/json" \-d '{"model":"private-qwen","messages":[{"role":"user","content":"In one sentence, what is Kubernetes?"}]}'
The request still succeeds. Although the caller specified private-qwen, LiteLLM falls back to hosted-relax. The response's model field shows DeepSeek-V41-Flash: relaxAI handled it.
The gateway recovered from a private backend outage. Because fallback requests leave the cluster, the rule should only apply to data approved for hosted processing.
Restore the private backend:
kubectl scale deployment qwen3-8b -n llm-gateway --replicas=1
Monitor the pod as vLLM starts again:
kubectl get pods -n llm-gateway -w
Wait until qwen3-8b returns to 1/1 Running.
With both backends available again, the next section examines the cost information LiteLLM returns for each request.
Reading per-request cost
LiteLLM calculates the cost of each request using the token rates configured for its backends. The result is available in the response headers, without requiring a separate database or logging setup.
The input_cost_per_token and output_cost_per_token values defined earlier provide these rates:
- model_name: hosted-relaxlitellm_params:model: openai/DeepSeek-V41-Flashapi_base: https://api.relax.ai/v1api_key: os.environ/RELAX_API_KEYinput_cost_per_token: 0.00000018output_cost_per_token: 0.00000072
These rates estimate hosted usage; update them to match relaxAI's current prices. LiteLLM records zero per-token cost for private inference, but the L40S still incurs hourly charges.
Send a request to hosted-relax with -i to include response headers:
curl -s -i "http://$GW:4000/v1/chat/completions" \-H "Authorization: Bearer $KEY" \-H "Content-Type: application/json" \-d '{"model":"hosted-relax","messages":[{"role":"user","content":"Write two sentences about GPUs."}]}' \| grep -i 'x-litellm-response-cost'
The x-litellm-response-cost header reports the estimated request cost, calculated from token usage and the configured rates.

x-litellm-response-cost header on a hosted request
Now send the same request to the private backend and read its headers the same way:
curl -s -i "http://$GW:4000/v1/chat/completions" \-H "Authorization: Bearer $KEY" \-H "Content-Type: application/json" \-d '{"model":"private-qwen","messages":[{"role":"user","content":"Write two sentences about GPUs."}]}' \| grep -i 'x-litellm-response-cost'
The private request should report a cost of zero, reflecting its configured per-token rate rather than the GPU's operating expense.

x-litellm-response-cost at zero on a private request
You've now checked routing, fallback, and per-request cost. The next section sends one request to each backend in a single pass.
Verifying the whole path
The previous tests confirmed the gateway's three core capabilities:
- Routing: Both private-qwen and hosted-relax respond through the same endpoint.
- Fallback: LiteLLM redirects failed private requests to relaxAI.
- Per-request cost: Response headers report the cost of each call, with hosted usage priced per token and private inference configured at zero.
As a final check, run the following loop to send a request to each model through the gateway:
for model in hosted-relax private-qwen; doecho "--- $model ---"curl -s -i "http://$GW:4000/v1/chat/completions" \-H "Authorization: Bearer $KEY" \-H "Content-Type: application/json" \-d "{\"model\":\"$model\",\"messages\":[{\"role\":\"user\",\"content\":\"Write two sentences about GPUs.\"}]}" \| grep -i 'x-litellm-response-cost'echodone
Both backends still answer through the one endpoint after the fallback test.

Hosted vs private cost
Clean up
The L40S node and the LoadBalancer bill by the hour until you delete them. When you finish, tear everything down.
Delete the gateway Service first, which releases the LoadBalancer:
kubectl delete svc litellm -n llm-gateway
Then delete the cluster, which removes both nodes:
civo kubernetes delete llm-gateway --region NYC1 -y
Confirm the cluster is gone:
civo kubernetes ls --region NYC1
llm-gateway no longer appears in the list, and billing stops.
What’s next
This setup can expand without changing its design:
- Add backends: Register more providers or models in model_list.
- Refine routing: Use router_settings to balance traffic or prioritize cheaper deployments.
- Manage access: Assign separate API keys, budgets, and rate limits.
- Secure the gateway: It currently uses HTTP, exposing the master key in transit. Before real use, add HTTPS through an Ingress and restrict access with loadBalancerSourceRanges.
- Version-control configuration: Manage ConfigMap updates through a deployment pipeline.
The same endpoint and fallback rules remain as you scale.
Key takeaways
You now have a LiteLLM gateway connecting self-hosted and hosted models through one endpoint.
- One endpoint: Applications use a single address, with LiteLLM routing requests to the selected backend.
- Automatic fallback: If the private model fails, requests switch to the hosted backend.
- Cost tracking: Per-request costs help compare hosted and private inference.
- Minimal infrastructure: LiteLLM runs on CPU, leaving the GPU for the self-hosted model.
- One provider: Civo runs your GPU, and relaxAI is Civo’s own UK-hosted API.
Routing, fallback, and cost settings live in one configuration file, so changing a backend is a one-file edit.

Software Engineer at GoCardless
Mostafa Ibrahim is a software engineer and technical writer specializing in developer-focused content for SaaS and AI platforms. He currently works as a Software Engineer at GoCardless, contributing to production systems and scalable payment infrastructure.
Alongside his engineering work, Mostafa has written more than 200 technical articles reaching over 500,000 readers. His content covers topics including Kubernetes deployments, AI infrastructure, authentication systems, and retrieval-augmented generation (RAG) architectures.
Share this article
Further Reading
27 November 2025
LLM-powered incident analysis dashboard on Civo
5 March 2026