Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Kubernetes for SREs

Module 8 Lesson 8.d 1h Difficulty 3/5

Prerequisites 6.f, 7.a

The idea in one minute#

Kubernetes will happily run a service that falls over during every deploy, gets killed for memory at random, has all replicas on one node, and cannot survive a cluster upgrade. Whether it does depends on a dozen settings in the manifest: probes, resource requests and limits, rollout strategy, PodDisruptionBudgets, topology spread, autoscaling, and graceful termination.

This lesson is the SRE checklist for a production workload, with a complete annotated manifest and a small linter that checks it.

An analogy#

A shipping container port. Kubernetes is the crane system: it moves containers around tirelessly. But if containers are not labelled with their weight (requests), not strapped down (limits), and the crane operator is not told which ones must never be moved at the same time (disruption budgets), the crane will cheerfully drop your cargo.

A picture#

flowchart TB
  D[":kubernetes: <b>Deployment</b>"] --> P1["Pod — zone A"] & P2["Pod — zone B"] & P3["Pod — zone C"]
  subgraph POD["Each pod"]
    direction LR
    SP["startupProbe<br/><small>slow start allowed</small>"] --> RP["readinessProbe<br/><small>receive traffic?</small>"]
    LP["livenessProbe<br/><small>restart if wedged</small>"]
    RL["requests / limits<br/><small>scheduling and QoS</small>"]
    TG["preStop + grace period<br/><small>drain</small>"]
  end
  PDB[":i-shield-check: <b>PodDisruptionBudget</b><br/><small>minAvailable during drains</small>"] -.-> D
  HPA[":i-gauge: <b>HPA</b><br/><small>scale on load</small>"] -.-> D
  TSC[":i-split: <b>topologySpreadConstraints</b><br/><small>across zones and nodes</small>"] -.-> D
  class D io
  class P1,P2,P3 compute
  class SP,RP,LP,RL,TG neutral
  class PDB,HPA,TSC queue

How it really works#

Probes#

ProbeQuestionOn failureCommon mistake
startupProbeHas the app finished starting?Keep waiting (up to failureThreshold × periodSeconds), then restartMissing, so liveness kills slow-starting apps in a loop
readinessProbeShould it receive traffic now?Removed from Service endpoints, not restartedChecking dependencies, so a DB blip removes every pod (7.a)
livenessProbeIs the process wedged beyond recovery?Container restartedToo aggressive or dependency-checking: restarts healthy pods under load, causing cascades

Rules: liveness checks only the process itself (can it answer a trivial request?) and is generous; readiness reflects “can I serve right now” (including “I am shutting down”, 6.f) and reacts quickly; startup covers slow initialisation. Many services are better off without a liveness probe than with a bad one.

Requests, limits and QoS#

  • Requests are what the scheduler reserves. Set them from measured usage at peak (p95–p99 of real usage), or the scheduler overcommits nodes.
  • Memory limit: exceeding it means an OOM kill. Set it above peak usage with margin; for most services, memory request = memory limit (predictable).
  • CPU limit: exceeding it means throttling (CFS quota), which causes latency spikes even when the node has idle CPU. Many teams set CPU requests but no CPU limit for latency-sensitive services; others set limits generously. Know which you chose and watch container_cpu_cfs_throttled_periods_total.
  • QoS classes: Guaranteed (requests = limits for all resources) is evicted last; Burstable next; BestEffort (nothing set) first. Production services should not be BestEffort.
  • Go specifically: set GOMEMLIMIT a little below the memory limit so the garbage collector works harder before the kernel kills the process, and since Go 1.25 the runtime respects the container’s CPU limit when setting GOMAXPROCS (earlier versions needed automaxprocs).

Rollout strategy#

YAML
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxUnavailable: 0     # never drop below desired capacity during a deploy
    maxSurge: 25%         # create new pods first
minReadySeconds: 10       # a pod must stay ready for 10 s before it counts
progressDeadlineSeconds: 600
revisionHistoryLimit: 10  # keep old ReplicaSets for `kubectl rollout undo`

For canaries with analysis, use Argo Rollouts or Flagger (8.b).

Disruptions#

Voluntary disruptions — node drains for upgrades, cluster autoscaler scale-down — respect a PodDisruptionBudget:

YAML
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: checkout }
spec:
  minAvailable: 80%        # or maxUnavailable: 1
  selector: { matchLabels: { app: checkout } }

Without one, a node drain can evict every replica at once. With one that is too strict (maxUnavailable: 0), node drains block forever and cluster upgrades stall — also an incident.

Spreading across failure domains#

