Stage 4, Part 1 of 9 · p. 29, Workloads & Lifecycle Deep Dive

PART 1: CORE THEORY

1. The Workload Hierarchy

Kubernetes provides multiple workload types, each designed for a specific kind of application. Choosing the wrong one is a common source of production pain.

The Full Workload Family

text
┌─────────────────────────────────────────────────────────────┐
│                    WORKLOAD TYPES                           │
│                                                             │
│  STATELESS                          STATEFUL                │
│  ┌───────────────┐                  ┌───────────────┐      │
│  │  Deployment   │                  │  StatefulSet  │      │
│  │  (ReplicaSet) │                  │  (Ordered,    │      │
│  │               │                  │   Stable ID)  │      │
│  └───────────────┘                  └───────────────┘      │
│                                                             │
│  NODE-LEVEL                         BATCH                  │
│  ┌───────────────┐                  ┌───────────────┐      │
│  │  DaemonSet    │                  │  Job          │      │
│  │  (One per     │                  │  CronJob      │      │
│  │   node)       │                  │  (Scheduled)  │      │
│  └───────────────┘                  └───────────────┘      │
│                                                             │
│  RAW                                                        │
│  ┌───────────────┐                                          │
│  │  Pod          │  (Rarely used directly)                 │
│  └───────────────┘                                          │
└─────────────────────────────────────────────────────────────┘

Decision Matrix

WorkloadStateless?Identity?Storage?Ordering?Use Case
Deployment✅❌Shared❌Web apps, APIs
StatefulSet❌✅Per-Pod✅Databases, queues
DaemonSet✅N/ANode-localN/AAgents, CNI
Job✅❌Optional❌Batch, migrations
CronJob✅❌Optional❌Scheduled tasks
Pod✅❌Optional❌Debugging

The Controller Pattern

All workloads follow the same pattern:

text
User creates resource
    │
    ▼
Controller observes
    │
    ▼
Controller creates child resources (Pods, ReplicaSets)
    │
    ▼
Controller reconciles continuously

Each workload is a controller with specific logic:


2. Deployments

A Deployment is the standard workload for stateless applications. It manages ReplicaSets, which manage Pods.

The Deployment → ReplicaSet → Pod Hierarchy

text
Deployment (web)
    │
    └── ReplicaSet (web-abc123)   ← Current version
            ├── Pod web-abc123-1
            ├── Pod web-abc123-2
            └── Pod web-abc123-3
    │
    └── ReplicaSet (web-def456)   ← Old version (scaled to 0)
            └── (0 pods)

Why ReplicaSets? They enable rolling updates and rollbacks. Each version of your Deployment gets its own ReplicaSet.

Deployment Strategies

StrategyBehaviorDowntimeUse Case
RollingUpdateGradual replacement❌ NoneDefault, production
RecreateKill all, then create new⚠️ YesDev, incompatible versions

RollingUpdate Parameters

yaml
spec:
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1              # Extra pods during update
      maxUnavailable: 0        # Pods that can be down

The math:

maxSurgemaxUnavailableBehavior
10Surge by 1, never drop below desired
25%25%Balanced (default)
01No extra pods, one unavailable
11Fast but risky

For zero-downtime: maxUnavailable: 0 and at least 2 replicas.

The Update Lifecycle

text
1. User applies new Deployment (new image)
2. Deployment creates NEW ReplicaSet
3. New ReplicaSet scales up (respecting maxSurge)
4. Old ReplicaSet scales down (respecting maxUnavailable)
5. Repeat until new RS has all replicas, old RS has 0
6. Old RS is retained for rollback

Rollback and History

bash
# View history
kubectl rollout history deployment/web

# Rollback to previous
kubectl rollout undo deployment/web

# Rollback to specific revision
kubectl rollout undo deployment/web --to-revision=2

# Pause/resume (for multi-step changes)
kubectl rollout pause deployment/web
kubectl set image deployment/web web=nginx:1.26
kubectl set resources deployment/web --limits=cpu=500m
kubectl rollout resume deployment/web

# Restart (rolling restart)
kubectl rollout restart deployment/web

