dcorneschi@devops:~/kubernetes$

In-Place Pod Resize with the Vertical Pod Autoscaler (VPA)

Kubernetes 2830 words ~15 min read

In-Place Pod Resize with the Vertical Pod Autoscaler (VPA) In-Place Pod Resize with VPA: Resize without recreating, and what can still go wrong. resizePolicy, Deferred, InPlaceOrRecreate, QoS, JVM and Go. Icons: resize, resizePolicy, Deferred, VPA, QoS class, JVM heap, eviction. In-Place Pod Resize with VPA Resize without recreating, and what can still go wrong resizePolicy · Deferred · InPlaceOrRecreate · QoS · JVM and Go resize resizePolicy Deferred VPA QoS class JVM heap eviction

For most of Kubernetes’ history, changing a pod’s CPU or memory meant recreating the pod: connections drop, caches start cold, and long-running work restarts. The Vertical Pod Autoscaler inherited that: to apply a recommendation it evicted the pod.

Two features change that:

  • In-place pod resize, GA since Kubernetes 1.35: a container’s CPU and memory requests and limits can change on a running pod through the pod’s resize subresource. The kubelet updates the cgroup; the pod and usually the container keep running.
  • VPA InPlaceOrRecreate: the VPA updater patches the resize subresource instead of evicting, and evicts only when the resize is rejected.

Both reduce restarts; neither removes them. And a container whose cgroup grew is not the same as an application that uses the extra memory.

Everything below was run on a single-node kind v0.33.0 cluster (Kubernetes 1.37.0, cgroup v2, 2 CPUs, about 3.8 GiB allocatable) with kubectl 1.37.2, VPA 1.8.1 and metrics-server v0.9.1.

How a Resize Works

The resize path. A client (kubectl patch --subresource resize, or the VPA updater) changes spec.containers[].resources. The API server rejects the change if it touches anything but CPU and memory, removes a limit, changes the pod's QoS class, or asks for more than the node's allocatable (Forbidden). Otherwise the pod's generation goes up and the kubelet decides: if the node has no free capacity the resize is Deferred (PodResizePending) and applied by itself once capacity frees up; if it fits, the kubelet updates the cgroup (NotRequired) or restarts the container (RestartContainer, after the termination grace period). status.containerStatuses[].resources shows what the container really has; ResizeStarted and ResizeCompleted events mark the change; the pod UID stays the same.

The feature gate InPlacePodVerticalScaling is on and can’t be turned off in 1.37 (kubernetes_feature_enabled{name="InPlacePodVerticalScaling",stage=""} 1 in the API server’s /metrics).

Desired and Actual

Field Meaning
spec.containers[*].resources What you asked for. Mutable for CPU and memory, only through resize
status.containerStatuses[*].resources What the container runs with now, as reported by the kubelet
status.containerStatuses[*].allocatedResources What the kubelet has reserved on the node for it
metadata.generation / status.observedGeneration Each resize bumps the generation; the kubelet reports the one it has seen

When spec and status differ, a resize is still pending or in progress.

Triggering a Resize

The normal pod update path still refuses resource changes:

kubectl patch pod resize-demo --patch '{"spec":{"containers":[{"name":"app","resources":{"requests":{"cpu":"600m"},"limits":{"cpu":"600m"}}}]}}'
The Pod "resize-demo" is invalid: spec: Forbidden: pod updates may not change fields other than `spec.containers[*].image`,`spec.initContainers[*].image`,`spec.activeDeadlineSeconds`,`spec.tolerations` (only additions to existing tolerations),`spec.terminationGracePeriodSeconds` ...

The resize subresource accepts them:

kubectl patch pod resize-demo --subresource resize --patch \
  '{"spec":{"containers":[{"name":"app","resources":{"requests":{"cpu":"800m"},"limits":{"cpu":"800m"}}}]}}'

kubectl edit pod resize-demo --subresource resize
kubectl apply -f resize.yaml --subresource resize --server-side

