Introduction
Autoscaling stateless workloads in Kubernetes requires binding workload replica counts directly to live resource consumption metrics. When sudden traffic surges hit an application, manual pod scaling via kubectl scale introduces latency that leads to request queuing, latency spikes, or dropped connections. Relying on oversized static replica counts wastes cluster compute capacity during off-peak hours.
The Horizontal Pod Autoscaler (HPA) automates this lifecycle by running a continuous control loop inside the kube-controller-manager. It queries resource metrics exposed by the Kubernetes Metrics API, calculates the difference between current consumption and target thresholds, and updates the spec.replicas field of the target controller (Deployment, ReplicaSet, or StatefulSet). Implementing HPA successfully requires a deployed metric pipeline, accurate pod resource requests, properly tuned stabilization windows to prevent flapping, and an understanding of how pod scaling coordinates with node-level autoscalers.
+-----------------------------------------------------------------------+| kube-controller-manager || || +-------------------+ Query Metrics +------------------+ || | HPA Controller | -----------------------> | metrics-server | || +-------------------+ +------------------+ || | ^ |+-----------|----------------------------------------------|------------+ | Update spec.replicas | Scrape v | Summary API+------------------------+ +------------------+| Deployment / Pods | | kubelet || (spec.containers[]. | | (cAdvisor pod || resources.requests) | | metrics) |+------------------------+ +------------------+Control Loop Mechanics and the Scaling Algorithm
The horizontal pod autoscaler does not react instantly to single-second metric fluctuations. Instead, it operates on a polling period governed by the --horizontal-pod-autoscaler-sync-period flag on the kube-controller-manager, which defaults to 15 seconds.
During each sync loop, the controller queries the metrics API (metrics.k8s.io for core metrics such as CPU and memory, or custom.metrics.k8s.io / external.metrics.k8s.io for application-level metrics). The controller computes the required replica count using a deterministic ratio formula:
desiredReplicas = ceil[ currentReplicas * ( currentMetricValue / desiredMetricValue ) ]Assume a Deployment currently runs 4 replicas. The target CPU utilization is configured at 50%, but the current average utilization across all running pods sits at 75%. The controller computes:
desiredReplicas = ceil[ 4 * ( 75 / 50 ) ] = ceil[ 4 * 1.5 ] = 6 replicasThe controller includes an internal tolerance threshold to prevent erratic scaling actions caused by minor metric jitter. The default tolerance is 0.10 (10%), configured by the --horizontal-pod-autoscaler-tolerance flag. If the ratio (currentMetricValue / desiredMetricValue) yields a result between 0.90 and 1.10, the controller skips scaling entirely.
The autoscaler also discards unready pods and pods missing metrics from the average calculation. If a container within a pod has not completed its readiness probe, or if a pod is marked for deletion (metadata.deletionTimestamp is set), its resource consumption is ignored. For scale-up decisions, pods that have recently started without recorded metrics are assumed to be consuming 100% of their target metric value to avoid underestimating necessary capacity during sudden bursts.
Metrics Server Pipeline Requirements
Core metrics (CPU and memory usage) originate in cAdvisor, an agent integrated directly into the kubelet running on every worker node. However, the HPA controller cannot scrape thousands of kubelet instances directly. A cluster requires the Metrics Server, an in-memory aggregator that pulls container runtime stats from each node’s Summary API and serves them through the Kubernetes API aggregation layer at metrics.k8s.io.
Verify if the API service exists in the cluster:
kubectl get apiservices v1beta1.metrics.k8s.ioIf the command returns a NotFound error or reports False under the AVAILABLE column, install the Metrics Server. Apply the official manifest:
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yamlIn custom-built clusters, bare-metal environments, or local test clusters where kubelet serving certificates are self-signed, the Metrics Server pod may enter a crash loop because it cannot validate the kubelet TLS certificate. Check the logs:
kubectl logs -n kube-system -l k8s-app=metrics-serverIf the logs display x509: certificate signed by unknown authority, patch the Metrics Server deployment to skip TLS verification for node communication:
apiVersion: apps/v1kind: Deploymentmetadata: name: metrics-server namespace: kube-systemspec: template: spec: containers: - name: metrics-server args: - --cert-dir=/tmp - --secure-port=4443 - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname - --kubelet-use-node-status-port - --metric-resolution=15s - --kubelet-insecure-tlsApply the patch and confirm that metric scraping works:
kubectl patch deployment metrics-server -n kube-system --patch-file metrics-server-patch.yamlkubectl rollout status deployment metrics-server -n kube-systemWait 30 seconds for the first collection cycle to finish, then query node and pod metrics directly using kubectl:
kubectl top nodeskubectl top pods -AIf these commands return resource usage tables instead of error messages, the pipeline is operational and the HPA can consume core resource metrics.
Workload Baseline: Resource Requests and Limits
The HPA CPU percentage metric calculates utilization relative to the container’s configured resource requests, not its limits or the total capacity of the host node. If a pod definition omits resources.requests.cpu, the HPA cannot compute a utilization percentage and enters a FailedGetResourceMetric state.
Deploy an HTTP service configured with explicit resource boundaries to serve as the baseline scaling workload:
apiVersion: apps/v1kind: Deploymentmetadata: name: api-gateway namespace: production labels: app: api-gatewayspec: replicas: 2 selector: matchLabels: app: api-gateway template: metadata: labels: app: api-gateway spec: containers: - name: web image: registry.k8s.io/hpa-example:latest ports: - containerPort: 80 name: http resources: requests: cpu: 100m memory: 128Mi limits: cpu: 500m memory: 256Mi readinessProbe: httpGet: path: / port: 80 initialDelaySeconds: 5 periodSeconds: 5---apiVersion: v1kind: Servicemetadata: name: api-gateway namespace: productionspec: type: ClusterIP ports: - port: 80 targetPort: 80 selector: app: api-gatewayCreate the namespace and apply the workload:
kubectl create namespace productionkubectl apply -f app-deployment.yamlIn this definition:
requests.cpu: 100mmeans each replica reserves 0.1 of a CPU core. When HPA targets 50% CPU utilization, it will attempt to scale pods when the average container CPU usage hits 50m (0.05 cores).limits.cpu: 500mprovides headroom for short computational bursts without triggering container throttling immediately.requests.memory: 128Mireserves physical RAM. Unlike CPU, memory cannot be throttled or compressed. If memory hits the limit (256Mi), the Linux kernel OOM killer terminates the container.
Imperative Autoscaling with Kubectl
The fastest method to configure an HPA is through the kubectl autoscale command. This creates an HorizontalPodAutoscaler object targeting the specified workload:
kubectl autoscale deployment api-gateway \ --namespace=production \ --cpu-percent=50 \ --min=2 \ --max=10Inspect the newly generated HPA resource:
kubectl get hpa -n productionThe output displays key operational parameters:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGEapi-gateway Deployment/api-gateway <unknown>/50% 2 10 2 12sThe TARGETS column shows <unknown>/50% for the first 15 to 30 seconds while the HPA controller awaits its first poll cycle against the metrics API. Once collected, the current percentage replaces <unknown>:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGEapi-gateway Deployment/api-gateway 1%/50% 2 10 2 45sCheck the detailed status and event stream using kubectl describe:
kubectl describe hpa api-gateway -n productionThe output contains status conditions that explain the autoscaler’s state:
AbleToScale: Indicates whether the HPA controller can access the target deployment and change its replica count.ScalingActive: Indicates whether the HPA controller successfully retrieved current metrics from the API.ScalingLimited: Indicates whether the desired replica count hit the configured--minor--maxboundaries.
Delete the imperative autoscaler before moving to declarative version control:
kubectl delete hpa api-gateway -n productionDeclarative HPA Configuration (autoscaling/v2)
Production configurations should be managed declaratively using the autoscaling/v2 API version. This version supports multiple metrics, explicit scale-up and scale-down behaviors, custom metrics, and distinct metric target types (Utilization, Value, and AverageValue).
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: api-gateway-scaler namespace: productionspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: api-gateway minReplicas: 2 maxReplicas: 15 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 60 - type: Resource resource: name: memory target: type: AverageValue averageValue: 180MiApply the declarative configuration:
kubectl apply -f hpa-v2.yamlMulti-Metric Evaluation Logic
When an HPA manifest specifies more than one metric (as seen above with both CPU and memory), the controller evaluates each metric independently according to the standard algorithm.
The autoscaler then selects the highest calculated replica count among all evaluated metrics.
For example, if the current CPU utilization demands 6 replicas to return to 60%, but current memory consumption calculates a requirement for 9 replicas to stay below 180Mi per pod, the controller sets the deployment target to 9 replicas. This ensures that the most constrained resource always receives adequate scaling capacity.
The metric target types operate under different semantics:
Utilization: Target value is a percentage of the pod’sresources.requests. Supported only for CPU and memory resource metrics.AverageValue: Target is an absolute metric value (such as180Mifor memory or500mfor CPU) averaged across all pods managed by the controller.Value: An absolute metric value that applies to a single metric source regardless of pod count, typically used withExternalmetrics (such as total depth of an Amazon SQS queue).
Fine-Tuning Scaling Policies and Flapping Prevention
A primary failure mode of automated scaling is flapping (also called thrashing). Flapping occurs when a traffic spike triggers rapid scale-up, which causes average utilization to drop drastically, prompting the autoscaler to scale down immediately. As soon as the pods terminate, the remaining pods are overwhelmed, causing another scale-up. This loop wastes cluster scheduling cycles and degrades user experience.
The behavior specification in autoscaling/v2 allows engineers to decouple scale-up velocity from scale-down velocity and establish stabilization windows.
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: api-gateway-tuned namespace: productionspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: api-gateway minReplicas: 2 maxReplicas: 20 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 behavior: scaleUp: stabilizationWindowSeconds: 0 selectPolicy: Max policies: - type: Percent value: 100 periodSeconds: 15 - type: Pods value: 4 periodSeconds: 15 scaleDown: stabilizationWindowSeconds: 300 selectPolicy: Min policies: - type: Percent value: 10 periodSeconds: 60Apply this tuned configuration:
kubectl apply -f hpa-tuned-behavior.yamlDetailed Behavior Mechanics
The scaleUp configuration prioritizes rapid responsiveness:
stabilizationWindowSeconds: 0: Scaling up happens immediately when the metric crosses the threshold. No delay is introduced when processing surges.selectPolicy: Max: If multiple policies match, the controller selects the policy that produces the highest pod count change.policies: Every 15 seconds, the HPA can increase the replica count by either 100% (doubling the current count) or by 4 pods, whichever is greater. If running 2 pods, it will add 4 pods (to reach 6). If running 10 pods, it will add 10 pods (to reach 20).
The scaleDown configuration enforces safety and stability:
stabilizationWindowSeconds: 300: The autoscaler looks back over the past 5 minutes (300 seconds). It will only scale down to the maximum desired replica count computed within that window. If traffic dipped for 30 seconds and returned, no pods are terminated.selectPolicy: Min: The controller chooses the policy that removes the fewest pods.policies: The cluster will not remove more than 10% of the active replicas within a 60-second window. For an active deployment of 10 pods, it can only terminate 1 pod per minute, preventing abrupt capacity drop-offs while internal caches warm up.
To disable scale-down completely (common for applications that take a long time to warm up caches and must remain at peak capacity until an operational maintenance window), set the policy to disabled:
behavior: scaleDown: selectPolicy: DisabledSimulating Traffic and Validating Scaling Execution
To verify that the autoscaler responds correctly to load, generate synthetic CPU pressure inside the api-gateway workload.
Start a watch command in one terminal to monitor the HPA status in real time:
kubectl get hpa api-gateway-tuned -n production --watchIn a second terminal, monitor the target deployment and pod creation events:
kubectl get pods -n production -l app=api-gateway -wIn a third terminal, run a load generation pod that repeatedly calls the api-gateway service:
kubectl run -i --tty load-generator \ --rm \ --image=busybox:1.36 \ --restart=Never \ --namespace=production \, /bin/sh -c "while true; do wget -q -O- http://api-gateway.production.svc.cluster.local; done"Within 30 to 60 seconds, the load generator drives CPU utilization upward. Inspect the kubectl get hpa terminal output:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGEapi-gateway-tuned Deployment/api-gateway 1%/70% 2 20 2 2mapi-gateway-tuned Deployment/api-gateway 89%/70% 2 20 2 3mapi-gateway-tuned Deployment/api-gateway 124%/70% 2 20 4 3m15sapi-gateway-tuned Deployment/api-gateway 78%/70% 2 20 6 3m30sNotice how the replica count jumped from 2 to 4, and then to 6. Because selectPolicy: Max allowed adding 4 pods, the controller increased capacity quickly, stabilizing the utilization close to the 70% target.
Terminate the load generator by pressing Ctrl+C in its terminal.
Observe the watch output for the scale-down behavior. The utilization immediately drops:
api-gateway-tuned Deployment/api-gateway 0%/70% 2 20 6 4mDespite utilization remaining at 0%, the replica count stays at 6 for the next 300 seconds. Once the 5-minute stabilizationWindowSeconds expires, the controller terminates pods incrementally according to the 10% per 60 seconds constraint until it reaches minReplicas: 2.
Inspect the events recorded during this operational cycle:
kubectl describe hpa api-gateway-tuned -n productionThe event log confirms the algorithm decisions:
Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal SuccessfulRescale 2m horizontal-pod-autoscaler New size: 4; reason: cpu resource utilization (percentage of request) above target Normal SuccessfulRescale 90s horizontal-pod-autoscaler New size: 6; reason: cpu resource utilization (percentage of request) above target Normal SuccessfulRescale 10s horizontal-pod-autoscaler New size: 5; reason: All metrics below targetScaling on Custom and External Metrics
Scaling on CPU and memory is often insufficient for asynchronous workers or event-driven microservices. An event processor worker pulling tasks from a queue might consume very little CPU while idle, yet fall drastically behind processing jobs if message backlogs accumulate.
Kubernetes accommodates this via the Custom Metrics API (custom.metrics.k8s.io) and External Metrics API (external.metrics.k8s.io).
+------------------+ +----------------------+ +-----------------------+| Prometheus / | Scrapes | Prometheus Server | Queries | Prometheus Adapter || App Endpoints | <------ | (TSDB) | <------ | (custom.metrics.k8s) |+------------------+ +----------------------+ +-----------------------+ ^ | Polls API +-----------------------+ | kube-controller- | | manager (HPA) | +-----------------------+To scale on application-specific metrics (such as HTTP request rates per second or active worker job queues), two main solutions are standard in the ecosystem:
- Prometheus Adapter: Translates Prometheus PromQL queries into Kubernetes metric API responses.
- KEDA (Kubernetes Event-driven Autoscaling): Installs custom controllers and scalers that feed directly into the Kubernetes HPA by managing external metric bindings.
Configuring HPA for Custom Metrics
Below is an example of an HPA configured to scale an API tier based on the average rate of HTTP requests per pod, pulled from an active custom metrics provider:
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: api-ingress-scaler namespace: productionspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: api-gateway minReplicas: 3 maxReplicas: 30 metrics: - type: Pods pods: metric: name: http_requests_per_second target: type: AverageValue averageValue: 500m # 0.5 requests per second per pod - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 80When targeting metrics of type Pods, the custom metric must describe a per-pod metric collected across all pods targeted by the HPA selector. The controller queries the Custom Metrics API, aggregates the total rate, divides it by the active pod count, and runs the scaling calculation.
Scaling on External Metrics (Message Queues)
For metrics that exist entirely outside the Kubernetes cluster (such as an AWS SQS queue length, RabbitMQ message count, or Kafka consumer lag), use the External metric type:
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: queue-worker-scaler namespace: productionspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: queue-worker minReplicas: 1 maxReplicas: 50 metrics: - type: External external: metric: name: aws_sqs_approximate_number_of_messages selector: matchLabels: queue-name: orders-processing target: type: Value value: 100 # Maintain 1 replica per 100 messages in queueWith type: Value, the autoscaler divides the absolute external metric value by the target value to compute replicas:
desiredReplicas = ceil( 1500 messages / 100 target ) = 15 replicasPodDisruptionBudgets and Node Autoscaler Interaction
Pod autoscaling does not operate in isolation. It functions within an ecosystem alongside the node-level Cluster Autoscaler (or Karpenter) and Pod Disruption Budgets (PDB). Conflicts between these systems can halt scaling or cause unexpected pod terminations.
+----------------------------------------------------------------------------------+| Kubernetes Cluster || || +-------------------+ || | HPA | Scales up pods based on demand || +-------------------+ || | || v (Creates 20 Pods) || +-------------------+ || | Scheduler | Pod state: Pending (Insufficient CPU on current nodes) || +-------------------+ || | || v (Watches Pending Pods) || +-------------------+ || | Cluster Autoscaler| Provisions new cloud compute instances / VM nodes || +-------------------+ |+----------------------------------------------------------------------------------+Pod Scheduling Bottlenecks During Scale-Up
When the HPA initiates an aggressive scale-up (for instance, jumping from 4 to 20 pods), the Kubernetes scheduler places those pods across available nodes. If the cluster nodes lack sufficient unreserved CPU or memory requests, newly created pods enter a Pending state.
At this juncture, the HPA has fulfilled its role, but the application capacity has not increased. The node-level autoscaler (Cluster Autoscaler or Karpenter) must detect pods in a Pending state with an OutOfResource or Insufficient cpu scheduling failure and trigger the provisioning of new compute nodes.
This introduces a concrete latency timeline:
- HPA evaluation loop detects metric threshold breach (0 to 15 seconds).
- Deployment updates replica count; scheduler marks excess pods as
Pending(1 to 2 seconds). - Cluster Autoscaler detects unschedulable pods and calls the cloud provider API to provision nodes (10 to 30 seconds).
- Virtual machines boot, initialize the operating system, and join the Kubernetes control plane (1 to 3 minutes).
- Kubelet pulls container images and transitions pods to
Running(10 to 60 seconds).
To mitigate this multi-minute delay during mission-critical spikes:
- Configure low-priority “balloon” pause pods via Kubernetes
PriorityClass. When high-priority application pods scale up, the scheduler evicts the balloon pods instantly to claim their reserved space, leaving the balloon pods to wait in aPendingstate while new nodes spin up in the background. - Set conservative
averageUtilizationthresholds (such as 60% instead of 85%) to allow the running pods to absorb the load while waiting for new nodes to initialize.
Mitigating Scale-Down Disruptions with PDB
When the HPA initiates a scale-down, it terminates pods. If a node draining event or node scale-down occurs simultaneously, the service risks dropping active requests. Protect the application by defining a PodDisruptionBudget:
apiVersion: policy/v1kind: PodDisruptionBudgetmetadata: name: api-gateway-pdb namespace: productionspec: minAvailable: 50% selector: matchLabels: app: api-gatewayWith this PDB in place, external eviction controllers (such as the Cluster Autoscaler removing underutilized nodes) cannot evict pods if doing so drops the available capacity below 50% of the current deployment size.
Note that the HPA controller itself modifies spec.replicas directly on the Deployment; it is not bound by the PDB when scaling down its own workload. The PDB protects against concurrent cluster-level maintenance actions while HPA adjustments occur.
Troubleshooting HPA Failure States
When an HPA is misconfigured or its dependency pipeline breaks, the controller reports errors in kubectl describe hpa. Below are common failure states encountered in production, their root causes, and verification steps.
Metric Value Shows Unknown
Running kubectl get hpa displays <unknown>/50% continuously under the TARGETS header.
Inspect the resource conditions:
kubectl describe hpa <hpa-name> -n <namespace>Diagnostic 1: Missing Resource Requests in Deployment
If the conditions display:
Warning FailedGetResourceMetric 2m (x6 over 4m) horizontal-pod-autoscalermissing request for cpu on container web in pod api-gateway-75d5f8c85c-abcdeThe application pods do not specify resource requests for the target metric. The HPA cannot calculate a percentage without a base request value.
Resolve this by updating the Deployment manifest to include:
resources: requests: cpu: 100mApply the deployment manifest and wait for the pods to roll out.
Diagnostic 2: Metrics Server Unreachable
If the conditions display:
Warning FailedGetResourceMetric 1m (x4 over 3m) horizontal-pod-autoscalerunable to get metrics for resource cpu: no metrics returned from resource metrics APIThe HPA controller cannot reach the metrics API service, or the Metrics Server cannot scrape the kubelets.
Check the status of the API registration:
kubectl get apiservice v1beta1.metrics.k8s.io -o yamlLook at the status.conditions array. If Available is False, inspect the Metrics Server pod logs:
kubectl logs -n kube-system -l k8s-app=metrics-server --tail=50Verify that the cluster networking allows traffic from the control plane to the metrics server pod on port 4443.
HPA Not Scaling Down
The load test has finished, CPU usage is near 0%, but the HPA does not reduce pod count.
Run:
kubectl describe hpa <hpa-name> -n <namespace>Check the Conditions section for ScalingLimited:
Type Status Reason Message---- ------ ------ -------AbleToScale True ReadyForNewScale recommended size matches current sizeScalingActive True ValidMetricFound the HPA was able to successfully calculate a replica countScalingLimited True TooFewReplicas the desired replica count is less than the minimum alreadyIf Status is True and the reason is TooFewReplicas, the current replica count has already reached minReplicas.
If the replicas remain high above minReplicas, inspect the behavior.scaleDown settings in your HPA manifest. If stabilizationWindowSeconds is configured for a long duration (for example, 3600 for 1 hour), the HPA will retain the peak replica count for that duration. Check the current age of the last scale-up event in the event log:
kubectl get events -n <namespace> --field-selector involvedObject.kind=HorizontalPodAutoscalerInvalid Selector Errors
If the HPA reports an inability to match pods:
Warning FailedComputeMetricsReplicas 45s horizontal-pod-autoscalerselector was not matched to any podsThis error occurs when the scaleTargetRef points to a deployment whose internal label selectors do not match the running pods, or the target deployment was deleted and recreated with a different name. Ensure the scaleTargetRef.name matches the exact name in metadata.name of the target Deployment.
Production Architectural Trade-Offs
Autoscaling introduces operational trade-offs that require consideration before rolling out across production environments.
| Configuration Area | Aggressive Autoscaling | Conservative Autoscaling |
|---|---|---|
| Target Utilization | High (75% to 85%) | Moderate (50% to 65%) |
| Compute Cost | Optimized; minimal excess idle capacity | Higher baseline cost; extra headroom paid continuously |
| Response to Sudden Surges | High risk of request queuing or dropped connections during traffic spikes | High resilience; headroom absorbs traffic while pods start |
| Scale-Down Stabilization | Short (30 to 60 seconds) | Long (300 to 600 seconds) |
| Flapping Risk | High; pods create and destroy rapidly during jitter | Low; smooth capacity curve over time |
| Pod Lifecycle Overhead | High load on container runtime and image registries | Minimal lifecycle churn; stable node state |
Memory-Based Autoscaling Caveat
Autoscaling purely on memory utilization is dangerous for runtimes managed by a garbage collector (Java virtual machine, Go runtime, Node.js).
These runtimes do not release allocated heap memory back to the Linux operating system immediately when traffic subsides. The runtime retains allocated pages for future allocations. From the perspective of cAdvisor and the HPA, memory consumption remains high even when active application throughput drops to zero.
If an HPA targets 70% memory utilization on a JVM application:
- Load spikes, heap expands, memory consumption hits 80%.
- HPA scales up replicas to bring the average down.
- Traffic stops. The JVM retains its heap.
- Memory usage never drops below 70%.
- The HPA never scales down, keeping the deployment scaled up permanently.
When managing runtimes with non-reclaiming allocators, scale horizontally on CPU utilization, request throughput, or message queue lag, while using memory requests and limits strictly for scheduling protection and OOM containment.
Operational Checklist for Production Deployments
Before applying horizontal autoscalers to production workloads, verify each of the following engineering prerequisites:
- Explicit Resource Requests: Ensure all containers within the target pod template define both
cpuandmemoryunderresources.requests. - Metrics Server Health: Verify that
kubectl top nodesandkubectl top podsreturn valid resource telemetry across all worker nodes. - Readiness Probes: Configure accurate HTTP or TCP readiness probes on your workloads. Pods starting during a scale-up must not receive production traffic until their internal caches and thread pools have initialized.
- Decoupled Scale Behaviors: Implement an
autoscaling/v2manifest with an immediate scale-up policy (stabilizationWindowSeconds: 0) and a gradual scale-down policy (stabilizationWindowSeconds: 300or higher). - Headroom Buffer: Set target CPU utilization between 50% and 70%. Never configure an autoscaling threshold above 85%, as standard metric collection delays will cause traffic to saturate the deployment before the HPA can add replicas.
- Disruption Budgets: Apply a
PodDisruptionBudgetalongside your deployment to preserve minimum operational availability during node migrations and cluster updates. - Node Capacity Coordination: Ensure that node-level autoscalers (Cluster Autoscaler or Karpenter) are tuned to react quickly to
Pendingpods created when an HPA scales a deployment beyond current cluster capacity.