# Status
kubectl rollout status deployment/web

Revision History Limit

yaml
spec:
  revisionHistoryLimit: 10    # Keep last 10 ReplicaSets (default)

Production tip: Keep enough history for rollback. 10 is usually fine; 5 for resource-constrained clusters.

Progress Deadline

yaml
spec:
  progressDeadlineSeconds: 600    # Fail if not progressing in 10 min

If the rollout doesn't progress within this time, the Deployment is marked as failed. The ReplicaSet isn't deleted, but kubectl rollout status will exit with error.

Common Deployment Anti-Patterns

Anti-PatternWhy It's Bad
maxUnavailable: 100%All pods down during update
replicas: 1No HA; every update is downtime
No readiness probeTraffic routed to not-ready pods
revisionHistoryLimit: 0Can't rollback
:latest image tagNon-deterministic updates
No resource requests/limitsUnpredictable scheduling

3. StatefulSets

A StatefulSet manages stateful applications that require:

The Identity Guarantee

AspectDeploymentStatefulSet
Pod nameweb-abc123-xyz (random)web-0, web-1, web-2 (ordered)
HostnameSame as Pod nameSame as Pod name (stable)
DNSRandomweb-0.web.default.svc.cluster.local
StorageShared or nonePer-Pod PVC (persistent)
Startup orderParallelSequential (0 → 1 → 2)
Termination orderParallelReverse (2 → 1 → 0)

The Headless Service Requirement

StatefulSets require a Headless Service (clusterIP: None) for stable DNS.

yaml
apiVersion: v1
kind: Service
metadata:
  name: db-headless
spec:
  clusterIP: None
  selector:
    app: db
  ports:
  - port: 5432
    name: postgres

Each Pod gets its own DNS record:

StatefulSet Example

yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
spec:
  serviceName: postgres-headless
  replicas: 3
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:16-alpine
        env:
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: pg-secret
              key: password
        - name: PGDATA
          value: /var/lib/postgresql/data/pgdata
        ports:
        - containerPort: 5432
          name: postgres
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      storageClassName: fast-ssd
      resources:
        requests:
          storage: 100Gi

Each Pod gets its own PVC: data-postgres-0, data-postgres-1, data-postgres-2. These PVCs are NOT deleted when the StatefulSet is deleted (data preservation).

Update Strategies

StrategyBehaviorDowntime
RollingUpdateUpdate Pods in reverse order❌ None (if HA)
OnDeleteManual Pod deletion triggers updateManual control
PartitionedUpdate only Pods ≥ partitionCanary releases

Partitioned rolling update is the StatefulSet equivalent of canary:

yaml
spec:
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      partition: 2    # Only update Pods with ordinal >= 2

This updates postgres-2 only, letting you validate before updating postgres-1 and postgres-0.

The Scaling Behavior

Scale up: Pods created in order 0, 1, 2 (each waits for the previous to be Ready).

Scale down: Pods deleted in reverse order 2, 1, 0.

When to Use StatefulSets

ApplicationWhy StatefulSet
PostgreSQL / MySQLNeeds stable storage per replica
MongoDB replica setsMembers need stable identities
Kafka / RabbitMQBrokers need stable IDs
ElasticsearchNodes need stable names
ZooKeeper / etcdConsensus requires stable IDs
CassandraRing topology needs ordering

When NOT to Use StatefulSets

ApplicationUse Instead
Stateless web appDeployment
App with shared storageDeployment + ReadWriteMany PVC
App without stable ID needsDeployment

The Operational Complexity

StatefulSets are harder to operate than Deployments:

ChallengeWhy
Ordered startupSlow if 100 replicas
PVC managementPVCs persist after deletion
Data migrationNo automatic data movement
BackupPer-Pod backup needed
DebuggingHarder to reset (data persists)

Rule of thumb: Use StatefulSet only if you need stable identity + per-Pod storage. Otherwise, use Deployment.


4. DaemonSets

A DaemonSet ensures a Pod runs on every node (or a subset). Used for node-level services.

How DaemonSets Work

text
Cluster with 5 nodes
    │
    ▼
