Introduction

The incident began as an HPA vs VPA conflict during a traffic spike. Checkout traffic doubled in four minutes, CPU rose, and the Horizontal Pod Autoscaler added replicas exactly as configured. At the same time, the Vertical Pod Autoscaler was running in Recreate mode and decided the pods were over-provisioned, so it lowered CPU requests and evicted pods to apply the new size. Each controller saw a different truth. HPA saw utilization climbing because the request denominator had shrunk. VPA saw lower per-pod usage after replicas spread the load. Within fifteen minutes the Deployment had far more pods than the traffic justified, nodes were packed with churned pods, and the on-call engineer disabled VPA to stop the loop.

HPA vs VPA is not a contest between two interchangeable autoscalers. HPA changes the number of pods. VPA changes the size of pods. That sentence sounds simple, but production failures happen when teams treat both controllers as generic scaling knobs and let them optimize the same resource from opposite directions. HPA is built for demand that can be parallelized. VPA is built for workloads whose requests no longer match reality. Used with clear ownership, they complement each other. Used carelessly on CPU, they can manufacture the outage they were meant to prevent.

This guide explains how HPA computes replicas, how VPA builds recommendations, where each controller breaks, and how to combine them without creating a feedback loop. It includes production YAML for autoscaling/v2 and autoscaling.k8s.io/v1, a side-by-side comparison, troubleshooting paths for unknown metrics and eviction churn, and a decision guide by workload type. Pod autoscaling is only one layer of the system; node capacity still matters, which is why teams often pair this topic with Karpenter vs Cluster Autoscaler when replicas need somewhere to run.


1. HPA vs VPA: The Core Difference Between Replicas and Pod Size

HPA vs VPA is a choice between changing how many pods run and changing how large each pod is. HPA adds or removes replicas when demand moves, while VPA recommends or applies new CPU and memory requests for individual pods. The right answer depends on whether load is parallel, vertical, or both.

Horizontal scaling assumes work can be split across more identical units. A stateless HTTP API fits that model: ten pods can handle roughly ten shares of traffic if the service has no local state, downstream dependencies can absorb the load, and the load balancer spreads requests evenly. HPA is effective because it changes capacity by adding whole pods, each with the same requests, limits, image, and configuration. The failure mode is also horizontal: too many replicas can overwhelm databases, exhaust node capacity, or turn a downstream bottleneck into a retry storm.

Vertical scaling assumes the pod itself is the wrong size. A JVM service may need more memory for heap and metaspace, a sidecar may reserve CPU it never uses, or a batch worker may need a larger memory request to avoid OOM kills. VPA addresses that shape by recommending requests based on observed usage. It does not create more parallelism. It makes each unit bigger or smaller, which can improve scheduling density and reduce throttling or OOM risk when the recommendation is stable and bounded.

The distinction matters because requests are not just sizing hints. CPU requests influence HPA utilization math, scheduling decisions, and CPU shares under contention. Memory requests influence scheduling and eviction pressure. When VPA changes requests, it changes the denominator HPA uses for CPU utilization and the bin-packing assumptions the scheduler used a minute earlier. That is why HPA vs VPA design starts with ownership: one controller should own replica count, another may advise on pod size, and both should not chase CPU at the same time.

A useful mental model is to separate demand from shape. Demand asks, how much total capacity does the service need right now? Shape asks, how should that capacity be divided into pods? HPA answers demand by changing replica count. VPA answers shape by changing requests per pod. If traffic doubles, shape alone cannot save a service that needs parallelism. If every pod is oversized, replicas alone waste node capacity. Mature platforms tune both, but they sequence the changes so the controllers do not rewrite each other's inputs during an incident.


2. HPA vs VPA: What the Horizontal Pod Autoscaler Actually Does

HPA vs VPA starts with HPA, the built-in Horizontal Pod Autoscaler that scales a workload's replica count from metrics. It reads CPU, memory, custom, or external signals, compares them with targets, and adjusts replicas within configured bounds. HPA is reactive, horizontal, and best when more identical pods can absorb more work.

