Skip to content
masdzub.com
~/articles/kubernetes — one from the notebook

Kubernetes Pod Autoscaling: Production Setup and Architecture with HPA

Configure Horizontal Pod Autoscaling via kubectl and declarative manifests. Covers metrics-server setup, stabilization windows, and troubleshooting.

masdzub@website:~$ cat ~/articles/kubectl-autoscaling-setup-for-pod-deployment.aspx.md
# 1 file · 21 min read · topic: kubernetes · status: published

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 replicas

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

Terminal window
kubectl get apiservices v1beta1.metrics.k8s.io

If the command returns a NotFound error or reports False under the AVAILABLE column, install the Metrics Server. Apply the official manifest:

Terminal window
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml

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

Terminal window
kubectl logs -n kube-system -l k8s-app=metrics-server

If the logs display x509: certificate signed by unknown authority, patch the Metrics Server deployment to skip TLS verification for node communication:

metrics-server-patch.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: metrics-server
namespace: kube-system
spec:
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-tls

Apply the patch and confirm that metric scraping works:

Terminal window
kubectl patch deployment metrics-server -n kube-system --patch-file metrics-server-patch.yaml
kubectl rollout status deployment metrics-server -n kube-system

Wait 30 seconds for the first collection cycle to finish, then query node and pod metrics directly using kubectl:

Terminal window
kubectl top nodes
kubectl top pods -A

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

app-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-gateway
namespace: production
labels:
app: api-gateway
spec:
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: v1
kind: Service
metadata:
name: api-gateway
namespace: production
spec:
type: ClusterIP
ports:
- port: 80
targetPort: 80
selector:
app: api-gateway

Create the namespace and apply the workload:

Terminal window
kubectl create namespace production
kubectl apply -f app-deployment.yaml

In this definition:

  • requests.cpu: 100m means 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: 500m provides headroom for short computational bursts without triggering container throttling immediately.
  • requests.memory: 128Mi reserves 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:

Terminal window
kubectl autoscale deployment api-gateway \
--namespace=production \
--cpu-percent=50 \
--min=2 \
--max=10

Inspect the newly generated HPA resource:

Terminal window
kubectl get hpa -n production

The output displays key operational parameters:

NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
api-gateway Deployment/api-gateway <unknown>/50% 2 10 2 12s

The 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 AGE
api-gateway Deployment/api-gateway 1%/50% 2 10 2 45s

Check the detailed status and event stream using kubectl describe:

Terminal window
kubectl describe hpa api-gateway -n production

The 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 --min or --max boundaries.

Delete the imperative autoscaler before moving to declarative version control:

Terminal window
kubectl delete hpa api-gateway -n production

Declarative 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).

hpa-v2.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api-gateway-scaler
namespace: production
spec:
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: 180Mi

Apply the declarative configuration:

Terminal window
kubectl apply -f hpa-v2.yaml