DaemonSet "fluentd" (replicas=5, implicit)
    │
    ├── Pod on node-1
    ├── Pod on node-2
    ├── Pod on node-3
    ├── Pod on node-4
    └── Pod on node-5

When a new node joins, a new Pod is automatically created. When a node leaves, its Pod is garbage collected.

Common DaemonSets

DaemonSetPurpose
kube-proxyNetworking
CNI pluginPod networking (Cilium, Calico)
CSI node pluginStorage
Fluent Bit / FilebeatLog collection
Prometheus Node ExporterNode metrics
Datadog / New Relic agentAPM
Falco / TetragonRuntime security
NVIDIA device pluginGPU scheduling

DaemonSet Example

yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: node-exporter
  namespace: monitoring
spec:
  selector:
    matchLabels:
      app: node-exporter
  template:
    metadata:
      labels:
        app: node-exporter
    spec:
      hostNetwork: true
      hostPID: true
      tolerations:
      - operator: Exists        # Tolerate all taints
      containers:
      - name: node-exporter
        image: prom/node-exporter:v1.7.0
        args:
        - "--path.procfs=/host/proc"
        - "--path.sysfs=/host/sys"
        - "--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)"
        ports:
        - containerPort: 9100
          hostPort: 9100
          name: metrics
        resources:
          limits:
            cpu: 200m
            memory: 200Mi
          requests:
            cpu: 100m
            memory: 100Mi
        volumeMounts:
        - name: proc
          mountPath: /host/proc
          readOnly: true
        - name: sys
          mountPath: /host/sys
          readOnly: true
      volumes:
      - name: proc
        hostPath:
          path: /proc
      - name: sys
        hostPath:
          path: /sys

The Toleration Requirement

DaemonSet Pods on control plane nodes need a toleration for the control-plane taint:

yaml
tolerations:
- key: node-role.kubernetes.io/control-plane
  operator: Exists
  effect: NoSchedule

Most DaemonSets use operator: Exists (tolerate all taints) to run on all nodes.

Node Selection

yaml
spec:
  template:
    spec:
      nodeSelector:
        node-type: gpu       # Only on GPU nodes
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: topology.kubernetes.io/zone
                operator: In
                values: [us-east-1a, us-east-1b]

Update Strategies

StrategyBehavior
RollingUpdateUpdate pods one node at a time
OnDeleteUpdate only when Pod is deleted
yaml
spec:
  updateStrategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1        # Update 1 node at a time
      maxSurge: 0              # No extra Pods (fixed per node)

Note: DaemonSets don't support maxSurge > 0 because there's exactly one Pod per node.

DaemonSet Use Cases

Use CaseExample
Log collectionFluent Bit on every node
Metrics collectionnode-exporter on every node
NetworkingCilium agent on every node
StorageCSI node plugin on every node
SecurityFalco on every node
GPUNVIDIA device plugin on GPU nodes

5. Jobs and CronJobs

Jobs

A Job runs Pods to completion. Unlike Deployments (which run forever), Jobs finish.

Job Patterns

PatternDescription
SingleOne Pod runs to completion
Parallel fixedN Pods complete successfully
Work queueN workers process a queue
IndexedEach Pod gets a unique index

Single Job

yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: db-migrate
spec:
  template:
    spec:
      restartPolicy: OnFailure
      containers:
      - name: migrate
        image: myapp:1.0
        command: ["python", "manage.py", "migrate"]

Parallel Fixed

yaml
spec:
  completions: 10          # Total successful completions needed
  parallelism: 3           # Max concurrent Pods

Behavior: 3 Pods run concurrently. As each completes, a new one starts until 10 have succeeded.

Work Queue

yaml
spec:
  parallelism: 5           # 5 workers
  completions: 5           # Each worker processes until queue empty
  # No completions specified = runs until all workers exit

Indexed Jobs (K8s 1.24+)

yaml
spec:
  completions: 10
  parallelism: 3
  completionMode: Indexed
  template:
    spec:
      containers:
      - name: worker
        image: myapp:1.0
        env:
        - name: JOB_COMPLETION_INDEX
          valueFrom:
            fieldRef:
              fieldPath: metadata.annotations['batch.kubernetes.io/job-completion-index']
        command: ["process.sh", "$(JOB_COMPLETION_INDEX)"]

