Lesson 21 of 24Kubernetes
Config, Secrets, Probes and Autoscaling
Run a service well on Kubernetes: config and secrets, the three probes, requests and limits, graceful shutdown, autoscaling, disruption budgets and RBAC.
At 14:02 the primary database fails over, a routine 40-second blip. At 14:03 every API pod in the cluster restarts at once, and the site is down for several minutes instead of 40 seconds. The cause was one line: a liveness probe that checked the database. Running a service on Kubernetes is mostly about settings like that one: how config reaches the pod, how Kubernetes decides a pod is healthy, how much CPU and memory it may use, how it shuts down, and how it scales. Each has a default that looks fine in a demo and fails under real traffic. This lesson goes through them in the order you meet them on the job.
ConfigMaps: env vars or files
A ConfigMap holds non-secret settings. You can hand it to a container in two ways, and they behave differently when the ConfigMap changes.
apiVersion: v1
kind: ConfigMap
metadata:
name: api-config
data:
LOG_LEVEL: info
FEATURE_FLAGS: "search_v2=false"
limits.yaml: |
rate_per_minute: 600
---
# in the Deployment's container spec
envFrom:
- configMapRef: { name: api-config } # read once, at container start
volumeMounts:
- { name: config, mountPath: /etc/api } # files: refreshed by the kubelet
# in the pod spec
volumes:
- name: config
configMap: { name: api-config }- Env vars are read once, when the container starts. Edit the ConfigMap and running pods keep the old values until they restart.
- Mounted files are updated by the kubelet after a delay (typically within a minute or two). Your app still has to notice and reload. Files mounted with
subPathnever update.
The common trap: someone edits a ConfigMap, nothing changes, and half the pods get the new value days later when they happen to restart. Make config changes trigger a rollout instead. Helm charts usually add a checksum/config annotation to the pod template computed from the ConfigMap, and Kustomize's configMapGenerator appends a content hash to the ConfigMap's name. Either way, new config means a new pod template, so the Deployment rolls out (safely, behind readiness) and can be rolled back. For a one-off, kubectl rollout restart deploy/api does the same.
Secrets are not encrypted by default
A Secret looks like a ConfigMap with values in base64. Base64 is an encoding, not encryption: anyone who can read the object can decode it in one command. Three things actually protect Secrets:
- Encryption at rest of the cluster's datastore (etcd), ideally with a cloud KMS key. Self-managed clusters must configure it; managed services increasingly turn it on by default, but confirm for your provider.
- RBAC.
getorliston Secrets in a namespace means reading every Secret there. So does permission to create pods in that namespace, since a pod can mount any Secret in it. Grant both narrowly. - Keep the source of truth outside the cluster. The External Secrets Operator syncs values from AWS Secrets Manager, Vault, GCP Secret Manager and others into ordinary Secrets on a refresh interval. The Secrets Store CSI Driver mounts them as files straight from the external store. Rotation then happens in one place.
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: api-secrets
spec:
refreshInterval: 1h
secretStoreRef: { kind: ClusterSecretStore, name: aws-secrets-manager }
target: { name: api-secrets } # the Kubernetes Secret it creates
data:
- secretKey: DATABASE_URL
remoteRef: { key: prod/api, property: database_url }Never commit plain Secret manifests to git. If secrets must live in git (common with GitOps), encrypt them with Sealed Secrets or SOPS.
Three probes, three different consequences
Each probe answers a different question, and the consequence of failing is what matters:
| Probe | Question | On failure |
|---|---|---|
| startup | Has the app finished booting? | Keeps liveness and readiness switched off until it passes; if it never passes within its budget, the container is restarted |
| readiness | Should this pod get traffic right now? | Pod is marked not ready and taken out of Service endpoints. No restart. |
| liveness | Is the process stuck beyond repair? | The kubelet kills and restarts the container |
Defaults for every probe: periodSeconds: 10, timeoutSeconds: 1, failureThreshold: 3. So a liveness probe restarts a container after about 30 seconds of failures, and a 1-second timeout is tight for an endpoint under load.
The rule that prevents the opening outage: liveness checks only the process itself, never a dependency. If the database is down, restarting your API does not fix the database. It just turns a dependency blip into a restart storm, with every replica booting at once and then stampeding the recovering database with new connections. Run the model: one character per 10 seconds, # means the pod can serve, the database is down for 40 seconds and the app takes 50 seconds to boot.
Press Run (⌘ Enter) to see what happens.The bad probe turns a 40-second blip into a 70-second outage, and every replica does it at the same moment. Try BOOT_S = 120 to see how much worse it gets for a slow-booting service.
Readiness is where dependency awareness can live, carefully. A pod that cannot serve anything useful may report not ready so traffic shifts to pods that can. But if every pod depends on the same database, all of them go unready together, the Service has no endpoints, and callers get a gateway 503 instead of your app's clear error. Many teams keep readiness about the pod itself (booted, warmed up, not shutting down) and handle dependency failures in the app with timeouts and fast errors.
startupProbe: # up to 24 x 5s = 2 minutes to boot
httpGet: { path: /livez, port: 8000 }
periodSeconds: 5
failureThreshold: 24
readinessProbe: # quick to pull a pod out of rotation
httpGet: { path: /readyz, port: 8000 }
periodSeconds: 5
failureThreshold: 2
livenessProbe: # slow to kill: about 30s of real hangs
httpGet: { path: /livez, port: 8000 }
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3The startup probe replaces the old habit of a huge initialDelaySeconds on liveness: it gives a slow boot plenty of time without making liveness slow to react later.
Requests, limits and QoS
Requests are what the scheduler reserves: a pod is placed only on a node with that much unrequested capacity. Limits are enforced at run time, and the two resources behave very differently:
- Exceed the memory limit and the kernel kills the process:
OOMKilled, exit 137. - Hit the CPU limit and the container is throttled: the kernel pauses it for the rest of each scheduling period. Nothing crashes; latency spikes, often in bursts that are hard to trace.
That asymmetry is why many teams set a memory limit (often equal to the request) but no CPU limit: a CPU request guarantees each pod its share under contention, and idle CPU on the node can absorb bursts. Others keep CPU limits for predictable multi-tenant clusters. Either way, size from data: look at real usage in kubectl top or your metrics over a week, set requests near typical usage and memory limits with headroom above the peak.
Requests and limits also set the pod's QoS class, which decides who is evicted first when a node runs short of memory:
| QoS class | When | Under node memory pressure |
|---|---|---|
| Guaranteed | Every container has CPU and memory requests equal to limits | Evicted last |
| Burstable | At least one request or limit, but not Guaranteed | Evicted when using more than requested |
| BestEffort | No requests or limits at all | Evicted first |
A pod with no requests is BestEffort: the scheduler thinks it costs nothing, packs it anywhere, and it is the first to die. Always set requests.
Match each symptom to its most likely cause.
Graceful shutdown in Kubernetes
Docker in Production covered SIGTERM, PID 1 and exec form. Kubernetes adds one race. When a pod is deleted, two things start at the same time: the kubelet begins shutting the container down, and the control plane removes the pod from EndpointSlices, which every node's kube-proxy then applies on its own schedule. If the app stops accepting connections before the last node has updated its rules, those nodes still send it new connections, which fail.
A rollout or scale-down deletes the pod. The 30 second terminationGracePeriodSeconds clock starts now.
spec:
terminationGracePeriodSeconds: 45 # preStop + drain must fit inside this
containers:
- name: api
lifecycle:
preStop:
sleep: { seconds: 5 } # native sleep action; on older clusters use exec: sleep 5The grace period covers the preStop hook and the drain together. Long-running work (a 10-minute report request, a WebSocket) needs a longer grace period, or a design that can hand work back to a queue.
Autoscaling
Horizontal Pod Autoscaler (HPA) changes replicas to keep a metric near a target. The core formula is desired = ceil(current * metric / target), skipped when the ratio is within a 10% tolerance of 1.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: api }
minReplicas: 3
maxReplicas: 30
metrics:
- type: Resource
resource:
name: cpu
target: { type: Utilization, averageUtilization: 60 } # percent of the CPU request
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # the default: avoid flapping after a spikeUtilization is measured against the request, so an HPA on CPU without CPU requests does nothing. Remove replicas from the Deployment manifest once an HPA owns it, or every kubectl apply resets the count.
What does this print?
import math
def desired(current, metric, target, tolerance=0.1):
ratio = metric / target
if abs(ratio - 1) <= tolerance:
return current
return math.ceil(current * ratio)
print(desired(4, 90, 60), desired(4, 64, 60), desired(10, 30, 60))The other autoscalers, and what each one moves:
- VPA (Vertical Pod Autoscaler) recommends or sets requests from observed usage. Its recommendation mode is a cheap way to right-size. Do not let VPA and HPA act on the same CPU metric.
- KEDA scales on event sources (queue length in SQS or RabbitMQ, Kafka consumer lag, a cron window) and can scale workers to zero. It drives an HPA under the hood.
- Cluster Autoscaler adds nodes when pods are
Pendingfor lack of room and removes underused ones, within predefined node groups. Karpenter (common on EKS) picks instance types per batch of pending pods and consolidates aggressively, usually faster and cheaper.
Staying up during disruptions
Nodes are drained for upgrades and consolidation all the time. Three settings keep that from becoming an outage:
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: api
spec:
maxUnavailable: 1
selector:
matchLabels: { app: api }
---
# in the Deployment's pod spec
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels: { app: api }A PodDisruptionBudget limits voluntary disruptions (drains, autoscaler scale-down): the eviction API refuses to take more than one api pod down at a time. It does nothing for a node that crashes. A PDB that allows zero disruptions (for example minAvailable equal to the replica count) blocks node drains forever, a classic reason a cluster upgrade hangs. Topology spread constraints keep replicas spread across zones so a zone outage takes a third of your capacity, not all of it. Pod anti-affinity is the older, blunter tool for the same goal.
RBAC and workload identity
Every pod runs as a ServiceAccount (the namespace's default one if you do not choose). RBAC grants it permissions with a Role (verbs on resources in a namespace) and a RoleBinding; ClusterRole and ClusterRoleBinding are the cluster-wide versions. Most app pods never call the Kubernetes API, so give them their own ServiceAccount with no bindings and set automountServiceAccountToken: false. Check what an identity can do with kubectl auth can-i list secrets -n shop --as=system:serviceaccount:shop:api.
For cloud access, do not put cloud keys in Secrets. Use workload identity: the pod's ServiceAccount is mapped to a cloud role and receives short-lived credentials automatically. On EKS that is EKS Pod Identity (an association between the ServiceAccount and an IAM role, set through the EKS API) or the older IRSA (an annotation plus an OIDC trust). GKE and AKS have their own Workload Identity equivalents. The AWS SDK picks the credentials up with no code change.
Order what happens when a pod is deleted during a rollout, with a preStop hook configured.
- Tap the steps below in the right order.
- readiness probe
- Decides whether a pod receives traffic; failure removes it from Service endpoints without a restart.
- liveness probe
- Decides whether a container is stuck; failure makes the kubelet restart it.
- startup probe
- Holds off the other probes until a slow-booting container has started.
- QoS class
- Guaranteed, Burstable or BestEffort, derived from requests and limits; decides eviction order.
- CPU throttling
- The kernel pausing a container that reached its CPU limit, seen as latency rather than crashes.
- HorizontalPodAutoscaler
- Changes a workload's replica count to keep a metric, such as CPU utilization, near a target.
- PodDisruptionBudget
- Limits how many pods of a workload voluntary disruptions like node drains may take down at once.