Multi-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’s resources.requests. Supported only for CPU and memory resource metrics.
  • AverageValue: Target is an absolute metric value (such as 180Mi for memory or 500m for 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 with External metrics (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.

hpa-tuned-behavior.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api-gateway-tuned
namespace: production
spec:
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: 60

Apply this tuned configuration:

Terminal window
kubectl apply -f hpa-tuned-behavior.yaml

Detailed 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: Disabled

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

Terminal window
kubectl get hpa api-gateway-tuned -n production --watch

In a second terminal, monitor the target deployment and pod creation events:

Terminal window
kubectl get pods -n production -l app=api-gateway -w

In a third terminal, run a load generation pod that repeatedly calls the api-gateway service:

Terminal window
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 AGE
api-gateway-tuned Deployment/api-gateway 1%/70% 2 20 2 2m
api-gateway-tuned Deployment/api-gateway 89%/70% 2 20 2 3m
api-gateway-tuned Deployment/api-gateway 124%/70% 2 20 4 3m15s
api-gateway-tuned Deployment/api-gateway 78%/70% 2 20 6 3m30s

Notice 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 4m

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

Terminal window
kubectl describe hpa api-gateway-tuned -n production

The 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 target

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

  1. Prometheus Adapter: Translates Prometheus PromQL queries into Kubernetes metric API responses.
  2. 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:

hpa-custom-metrics.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api-ingress-scaler
namespace: production
spec:
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: 80

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

hpa-external-metrics.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: queue-worker-scaler
namespace: production
spec:
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 queue

With type: Value, the autoscaler divides the absolute external metric value by the target value to compute replicas:

desiredReplicas = ceil( 1500 messages / 100 target ) = 15 replicas

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

  1. HPA evaluation loop detects metric threshold breach (0 to 15 seconds).
  2. Deployment updates replica count; scheduler marks excess pods as Pending (1 to 2 seconds).
  3. Cluster Autoscaler detects unschedulable pods and calls the cloud provider API to provision nodes (10 to 30 seconds).
  4. Virtual machines boot, initialize the operating system, and join the Kubernetes control plane (1 to 3 minutes).
  5. 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 a Pending state while new nodes spin up in the background.
  • Set conservative averageUtilization thresholds (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:

app-pdb.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: api-gateway-pdb
namespace: production
spec:
minAvailable: 50%
selector:
matchLabels:
app: api-gateway

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

Terminal window
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-autoscaler
missing request for cpu on container web in pod api-gateway-75d5f8c85c-abcde

The 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: 100m

Apply 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-autoscaler
unable to get metrics for resource cpu: no metrics returned from resource metrics API

The HPA controller cannot reach the metrics API service, or the Metrics Server cannot scrape the kubelets.

Check the status of the API registration:

Terminal window
kubectl get apiservice v1beta1.metrics.k8s.io -o yaml

Look at the status.conditions array. If Available is False, inspect the Metrics Server pod logs:

Terminal window
kubectl logs -n kube-system -l k8s-app=metrics-server --tail=50

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

Terminal window
kubectl describe hpa <hpa-name> -n <namespace>

Check the Conditions section for ScalingLimited:

Type Status Reason Message
---- ------ ------ -------
AbleToScale True ReadyForNewScale recommended size matches current size
ScalingActive True ValidMetricFound the HPA was able to successfully calculate a replica count
ScalingLimited True TooFewReplicas the desired replica count is less than the minimum already

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

Terminal window
kubectl get events -n <namespace> --field-selector involvedObject.kind=HorizontalPodAutoscaler

Invalid Selector Errors

If the HPA reports an inability to match pods:

Warning FailedComputeMetricsReplicas 45s horizontal-pod-autoscaler
selector was not matched to any pods

This 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 AreaAggressive AutoscalingConservative Autoscaling
Target UtilizationHigh (75% to 85%)Moderate (50% to 65%)
Compute CostOptimized; minimal excess idle capacityHigher baseline cost; extra headroom paid continuously
Response to Sudden SurgesHigh risk of request queuing or dropped connections during traffic spikesHigh resilience; headroom absorbs traffic while pods start
Scale-Down StabilizationShort (30 to 60 seconds)Long (300 to 600 seconds)
Flapping RiskHigh; pods create and destroy rapidly during jitterLow; smooth capacity curve over time
Pod Lifecycle OverheadHigh load on container runtime and image registriesMinimal 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:

  1. Load spikes, heap expands, memory consumption hits 80%.
  2. HPA scales up replicas to bring the average down.
  3. Traffic stops. The JVM retains its heap.
  4. Memory usage never drops below 70%.
  5. 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:

  1. Explicit Resource Requests: Ensure all containers within the target pod template define both cpu and memory under resources.requests.
  2. Metrics Server Health: Verify that kubectl top nodes and kubectl top pods return valid resource telemetry across all worker nodes.
  3. 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.
  4. Decoupled Scale Behaviors: Implement an autoscaling/v2 manifest with an immediate scale-up policy (stabilizationWindowSeconds: 0) and a gradual scale-down policy (stabilizationWindowSeconds: 300 or higher).
  5. 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.
  6. Disruption Budgets: Apply a PodDisruptionBudget alongside your deployment to preserve minimum operational availability during node migrations and cluster updates.
  7. Node Capacity Coordination: Ensure that node-level autoscalers (Cluster Autoscaler or Karpenter) are tuned to react quickly to Pending pods created when an HPA scales a deployment beyond current cluster capacity.
found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.