AI / INFRASTRUCTURE ENGINEERING
Why Kubernetes Became Critical Infrastructure for AI
GPU scheduling, distributed training, inference serving, autoscaling, fault tolerance and the economics of operating AI systems at scale.

01 / SYSTEM / RESPONSIBILITY
The problem starts when the GPU stops being yours
A model on a single GPU VM is an application. A fleet serving several teams becomes a resource-allocation problem. Who gets the next accelerator? Can an experiment displace a customer-facing model? Who restores a failed training run? How does an operator know whether an expensive GPU is computing, waiting for data or simply keeping weights in memory?
Kubernetes does not make machine learning possible. It makes complex AI workloads easier to coordinate, operate, govern and scale across shared infrastructure. “Critical” describes its role in many shared platforms, not a requirement for every AI application. A single well-managed VM can be the better engineering decision.
The transition is gradual. A GPU pool adds placement and ownership. Distributed training adds coordinated workers and network dependencies. Shared inference adds latency objectives, admission pressure, model versions and abuse controls. The difficult boundary is no longer launching a process: it is making competing workloads behave predictably during scarcity and failure.
This publication asks one question: when does Kubernetes become the right foundation, and what must be added to make it operationally effective? It is a documentation-backed architecture interpretation, not a claim that I deployed this platform. Cluster examples below are unexecuted. The small local checkpoint experiment has separately captured results.
From one machine to a platform
Each transition introduces a new coordination problem; more Pods do not resolve it by themselves.
- 01Single GPU VM
- 02Shared GPU pool
- 03Distributed workers
- 04Multi-team serving
02 / SYSTEM / RESPONSIBILITY
Why Kubernetes became the orchestration layer
Kubernetes offers a common control surface: desired state in an API, controllers reconciling that state, and schedulers assigning Pods to nodes. A Job describes bounded work; a Deployment maintains serving replicas. Custom resources let operators express domain objects without inventing an entirely separate infrastructure control plane. These are general distributed-systems primitives, not machine-learning algorithms.
Resource requests inform placement; limits constrain supported resources. Namespaces organize ownership, while policies and quotas make that ownership enforceable. Services provide stable endpoints as Pods change. Persistent-volume abstractions separate a workload’s storage request from a storage implementation. None removes the need to understand the underlying machine, network or filesystem.
An operator is useful when the lifecycle has domain knowledge: install a compatible device stack, manage a training group, or reconcile a serving endpoint. It is also another controller to upgrade and observe. Prefer a small set with explicit responsibilities over several operators simultaneously managing the same replicas or node settings.
The architectural gain is a programmable contract between application and platform teams. The cost is accepting responsibility for reconciliation, policy, upgrades and failure modes. Start from Kubernetes concepts and define that contract before selecting the AI ecosystem around it.
03 / SYSTEM / RESPONSIBILITY
A GPU request is the end of a hardware enablement chain
A container cannot discover a usable NVIDIA GPU merely because its image contains CUDA libraries. The host needs a supported driver; the container runtime needs GPU device integration; the workload needs compatible user-space libraries and hardware support. The NVIDIA container toolkit participates in exposing devices to containers. A device plugin advertises allocatable accelerator resources to Kubernetes.
The GPU Operator automates components of that enablement stack, including driver/toolkit, discovery, device-plugin and monitoring integrations according to configuration. It is not a placement optimizer. Check its platform matrix before assuming that an operator release supports a particular kernel, OS or managed-node image.
For the traditional device-plugin path, Kubernetes GPU requests use extended resources such as nvidia.com/gpu. Our examples use whole integer devices with matching requests and limits. They deliberately do not cover Dynamic Resource Allocation: a separate resource-claim API and driver configuration require their own compatibility review.
Device allocation does not describe model fit. Weights, activation buffers, runtime overhead and the KV cache compete for GPU memory; utilization and memory occupancy are different signals. A model can exhaust memory at low compute utilization. Container portability therefore does not guarantee driver, CUDA, accelerator or network compatibility.
Discovery, allocation and execution
Enablement advertises resources; scheduling selects a node; the runtime exposes the allocated device. The operator manages components, not this entire sequence as a scheduler.
Enablement
- GPU node
- Driver + toolkit
- Device plugin
- Allocatable GPU
Placement
- Pod GPU request
- Scheduler
- Selected node
- GPU workload
| Mode | Useful when | Boundary / cost |
|---|---|---|
| Dedicated GPU | Predictable capacity for a large model or training worker | A whole allocated device may be underused; not a complete host security boundary. |
| MIG | Supported GPUs can partition compatible smaller workloads | Hardware-supported memory/compute partitions; available profiles constrain model fit. |
| Time-slicing | Trusted, bursty workloads tolerate contention | No per-replica memory or fault isolation; more shares do not mean proportionally more compute. |
04 / SYSTEM / RESPONSIBILITY
Admission, placement and topology are separate decisions
Node pools group accelerator types, purchase models or trust levels. Selectors and required node affinity restrict eligible nodes; preferred affinity expresses a preference. Taints repel workloads without a matching toleration. A toleration permits placement, but does not force it. Use both attraction and exclusion where a dedicated pool is intended; node-assignment rules explain the distinction.
Those controls do not automatically select an optimal NVLink/NVSwitch domain or InfiniBand path. A multi-GPU Pod fitting on one node says little about which devices communicate efficiently; a multi-node job adds NIC, fabric and collective-library constraints. Validate the actual hardware topology, exposed device resources and communication path. RDMA additionally needs appropriate host/network enablement, potentially managed through the NVIDIA Network Operator.
Kueue makes admission and quota policy explicit. Resource flavors identify capacity classes; ClusterQueues account for quota; LocalQueues provide namespaced submission points. Admission is permission to consume capacity, not a universal guarantee that every worker immediately runs. Its topology-aware features require their own configuration and supported integrations.
Gang scheduling coordinates a group’s placement so partial allocation does not strand costly workers waiting for peers. Volcano provides batch-scheduling mechanisms; it is not interchangeable with a quota admission controller. Fair sharing, priorities and preemption need an organizational policy: interrupting training without reliable checkpoints can waste more capacity than preemption recovers. A single-GPU service rarely needs this entire stack.
| Mechanism | Owns | Does not establish |
|---|---|---|
| Native scheduler | Pod placement subject to resources and configured constraints | Application rendezvous or optimal accelerator-fabric placement. |
| Kueue | Workload admission, quotas, flavors and configured sharing policy | Unconditional simultaneous Pod startup. |
| Volcano | Batch-oriented scheduling, queues and gang mechanisms | Training-state recovery or universal network optimization. |
05 / SYSTEM / RESPONSIBILITY
A distributed training run is a coordinated failure domain
Consider four workers, each with two GPUs. The launcher must assign ranks, world size and rendezvous information. The framework partitions work and coordinates gradient exchange; collective operations such as all-reduce make slow communication visible to all participants. Reserving eight GPUs is necessary but insufficient: bandwidth, placement, storage and worker startup must also align.
PyTorch torchrun handles distributed-process launch and elastic restart semantics when configured. It does not manufacture a valid checkpoint. Kubeflow Trainer supplies training-oriented APIs and orchestration. Ray introduces its own execution and resource model; KubeRay reconciles Ray resources on Kubernetes. Choose a framework for the application’s execution model, not because three project names appear in the same architecture diagram.
A training lifecycle needs bounded admission wait, image pull, dataset access, rendezvous, execution, checkpoint publication and terminal cleanup. Define timeouts for each stage. A worker that starts but cannot join its peers can hold a scarce GPU while making no progress. A job that completes but retains diagnostic artifacts indefinitely can create a different storage problem.
The useful completion signal is more than a green Pod. The final artifact must be durable, associated with the intended dataset and configuration, and retrievable by the next stage. Keep provenance and checkpoint retention separate from Pod cleanup. The Kubeflow Trainer overview is a starting point; distinguish current Trainer APIs from legacy examples before copying manifests.
Distributed workers and durable state
Logical reference topology: worker communication is bidirectional; every worker must participate in the framework’s coordination protocol.
Control
- Admission
- Training controller
- Rendezvous
- Worker group
Execution
- Worker ranks
- Collective exchange
- Optimizer step
- Checkpoint commit
Durability
- Dataset store
- Worker readers
- Checkpoint store
- Final artifact
| Dimension | Training | Inference |
|---|---|---|
| Coordination | Gradient/parameter exchange across training steps | Model-parallel communication or independent serving replicas. |
| State | Optimizer, scheduler, data position and RNG state | Weights plus request/KV state; lost streams need explicit client policy. |
| Success | Durable artifact and reproducible experiment provenance | Latency, throughput, error and response-quality objectives. |
06 / SYSTEM / RESPONSIBILITY
The serving runtime owns the model’s inner loop
An inference request crosses several boundaries: authentication and rate limits, routing, queueing, tokenization, prefill, iterative decoding and response streaming. Model weights must already be loaded before useful service begins. Batching can increase throughput while changing waiting time; KV-cache capacity constrains simultaneous sequences and context lengths.
Kubernetes manages the lifecycle and resource envelope around this process. It does not batch tokens or optimize attention kernels. vLLM is an inference runtime with its own memory and request-scheduling behavior. Triton provides a serving runtime with backend-specific capabilities. KServe manages model-serving resources and their lifecycle above runtimes; it is not a substitute for them.
Ray Serve supports application-level serving composition and scaling within Ray’s execution model. KubeRay can operate the underlying Ray cluster. Installing all these layers without a clear division creates overlapping control loops. The KServe architecture documentation currently describes deployment modes separately; its documentation version and a GitHub release are not automatically the same compatibility baseline.
A readiness probe should mean the replica can serve, not merely that a port is listening. A startup probe grants a bounded loading window. A successful health response still does not establish latency under concurrency or the correct model revision. Verify an authenticated end-to-end request before exposing traffic. The vLLM deployment guide informs the example below; the dedicated vLLM review examines the runtime boundary in more detail.
LLM request lifecycle
Readiness excludes replicas still loading weights. Streaming and cancellation remain application concerns.
- 01Gateway
- 02Request queue
- 03Tokenizer / prefill
- 04Decode + KV cache
- 05Stream response
| Component | Primary responsibility | Important limit |
|---|---|---|
| Kubernetes | Pods, placement, Services, lifecycle | No model execution or token-aware scheduling. |
| KServe | Serving APIs, lifecycle and deployment integration | Behavior depends on mode, runtime and installed integrations. |
| vLLM | LLM execution, batching and memory management | Does not provision a secure multi-tenant cluster. |
| Triton | Inference serving across supported backends | Capabilities depend on backend and model configuration. |
| Ray Serve | Composed serving applications within Ray | Adds a distributed runtime and another operational boundary. |
07 / SYSTEM / RESPONSIBILITY
Scale on useful demand, account for the time to become useful
CPU utilization is often a poor proxy for an accelerator service. GPU utilization alone is also ambiguous: a saturated GPU might be efficiently batching requests or failing the latency objective. Observe queue depth, waiting time, concurrency, tokens per second and time to first token together. Calibrate against realistic prompt/output lengths; requests are not uniform units of work.
HPA adjusts workload replicas using available metrics. KEDA adds event-source scaling and activation behavior. Node provisioning is a separate loop: Karpenter responds within configured NodePools and provider capabilities. An additional replica can remain Pending when no compatible GPU capacity is available.
Scale-to-zero needs a demand signal that survives zero replicas and a request-handling strategy while capacity returns. A metric emitted only by the sleeping model cannot wake itself. A durable upstream queue or supported activation layer can bridge that gap, but users still experience provision, image pull, weight download, initialization and warm-up. Our synchronous serving example keeps one replica warm.
Kubernetes does not automatically lower GPU cost. Consolidation can improve utilization, while operators, idle safety capacity, storage traffic and on-call work add cost. Reserved capacity trades flexibility for a commitment; on-demand capacity trades commitment for price and availability risk. Compare cost per completed useful job or accepted output token at a specified service level, not simply cost per allocated GPU-hour.
Demand crosses two scaling loops
Illustrative control flow, not a guarantee that capacity exists or a request will survive cold start.
- 01External queue
- 02KEDA / HPA
- 03Pending GPU Pod
- 04Node provisioner
- 05Ready model
| Mechanism | Changes | Prerequisite |
|---|---|---|
| HPA | Replica count | A valid metric adapter and workload scaling behavior. |
| KEDA | Event-driven replica demand / activation | Supported trigger, authentication and a reliable demand signal. |
| Node autoscaling | Machine capacity | Provider integration, quota, available hardware and constraints. |
Illustrative cost model — not a cloud quotation
textAssume: 4 GPU nodes, 730 hours/month, $3/node-hour.
Always-on compute = 4 × 730 × $3 = $8,760/month.
Scheduled compute = 4 × 300 × $3 = $3,600/month.
Illustrative difference = $5,160 before other costs.
Total = compute + storage + network + control plane + operations.
Useful-work unit cost = total / successful useful units.
Break-even idle interval > restart cost / avoided hourly cost.| Technique | Possible benefit | Trade-off to measure |
|---|---|---|
| Warm minimum replicas | Avoid repeated cold starts | Paid idle capacity. |
| Batching / right-sizing | More useful work per GPU-hour | Latency, context limits and model quality constraints. |
| Time-slicing / MIG | Fit smaller workloads into a pool | Contention or partition/profile fragmentation. |
| Interruptible training | Lower acquisition price where available | Checkpoint overhead, lost work and uncertain completion. |
| Cache model artifacts | Reduce startup downloads | Storage cost, stale artifacts and cache authorization. |
08 / SYSTEM / RESPONSIBILITY
Restarting a process is not recovering a training run
When a GPU node disappears, Kubernetes can detect lost availability and controllers can create replacement Pods according to policy. That restores an execution opportunity. The framework must decide whether remaining ranks can continue, need to restart as a group, or have reached their retry budget. The communication layer must stop waiting for a participant that will never return.
Recovery then needs a trustworthy checkpoint containing the state required to resume: model parameters, optimizer and scheduler state, training position, and relevant random-number-generator state. Sharded checkpoints add coordination: do not advertise a complete revision while some shards are missing. Persistent storage needs the accessibility, durability and consistency semantics expected by the checkpoint protocol.
Checkpoint frequency is an economic choice. Short intervals reduce replay after interruption but consume I/O and compute time. Measure checkpoint duration separately from training throughput. Retain a known-good checkpoint until the replacement is committed and verified. A storage abstraction alone does not establish atomic multi-object publication or cross-region recovery.
Kubernetes Job retry and cleanup behavior covers container/Pod execution, not business-level exactly-once completion. Make artifact publication idempotent. The local test later in this article only exercises a file replacement boundary; it does not demonstrate a failed GPU worker recovering a real distributed training run.
Failure → restore → resume
Reference recovery sequence. Controllers and framework must agree on membership; storage must contain a complete checkpoint.
- 01Worker lost
- 02Group failure detected
- 03Replacement admitted
- 04Checkpoint verified
- 05State restored
- 06Training resumes
09 / SYSTEM / RESPONSIBILITY
The ecosystem adds domain contracts, not automatic integration
A Kubernetes API can represent a training workload, but it does not decide which experiment should be promoted. A model registry records versions and lifecycle metadata; experiment tracking associates parameters, datasets and results; workflow engines sequence stages. These components need shared identifiers and permissions or an ostensibly integrated platform becomes a collection of disconnected dashboards.
Kubeflow groups machine-learning platform capabilities, with independently evolving components. KServe addresses serving management. KubeRay operates Ray resources such as RayCluster, RayJob and RayService. Ray supplies its own execution abstractions. Treat this as a responsibility map, not a recommendation to install every project.
Pick a minimal vertical slice: submit one bounded training workload, persist one artifact, deploy one version and observe one real request. Only then add orchestration layers needed by multiple teams. Record who owns each custom resource, webhook, upgrade and incident. A platform that cannot explain which controller changes a replica count is difficult to debug safely.
10 / SYSTEM / RESPONSIBILITY
Accelerators expose the slowest part of the data path
A GPU can be expensive while idle because workers cannot read batches quickly enough. Dataset preprocessing, object-store request patterns and small-file access may dominate an otherwise impressive compute configuration. Likewise, deploying ten replicas can trigger ten simultaneous weight downloads and turn a rollout into a storage or network event.
Choose storage by access pattern: object storage for durable artifacts, a suitable shared filesystem where coordinated POSIX access is required, and node-local caches when disposable copies are acceptable. Persistent-volume access modes, attachment constraints and zone locality affect rescheduling. A ReadWriteOnce volume is not a general multi-node checkpoint service; a local disk is not a node-loss recovery plan.
Training communication and serving traffic can demand different network treatment. RDMA requires compatible NICs, drivers, plugins, fabric configuration and framework use. An ordinary Service does not make collectives use InfiniBand. Measure an end-to-end communication test on the intended topology before committing a distributed workload to it.
Treat artifact caches as part of the security and freshness model. Key by immutable model revision, verify integrity, bound eviction, and avoid exposing private weights to unrelated tenants. The Kubernetes persistent-volume documentation explains lifecycle and access semantics; it does not certify application checkpoint correctness.
11 / SYSTEM / RESPONSIBILITY
A namespace is an organizing boundary, not complete tenant isolation
Separate users, service identities and infrastructure controllers. RBAC should constrain API actions; service accounts and cloud workload identity should scope data access. Avoid distributing broad storage credentials to every training Pod. Secrets need controlled access and rotation, and logging must not inadvertently retain prompts, credentials or protected datasets.
Multi-tenancy guidance distinguishes isolation approaches and their trade-offs. Namespaces and quotas are useful but insufficient alone. NetworkPolicy enforcement depends on the networking implementation; image provenance, admission restrictions and host-level configuration remain important. Privileged device-enablement components belong to a tightly controlled platform layer.
GPU sharing also has boundaries. NVIDIA documents that time-sliced replicas do not provide the memory/fault isolation of MIG. Hardware partitioning is not a substitute for dataset authorization or an overall hostile-tenant threat model. Dedicated nodes or stronger isolation may be appropriate when trust differs materially.
Expose a model API through authenticated routing, rate limits and bounded request sizes. Authorize model and dataset access separately. Audit privileged changes, artifact publication and tenant access without assuming every prompt should be retained. The local examples deliberately expose only a ClusterIP Service; they are not a complete security baseline.
12 / SYSTEM / RESPONSIBILITY
Observe waiting, useful work and recovery as separate signals
A green Deployment is a weak description of an AI service. Follow a request from gateway acceptance to queue wait, prefill, first token, decode and completion. Record errors and cancellations alongside throughput: tokens per second can rise while customer latency gets worse. Aggregate histograms correctly and retain useful model/revision dimensions without unbounded cardinality.
DCGM Exporter exposes GPU telemetry for Prometheus-compatible collection. Combine utilization and memory with runtime queues and loading duration. Grafana can visualize those time series, but dashboards do not establish an SLO or prove causality. vLLM’s metrics reference supplies runtime-specific names; inspect the actual version’s endpoint before adopting a query.
For training, record admission wait, worker startup skew, job success/failure, checkpoint duration and replayed work. For capacity, record node provision time, failed capacity requests, idle allocations and attributable infrastructure cost. Those measurements explain why a workload is waiting rather than collapsing every delay into “GPU shortage.”
OpenTelemetry signals can connect traces, metrics and logs across gateway and application components. Define a safe correlation scheme; do not use complete prompts as metric labels. Alert on sustained user impact and broken recovery paths, not every utilization fluctuation.
Signals across the serving stack
Use shared request/model identifiers where safe; hardware metrics alone cannot explain user-visible latency.
Experience
- Gateway errors
- Queue wait
- First token
- Completion latency
Runtime
- Model load
- GPU memory
- Decode tokens
- Runtime failures
Platform
- Pod pending
- Node provision
- Storage I/O
- Allocated cost
13 / SYSTEM / RESPONSIBILITY
The correct alternative may be much simpler
A team with one model, predictable traffic and no existing cluster can spend more operating Kubernetes than it gains from orchestration. A GPU VM has fewer moving parts. A managed inference service transfers some capacity and lifecycle responsibility to a provider, with constraints on runtimes, regions, economics and control. Managed batch training can be a better fit for bounded experiments than a permanent platform.
Slurm is a serious alternative for batch/HPC allocation and scheduling. Evaluate the application mix, fabric, user workflows and operational skills instead of treating Kubernetes as a universal successor. Service-oriented infrastructure and tightly coupled scientific jobs can justify different schedulers, including coexistence where ownership is clear.
The decision should survive a failure exercise. Who answers an incident during a model rollout? Who validates a driver upgrade? Who owns quota disputes? If the organization cannot name those owners, a sophisticated reference architecture is not yet an operable platform.
Kubernetes becomes persuasive when multiple workloads benefit from a shared API, policy, deployment and observability foundation—and when an organization can sustain that foundation. Existing Kubernetes expertise lowers adoption cost, but does not remove the accelerator-specific learning curve.
| Option | Strong fit | Cost / limitation |
|---|---|---|
| Single GPU VM | One team, modest stable workload | Manual lifecycle and limited shared governance. |
| Managed inference / serverless | Supported model/runtime with clear endpoint needs | Provider constraints, cold starts and pricing model. |
| Managed batch training | Bounded jobs with provider-integrated storage | Less control over infrastructure and portability. |
| Managed containers | Application deployment with supported accelerator options | GPU types, scheduling and scaling features vary. |
| Slurm / HPC | Batch allocation and tightly coupled compute workflows | Serving and cloud-native application integration need design. |
| Kubernetes + focused extensions | Shared mixed workloads and platform ownership | Controllers, upgrades, integration testing and on-call cost. |
14 / SYSTEM / RESPONSIBILITY
Reference design: separate control, compute and evidence
This is a production-oriented reference design, not a deployed system. An authenticated gateway fronts model services. Serving workloads use an approved runtime and immutable model revision. Training submits through quota-aware admission into separate capacity classes. A provider-specific node provisioner may expand eligible pools; reserved capacity can supply a predictable base.
Keep artifact storage, registry, dataset permissions and checkpoint policy explicit. Use separate identities for training readers, artifact writers and inference readers. The observability path combines hardware, application and controller signals. Platform operators own driver/network compatibility and upgrades; model teams own model behavior, checkpoints and acceptance tests.
Before calling this ready, exercise an unavailable accelerator, slow model download, invalid checkpoint, revoked data permission, exhausted quota and broken metrics endpoint. Verify that errors are visible and that a recovery does not silently serve the wrong model. Rollouts need an abort path as well as a happy path.
This is distinct from the portfolio’s delivery scenarios: Kubernetes CI/CD concerns application release engineering. Here the focus is the accelerator platform and its operational contracts. The retrieval-document investigation covers the data preparation boundary, not GPU scheduling.
Cloud-native AI platform — reference design
Logical responsibility map, not a claim of installed integrations or measured production capacity.
Serving
- Authenticated API
- Serving controller
- Model runtime
- GPU serving pool
Training
- Team submission
- Quota admission
- Training controller
- GPU training pool
Artifacts
- Governed datasets
- Checkpoints
- Model registry
- Versioned weights
Operations
- Policy + identity
- Metrics + traces
- Node provisioner
- Driver / network stack
15 / ENGINEERING LABS / CONFIGURATION EXAMPLES
Inspect the configuration. Keep the evidence boundary visible.
Examples A–G are unexecuted configuration examples. H is an executed local filesystem test. YAML parsing and partial CRD schema checks are not deployment evidence. No GPU benchmark or cluster output is presented.
Download configurations, source and captured local test output →
UNEXECUTED CONFIGURATION EXAMPLE
A — Allocate a GPU and wait for a usable model
The smallest serving unit still needs resource accounting, model storage and a loading boundary. This Deployment uses one GPU and a pinned vLLM release tag. It does not download arbitrary remote model code. Recreate avoids a rolling update temporarily requiring a second GPU, at the cost of downtime.
Prerequisites. A disposable cluster with an approved NVIDIA driver/toolkit/device plugin; an ai-lab namespace; a prepopulated model-weights PVC containing a compatible, licensed model and tokenizer; enough GPU memory. Verify the image tag, architecture and CUDA/driver matrix before pulling. CPU/RAM values are illustrative sizing, not measured requirements.
inference.yaml
YAML# UNEXECUTED CONFIGURATION EXAMPLE. Prepopulate model-weights PVC first.
apiVersion: apps/v1
kind: Deployment
metadata:
name: inference
namespace: ai-lab
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels: {app: inference}
template:
metadata:
labels: {app: inference}
spec:
containers:
- name: engine
image: vllm/vllm-openai:v0.32.0
args: ["--model", "/models", "--served-model-name", "demo", "--max-model-len", "2048", "--gpu-memory-utilization", "0.8"]
ports: [{name: http, containerPort: 8000}]
resources:
requests: {cpu: "2", memory: 8Gi, nvidia.com/gpu: "1"}
limits: {cpu: "4", memory: 16Gi, nvidia.com/gpu: "1"}
startupProbe:
httpGet: {path: /health, port: http}
periodSeconds: 10
failureThreshold: 90
readinessProbe:
httpGet: {path: /health, port: http}
periodSeconds: 10
volumeMounts:
- {name: weights, mountPath: /models, readOnly: true}
- {name: shm, mountPath: /dev/shm}
volumes:
- name: weights
persistentVolumeClaim: {claimName: model-weights}
- name: shm
emptyDir: {medium: Memory, sizeLimit: 1Gi}
Run / inspect — example A
shellkubectl create namespace ai-lab
kubectl get nodes -o 'custom-columns=NAME:.metadata.name,GPU:.status.allocatable.nvidia\.com/gpu'
kubectl apply --dry-run=server -f inference.yaml
kubectl apply -f inference.yaml
kubectl rollout status deployment/inference -n ai-lab --timeout=15m
kubectl describe pod -n ai-lab -l app=inferenceBehavior. Expected, not observed: a compatible node is selected; weights load; /health becomes ready before Service traffic is accepted. The startup budget is 900 seconds and must be measured for the chosen model.
Failure cases. Pending: inspect GPU availability, PVC binding and events. CrashLoop: inspect image/runtime compatibility, model format and memory. Never resolve a probe failure merely by making its timeout unlimited.
Validation boundary. No capacity, model-quality, security-hardening or latency result is claimed. The PVC must already exist; its creation depends on the environment. Shared memory consumes node RAM. No liveness restart loop is added without observing engine failure behavior.
UNEXECUTED CONFIGURATION EXAMPLE
B — Express placement without claiming topology guarantees
Apply this strategic merge patch to the existing Deployment. It restricts placement to an administrator-approved accelerator pool and permits its dedicated taint. It is deliberately not a second standalone Deployment with subtly different settings.
Prerequisites. An administrator has labeled eligible nodes ai.example.com/accelerator=approved-gpu and, where intended, tainted them dedicated=gpu:NoSchedule. Do not relabel arbitrary hardware to make a Pending Pod disappear.
placement-patch.yaml
YAML# Strategic merge patch for inference.yaml, NOT a standalone Kubernetes object.
spec:
template:
spec:
tolerations:
- key: dedicated
operator: Equal
value: gpu
effect: NoSchedule
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: ai.example.com/accelerator
operator: In
values: [approved-gpu]
Run / inspect — example B
shellkubectl patch deployment inference -n ai-lab --type=strategic --patch-file placement-patch.yaml
kubectl get pods -n ai-lab -o wide
kubectl get events -n ai-lab --sort-by=.metadata.creationTimestampBehavior. Expected: new Pods must satisfy the required affinity. The toleration allows the dedicated pool; it does not itself select that pool.
Failure cases. A label mismatch, another untolerated taint, exhausted GPUs or incompatible volume locality can still prevent placement. Describe the Pending Pod before changing constraints.
Validation boundary. This says nothing about device-level NVLink locality, RDMA paths or simultaneous placement of several workers. Hardware/fabric validation is a separate exercise.
UNEXECUTED CONFIGURATION EXAMPLE
C — A bounded GPU Job with persistent checkpoint state
A tiny synthetic PyTorch regression illustrates state that survives a replacement Pod. The Job starts suspended for Kueue admission. It runs one worker, not distributed training. The Dockerfile pins torch 2.9.0 with the officially documented cu128 wheel index as an example baseline, not a latest-version recommendation.
Prerequisites. Examples B and D establish eligible capacity and admission. Build and push the image to your own registry, replace registry.example.com/replace-me, and provision a compatible default StorageClass. The checkpoint directory must be writable. Review the base image, dependency lock and GPU compatibility before use.
Dockerfile
Dockerfile# Example baseline, not a verified image/driver combination or hardened image.
FROM python:3.12-slim
RUN pip install --no-cache-dir torch==2.9.0 --index-url https://download.pytorch.org/whl/cu128
WORKDIR /app
COPY train.py .
CMD ["python", "train.py"]
train.py
Python"""UNEXECUTED GPU example: synthetic regression, single process/single GPU."""
from pathlib import Path
import os
import torch
if not torch.cuda.is_available():
raise RuntimeError("CUDA unavailable: inspect driver, runtime and device allocation")
torch.manual_seed(7)
model = torch.nn.Linear(4, 1).cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
checkpoint = Path("/checkpoints/state.pt")
start = 0
if checkpoint.exists():
# Only load trusted, self-produced checkpoints.
state = torch.load(checkpoint, map_location="cpu", weights_only=True)
model.load_state_dict(state["model"])
optimizer.load_state_dict(state["optimizer"])
torch.set_rng_state(state["cpu_rng"])
torch.cuda.set_rng_state(state["gpu_rng"])
start = state["step"]
for step in range(start, 200):
x = torch.randn(32, 4, device="cuda")
y = x.sum(dim=1, keepdim=True)
optimizer.zero_grad()
loss = (model(x) - y).square().mean()
loss.backward()
optimizer.step()
if (step + 1) % 10 == 0:
temp = checkpoint.with_suffix(".tmp")
checkpoint.parent.mkdir(parents=True, exist_ok=True)
with temp.open("wb") as handle:
torch.save({"step": step + 1, "model": model.state_dict(),
"optimizer": optimizer.state_dict(),
"cpu_rng": torch.get_rng_state(),
"gpu_rng": torch.cuda.get_rng_state()}, handle)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp, checkpoint)
# No claim of cross-device bitwise reproducibility or distributed recovery.
checkpoint-pvc.yaml
YAML# Choose a compatible StorageClass; this is not a shared multi-writer store.
apiVersion: v1
kind: PersistentVolumeClaim
metadata: {name: checkpoints, namespace: ai-lab}
spec:
accessModes: [ReadWriteOnce]
resources:
requests: {storage: 5Gi}
training.yaml
YAML# Build/push your own image and replace this placeholder before applying.
apiVersion: batch/v1
kind: Job
metadata:
name: tiny-training
namespace: ai-lab
labels: {kueue.x-k8s.io/queue-name: training}
spec:
suspend: true
backoffLimit: 2
activeDeadlineSeconds: 900
ttlSecondsAfterFinished: 3600
template:
spec:
restartPolicy: Never
tolerations:
- {key: dedicated, operator: Equal, value: gpu, effect: NoSchedule}
containers:
- name: train
image: registry.example.com/replace-me/tiny-training:local
resources:
requests: {cpu: "2", memory: 4Gi, nvidia.com/gpu: "1"}
limits: {cpu: "2", memory: 4Gi, nvidia.com/gpu: "1"}
volumeMounts:
- {name: checkpoints, mountPath: /checkpoints}
volumes:
- name: checkpoints
persistentVolumeClaim: {claimName: checkpoints}
Run / inspect — example C
shelldocker build -t YOUR_REGISTRY/tiny-training:reviewed .
docker push YOUR_REGISTRY/tiny-training:reviewed
# Edit training.yaml to use that exact image, preferably its digest.
kubectl apply -f checkpoint-pvc.yaml
kubectl apply -f training.yaml
kubectl get jobs,pods,pvc -n ai-lab
kubectl logs -n ai-lab job/tiny-trainingBehavior. Expected: Kueue admits the suspended Job when quota permits; the process writes a checkpoint every ten steps and exits after 200. Retries reload a trusted checkpoint if present. No training log is supplied because this job was not executed.
Failure cases. CUDA unavailable fails explicitly. ImagePullBackOff indicates registry/image problems. Volume attachment or permission failures precede checkpointing. A corrupted checkpoint must fail rather than silently restart from a different state.
Validation boundary. ReadWriteOnce is not a distributed checkpoint store. Atomic file replacement is not a full power-loss or multi-shard commit protocol. Job TTL removes Job/Pod history, not the PVC; export diagnostics before cleanup. RNG restoration does not prove cross-hardware determinism.
UNEXECUTED CONFIGURATION EXAMPLE
D — Make training admission a quota decision
ResourceFlavor, ClusterQueue and LocalQueue form a coherent submission path. The flavor names a node-label class; the ClusterQueue budgets CPU, memory and two GPU units; the LocalQueue gives the ai-lab namespace a submission target. Kueue v0.20.2 serves v1beta2 for these resources.
Prerequisites. Kueue v0.20.2 CRDs/controller and batch Job integration must be installed by the platform owner. Namespace labeling and cluster-scoped queues require appropriate permissions. The example namespace selector deliberately avoids allowing every namespace to consume this queue.
queues.yaml
YAML# Kueue v0.20.2 CRDs/controllers required; administrator-owned resources.
apiVersion: kueue.x-k8s.io/v1beta2
kind: ResourceFlavor
metadata: {name: approved-gpu}
spec:
nodeLabels: {ai.example.com/accelerator: approved-gpu}
---
apiVersion: kueue.x-k8s.io/v1beta2
kind: ClusterQueue
metadata: {name: training-pool}
spec:
namespaceSelector:
matchLabels: {ai.example.com/training: enabled}
resourceGroups:
- coveredResources: [cpu, memory, nvidia.com/gpu]
flavors:
- name: approved-gpu
resources:
- {name: cpu, nominalQuota: "8"}
- {name: memory, nominalQuota: 32Gi}
- {name: nvidia.com/gpu, nominalQuota: "2"}
---
apiVersion: kueue.x-k8s.io/v1beta2
kind: LocalQueue
metadata: {name: training, namespace: ai-lab}
spec: {clusterQueue: training-pool}
Run / inspect — example D
shellkubectl label namespace ai-lab ai.example.com/training=enabled
kubectl apply --dry-run=server -f queues.yaml
kubectl apply -f queues.yaml
kubectl get clusterqueues
kubectl get localqueues,workloads -n ai-labBehavior. Expected: the Job from C references LocalQueue training; quota admission can unsuspend it. A queue with nominal GPU quota does not create GPUs.
Failure cases. Unknown API version means the installed CRDs differ. A wrong namespace selector, flavor labels or queue name can prevent admission or later placement. Review Workload conditions and controller events.
Validation boundary. Five custom-resource specs in D/E passed local release-pinned OpenAPI checks. That excludes CEL, webhooks and live reconciliation. This example does not configure fair sharing, preemption or gang placement.
UNEXECUTED CONFIGURATION EXAMPLE
E — Scale from an upstream queue, keep a warm replica
The Prometheus trigger reads an application-owned pending-request gauge. It is an explicit instrumentation contract, not a built-in vLLM metric. minReplicaCount stays at one: this example is not an implementation of synchronous scale-to-zero.
Prerequisites. KEDA v2.21.0; a Prometheus-compatible HTTPS endpoint with a trusted certificate; a restricted bearer credential in the metrics-reader Secret; a gateway exporting ai_gateway_pending_requests with model="demo". Replace the example endpoint with the actual service name. Multiple replicas require model storage supporting their placement or per-node/per-Pod caches; A’s PVC is not automatically suitable.
scaling.yaml
YAML# KEDA v2.21.0; a protected in-cluster Prometheus-compatible API is assumed.
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata: {name: metrics-auth, namespace: ai-lab}
spec:
secretTargetRef:
- {parameter: bearerToken, name: metrics-reader, key: token}
---
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: {name: inference-queue, namespace: ai-lab}
spec:
scaleTargetRef: {name: inference}
pollingInterval: 15
cooldownPeriod: 300
minReplicaCount: 1
maxReplicaCount: 4
triggers:
- type: prometheus
metadata:
serverAddress: https://prometheus.monitoring.svc:9090
query: sum(ai_gateway_pending_requests{model="demo"})
threshold: "8"
activationThreshold: "1"
authModes: bearer
ignoreNullValues: "false"
authenticationRef: {name: metrics-auth}
Run / inspect — example E
shellkubectl create secret generic metrics-reader -n ai-lab --from-file=token=/path/to/restricted-token
kubectl apply --dry-run=server -f scaling.yaml
kubectl apply -f scaling.yaml
kubectl get scaledobjects,hpa -n ai-lab
kubectl describe scaledobject inference-queue -n ai-labBehavior. Expected: one metric series drives demand up to four replicas using threshold eight. This is an illustrative threshold requiring load testing; GPU acquisition and model readiness can lag replica demand substantially.
Failure cases. TLS/authentication errors, missing metrics or a multi-series query break the control signal. ignoreNullValues=false avoids treating absent data as an innocent empty queue. Capacity exhaustion still leaves replicas Pending.
Validation boundary. No separate manually managed HPA should compete for the same Deployment. A durable request buffer, retry policy, warm-up budget and provider-specific node provisioning are not included. No cost saving is measured.
UNEXECUTED CONFIGURATION EXAMPLE
F — Verify the model endpoint without publishing it
A ClusterIP Service separates replica lifecycle from the caller. Port forwarding provides a local inspection path without creating a public unauthenticated endpoint. Health, model identity and an actual completion exercise different boundaries.
Prerequisites. A is Ready; the configured local model supports the completion endpoint. Run the port-forward command in a separate terminal and retain the default loopback bind. The response content depends on the model; no response is fabricated here.
service.yaml
YAML# Internal only: no public unauthenticated model endpoint.
apiVersion: v1
kind: Service
metadata: {name: inference, namespace: ai-lab}
spec:
selector: {app: inference}
ports: [{name: http, port: 8000, targetPort: http}]
type: ClusterIP
Run / inspect — example F
shellkubectl apply -f service.yaml
kubectl port-forward -n ai-lab service/inference 8000:8000
# In another terminal:
curl --fail http://127.0.0.1:8000/health
curl --fail http://127.0.0.1:8000/v1/models
curl --fail http://127.0.0.1:8000/v1/completions -H "Content-Type: application/json" -d '{"model":"demo","prompt":"Explain a GPU in one sentence.","max_tokens":32}'Behavior. Expected: health succeeds, the model list includes demo, and a completion request returns a compatible response. Record the model revision alongside any captured response.
Failure cases. Connection refusal, no ready endpoints, a mismatched model alias or unsupported request format distinguish networking, readiness and application failures. A health success alone is insufficient.
Validation boundary. No throughput, streaming cancellation, authentication gateway, multi-replica routing or model-safety evaluation is performed. Production exposure needs its own security and load tests.
UNEXECUTED CONFIGURATION EXAMPLE
G — Read GPU and request signals together
These queries combine device utilization with inference waiting and latency. The percentile expression aggregates histogram buckets before histogram_quantile; averaging per-Pod percentiles would answer a different question.
Prerequisites. Prometheus scrapes DCGM Exporter and the runtime’s /metrics endpoint; labels and metric names match the deployed releases. The final gateway metric is an example instrumentation contract. Restrict each query to the intended namespace/model in a real multi-tenant system.
metrics.promql
PromQL# Inspect the actual /metrics endpoint before using these expressions.
avg by (namespace, pod) (DCGM_FI_DEV_GPU_UTIL)
sum(vllm:num_requests_waiting)
histogram_quantile(0.95,
sum by (le) (rate(vllm:time_to_first_token_seconds_bucket[5m])))
sum(rate(vllm:generation_tokens_total[5m]))
# Request error ratio is an example gateway contract, not a vLLM built-in.
sum(rate(ai_gateway_requests_total{outcome="error"}[5m]))
/ sum(rate(ai_gateway_requests_total[5m]))
Run / inspect — example G
shellkubectl port-forward -n ai-lab service/inference 8000:8000
# In another terminal, inspect metric names before writing dashboards:
curl --fail http://127.0.0.1:8000/metrics
kubectl top pods -n ai-labBehavior. Expected: metrics expose runtime demand and device activity where their exporters support them. kubectl top needs Metrics Server and reports CPU/memory; it is not a GPU utilization command. Platform-approved nvidia-smi diagnostics can inspect driver/device state, but do not prove application throughput.
Failure cases. An empty query may mean a missing scrape or changed metric, not zero load. Zero request volume makes an error-ratio denominator undefined. GPU shares can complicate per-tenant attribution.
Validation boundary. PromQL was reviewed against documentation but not executed by a Prometheus server. No chart values, SLO achievement or performance scores are claimed.
EXECUTED TEST — LOCAL FILESYSTEM ONLY
H — Test the local checkpoint commit boundary
This deliberately small experiment tests a property independent of GPUs: an exception after writing a temporary file but before replacement leaves the previous committed checkpoint readable. It also checks round-trip state and rejects invalid JSON.
Prerequisites. Python 3 standard library and a local writable filesystem. Run in the downloaded source directory. The captured output belongs only to this fixture and its recorded environment; the GPU training script is a different, unexecuted example.
checkpoint.py
Python"""Local filesystem example only; not an object-store/distributed checkpoint manager."""
import json
import os
from pathlib import Path
def save(path: Path, state: dict, before_replace=lambda: None):
temp = path.with_suffix(".tmp")
with temp.open("w") as stream:
json.dump(state, stream)
stream.flush()
os.fsync(stream.fileno())
before_replace()
os.replace(temp, path)
def load(path: Path):
return json.loads(path.read_text())
test_checkpoint.py
Pythonimport tempfile
import unittest
from pathlib import Path
from checkpoint import save, load
class CheckpointBoundary(unittest.TestCase):
def test_round_trip(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "state.json"
save(path, {"step": 10})
self.assertEqual(load(path), {"step": 10})
def test_failure_before_replace_keeps_previous_commit(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "state.json"
save(path, {"step": 10})
def fail():
raise RuntimeError("injected failure before replace")
with self.assertRaises(RuntimeError):
save(path, {"step": 20}, fail)
self.assertEqual(load(path)["step"], 10)
def test_corruption_is_not_silently_accepted(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "state.json"
path.write_text("truncated")
with self.assertRaises(ValueError):
load(path)
if __name__ == "__main__":
unittest.main(verbosity=2)
Run / inspect — example H
shellpython3 -m unittest discover -s . -p "test_checkpoint.py" -vBehavior. Observed locally: three tests passed. The interrupted write preserved step 10 rather than committing step 20. The captured output and source hashes are included in the source archive.
Failure cases. The test injects a Python exception, not a node crash, storage outage or power failure. It does not fsync the containing directory or coordinate multiple writers. Corruption is surfaced, not repaired.
Validation boundary. Validates local file commit selection and error visibility. Does not validate CUDA, training convergence, persistent-volume durability, distributed membership, object-store consistency or full checkpoint recovery.
CAPTURED LOCAL OUTPUT · 3.9.6 · macOS-27.0.1-arm64-arm-64bit
Actual checkpoint fixture output
Captured unittest outputtest_corruption_is_not_silently_accepted (test_checkpoint.CheckpointBoundary) ... ok
test_failure_before_replace_keeps_previous_commit (test_checkpoint.CheckpointBoundary) ... ok
test_round_trip (test_checkpoint.CheckpointBoundary) ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.003s
OK
16 / OPEN-SOURCE PROJECTS WORTH STUDYING
Read the integration boundary before adopting the project
Repository READMEs, license files, release metadata and recent activity were inspected on 2026-10-21. All listed repositories were unarchived in that snapshot. A push date is a maintenance signal, not proof of maintainer responsiveness or production maturity. These releases are not a tested combined stack; immutable README links preserve what was inspected.
NVIDIA/k8s-device-plugin ↗
Advertises GPU resources and allocation integration to kubelet.
Trade-off. Requires a compatible host/runtime stack; sharing settings change resource semantics.
Inspect the reviewed README ↗NVIDIA/gpu-operator ↗
Reconciles NVIDIA GPU enablement components on supported platforms.
Trade-off. Privileged lifecycle ownership and a platform compatibility matrix; not a scheduler.
Inspect the reviewed README ↗kubernetes-sigs/kueue ↗
Admissions and quotas before supported batch workloads run.
Trade-off. Requires controller/job integration; topology features need explicit configuration.
Inspect the reviewed README ↗kedacore/keda ↗
Connects external demand sources to workload scaling.
Trade-off. A scaler needs a durable valid signal, authentication and an activation strategy.
Inspect the reviewed README ↗kubernetes-sigs/karpenter ↗
Node provisioning core and provider integration contracts.
Trade-off. The provider implementation, NodeClass, quota and available capacity constrain behavior.
Inspect the reviewed README ↗kubeflow/trainer ↗
Training-specific workload APIs and orchestration.
Trade-off. Framework and runtime configuration still own distributed execution and recovery.
Inspect the reviewed README ↗kserve/kserve ↗
Serving control-plane resources above inference runtimes.
Trade-off. Deployment mode and runtime integration matter; docs/release versions can differ.
Inspect the reviewed README ↗ray-project/kuberay ↗
Kubernetes operators for Ray clusters, jobs and services.
Trade-off. Does not replace Ray’s own task/resource model. Follow repository redirects.
Inspect the reviewed README ↗ray-project/ray ↗
Distributed execution and libraries including Train and Serve.
Trade-off. Adds runtime-level scheduling, state and operational dependencies.
Inspect the reviewed README ↗triton-inference-server/server ↗
Inference serving with backend-specific execution support.
Trade-off. Model/backend compatibility and configuration govern actual capabilities.
Inspect the reviewed README ↗vllm-project/vllm ↗
LLM runtime, batching and memory-aware serving.
Trade-off. Hardware/model support, memory budget and workload shape require measurement.
Inspect the reviewed README ↗volcano-sh/volcano ↗
Batch scheduling, queues and coordinated placement mechanisms.
Trade-off. Additional scheduler policy and integrations; no application checkpoint guarantee.
Inspect the reviewed README ↗17 / ENGINEERING CONCLUSION
A programmable platform, not a substitute for engineering
Kubernetes became important to AI because it gives shared accelerator infrastructure a programmable operating model. Teams can describe work, enforce resource boundaries and reconcile failures through a common API. That matters when coordination becomes more difficult than starting a model.
It does not replace the runtime, training framework, storage design or operational expertise. Admission does not guarantee placement; placement does not guarantee efficient communication; restart does not guarantee recovery; a replica does not guarantee useful capacity. Keeping these boundaries visible is the difference between a convincing diagram and an architecture that can be tested.
Start with a measurable workload and a small platform contract. Add Kueue when admission policy matters, a serving platform when model lifecycle needs it, and specialized scheduling when placement semantics justify it. Keep the simpler option in the comparison. The strongest architecture is the one whose costs, failures and ownership you can explain.
18 / PRIMARY SOURCES / VALIDATION
Documentation is evidence of a contract, not of this deployment
Primary references accompany the claims above. Repository release snapshots and example API baselines were checked on 2026-10-21; moving “latest” documentation may change. The KServe architecture page reviewed identified version 0.20, while its repository release snapshot reported 0.21.0. No KServe manifest is asserted compatible across those versions.
- Kueue Job integration ↗ and v0.20.2 CRD schemas ↗.
- KEDA 2.21 Prometheus scaler ↗ and release CRDs ↗.
- vLLM release-pinned Kubernetes example ↗.
- PyTorch version-specific installation instructions ↗.
VALIDATES
- Primary documentation and release-source inspection with explicit review date.
- Ten YAML documents parse; five custom-resource spec objects pass release-pinned schema-subset checks.
- Three local filesystem tests pass; captured output and hashes accompany their source.
DOES NOT VALIDATE
- GPU, CUDA or network compatibility; container pulls; deployed Kubernetes resources.
- Admission webhooks/CEL, core resource schemas or controller reconciliation.
- Distributed recovery, model behavior, PromQL execution, performance, cost savings or production readiness.
Share this engineering analysis
CONTINUE EXPLORING