Library

Volume 1 · Containers & Kubernetes

Notebook
Sign in

Section 28

Kubernetes Deep Dive

1,134 words · about 5 min

28.1 Core Object Model

┌─────────────────────────────────────────────────────────┐
│ Deployment (desired state: 3 replicas, image v2.1)       │
│   └── ReplicaSet (ensures N pods match template)          │
│         ├── Pod (1+ containers, shared network/storage)   │
│         ├── Pod                                            │
│         └── Pod                                            │
└─────────────────────────────────────────────────────────┘
                        │
                 ┌──────▼──────┐
                 │   Service    │  (stable virtual IP, load-balances to pods via label selector)
                 └──────┬──────┘
                        │
                 ┌──────▼──────┐
                 │   Ingress    │  (L7 routing, TLS termination, host/path rules)
                 └─────────────┘

28.2 Pods, Deployments, Services

# Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: inference-api
spec:
  replicas: 3
  selector:
    matchLabels: { app: inference-api }
  template:
    metadata:
      labels: { app: inference-api }
    spec:
      containers:
        - name: inference-api
          image: myregistry/inference-api:v2.1
          ports: [{ containerPort: 8080 }]
          resources:
            requests: { cpu: "500m", memory: "512Mi" }
            limits: { cpu: "1", memory: "1Gi" }
---
# Service — stable ClusterIP load-balancing to pods
apiVersion: v1
kind: Service
metadata:
  name: inference-api-svc
spec:
  selector: { app: inference-api }
  ports:
    - port: 80
      targetPort: 8080
  type: ClusterIP
---
# Ingress — L7 routing + TLS
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: inference-api-ingress
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  tls:
    - hosts: ["api.example.com"]
      secretName: api-tls
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: inference-api-svc
                port: { number: 80 }

28.3 Liveness, Readiness, and Startup Probes

Probe Question It Answers Failure Action
Liveness “Is this container still alive/functional?” Kubelet restarts the container
Readiness “Is this container ready to receive traffic right now?” Removed from Service endpoints, no restart
Startup “Has the (slow) startup process finished yet?” Suppresses liveness checks until startup succeeds, then hands off
containers:
  - name: llm-inference
    image: myregistry/vllm-server:latest
    startupProbe:
      httpGet: { path: /health, port: 8080 }
      failureThreshold: 30     # allow up to 30 * 10s = 5 min for model load
      periodSeconds: 10
    livenessProbe:
      httpGet: { path: /health, port: 8080 }
      periodSeconds: 15
      failureThreshold: 3
    readinessProbe:
      httpGet: { path: /ready, port: 8080 }
      periodSeconds: 5
      failureThreshold: 2

Why this matters for AI workloads specifically: model-serving containers can take 60–300 seconds to load weights into GPU memory. Without a startupProbe, the default liveness probe will kill the pod mid-load, causing a crash-loop that never actually finishes starting.

28.4 Horizontal Pod Autoscaler (HPA) and KEDA

# Standard HPA — CPU/memory based
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: inference-api-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: inference-api
  minReplicas: 2
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target: { type: Utilization, averageUtilization: 70 }
---
# KEDA — event-driven scaling on queue depth (scale-to-zero capable)
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: claim-processor-scaler
spec:
  scaleTargetRef:
    name: claim-processor
  minReplicaCount: 0
  maxReplicaCount: 50
  triggers:
    - type: aws-sqs-queue
      metadata:
        queueURL: https://sqs.us-east-1.amazonaws.com/123456789/claims-queue
        queueLength: "5"    # target: 5 messages per replica

HPA vs. KEDA: HPA natively supports CPU/memory and custom metrics via the Metrics API; KEDA extends this to 50+ external event sources (SQS, Kafka, Service Bus, Prometheus, cron) and uniquely supports scale-to-zero, which vanilla HPA cannot do (HPA’s minimum is 1 replica). For bursty, queue-driven AI ingestion pipelines, KEDA is the natural choice.

28.5 ConfigMaps and Secrets

apiVersion: v1
kind: ConfigMap
metadata: { name: inference-config }
data:
  MODEL_NAME: "claude-sonnet"
  MAX_TOKENS: "4096"
  LOG_LEVEL: "info"
---
apiVersion: v1
kind: Secret
metadata: { name: inference-secrets }
type: Opaque
stringData:
  API_KEY: "will-be-injected-via-external-secrets-operator"
---
# Consuming both in a pod
spec:
  containers:
    - name: inference-api
      envFrom:
        - configMapRef: { name: inference-config }
        - secretRef: { name: inference-secrets }

Production note: native K8s Secrets are only base64-encoded, not encrypted at rest by default (unless envelope encryption is enabled at the etcd layer). For production, use External Secrets Operator or CSI Secret Store driver to sync from Key Vault/Secrets Manager/Secret Manager at runtime rather than storing plaintext-adjacent secrets as native K8s objects.

28.6 Interview Q&A

Q1: Explain the difference between liveness and readiness probes, and why getting this wrong is dangerous for a GPU inference pod.

A: Liveness answers “should this container be restarted?” — a failure kills and restarts the container. Readiness answers “should this pod currently receive traffic?” — a failure just pulls it out of the Service’s endpoint list without restarting anything. For a GPU inference pod loading a multi-gigabyte model into memory, if I only configure a liveness probe with a short failureThreshold, Kubernetes will decide the pod is unhealthy mid-load and restart it — creating an infinite crash loop that never finishes starting. The fix is a startupProbe with enough failureThreshold * periodSeconds to cover worst-case model load time; liveness checks are suppressed until the startup probe succeeds. Separately, I’d keep readiness strict and fast so the pod is pulled from traffic quickly if the model server becomes overloaded, without triggering a full restart.

Q2: When would you choose KEDA over standard HPA?

A: Standard HPA scales on CPU/memory (or custom Metrics API values) and cannot scale below 1 replica. KEDA is the right choice when scaling needs to be driven by an external event source — queue depth (SQS/Service Bus/Kafka lag), a Prometheus query, or a cron schedule — and, critically, when I need true scale-to-zero for cost efficiency on bursty workloads, like a document-ingestion pipeline that’s idle most of the day. I’d still use HPA (or both together — KEDA can manage the underlying HPA object) for steady-state CPU-bound scaling of an always-on API.

Q3: How do you manage secrets in Kubernetes without them ending up in plaintext anywhere?

A: Never store the actual secret value as a native K8s Secret manifest checked into Git — that’s base64, not encryption, and is trivially reversible. Use External Secrets Operator or the CSI Secret Store driver to sync secrets live from Key Vault/Secrets Manager/Secret Manager into the cluster at pod-mount time, so the source of truth stays in the cloud provider’s managed secret store with its own audit trail and rotation. Combine this with Workload Identity/IRSA so the pod’s own identity — not a static credential — is what authorizes the secret store to release the value. Enable etcd encryption at rest as defense-in-depth for whatever transient Secret objects the sync mechanism does create.