HPA is part of Kubernetes itself. You create a HorizontalPodAutoscaler object in autoscaling/v2, point scaleTargetRef at a scalable resource such as a Deployment, StatefulSet, or ReplicaSet, and declare one or more metrics with targets. The HPA controller periodically reads metrics, computes a desired replica count, and updates the scale subresource of the target. It does not create pods directly; the workload controller does that after the desired replica count changes. That separation keeps HPA focused on count, while Deployments and ReplicaSets handle pod creation, rollout, and replacement.

Resource metrics are the most common starting point. CPU and memory utilization come from the resource metrics API, normally served by metrics-server. Utilization is not raw usage; for CPU it is usage relative to requested CPU. A pod using 250 millicores with a 500 millicore request is at 50 percent CPU utilization. If containers have no CPU request, HPA cannot compute a meaningful utilization value and reports unknown metrics. This is why request hygiene is not optional for HPA. The same requests that help the scheduler place pods also define the scale signal.

HPA can also scale on custom and external metrics when an adapter exposes them through the custom metrics or external metrics APIs. Prometheus Adapter is a common route for application metrics, while KEDA can generate and manage HPA behavior from event sources such as queues. Those integrations matter because CPU is often a lagging proxy for demand. Requests per second, queue depth, consumer lag, and active connections can describe pressure earlier than CPU. The control-plane pieces behind metrics and controllers are covered in Kubernetes architecture and workload orchestration, which helps when debugging why a metric never reaches HPA.

Standard HPA does not scale a normal Deployment to zero. minReplicas is the floor, and production services usually keep at least a small number of warm replicas for availability and latency. Event-driven systems that need scale-to-zero normally use a specialized scaler or accept that HPA is the wrong tool for that job. HPA also cannot fix a service whose bottleneck is a single database writer, a global lock, or a downstream quota. Adding replicas to a non-parallel bottleneck increases pressure without increasing useful throughput.


3. HPA vs VPA: How HPA Computes Desired Replicas

HPA vs VPA math matters because HPA computes desired replicas from the ratio between current and desired metric values, then rounds up. It checks metrics on a short sync loop, ignores small changes inside a tolerance band, and uses behavior policies to slow or speed scale-up and scale-down decisions.

The core formula is desiredReplicas = ceil(currentReplicas * currentMetricValue / desiredMetricValue). If a Deployment runs 10 replicas, average CPU utilization is 80 percent, and the target is 50 percent, the ratio is 1.6 and HPA proposes 16 replicas. If utilization falls to 25 percent with the same target, the ratio is 0.5 and HPA proposes 5 replicas, subject to minReplicas, maxReplicas, tolerance, missing-metric handling, and behavior rules. The formula is simple; the operational work is choosing a metric and target that represent real saturation rather than noise.

The controller runs on a sync period, commonly 15 seconds by default, but that does not mean replicas should change every 15 seconds. HPA applies a tolerance band, commonly 10 percent, so small metric movement around the target does not trigger constant scaling. It also handles missing metrics and not-ready pods conservatively to avoid scaling on partial data. New pods may not report metrics immediately, and pods that are terminating or not ready should not distort the average. These details explain why HPA can look calm during the first minute of a spike and then move quickly once enough pods report usable metrics.

Behavior rules in autoscaling/v2 control how aggressively HPA changes replicas. scaleUp and scaleDown can set stabilizationWindowSeconds and policies based on Pods or Percent over a period. A common production pattern is fast scale-up and slower scale-down: allow replicas to rise quickly during a spike, then wait several minutes before removing capacity so brief dips do not cause flapping. The default scale-down stabilization window is conservative for a reason. Removing pods too quickly can create a second spike when traffic returns, while keeping extra replicas for a few minutes is usually cheaper than paging on latency.