YAML
topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector: { matchLabels: { app: checkout } }
  - maxSkew: 1
    topologyKey: kubernetes.io/hostname
    whenUnsatisfiable: ScheduleAnyway
    labelSelector: { matchLabels: { app: checkout } }

Autoscaling#

  • HPA on CPU utilisation (of requests), or better on a load metric (requests per second per pod, concurrency) via custom or external metrics; KEDA for queue length and event sources.
  • minReplicas sized for zone loss and spike absorption; maxReplicas sized for the database behind you (7.d).
  • behavior to scale up fast and down slowly, avoiding flapping.
  • Do not let HPA (replicas) and VPA (requests) both act on CPU for the same workload.

The cluster is a dependency#

Treat the platform as a dependency with its own failure modes: control-plane (API server, etcd) outages, admission webhooks that fail closed and block all deploys, DNS (CoreDNS) overload, IP address exhaustion, node image upgrades, and Kubernetes minor-version upgrades (a new minor release roughly every four months; each supported for about 14 months — 1.36 was released in April 2026). Running workloads keep running when the control plane is down — static stability — but nothing can be changed or rescheduled.

A production manifest#

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: checkout
  labels: { app: checkout, team: payments }
spec:
  replicas: 6
  revisionHistoryLimit: 10
  minReadySeconds: 10
  strategy: { type: RollingUpdate, rollingUpdate: { maxUnavailable: 0, maxSurge: 25% } }
  selector: { matchLabels: { app: checkout } }
  template:
    metadata: { labels: { app: checkout, team: payments } }
    spec:
      terminationGracePeriodSeconds: 45
      topologySpreadConstraints:
        - { maxSkew: 1, topologyKey: topology.kubernetes.io/zone, whenUnsatisfiable: DoNotSchedule,
            labelSelector: { matchLabels: { app: checkout } } }
      containers:
        - name: checkout
          image: registry.example.com/checkout@sha256:3f1c…   # a digest, not a tag
          ports: [{ containerPort: 8080 }]
          env:
            - { name: GOMEMLIMIT, value: "460MiB" }
          resources:
            requests: { cpu: "500m", memory: "512Mi" }
            limits:   { memory: "512Mi" }                   # no CPU limit: avoid throttling
          startupProbe:   { httpGet: { path: /healthz, port: 8080 }, periodSeconds: 2, failureThreshold: 30 }
          readinessProbe: { httpGet: { path: /readyz,  port: 8080 }, periodSeconds: 2, failureThreshold: 1 }
          livenessProbe:  { httpGet: { path: /healthz, port: 8080 }, periodSeconds: 10, failureThreshold: 6, timeoutSeconds: 2 }
          lifecycle:
            preStop: { sleep: { seconds: 5 } }

A worked example#

Three incidents in one quarter at a company running on Kubernetes:

IncidentCauseSetting that would have prevented it
All checkout pods restarted during a DB slowdownLiveness probe called the database; DB slow → probes failed → restarts → cold caches → worseLiveness checks the process only
Payment API down for 4 minutes during a node upgradeNo PDB; both replicas were on the drained nodePDB + topology spread + more than 2 replicas
p99 latency spikes every few secondsCPU limit 1 core; Go service bursting to 3 cores during GCRemove CPU limit or raise it; watch throttling

The program is a small linter that checks a Deployment (as JSON, so it needs no YAML library) against this lesson’s rules.

Code#

Go
// k8slint.go — check a Deployment against SRE rules: probes, resources, rollout, spread, digest.
package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

type probe struct {
	HTTPGet *struct {
		Path string `json:"path"`
	} `json:"httpGet"`
	FailureThreshold int `json:"failureThreshold"`
	PeriodSeconds    int `json:"periodSeconds"`
}

type container struct {
	Name      string `json:"name"`
	Image     string `json:"image"`
	Resources struct {
		Requests map[string]string `json:"requests"`
		Limits   map[string]string `json:"limits"`
	} `json:"resources"`
	Liveness  *probe `json:"livenessProbe"`
	Readiness *probe `json:"readinessProbe"`
	Startup   *probe `json:"startupProbe"`
	Env       []struct {
		Name string `json:"name"`
	} `json:"env"`
}

type deployment struct {
	Metadata struct{ Name string } `json:"metadata"`
	Spec     struct {
		Replicas int `json:"replicas"`
		Strategy struct {
			RollingUpdate struct {
				MaxUnavailable any `json:"maxUnavailable"`
			} `json:"rollingUpdate"`
		} `json:"strategy"`
		Template struct {
			Spec struct {
				Containers []container `json:"containers"`
				Spread     []any       `json:"topologySpreadConstraints"`
			} `json:"spec"`
		} `json:"template"`
	} `json:"spec"`
}