Each Pod gets a unique index from 0 to completions-1. Perfect for sharded batch jobs.

Job Parameters

ParameterPurposeDefault
completionsTotal successes needed1
parallelismMax concurrent Pods1
backoffLimitRetries before failure6
activeDeadlineSecondsTimeout for whole JobNone
ttlSecondsAfterFinishedAuto-delete after N secondsNone
completionModeNonIndexed or IndexedNonIndexed

CronJobs

A CronJob creates Jobs on a schedule.

yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: backup
spec:
  schedule: "0 2 * * *"        # 2 AM daily
  timeZone: "America/New_York"  # Optional (K8s 1.27+)
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 3
  startingDeadlineSeconds: 300
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
          - name: backup
            image: backup-tool:1.0
            command: ["/backup.sh"]

Cron Schedule Format

text
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, Sun=0)
│ │ │ │ │
* * * * *
ScheduleMeaning
0 * * * *Every hour
0 0 * * *Every day at midnight
0 2 * * *Every day at 2 AM
0 0 * * 0Every Sunday
0 0 1 * *First of month
*/15 * * * *Every 15 minutes

Concurrency Policy

PolicyBehavior
AllowMultiple Jobs run concurrently
ForbidSkip if previous Job still running
ReplaceKill previous, start new

CronJob Best Practices

PracticeWhy
Set concurrencyPolicyPrevent overlap
Set startingDeadlineSecondsDon't run too late
Use activeDeadlineSecondsPrevent runaway jobs
Set resource limitsPredictable scheduling
Set ttlSecondsAfterFinishedAuto-cleanup
Use timeZoneCorrect scheduling
Idempotent jobsSafe retries

Time Zones (K8s 1.27+)

yaml
spec:
  schedule: "0 2 * * *"
  timeZone: "America/New_York"    # Schedules in EST

Without timeZone, schedules are in UTC.


6. Pod Lifecycle

Pod Phases

PhaseMeaning
PendingAccepted, waiting for scheduling or image pull
RunningAt least one container running
SucceededAll containers exited successfully (exit 0)
FailedAt least one container failed (exit ≠ 0)
UnknownCan't determine state (usually node issue)

Container States

StateMeaning
WaitingNot started (pulling image, waiting for dependency)
RunningExecuting
TerminatedFinished or crashed

Common Waiting Reasons

ReasonCause
ContainerCreatingRuntime is setting up
CrashLoopBackOffContainer keeps crashing
ImagePullBackOffCan't pull image
ErrImagePullImage pull error
CreateContainerConfigErrorBad config (missing ConfigMap/Secret)
CreateContainerErrorRuntime failed to create
RunContainerErrorContainer failed to start
PodInitializingInit containers still running

The Full Lifecycle

text
1. User creates Pod
   │
   ▼
2. Scheduler assigns to Node (Pending → Scheduled)
   │
   ▼
3. Kubelet pulls images
   │
   ▼
4. Init containers run sequentially
   │
   ▼
5. Main containers start
   │
   ▼
6. Startup probes (if defined) run
   │
   ▼
7. Liveness and Readiness probes start
   │
   ▼
8. Pod becomes Ready (Running → Ready)
   │
   ▼
9. Terminating (when deleted or evicted)
   │
   ▼
10. PreStop hook runs (if defined)
   │
   ▼
11. SIGTERM sent to containers
   │
   ▼
12. terminationGracePeriodSeconds wait
   │
   ▼
13. SIGKILL if still running
   │
   ▼
14. Pod removed

Restart Policy

PolicyBehavior
AlwaysRestart on any exit (default for Deployments)
OnFailureRestart only on non-zero exit
NeverNever restart

Restart Backoff

Kubernetes uses exponential backoff for restarts:

text
1st restart: 10s
2nd: 20s
3rd: 40s
4th: 80s
5th: 160s
6th: 300s (max)

The restart counter resets after 10 minutes of successful running.


1:1 copy of the class Google Doc, code in code blocks.