Multiple metrics change the decision from a single ratio to a maximum across metric proposals. If CPU suggests 12 replicas and requests per second suggests 18, HPA chooses the larger value so the most demanding signal wins. That behavior is safe for availability but dangerous when one metric is badly calibrated. A noisy custom metric with an unrealistic target can pin the workload at maxReplicas. Treat every metric as a control input with an owner, a dashboard, and a tested target. HPA is only as trustworthy as the metric pipeline feeding it.


4. HPA vs VPA: What the Vertical Pod Autoscaler Actually Does

HPA vs VPA turns vertical with VPA, an add-on that watches historical CPU and memory usage and recommends better pod requests. Its Recommender builds decaying usage histograms, the Admission Controller applies values to new pods, and the Updater evicts pods when applied updates require replacement.

VPA is not built into the Kubernetes control plane in the same way as HPA. It is installed as custom resource definitions and controllers, normally from the Kubernetes autoscaler project. The user-facing object is VerticalPodAutoscaler in autoscaling.k8s.io/v1. It targets a controller such as a Deployment or StatefulSet and defines update policy plus resource policy. VPA observes pods owned by that controller, learns from their usage, and produces recommendations per container. The recommendation includes target, lowerBound, upperBound, and uncappedTarget values for CPU and memory.

The Recommender is the brain. It consumes usage history, normally from metrics-server, and builds exponentially decaying weighted histograms so recent behavior matters more than old behavior while short spikes do not completely dominate. CPU recommendations aim to give enough headroom for observed demand. Memory recommendations are more sensitive to peaks and OOM events because memory pressure is less forgiving than CPU throttling. A container that was OOM-killed needs a higher memory recommendation than a container that merely touched a high percentile once during a deploy.

The Admission Controller and Updater apply recommendations in different ways. The Admission Controller mutates new pods at creation time when the update mode allows initial application. The Updater watches existing pods and evicts those whose current requests differ enough from the recommendation when the mode permits updates. Eviction only makes sense for controller-managed pods, because the controller recreates replacements. A standalone pod has no controller to replace it, so VPA should not be treated as a safe updater for bare pods.

Recommendations need time and bounds. A fresh VPA object may have little to say until it sees enough samples across traffic patterns, deploys, and daily cycles. Teams often run VPA in Off mode first, compare recommendations with current requests, and only then decide whether Initial or a more active mode is justified. resourcePolicy minAllowed and maxAllowed are not decoration; they are guardrails that keep a recommender from shrinking a JVM below its safe memory floor or growing a sidecar into node capacity it does not need.


5. HPA vs VPA: Side-by-Side Comparison for Production Teams

HPA vs VPA differences are easiest to see side by side: HPA is built in and changes replicas, VPA is installed separately and changes pod resources. HPA reacts to current load, VPA learns from history, and both depend on metrics, requests, and guardrails that match the workload's failure modes.

The table below is a routing aid, not a ranking. HPA wins when the service can use more copies. VPA wins when the copies are the wrong size. Many production systems need HPA for traffic and VPA recommendations for request hygiene, but the safe combination separates signals and timing. If a team cannot explain which controller owns CPU, the design is not ready for automation.

DimensionHPAVPA
Primary actionChanges replica countChanges pod CPU and memory requests, optionally limits
Built into KubernetesYes, autoscaling/v2No, installed as CRDs and controllers
SignalCurrent metrics such as CPU, memory, custom, or external metricsHistorical usage, OOM events, and decaying histograms
SpeedReacts in seconds to minutesLearns over hours to days
Pod restartsNew pods are added or removedDepends on update mode; Recreate evicts pods
Best fitStateless services with parallel demandRightsizing pods with poor requests
Main riskFlapping, missing metrics, bad targetsEviction churn, bad floors, request feedback loops

Installation and blast radius differ. HPA is a namespaced object that changes one workload's scale. VPA includes cluster-level components, admission mutation, and eviction behavior, so its operational review should be stricter. A bad HPA target can over-scale a Deployment. A bad VPA policy can repeatedly evict pods across a workload. Both deserve staging tests, but VPA deserves extra attention to PodDisruptionBudgets, rollout behavior, and the minimum replica count that must remain available during updates.

