Skip to Content

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 , founding engineer running Kubernetes in production. Updated .

node-14 CPU allocatableapi 1 CPUweb 0.5 CPUworker 2 CPU0.5 freerequestsneeds 1Pending:does not fitAutoscalertarget 60% CPU60%podpodpodpodpod2 → 5 replicas
The chapter in one pictureRequests decide where pods fit. The autoscaler decides how many you need.

By the end you can

0 of 5

Requests and limits

container resources
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

Each pod really uses about 150m of CPU. The grey part of each block is reserved but idle.

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:

ClassWhenEvicted
GuaranteedEvery container has CPU and memory requests equal to limitsLast
BurstableAt least one request or limit set, but not GuaranteedAfter BestEffort, starting with pods furthest above their requests
BestEffortNo requests or limits at allFirst

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?

node-1 · 8 GiB for pods

    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 OOMKilled and 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

    1. metrics-serverreads kubelets
    2. HPA controllerevery 15s
    3. Deploymentreplicas
    4. Schedulerplaces pods
    5. Node autoscaleradds nodes

    Step 0 of 5

    Press Play, or step through with Next.

    Interactive

    How the autoscaler picks a replica count

    hpa.yaml
    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:

    1. Measure real usage over a couple of weeks: kubectl top pods for a glance, Prometheus for p95 over time (chapter 14).
    2. Set CPU requests near typical usage and memory requests near peak usage plus a margin.
    3. Let the HPA add replicas for peaks, instead of sizing every pod for the worst minute.
    4. Run stateless, interruption-tolerant work on spot capacity, and let a node autoscaler consolidate half-empty nodes.

    Hands-on: autoscale under load

    Live lab · no install

    Autoscale under load

    Install metrics, set requests, then flood the app and watch replicas appear.

    kind-learn
    1. Tasks0/7
    2. Try to read usage

      Usage comes from metrics-server, which kind does not install.

      kubectl top nodes
    3. Install 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 nodes
    4. See what the node has promised

      Requests, not usage, decide how full a node is.

      kubectl describe node learn-control-plane | tail -n 8
    5. Give web requests and limits
      kubectl set resources deployment web --requests=cpu=50m,memory=64Mi --limits=memory=128Mi
    6. Add the autoscaler

      hpa.yaml targets 60% of the CPU request, between 2 and 10 replicas.

      kubectl apply -f hpa.yaml
      kubectl get hpa
    7. Generate 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 hpa

      CPU per pod falls as replicas rise, until the average sits near the target.

    8. 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
    9. Lab complete. Keep experimenting, or press Reset to start again.
    ↑↓ history · Tab complete · Ctrl+C stop
    Cluster map live
    • 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:

    Terminal
    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:

    Terminal
    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         2m
    web 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
    Terminal
    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

    1. 1. What does the scheduler use to decide whether a pod fits on a node?
    2. 2. A container exceeds its CPU limit. What happens?
    3. 3. The node runs out of memory. Which pod is evicted first?
    4. 4. 3 replicas, average CPU 90% of request, target 60%. What does the HPA want?
    5. 5. Pods request 1 CPU each but use about 0.1. What is the cost effect?

    Further reading