Anything else in a resize patch is ignored: a patch that also set image: busybox:1.37 returned patched, and the image stayed busybox:1.38.

Server-side apply takes ownership field by field. After a kubectl edit, the apply failed until --force-conflicts:

error: Apply failed with 2 conflicts: conflicts with "kubectl-edit" with subresource "resize" using v1:
- .spec.containers[name="app"].resources.limits.cpu
- .spec.containers[name="app"].resources.requests.cpu

Checking the Result

For the CPU resize above (500m to 800m, CPU resizePolicy: NotRequired):

  Before After
Pod UID ba50c6bd-e26e-... ba50c6bd-e26e-... (same pod)
generation / observedGeneration 1 / 1 2 / 2
restartCount 0 0
cpu.max in the container 50000 100000 80000 100000
kubectl get pod resize-demo -o jsonpath='{.status.containerStatuses[0].resources}{"\n"}'
kubectl get pod resize-demo -o jsonpath='{.metadata.generation} {.status.observedGeneration}{"\n"}'
kubectl exec resize-demo -- cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/memory.max
kubectl get events --field-selector involvedObject.name=resize-demo

The kubelet records the change as events:

ResizeStarted     Pod resize started: {"containers":[{"name":"app","resources":{"limits":{"cpu":"800m","memory":"128Mi"},"requests":{"cpu":"800m","memory":"128Mi"}}}],"generation":2}
ResizeCompleted   Pod resize completed: {"containers":[{"name":"app","resources":{"limits":{"cpu":"800m","memory":"128Mi"},"requests":{"cpu":"800m","memory":"128Mi"}}}],"generation":2}

resizePolicy: Restart or Not

Each container says per resource whether a change needs a restart:

spec:
  containers:
  - name: app
    resizePolicy:
    - resourceName: cpu
      restartPolicy: NotRequired        # default: update the cgroup live
    - resourceName: memory
      restartPolicy: RestartContainer   # restart the container to apply
    resources:
      requests: {cpu: 500m, memory: 128Mi}
      limits:   {cpu: 500m, memory: 128Mi}
  • NotRequired: the cgroup changes, the process keeps running, restartCount stays the same.
  • RestartContainer: the container restarts with the new values; the pod stays. Memory 128Mi to 256Mi on the pod above: Killing Container app resize requires restart, restartCount 0 to 1, memory.max 268435456.
  • The restart honours the grace period. The test container (sh as PID 1 ignores SIGTERM) needed the full 30 s terminationGracePeriodSeconds; PodResizeInProgress stayed True until the new container started.
  • Pods with restartPolicy: Never can’t use RestartContainer:
The Pod "never" is invalid: spec.containers[0].resizePolicy: Invalid value: "RestartContainer": must be 'NotRequired' when pod `restartPolicy` is 'Never'

What the API Server Rejects

Change Error
Anything but CPU or memory only cpu and memory resources are mutable
Remove a limit resource limits cannot be removed
Guaranteed: requests different from limits Invalid value: "Guaranteed": Pod QOS Class may not change as a result of resizing
Burstable: requests equal to limits for CPU and memory Invalid value: "Burstable": Pod QOS Class may not change as a result of resizing
BestEffort: add any request Invalid value: "BestEffort": Pod QOS Class may not change as a result of resizing
More than the node’s allocatable Forbidden: node didn't have enough allocatable resources: cpu, requested: 4000, allocatable: 2000

The QoS class is fixed for the life of the pod, so the resources a pod starts with decide what VPA can do with it later (see BestEffort Pods Get Evicted). Burstable pods can change freely inside the class: requests 150m/limits 300m was accepted.

In 1.37 a resize larger than the whole node is rejected by the API server. It no longer becomes a PodResizePending condition with reason Infeasible.

Deferred: Waiting for Capacity

A resize that fits the node but not its free capacity is accepted and parked:

kubectl patch pod resize-demo --subresource resize --patch \
  '{"spec":{"containers":[{"name":"app","resources":{"requests":{"cpu":"1500m"},"limits":{"cpu":"1500m"}}}]}}'
kubectl get pod resize-demo -o jsonpath='{.status.conditions[?(@.type=="PodResizePending")]}'
{"type":"PodResizePending","status":"True","reason":"Deferred","message":"Node didn't have enough resource: cpu, requested: 1500, used: 950, capacity: 2000"}

The spec said 1500m, the status kept 800m, and the event was ResizeDeferred Pod resize OutOfcpu. After scaling CoreDNS to 0 freed 200m, the kubelet applied a deferred 1200m resize 6 seconds later, without a new patch and without a restart.

A Bigger Pod Can Be Preempted

Growing in place uses node capacity that other pods may need. When CoreDNS was scaled back to 2, its pods (system-cluster-critical priority) didn’t fit next to the 1200m pod, and the scheduler made room:

resize-demo   Preempted   Preempted by pod 47013aa1-1d69-434b-9039-2e252fe93b59 on node resize-control-plane
resize-demo   Killing     Stopping container app

The resized pod was deleted. Leave headroom on nodes that run VPA in-place, and give important workloads a PriorityClass.

Shrinking Memory

CPU is compressible: lowering it only throttles. Memory isn’t. A pod holding 150 MiB (memory.current 162029568) was resized from 256Mi to 100Mi with memory NotRequired:

ResizeError   Pod resize error: ... "error":"cannot decrease memory limits: [attempting to set pod memory limit (104857600) below current usage (161611776), attempting to set container \"app\" memory limit (104857600) below current usage (161611776)]"

The kubelet refused to lower memory.max and kept retrying. The spec showed 100Mi, the status 256Mi, the container kept running, and PodResizeInProgress stayed True with reason: Error. A resize to 200Mi (above usage) then applied at once without a restart.

With RestartContainer the kubelet restarts the container at the lower limit instead, and if the application needs more than that, it is OOMKilled in a loop. That is exactly what VPA did in the test below.

Other Containers and Pod-Level Resources

What Result in 1.37
Sidecar (init container with restartPolicy: Always) Resized in place, 0 restarts
Regular init container Accepted (InPlacePodVerticalScalingInitContainers is GA); initContainerStatuses reported the new value
Pod-level spec.resources (beta, on by default) Resized from 200m to 300m CPU: status.resources showed 300m and the pod cgroup’s cpu.max 30000 100000, 0 restarts
Exclusive CPUs or memory (static CPU or Memory Manager) Not supported: InPlacePodVerticalScalingExclusiveCPUs and ...ExclusiveMemory are alpha and off

Deployments Don’t Resize, Pods Do

resize exists only on pods. A change to a Deployment’s pod template creates a new ReplicaSet and new pods (new UIDs), as before.

Resizing a Deployment’s pod directly leaves the template alone:

  • The resized pod ran with 200m; the template still said 100m.
  • kubectl scale deploy web --replicas=2 added a pod with 100m.
  • Nothing reconciles the old pod back: the ReplicaSet doesn’t compare resources.

That is the gap VPA fills: it keeps resizing each pod toward its recommendation, and its admission controller sets the values on new pods.

VPA InPlaceOrRecreate

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: web-vpa
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  updatePolicy:
    updateMode: InPlaceOrRecreate
  resourcePolicy:
    containerPolicies:
    - containerName: "*"
      minAllowed: {cpu: 100m, memory: 128Mi}
      maxAllowed: {cpu: "1", memory: 1Gi}
      controlledResources: [cpu, memory]

In VPA 1.8.1 the mode needs no VPA feature gate (the updater ran with no arguments). Auto still works but warns:

Warning: spec.updatePolicy: "Auto" mode is deprecated and will be removed in a future API version. Use explicit update modes like: [InPlace InPlaceOrRecreate Initial Off Recreate]. See https://github.com/kubernetes/autoscaler/issues/8424 for more details.