Time horizon is another practical difference. HPA is a feedback controller for now: metric rises, replicas rise. VPA is a learning controller for shape: usage history accumulates, recommendation improves. That makes VPA poor at handling a sudden spike by itself and HPA poor at fixing chronic under-requesting. If pods OOM every day at the same memory request, HPA may add replicas while each replica still dies. If traffic doubles for ten minutes, VPA cannot create parallelism. The comparison should start from the failure you are trying to prevent.

Cost and reliability pull in opposite directions. Oversized requests waste schedulable capacity and can leave nodes underutilized. Undersized requests cause throttling, OOM kills, noisy-neighbor pressure, and misleading HPA utilization. HPA can hide undersized pods by adding replicas until node capacity or downstream limits stop it. VPA can expose undersized pods by recommending larger requests, but applying those recommendations may reduce density. Production tuning is therefore a capacity conversation, not just an autoscaler setting.


6. HPA vs VPA: HPA YAML Walkthrough With autoscaling/v2

HPA vs VPA configuration begins with an autoscaling/v2 HorizontalPodAutoscaler that targets a scalable workload, sets replica bounds, and declares metrics with targets. Production HPA objects also need resource requests on containers, a working metrics pipeline, and behavior rules that prevent replica counts from flapping during noisy traffic.

The example below scales a checkout API on CPU utilization and a per-pod request-rate metric. CPU protects against compute saturation. Requests per second gives the controller a demand signal that can move before CPU becomes the bottleneck. The behavior block allows fast scale-up, slower scale-down, and a scale-down policy that removes at most a quarter of replicas per minute after the stabilization window. That combination is intentionally asymmetric: availability during spikes matters more than reclaiming replicas a minute earlier.

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: checkout-api
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: checkout-api
  minReplicas: 3
  maxReplicas: 40
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 65
    - type: Pods
      pods:
        metric:
          name: httprequestspersecond
        target:
          type: AverageValue
          averageValue: "120"
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 25
          periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 100
          periodSeconds: 60
        - type: Pods
          value: 4
          periodSeconds: 60
      selectPolicy: Max

Read the object from top to bottom. scaleTargetRef must match the workload's apiVersion, kind, and name exactly. minReplicas is an availability decision, not just a cost setting. maxReplicas is a safety bound that should reflect node capacity, downstream limits, and the maximum blast radius the team accepts. Metrics with type Resource use utilization or average value targets. Metrics with type Pods depend on a custom metrics adapter exposing httprequestspersecond for the target pods. If that adapter is absent, HPA reports problems for that metric and the team should not pretend the signal exists.

The Deployment behind this HPA must set CPU and memory requests. Without CPU requests, the CPU utilization target has no denominator. Without memory requests, scheduling and eviction behavior become harder to reason about even if HPA scales on CPU. Requests should be plausible before HPA is enabled; HPA cannot rescue a workload whose requests are fictional. For command-level inspection habits, kubectl master guide is the companion reference for describe, get, top, and events workflows used during autoscaling incidents.

Test HPA with load, not hope. Apply the object in staging, generate traffic, watch kubectl get hpa -w, and confirm that replicas rise for the right reason. Then stop the load and confirm scale-down waits through the stabilization window instead of collapsing capacity immediately. Record the metric values that correspond to latency pain. If CPU reaches 65 percent only after p95 latency has already failed, CPU is the wrong primary signal and the target or metric choice needs work.


7. HPA vs VPA: VPA YAML Walkthrough and Update Modes

HPA vs VPA configuration for VPA uses a VerticalPodAutoscaler custom resource that targets a controller, limits recommendations with minAllowed and maxAllowed, and chooses an update mode. Off mode only recommends, Initial applies at creation, Recreate evicts pods, and InPlaceOrRecreate tries live resizing where the cluster supports it.

