Kubernetes Field Guide · Chapter 9 of 16
Requests, limits and autoscaling
Requests tell the scheduler how much room a pod needs. Limits cap what it may use. Together they decide where pods land, which pods die first when a node runs short, how autoscaling behaves, and how many nodes you pay for.
- 40 min
- Advanced
- Hands-on
- Free
By Joshua Sequeira, founding engineer running Kubernetes in production. Updated .
By the end you can
0 of 5
Live lab in this chapter
A real-feeling terminal and a live cluster map, right in your browser. Every command block below has a ▶ Run in lab button.
Requests and limits
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 256Mi- A quarter of a CPU core reserved on the node. 1000m is one core.
- Reserved memory. Mi is mebibytes; M is megabytes, slightly smaller. Use Mi and Gi.
- The container is killed above this. Setting it equal to the request makes memory predictable.
- Deliberate. See throttling below.
- Requests are a reservation. The scheduler only places a pod on a node with that much unrequested capacity. They are also what CPU shares are based on when the node is busy.
- Limits are a ceiling enforced by the kernel at runtime.
Play with the request size. Each pod really uses about 150m, whatever it requests:
Interactive
Requests decide how many nodes you pay for
QoS classes and eviction
When a node runs short of memory, the kubelet evicts pods to protect itself. The order depends on each pod's QoS class, which comes from its requests and limits:
| Class | When | Evicted |
|---|---|---|
| Guaranteed | Every container has CPU and memory requests equal to limits | Last |
| Burstable | At least one request or limit set, but not Guaranteed | After BestEffort, starting with pods furthest above their requests |
| BestEffort | No requests or limits at all | First |
Watch it happen. Five pods share a node with 8 GiB for pods; push memory use up until it runs short:
Interactive
The node runs out of memory. Who goes first?
This is a simplified model: the real kubelet also weighs pod priority, and evicts before memory is completely gone. A pod with no requests is also invisible to the scheduler, so it can land on a node that is already full. Every production container should have requests. A LimitRange in a namespace can set defaults for anyone who forgets.
OOMKilled and CPU throttling
- Memory over the limit: the kernel kills the container. You see
OOMKilledand exit code 137 (chapter 3). Fix the leak or raise the limit. - CPU over the limit: the container is throttled for the rest of each 100ms period. It does not die, it gets slow, and it can happen even when average usage looks low, because short bursts hit the limit.
Horizontal Pod Autoscaler
The HPA changes a Deployment's replica count to keep a metric near a target. For CPU, utilisation is measured against the request, which is one more reason requests must be right.
Step through it
The autoscaling loop under a traffic spike
- metrics-serverreads kubelets
- HPA controllerevery 15s
- Deploymentreplicas
- Schedulerplaces pods
- Node autoscaleradds nodes
Step 0 of 5
Press Play, or step through with Next.
Interactive
How the autoscaler picks a replica count
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
behavior:
scaleDown:
stabilizationWindowSeconds: 300- Aim for 60% of the CPU request across pods, leaving headroom for spikes while new pods start.
- Use the highest recommendation of the last 5 minutes before scaling down. Prevents flapping.
The HPA adds pods, not nodes. When pods go Pending for lack of room, a node autoscaler (Cluster Autoscaler, or Karpenter on AWS) adds nodes, and removes them when they empty. For queue-driven work, KEDA scales on queue length, even down to zero.
Right-sizing and cost
On a cloud, nodes are the bill, and nodes fill up by requests. Over-requesting is the most common Kubernetes waste:
- Measure real usage over a couple of weeks:
kubectl top podsfor a glance, Prometheus for p95 over time (chapter 14). - Set CPU requests near typical usage and memory requests near peak usage plus a margin.
- Let the HPA add replicas for peaks, instead of sizing every pod for the worst minute.
- Run stateless, interruption-tolerant work on spot capacity, and let a node autoscaler consolidate half-empty nodes.
Hands-on: autoscale under load
The lab is docked at the bottom of your screen.
Live lab · no install
Autoscale under load
Install metrics, set requests, then flood the app and watch replicas appear.
- Tasks0/7
Try to read usage
Usage comes from metrics-server, which kind does not install.
kubectl top nodesInstall metrics-server
On kind it needs one extra flag because kubelets use self-signed certificates.
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml kubectl patch -n kube-system deployment metrics-server --type=json -p '[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]' kubectl -n kube-system rollout status deploy/metrics-server kubectl top nodesSee what the node has promised
Requests, not usage, decide how full a node is.
kubectl describe node learn-control-plane | tail -n 8Give web requests and limits
kubectl set resources deployment web --requests=cpu=50m,memory=64Mi --limits=memory=128MiAdd the autoscaler
hpa.yaml targets 60% of the CPU request, between 2 and 10 replicas.
kubectl apply -f hpa.yaml kubectl get hpaGenerate load and watch it scale out
Keep running kubectl get hpa. New pods appear in the map as the average passes 60%.
kubectl run load --image=busybox:1.37 --restart=Never -- sh -c "while true; do wget -q -O- http://web > /dev/null; done" kubectl get hpaCPU per pod falls as replicas rise, until the average sits near the target.
Stop the load and watch it come back down
Scale-down waits for a stabilisation window (compressed here) so a short lull does not remove pods the next burst needs.
kubectl delete pod load kubectl get hpa- Lab complete. Keep experimenting, or press Reset to start again.
- ready
- starting / not ready
- failing
- terminating
Prefer your own machine? The same steps on a local cluster
The HPA needs metrics-server. kind's kubelets use self-signed certificates, so metrics-server needs one extra flag there:
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
kubectl patch -n kube-system deployment metrics-server --type=json -p '[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
kubectl -n kube-system rollout status deploy/metrics-server
kubectl top nodes
--kubelet-insecure-tls- Only for local clusters. Never in production.
top nodes- Works once metrics arrive, after about a minute.
Give web requests, then save the HPA above as hpa.yaml and apply it:
kubectl set resources deployment web --requests=cpu=50m,memory=64Mi --limits=memory=128Mi
kubectl apply -f hpa.yaml
kubectl run load --image=busybox:1.37 --restart=Never -- sh -c "while true; do wget -q -O- http://web > /dev/null; done"
kubectl get hpa web -w
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
web Deployment/web cpu: 4%/60% 2 10 4 30s
web Deployment/web cpu: 152%/60% 2 10 4 75s
web Deployment/web cpu: 98%/60% 2 10 8 90s
web Deployment/web cpu: 61%/60% 2 10 10 2mweb Service- From chapter 5. The load pod hits it in a tight loop.
TARGETS- Average CPU as a share of the request, against the 60% target.
Mini mission
Watch it scale back down
Stop the load and time how long it takes to return to the minimum. Which setting controls that, and why would you not want it at zero?
Reveal one safe solution
kubectl delete pod load
kubectl get hpa web -w
Replicas stay up for about five minutes, then drop to 2. That is stabilizationWindowSeconds: 300. At zero, a short lull would remove pods that the next burst needs, and new pods take time to start and become ready.
Check yourself
Quiz
0 of 5 answered