const manifest = `{
  "metadata": {"name": "payments-api"},
  "spec": {
    "replicas": 2,
    "strategy": {"rollingUpdate": {"maxUnavailable": "25%"}},
    "template": {"spec": {
      "containers": [{
        "name": "api",
        "image": "registry.example.com/payments-api:latest",
        "resources": {"requests": {"cpu": "250m"}, "limits": {"cpu": "1", "memory": "256Mi"}},
        "livenessProbe": {"httpGet": {"path": "/health/db"}, "failureThreshold": 1, "periodSeconds": 5}
      }]
    }}
  }
}`

func main() {
	var d deployment
	if err := json.Unmarshal([]byte(manifest), &d); err != nil {
		panic(err)
	}
	var findings []string
	add := func(sev, msg string) { findings = append(findings, fmt.Sprintf("[%s] %s", sev, msg)) }

	if d.Spec.Replicas < 3 {
		add("high", fmt.Sprintf("replicas=%d: fewer than 3 cannot survive a zone loss plus a deploy", d.Spec.Replicas))
	}
	if mu := fmt.Sprint(d.Spec.Strategy.RollingUpdate.MaxUnavailable); mu != "0" && mu != "<nil>" {
		add("medium", "maxUnavailable="+mu+": capacity drops during every deploy; prefer 0 with maxSurge")
	}
	if len(d.Spec.Template.Spec.Spread) == 0 {
		add("high", "no topologySpreadConstraints: replicas may share a node or zone")
	}
	for _, c := range d.Spec.Template.Spec.Containers {
		p := "container " + c.Name + ": "
		if !strings.Contains(c.Image, "@sha256:") {
			add("medium", p+"image is not pinned by digest ("+c.Image+")")
		}
		if c.Resources.Requests["memory"] == "" {
			add("high", p+"no memory request: the scheduler will overcommit the node")
		}
		if c.Resources.Limits["memory"] == "" {
			add("medium", p+"no memory limit")
		}
		if _, ok := c.Resources.Limits["cpu"]; ok {
			add("info", p+"CPU limit set: watch container_cpu_cfs_throttled_periods_total for latency spikes")
		}
		if c.Readiness == nil {
			add("high", p+"no readinessProbe: traffic arrives before the app is ready and during shutdown")
		}
		if c.Startup == nil && c.Liveness != nil {
			add("medium", p+"liveness without startupProbe: slow starts become restart loops")
		}
		if c.Liveness != nil {
			if c.Liveness.HTTPGet != nil && strings.Contains(c.Liveness.HTTPGet.Path, "db") {
				add("high", p+"livenessProbe checks a dependency ("+c.Liveness.HTTPGet.Path+"): a DB blip restarts every pod")
			}
			if c.Liveness.FailureThreshold*c.Liveness.PeriodSeconds < 30 {
				add("medium", p+"livenessProbe kills after <30 s of failures: too aggressive under load")
			}
		}
		hasMemLimit := false
		for _, e := range c.Env {
			if e.Name == "GOMEMLIMIT" {
				hasMemLimit = true
			}
		}
		if !hasMemLimit {
			add("info", p+"Go service without GOMEMLIMIT: GC is unaware of the memory limit")
		}
	}
	fmt.Printf("%s: %d findings (also check: PodDisruptionBudget, HPA, terminationGracePeriodSeconds)\n", d.Metadata.Name, len(findings))
	for _, f := range findings {
		fmt.Println("  " + f)
	}
}

In real clusters, policy engines (Kyverno, OPA Gatekeeper) and linters (kube-linter, Polaris, kube-score) enforce rules like these at admission time or in CI.

Remember this#

  • Probes: startup for slow starts, readiness for “can I serve now”, liveness only for a wedged process — never for dependencies.
  • Requests from measured usage; memory limit with margin; CPU limits cause throttling; set GOMEMLIMIT for Go.
  • Rollouts: maxUnavailable: 0, maxSurge, minReadySeconds, history for rollback.
  • PodDisruptionBudgets and topology spread make drains and zone losses survivable.
  • HPA min for zone loss, max for dependencies; the cluster itself is a dependency.

Try it#

  1. Run k8slint.go. Fix the manifest until only info findings remain.
  2. In a kind cluster, deploy two replicas without a PDB, drain the node they are on, and watch the Service’s endpoints. Then add a PDB and repeat.
  3. Graph CPU throttling for a service you own. Is it ever throttled while the node has idle CPU?

Check yourself#

  1. Why should a liveness probe never check the database?
  2. What happens when a container exceeds its memory limit? Its CPU limit?
  3. What does a PodDisruptionBudget protect against, and what goes wrong if it is too strict?
  4. Why set maxUnavailable: 0?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in