The example below starts in Off mode. That is deliberate. Off mode lets the Recommender publish recommendations without mutating pods, so the team can compare target values with current requests, check lower and upper bounds, and see whether the recommendation is stable across deploys and traffic cycles. controlledValues is RequestsOnly, which means VPA changes requests without rewriting limits. That choice reduces surprise for workloads where limits are tied to runtime behavior, QoS expectations, or application tuning.

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: checkout-api-vpa
  namespace: production
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: checkout-api
  updatePolicy:
    updateMode: "Off"
  resourcePolicy:
    containerPolicies:
      - containerName: checkout-api
        minAllowed:
          cpu: 250m
          memory: 512Mi
        maxAllowed:
          cpu: 2
          memory: 4Gi
        controlledResources: ["cpu", "memory"]
        controlledValues: RequestsOnly

Update modes decide how much authority VPA has. Off means recommendation only. Initial means the Admission Controller applies recommended resources when pods are created, but existing pods are not evicted for updates. Recreate means the Updater can evict pods so replacements start with new requests. InPlaceOrRecreate tries in-place pod resize where the Kubernetes version, runtime, and resource type support it, and falls back to recreation when needed. Auto is deprecated and should not be used in new manifests; treat it as a legacy alias for recreate-style behavior.

In-place resize changes the risk profile, but it does not erase it. Kubernetes 1.35 made in-place pod resize generally available in current documentation and release discussions, while older clusters should plan for eviction-based updates. Even where in-place resize works, increasing requests can fail if the node lacks allocatable capacity, and changing memory can interact with cgroup limits and application behavior. The safe rollout path is Off first, Initial second, then active modes only for workloads with healthy disruption budgets and enough replicas to absorb churn.

resourcePolicy is where platform judgment lives. minAllowed protects known floors such as JVM heap plus off-heap memory, agent overhead, or a minimum CPU share for latency-sensitive work. maxAllowed prevents a recommender from turning one container into a node-sized pod. controlledResources can limit VPA to memory only or CPU only when one resource is safer to automate. A VPA object without bounds is a recommendation engine with write access to your rollout behavior; production teams should not grant that access casually.


8. HPA vs VPA: Using Both Together Without the CPU Death Spiral

HPA vs VPA can work together only when they do not fight over the same signal. The dangerous pattern is HPA scaling on CPU utilization while VPA changes CPU requests, because every request change rewrites the utilization denominator and can trigger runaway replica growth during ordinary traffic spikes.

The death spiral is arithmetic. Start with 10 pods, each requesting 500 millicores and using 250 millicores. CPU utilization is 50 percent, matching the HPA target. VPA observes usage and recommends 250 millicores. After pods are recreated with the lower request, the same 250 millicores of usage becomes 100 percent utilization. HPA computes ceil(10 * 100 / 50) and asks for 20 replicas. Traffic spreads across 20 pods, per-pod usage falls toward 125 millicores, VPA recommends a smaller request again, utilization stays high, and HPA doubles again. The controllers are not broken; they are optimizing incompatible definitions.

The loop continues until maxReplicas, node capacity, downstream limits, or human intervention stops it. Along the way, pods churn from VPA updates, new pods start cold, caches miss, and the service may look busier because it is doing more coordination work. This is why the opening incident is plausible: a traffic spike provides the first push, but the feedback loop supplies the energy. The fix is not a larger maxReplicas. The fix is removing the shared CPU control path.

Safe combinations separate ownership. One pattern is HPA on requests per second, queue depth, or latency-related custom metrics while VPA runs in Off mode for recommendations. Another is HPA on CPU while VPA is limited to memory recommendations with RequestsOnly and careful bounds, though even memory changes need review because scheduling and OOM behavior change. A third pattern is manual rightsizing: run VPA in Off mode, apply request changes through Git during planned releases, and let HPA keep owning replicas. Manual does not mean primitive; it means the feedback loop is broken by review.

If both controllers must be active, write the ownership contract in the manifest review. HPA owns replica count from a named metric. VPA owns a named resource within named bounds, or it owns nothing and only recommends. The contract should state what happens during deploys, traffic spikes, node pressure, and rollback. Without that contract, every autoscaling incident becomes an argument between two controllers and a tired operator. With it, the team can disable one loop quickly because the intended authority was decided before the page.


