Claude API Kubernetes Production Deployment Guide
Running Claude in production on Kubernetes means solving a different set of problems than calling an API from a script. You need to manage API keys as secrets across namespaces, handle rate limits and transient failures without crashing pods, scale horizontally without hammering Anthropic's endpoints, and get visibility into latency and cost per request. This guide covers the concrete deployment patterns: secret management, Horizontal Pod Autoscaler tuning for LLM workloads, retry and circuit-breaker logic, and rollout strategy for a service that wraps the Claude API.
The short answer: treat the Claude API like any external dependency with variable latency and strict rate limits. That means isolating the call behind a dedicated service, injecting credentials via Kubernetes Secrets (or an external secrets operator), scaling on queue depth rather than raw CPU, and building retry/backoff directly into your HTTP client rather than relying on Kubernetes restarts.
Secrets management for API keys
Never bake API keys into container images or ConfigMaps. Use a native Secret object, or better, an external secrets operator (External Secrets Operator, Sealed Secrets, or your cloud provider's secrets manager) that syncs into Kubernetes.
apiVersion: v1
kind: Secret
metadata:
name: claude-api-credentials
namespace: production
type: Opaque
stringData:
SUBTOAPI_KEY: "sub_live_xxxxxxxxxxxxxxxx"
Mount it as an environment variable in your deployment spec rather than a mounted file, unless your app reads secrets from disk:
env:
- name: SUBTOAPI_KEY
valueFrom:
secretKeyRef:
name: claude-api-credentials
key: SUBTOAPI_KEY
If you're running multiple services or teams against the same Claude account, this is also where a hosted API key layer pays off. Instead of sharing one raw Anthropic key across every deployment and rotating it manually, SubToAPI issues scoped sub_live_... keys per service or team from your existing Claude access, so a compromised key in one namespace doesn't mean rotating credentials everywhere. See /docs/quickstart for how key issuance works.
Isolate the Claude call behind its own service
Don't call Claude directly from every pod that needs an LLM response. Put a thin internal service in front of it. This gives you one place to implement retries, timeouts, circuit breaking, and request logging, and it means you can swap providers or add caching without touching downstream consumers.
// claude-gateway/server.js
import express from "express";
const app = express();
app.use(express.json());
app.post("/complete", async (req, res) => {
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages: req.body.messages
})
});
if (!response.ok) {
return res.status(response.status).json(await response.json());
}
res.json(await response.json());
});
app.listen(8080);
Deploy this as its own Deployment with its own HPA, independent of your frontend or business-logic pods. This isolation also makes resource limits meaningful: Claude calls are I/O-bound, not CPU-bound, so you can run many lightweight replicas per node.
Scaling on queue depth, not CPU
LLM gateway pods spend most of their time waiting on an HTTP response, so CPU-based autoscaling is misleading — a pod can be "busy" (holding open connections) while using almost no CPU. Scale instead on concurrent in-flight requests or queue depth using a custom metric, or fall back to request-rate-based scaling via KEDA:
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: claude-gateway-scaler
spec:
scaleTargetRef:
name: claude-gateway
minReplicaCount: 2
maxReplicaCount: 20
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus-server.monitoring:80
metricName: http_requests_in_flight
threshold: "15"
query: sum(http_requests_in_flight{app="claude-gateway"})
Keep minReplicaCount at 2 or more for availability during rolling updates, and cap maxReplicaCount based on your rate limit ceiling — scaling past what your API key can actually sustain just produces more 429s, not more throughput.
Retries, backoff, and rate limits
Claude's API returns 429 on rate limit and transient 5xx errors under load. Your gateway pods should retry with exponential backoff and jitter, and respect Retry-After headers when present:
async function callWithRetry(payload, attempt = 0) {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
});
if (res.status === 429 && attempt < 4) {
const retryAfter = res.headers.get("retry-after");
const delay = retryAfter ? Number(retryAfter) * 1000 : 2 ** attempt * 500;
await new Promise(r => setTimeout(r, delay));
return callWithRetry(payload, attempt + 1);
}
return res;
}
Set container-level timeouts too — a stuck streaming request shouldn't hold a pod indefinitely. Combine this with a readiness probe that checks a lightweight internal health endpoint, not a live Claude call, so a temporary upstream slowdown doesn't trigger a cascade of pod restarts.
Rollouts and configuration changes
Use a standard RollingUpdate strategy with maxUnavailable: 0 for the gateway deployment so in-flight Claude requests aren't dropped mid-stream during deploys:
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
For model version changes or prompt updates, roll them out the same way you'd roll out code — behind a feature flag or canary deployment, with a small percentage of traffic routed to the new config first. This matters more for LLM calls than typical service changes, since a bad prompt or model swap doesn't throw an obvious error; it just produces worse output.
Observability
Track per-request latency, token usage, and error rate as Prometheus metrics exported from your gateway, not just generic HTTP metrics. Token counts matter because they drive cost, and a spike in max_tokens usage or retry rate is often the first sign of a prompt regression or an upstream issue. If you're using SubToAPI, usage metadata is already returned per request and visible in the dashboard, which covers cost tracking without instrumenting that yourself — see /docs/messages for the response fields.
If you want to get a working gateway deployed without managing raw Anthropic keys, rate-limit tiers, or billing reconciliation yourself, start with a free trial at /signup and point your Kubernetes deployment at a scoped key from day one. Plans range from Solo at €9 to Team and Scale tiers for multi-service deployments — details at /pricing.
questions
Do I need a service mesh to deploy Claude API calls on Kubernetes? No. A service mesh (Istio, Linkerd) adds retry and circuit-breaking at the network layer, which can replace some application-level retry logic, but it's not required. A dedicated gateway deployment with application-level retries, as shown above, is sufficient for most production setups.
Should I run the Claude gateway as a Deployment or a Job? Deployment. Claude calls are typically synchronous request/response within a larger service, so you want long-running, horizontally scalable pods behind a Service, not one-off Jobs. Use Jobs or CronJobs only for batch processing workloads that call Claude asynchronously.
How do I avoid hitting rate limits when scaling pods horizontally? Cap your HPA's maxReplicaCount based on your actual rate limit ceiling, implement exponential backoff with jitter on 429 responses, and consider a shared rate limiter (Redis-based token bucket) across pods so they coordinate rather than each independently retrying against the same limit.