Modes, installation and the recommender are covered in Kubernetes Vertical Pod Autoscaler (VPA).

How the Updater Applies It

VPA InPlaceOrRecreate flow. metrics-server reports usage; the recommender writes a recommendation into the VPA status; once a minute the updater compares each pod's requests with it. If they differ enough it patches the pod's resize subresource (event InPlaceResizedByVPA, annotation vpaInPlaceUpdated=true) and the kubelet applies it as for a manual resize. If the API server rejects the resize, for example because it would change the QoS class of a BestEffort pod, the updater logs In-place resize failed, falling back to eviction and evicts the pod; the admission controller then sets the recommendation on the replacement.

The updater log shows the decision for each pod:

updater.go:372] "In-place update deferred" pod="default/web-5fd777f86d-d4lm5"
updater.go:397] "In-place update approved" pod="default/web-5fd777f86d-bqxdb"
pods_inplace_restriction.go:262] "In-place patched pod /resize subresource using patches" ... "path":"/spec/containers/0/resources/requests/memory","value":"203699302"
  • VPA writes memory in bytes (203699302, not 194Mi), and scales limits in proportion to requests: on the Guaranteed test pods both changed together and the QoS stayed Guaranteed.
  • It resized one pod per updater run (once a minute) and logged In-place update deferred for the other.
  • The pod keeps its UID; the pod gets the annotation vpaInPlaceUpdated: "true".

The First Recommendation Can Be Too Small

The test Deployment held 150 MiB and burned CPU, starting at 100m/256Mi with memory resizePolicy: RestartContainer. Three minutes after the VPA was created, the updater resized one pod to 128Mi, the minAllowed floor, from the recommender’s early data:

ResizeStarted    Pod resize started: {"containers":[{"name":"app","resources":{"limits":{"cpu":"100m","memory":"128Mi"},...
Killing          Container app resize requires restart
ResizeError      ... cannot decrease memory limits: attempting to set pod memory limit ...
BackOff          Back-off restarting failed container app

The container restarted into 128Mi and was OOMKilled four times. One updater run later the recommendation had grown to 203699302 bytes and the pod was resized again, and after more OOM history to 323522422. Same pod UID throughout, 5 restarts.

Start new VPAs in Off mode until the recommendation has settled, and set minAllowed.memory at or above what the application needs to start.

BestEffort Pods Get Evicted

A Deployment with no requests (QoS BestEffort) under InPlaceOrRecreate:

updater.go:423] "In-place resize failed, falling back to eviction" error="Pod \"be-6d45d97c9d-7rg4v\" is invalid: spec: Invalid value: \"BestEffort\": Pod QOS Class may not change as a result of resizing"
EvictedByVPA   Pod was evicted by VPA Updater to apply resource recommendation.

The replacement started Burstable with requests cpu: 977m, memory: 250Mi and still no limits. Set requests (and limits, for Guaranteed) on every container so the pod starts in the class it will stay in.

Does the Application Use the New Limit?

A resize changes the cgroup. Many runtimes read the cgroup once at startup and size themselves from it. Tested with Guaranteed pods, memory doubled through resize:

Workload Memory resizePolicy memory.max What the runtime reported Restarts
JVM (Temurin 21.0.13, -XX:MaxRAMPercentage=50) NotRequired 384Mi to 768Mi maxMemory 185MiB before and after 0
JVM, same flags RestartContainer 384Mi to 768Mi maxMemory 185MiB to 371MiB 1
Go 1.27.4, no GOMEMLIMIT NotRequired 128Mi to 256Mi debug.SetMemoryLimit(-1) stayed 9223372036854775807 (no limit) 0
Go, GOMEMLIMIT=100MiB NotRequired 128Mi to 256Mi stayed 104857600 0
Go with automemlimit v1.0.0, ratio 0.9, refresh every 3 s NotRequired 128Mi to 256Mi 120795955 to 241591910 (90 % of the new limit) 0

And CPU, 100m to 1050m with NotRequired:

Workload cpu.max What the runtime reported Restarts
JVM 10000 100000 to 105000 100000 availableProcessors() 1 to 2 0
Go   GOMAXPROCS 2 before and after (the node has 2 CPUs) 0

Which runtimes follow a live resize. The cgroup changed in every test. The JVM's heap ceiling (maxMemory) stayed at its startup value with NotRequired and only grew after a RestartContainer restart, while availableProcessors followed a CPU resize live. Go has no memory limit unless GOMEMLIMIT is set, a fixed GOMEMLIMIT stays fixed, and only the automemlimit library with a refresh interval followed the new cgroup limit.

  • JVM heap: use RestartContainer for memory. With NotRequired the cgroup doubled but the heap ceiling didn’t move, so the extra memory is unusable as heap. The CPU count is re-read, so CPU can stay NotRequired.
  • Go: use automemlimit with a refresh interval if memory should follow resizes live:
import "github.com/KimMachineGun/automemlimit/memlimit"

memlimit.Set(
    memlimit.WithProvider(memlimit.FromCgroup),
    memlimit.WithRatio(0.9),
    memlimit.WithRefreshInterval(context.Background(), 3*time.Second),
)
  • automemlimit reads AUTOMEMLIMIT from the environment as its ratio, and it wins over WithRatio. A first test that used AUTOMEMLIMIT=1 as an on/off switch got a limit of 100 % of the cgroup (268435456), not 90 %.
  • Check the runtime, not only the pod. A resize can be ResizeCompleted with the right status.containerStatuses[*].resources while the application still uses its startup value.

Prerequisites

  • Kubernetes 1.35 or later (GA). On 1.33 and 1.34 the feature is beta (InPlacePodVerticalScaling).
  • cgroup v2 on the nodes: stat -fc %T /sys/fs/cgroup/ returned cgroup2fs.
  • For VPA: metrics-server and VPA 1.8.x. Installation (including the OpenSSL 3 requirement of vpa-up.sh on macOS) is in Kubernetes Vertical Pod Autoscaler (VPA).
  • Requests and limits on every container, and a resizePolicy that fits the runtime.

Operational Notes

  • Start in Off, read the recommendations, then switch to InPlaceOrRecreate. The first in-place resizes in the test were too small.
  • Set minAllowed and maxAllowed. minAllowed.memory below the application’s startup need causes OOM loops with RestartContainer.
  • Memory RestartContainer for runtimes that size the heap at start, like the JVM; NotRequired only when the runtime re-reads the limit.
  • Leave node headroom. Deferred resizes wait for capacity, and a pod that grew can be preempted by higher-priority pods.
  • Eviction stays possible. InPlaceOrRecreate falls back to eviction; keep PodDisruptionBudgets and more than one replica.
  • Don’t let VPA and HPA act on the same metric (VPA on CPU requests while HPA scales on CPU utilization): each change moves the other’s input.
  • Resized pods drift from the template. New replicas start from the template (or VPA’s admission value), not from a manually resized pod.

Quick Reference

Goal Command or field
Resize a pod kubectl patch pod <p> --subresource resize --patch '{"spec":{"containers":[...]}}'
Desired values spec.containers[*].resources
Applied values status.containerStatuses[*].resources
Restart or not spec.containers[*].resizePolicy[].restartPolicy: NotRequired / RestartContainer
Waiting for capacity condition PodResizePending, reason Deferred
Being applied or failing condition PodResizeInProgress (reason Error with a message)
What happened events ResizeStarted, ResizeCompleted, ResizeDeferred, ResizeError
Was it in place? metadata.uid unchanged; restartCount unchanged for NotRequired
What the container sees kubectl exec <p> -- cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/cpu.max
VPA mode spec.updatePolicy.updateMode: InPlaceOrRecreate
VPA resized it event InPlaceResizedByVPA, annotation vpaInPlaceUpdated: "true"
VPA fell back updater log In-place resize failed, falling back to eviction, event EvictedByVPA

See Also