9. HPA vs VPA: Troubleshooting HPA Metrics and Missing Requests

HPA vs VPA troubleshooting for HPA starts with the events on the HorizontalPodAutoscaler object, because unknown metrics usually mean missing requests, a broken metrics pipeline, or a bad scale target. Read the exact condition message first, then verify requests, metrics-server, adapters, and target references in that order.

Start with kubectl describe hpa and kubectl get hpa. The TARGETS column shows current and desired values, while conditions and events explain why the controller cannot compute replicas. Messages such as FailedGetResourceMetric or FailedComputeMetricsReplicas point to metric retrieval or calculation problems. An unknown CPU target often means metrics-server is unhealthy, the resource metrics API is unavailable, or pods do not define CPU requests. Do not tune the target percentage until the metric exists.

Check requests on the workload, not just the HPA object. Every container that contributes to resource utilization needs a request for that resource. Init containers, sidecars, and application containers can complicate the picture when one container has requests and another does not. Also verify scaleTargetRef: a typo in kind or name leaves HPA watching a target it cannot scale. If the workload is managed by GitOps or an operator, confirm that another controller is not resetting replicas after HPA changes them.

Custom metrics add another failure layer. The adapter must expose the metric for the right object type, namespace, and labels. A Prometheus query can be correct in Grafana and still be absent from the custom metrics API because the adapter rule, metric name, or series labels do not match. Test the metric through the API path HPA uses, not only through a dashboard. External metrics have similar risks: queue depth may exist in the provider while the adapter credentials, region, or metric selector are wrong.

Slow scale-down is often behavior, not failure. If replicas remain high after traffic drops, inspect stabilizationWindowSeconds and scale-down policies before declaring HPA stuck. Fast scale-up with slow scale-down is a deliberate production posture. The reverse problem, replicas rising too late, usually means the metric lags saturation or maxReplicas is too low. HPA troubleshooting should end with a metric story: what signal moved, when it moved, what replica count it produced, and whether latency improved. Without that story, target changes are guesses.


10. HPA vs VPA: Operating VPA Without Eviction Churn

HPA vs VPA operations for VPA center on controlling change: recommendations must respect floors, ceilings, disruption budgets, and rollout timing. Eviction-based updates can improve rightsizing, but they also churn pods, so production teams stage modes carefully and watch OOM events, restarts, and recommendation stability before enabling automation.

Eviction is the sharp edge. In Recreate mode, applying a new recommendation means old pods are evicted and replacements start with new requests. That is acceptable for a stateless Deployment with many replicas and a healthy PodDisruptionBudget. It is risky for a small StatefulSet, a leader-elected service, or a workload with long warm-up time. PodDisruptionBudgets can delay voluntary disruptions, but they are not a substitute for replica headroom. If maxUnavailable is tight and replicas are few, VPA updates may stall or create uncomfortable availability trade-offs.

Bounds prevent the recommender from learning the wrong lesson. A memory recommendation should not fall below the application's known working set, runtime overhead, and safety margin. A CPU recommendation should not be so low that throttling becomes the normal state. minAllowed is the floor that encodes those facts. maxAllowed is the ceiling that keeps one container from consuming node capacity needed by neighbors. Review lowerBound and upperBound as well as target; a wide gap can signal unstable usage, mixed traffic patterns, or containers that should be split into separate workloads.

OOM events deserve special handling. When a container is OOM-killed, VPA has evidence that the memory request or limit was too low for real work, but the root cause may be a leak, a cache that grows without bound, or a deploy that changed memory behavior. Raising requests can stop the bleeding while hiding the defect. Pair VPA changes with application metrics and restart analysis. If pods are crashing rather than merely resizing, use the diagnostic path in Kubernetes CrashLoopBackOff troubleshooting before assuming autoscaling is the primary fault.

Roll out VPA like a controller change, not a manifest tweak. Begin in Off mode for at least one full traffic cycle. Compare recommendations after deploys, batch windows, and peak periods. Move to Initial when new pods should start closer to the recommendation. Consider InPlaceOrRecreate only where version support and node capacity are understood. Keep Recreate for workloads that tolerate pod replacement well. Every mode change should have a rollback: set updateMode back to Off and let existing pods keep their current requests until the next planned rollout.


11. HPA vs VPA: Choosing by Workload Type

HPA vs VPA selection should follow workload shape: stateless services usually need HPA, memory-heavy or badly sized pods need VPA recommendations, and stateful systems need conservative vertical changes. Batch and queue-driven work often belongs with event-driven scaling rather than CPU-only HPA or aggressive VPA updates.

Stateless APIs are the cleanest HPA case. If requests are independent, sessions live outside the pod, and downstream systems can handle more concurrent calls, HPA on CPU plus a demand metric gives fast capacity. VPA still helps by recommending requests that make utilization meaningful. The safe pattern is HPA for replicas and VPA in Off mode for periodic rightsizing. Apply request changes during releases, watch latency and throttling, and keep maxReplicas tied to database and node limits rather than hope.

JVM services need more care. Heap size, garbage collection, metaspace, direct buffers, and thread stacks make memory floors real. VPA recommendations can reveal chronic over-requesting, but shrinking memory below the runtime's working set creates GC pressure or OOM kills. HPA on CPU can also mislead when GC threads burn CPU during memory pressure. For JVM workloads, set minAllowed from load-test evidence, prefer VPA Off or Initial, and consider HPA signals such as request rate or latency proxies instead of CPU alone.

Stateful workloads and databases are conservative territory. HPA is usually wrong for a database primary because replicas are not interchangeable capacity. Read replicas may scale horizontally in some architectures, but that is a data-layer decision, not a generic HPA setting. VPA recommendations can inform CPU and memory sizing for StatefulSet pods, yet active eviction must respect replication, leader election, storage attachment, and disruption budgets. The workload controller distinction in Deployment vs StatefulSet vs DaemonSet matters before any autoscaler is attached.

Batch and queue-driven work often needs event-driven scaling. A worker fleet should scale from queue depth, oldest message age, or consumer lag, not only CPU after work has already piled up. KEDA-style scaling can create HPA behavior from those signals and, where supported, handle idle periods better than plain CPU HPA. VPA can still rightsize worker pods, especially when jobs have predictable memory profiles. The broader platform rules in Kubernetes best practices apply here: requests, limits, probes, disruption budgets, and observability must be coherent before autoscaling is trusted.


12. HPA vs VPA: Troubleshooting Matrix and Production Checklist

HPA vs VPA production safety comes from pairing symptom routing with a short checklist: verify metrics, requests, bounds, update mode, disruption budget, and rollback path before enabling automation. The matrix below maps common autoscaling symptoms to likely causes, diagnosis commands, and fixes operators can apply during incidents.

Use the matrix as a routing table. Autoscaling symptoms look similar from kubectl get pods, but the fix differs sharply between a missing metric, a missing request, a stabilization window, and a VPA eviction policy. Read the HPA or VPA object first, then the workload, then the metrics pipeline. Changing targets before identifying the failing layer usually adds a second problem.

SymptomRoot CauseDiagnosis CommandResolution
HPA shows <unknown>/65%Metrics pipeline cannot supply CPU datakubectl describe hpa checkout-api -n productionFix metrics-server or adapter, then confirm kubectl top pods works
FailedGetResourceMetric eventsPods lack CPU or memory requestskubectl get deploy checkout-api -n production -o yamlSet requests on every container before using utilization targets
Replicas jump every minuteTarget is too close to noise and behavior is too loosekubectl get hpa checkout-api -n production -wRaise tolerance through target choice, add stabilization, and cap scale policies
Scale-down feels stuckScale-down stabilization window is holding replicaskubectl describe hpa checkout-api -n productionCheck behavior.scaleDown before changing minReplicas or targets
VPA recommendation stays emptyToo little history or metrics-server is missingkubectl describe vpa checkout-api-vpa -n productionVerify metrics-server and wait for enough usage history
Pods keep getting evictedVPA Recreate mode is applying frequent changeskubectl get events -n production --sort-by=.lastTimestampMove to Off or Initial, widen bounds, and review recommendation stability
Replicas explode after VPA updateHPA CPU utilization denominator changed when requests droppedkubectl get hpa,vpa -n productionStop CPU-based HPA plus CPU VPA on the same workload
Memory recommendation keeps risingOOM kills or memory growth are pushing target upwardkubectl describe pod -n production | grep -i oomFix leaks, set minAllowed floors, and review maxAllowed ceilings

Before enabling either controller in production, confirm the basics. The workload sets CPU and memory requests. metrics-server or the relevant adapter returns data through the API HPA or VPA actually uses. minReplicas and maxReplicas reflect availability and downstream limits. VPA starts in Off mode unless the team has evidence for a more active mode. PodDisruptionBudgets match the number of pods that can be unavailable during updates. Dashboards show replicas, requests, usage, throttling, OOM events, and latency on the same timeline.

Rollback should be boring. For HPA, rollback means restoring the previous metric target, bounds, or behavior and confirming replicas settle. For VPA, rollback means setting updateMode to Off, restoring prior requests through the workload manifest if needed, and letting pods roll normally. Keep autoscaler manifests in Git with the workload so reviewers see replica policy and resource policy together. HPA vs VPA incidents become shorter when the ownership contract, bounds, and rollback path were written before traffic forced the question.

Frequently Asked Questions

What is HPA in Kubernetes in the HPA vs VPA comparison?

HPA is the Horizontal Pod Autoscaler. It changes replica count for a scalable workload based on metrics such as CPU, memory, custom metrics, or external metrics. In HPA vs VPA terms, HPA answers demand by adding or removing pods, not by resizing the pods that already exist.

What is VPA in Kubernetes in the HPA vs VPA comparison?

VPA is the Vertical Pod Autoscaler. It observes historical CPU and memory usage and recommends better resource requests for pods. Depending on update mode, it can only recommend, apply values to new pods, evict pods for recreation, or try in-place resizing where the cluster supports it.

What is the difference between HPA and VPA?

The difference between HPA and VPA is direction. HPA scales horizontally by changing replica count. VPA scales vertically by changing per-pod CPU and memory requests. HPA reacts to current load, while VPA learns from usage history and improves pod sizing over time.

Can HPA and VPA work together safely?

Yes, if they do not control the same signal. A safe pattern is HPA on request rate, queue depth, or another demand metric while VPA stays in Off mode for recommendations. The unsafe pattern is HPA on CPU utilization plus VPA changing CPU requests, because the utilization denominator keeps moving.

Does VPA restart pods in an HPA vs VPA setup?

It depends on update mode. Off mode does not restart pods. Initial mode applies values when pods are created. Recreate mode evicts pods so replacements start with new requests. InPlaceOrRecreate tries live resizing where supported and falls back to recreation when needed.

When should you use VPA instead of HPA?

Use VPA instead of HPA when the main problem is pod sizing: requests are too high, too low, or disconnected from real usage. Use HPA when the service needs more parallel capacity. Many teams use HPA for replicas and VPA recommendations for periodic rightsizing.

Why is HPA not scaling in Kubernetes?

HPA usually fails to scale because metrics are unavailable, containers lack resource requests, the scale target is wrong, or behavior rules are delaying scale-down. Start with kubectl describe hpa, verify metrics-server or the adapter, and confirm every relevant container sets requests.

What causes the HPA vs VPA death spiral?

The death spiral happens when HPA scales on CPU utilization and VPA lowers CPU requests. Lower requests make the same usage look like higher utilization, so HPA adds replicas. More replicas lower per-pod usage, VPA lowers requests again, and the loop repeats until a bound stops it.

⚡ KUBERNETES SCENARIO INTERVIEW PREP

Preparing for Senior Platform & SRE Interviews

Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.

Explore Interview Scenarios →