kubernetes: HPA stuck at maxReplicas even though metric under target

What happened?

HPA does not reduce Deployment replica count even though resource metric is below target. It is stuck at maxReplicas.

What did you expect to happen?

Deployment replica count should be reduced.

How can we reproduce it (as minimally and precisely as possible)?

We can see multiple examples in our clusters but not sure how to reproduce it exactly.

Here’s some relevant kubectl output:

$ kubectl top pod -l app=application-one,country=ar
NAME                                                  CPU(cores)   MEMORY(bytes)
application-one-ar-76fd9bc76d-25wnr                   35m          909Mi
application-one-ar-76fd9bc76d-4d72r                   42m          778Mi
application-one-ar-76fd9bc76d-6pt7r                   35m          1189Mi
application-one-ar-76fd9bc76d-6z2mr                   29m          793Mi
application-one-ar-76fd9bc76d-cv6r9                   29m          837Mi
application-one-ar-76fd9bc76d-hrpd9                   32m          824Mi
application-one-ar-76fd9bc76d-mrgt8                   45m          1180Mi
application-one-ar-76fd9bc76d-qwjbs                   43m          1186Mi
application-one-ar-76fd9bc76d-sqf5h                   41m          797Mi
application-one-ar-76fd9bc76d-tlr6k                   39m          920Mi
application-one-collect-metrics-ar-7df9868cbf-h4db8   7m           595Mi


$ kubectl get deployment application-one-ar
NAME                 READY   UP-TO-DATE   AVAILABLE   AGE
application-one-ar   10/10   10           10          565d

$ kubectl get hpa application-one-ar
NAME                      REFERENCE                  TARGETS   MINPODS   MAXPODS   REPLICAS   AGE
application-one-ar   Deployment/application-one-ar   20%/70%   3         10        10         565d

$ kubectl get pod -l app=application-one,country=ar
NAME                                             READY   STATUS      RESTARTS   AGE
application-one-ar-76fd9bc76d-25wnr              1/1     Running     0          3h56m
application-one-ar-76fd9bc76d-4d72r              1/1     Running     0          147m
application-one-ar-76fd9bc76d-6pt7r              1/1     Running     0          4d
application-one-ar-76fd9bc76d-6z2mr              1/1     Running     0          147m
application-one-ar-76fd9bc76d-cv6r9              1/1     Running     0          176m
application-one-ar-76fd9bc76d-hrpd9              1/1     Running     0          147m
application-one-ar-76fd9bc76d-mrgt8              1/1     Running     0          3d4h
application-one-ar-76fd9bc76d-qwjbs              1/1     Running     0          4d
application-one-ar-76fd9bc76d-sqf5h              1/1     Running     0          146m
application-one-ar-76fd9bc76d-tlr6k              1/1     Running     0          3h56m
application-one-clean-up-ar-28257720-96544       0/1     Completed   0          2d5h
application-one-clean-up-ar-28259160-zj2f4       0/1     Completed   0          29h
application-one-clean-up-ar-28260600-687q4       0/1     Completed   0          5h19m
application-one-xxxx-ar-7df9868cbf-h4db8         1/1     Running     0          2d11h
application-one-yyyyy-ar-28240560-5vtwj          0/1     Completed   0          14d
application-one-zzzzz-ar-28250640-sr28d          0/1     Completed   0          7d3h

The Deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "115"
    meta.helm.sh/release-name: application-one-ar
    meta.helm.sh/release-namespace: default
  labels:
    app: application-one
    app.kubernetes.io/managed-by: Helm
    country: ar
    custom_app: application-one
    custom_country: ar
    custom_env: production
    custom_region: cloud-region-one
    environment: production
  name: application-one-ar
  namespace: default
spec:
  minReadySeconds: 10
  progressDeadlineSeconds: 300
  replicas: 10
  revisionHistoryLimit: 0
  selector:
    matchLabels:
      app: application-one
      country: ar
  strategy:
    rollingUpdate:
      maxSurge: 50%
      maxUnavailable: 0
    type: RollingUpdate
  template:
    metadata:
      annotations:
        kubectl.kubernetes.io/restartedAt: "2023-06-25T14:57:33+02:00"
        prometheus.io/path: /prometheus
        prometheus.io/port: "8080"
        prometheus.io/scrape: "true"
      creationTimestamp: null
      labels:
        app: application-one
        country: ar
        custom_app: application-one
        custom_country: ar
        custom_env: production
        custom_region: cloud-region-one
        environment: production
        module: web
    spec:
      containers:
      - env: # removed
        imagePullPolicy: Always
        name: application-one-ar-production
        ports:
        - containerPort: 8080
          protocol: TCP
        readinessProbe:
          failureThreshold: 6
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 5
        resources:
          limits:
            cpu: "3"
            memory: 1536M
          requests:
            cpu: 170m
            memory: 1536M
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: FallbackToLogsOnError
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      terminationGracePeriodSeconds: 30

status:
  availableReplicas: 10
  conditions:
  - lastTransitionTime: "2022-03-09T12:49:18Z"
    lastUpdateTime: "2023-09-21T14:24:09Z"
    message: ReplicaSet "application-one-ar-76fd9bc76d" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  - lastTransitionTime: "2023-09-25T12:54:20Z"
    lastUpdateTime: "2023-09-25T12:54:20Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  observedGeneration: 8975
  readyReplicas: 10
  replicas: 10
  updatedReplicas: 10

The HorizontalPodAutoscaler:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  annotations:
    meta.helm.sh/release-name: application-one-ar
    meta.helm.sh/release-namespace: default
  labels:
    app: application-one
    app.kubernetes.io/managed-by: Helm
    country: ar
    custom_app: application-one
    custom_country: ar
    custom_env: production
    custom_region: cloud-region-one
    environment: production
  name: application-one-ar
  namespace: default
spec:
  maxReplicas: 10
  metrics:
  - resource:
      name: cpu
      target:
        averageUtilization: 70
        type: Utilization
    type: Resource
  minReplicas: 3
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: application-one-ar
status:
  conditions:
  - lastTransitionTime: "2022-03-09T12:49:33Z"
    message: recommended size matches current size
    reason: ReadyForNewScale
    status: "True"
    type: AbleToScale
  - lastTransitionTime: "2023-09-21T14:22:44Z"
    message: the HPA was able to successfully calculate a replica count from cpu resource
      utilization (percentage of request)
    reason: ValidMetricFound
    status: "True"
    type: ScalingActive
  - lastTransitionTime: "2023-09-25T10:52:44Z"
    message: the desired count is within the acceptable range
    reason: DesiredWithinRange
    status: "False"
    type: ScalingLimited
  currentMetrics:
  - resource:
      current:
        averageUtilization: 21
        averageValue: 33m
      name: cpu
    type: Resource
  currentReplicas: 10
  desiredReplicas: 10
  lastScaleTime: "2023-09-19T10:49:13Z"

Anything else we need to know?

No response

Kubernetes version

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"24", GitVersion:"v1.24.3", GitCommit:"aef86a93758dc3cb2c658dd9657ab4ad4afc21cb", GitTreeState:"clean", BuildDate:"2022-07-13T14:21:56Z", GoVersion:"go1.18.4", Compiler:"gc", Platform:"darwin/arm64"}

Kustomize Version: v4.5.4

Server Version: version.Info{Major:"1", Minor:"25+", GitVersion:"v1.25.12-eks-2d98532", GitCommit:"0aa16cf4fac4da27b9e9e9ba570b990867f6a3d8", GitTreeState:"clean", BuildDate:"2023-07-28T16:52:04Z", GoVersion:"go1.20.6", Compiler:"gc", Platform:"linux/amd64"}

Cloud provider

AWS EKS

OS version

No response

Install tools

No response

Container runtime (CRI) and version (if applicable)

containerd://1.6.19

Related plugins (CNI, CSI, …) and versions (if applicable)

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 11
  • Comments: 34 (4 by maintainers)

Commits related to this issue

Most upvoted comments

FWIW, our AWS Support rep pointed us to this thread. LOL

What worked for me to resolve the issue with HPA not scaling down despite the fact the CPU/Memory utilization was below target was to remove spec.replicas from the deployment

If it is caused by spec.selector.matchLabels labels of Deployment/application-one-ar matching pods outside of that deployment, then this is quite disappointing:

  • It’s very poor UX to see the metric presented as way under the target but still desiredReplicas=maxReplicas. This makes no sense to a user.
  • This issue seems to be over 4 years old, constant comments in that issue also
  • I think it’s mentioned in the docs here but I think many users are unlikely to fully understand what is written and the implication of it

As I said here (3 years ago!):

The HPA scaleTargetRef uses deployment by name and that should be enough without having to worry about selectors.

I think this comment is still valid because from a user perspective a deployment is specified by name but underneath the pods are selected by something (potentially) totally different. This is kind of an obfuscation.

At a minimum, do you think a feature request to show this situation loud and clear in the status of the HorizontalPodAutoscaler would be valid?

I get the same problem with a HPA scaling based on memory

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: sessions-bus-autoscaler
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: sessions-bus
  maxReplicas: 3
  minReplicas: 1
  metrics:
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 90
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 0
      policies:
        - type: Pods
          value: 1
          periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 60
      policies:
        - type: Pods
          value: 1
          periodSeconds: 60

NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE sessions-bus-autoscaler Deployment/sessions-bus 50%/90% 1 3 3 44h sessions-bus-autoscaler Deployment/sessions-bus 54%/90% 1 3 3 44h sessions-bus-autoscaler Deployment/sessions-bus 52%/90% 1 3 3 44h sessions-bus-autoscaler Deployment/sessions-bus 51%/90% 1 3 3 44h sessions-bus-autoscaler Deployment/sessions-bus 50%/90% 1 3 3 44h

All the running pods are with the memory under the target and still doesn’t scale down. I also tried wpferreira01 workaround even though i have only one policy per scale type but it didn’t helped.

So is this the old classic HPA issue of the deployment selector labels matching pods outside of that deployment? e.g. application-one-xxxx-ar-7df9868cbf-h4db8 in the above output?

Anyone found a workaround or fix on this, I upgraded my kubernetes to v1.30 and deduct load testing on the environment then the autoscaler start to acting weird and keep scaling down and up on schedule even the metrics don’t seem to be over the threshold. first of all I though it is a metrics server issue but I did upgrade it and tried to do scaling policies but without luck to fix the issue. Any update please?

I did it using Keda autoscalling instead of default HPA

I moved from k8s to EKS on AWS, with 3 clusters, one of them 1.28 and two 1.29

Please reach out to AWS/EKS support @IgalSc

@max-rocket-internet I’ve been following #78761 since I experienced the same problem before and I agree that this should be treated as a bug.

While the selector conflict may be seen as a configuration bug on the part of the operator, and easily worked around by ensuring a minimal set of unique selectors between all Deployments of a given namespace, e.g. I always include app.kubernetes.io/component so I can differentiate between several processes from the same application, the selection behavior of the HPA controller does not match the Deployment/ReplicaSet controllers behaviors.

I did a quick look at the code and found out that the autoscaler controller uses Deployments /scale API to retrieve the selectors, which pretty much returns the selectors from the Deployment.spec.selectors right now. I believe this API should include the pod-template-hash label from the most recent fully progressed ReplicaSet in the .status.selector field. This would ensure the autoscaling controller is only selecting pods from the most recent healthy version and constrained to the referenced Deployment. I’m unsure if pod-template-hash can include the same value in some cases.

The side-effect I can think off with the addition of pod-template-hash on the scale selector is the HPA controller fighting the Deployment controller replica count reductions during rollout progressions, which might take a while to complete on Deployments with large number of replica.

i got the same issue

I solved my problem like this

behavior:
    scaleDown:
      stabilizationWindowSeconds: 0
      policies:
      - type: Pods
        value: 1
        periodSeconds: 60
      selectPolicy: Min

Spoke with @adrianmoisey (who also raised this in #124307) and will open a KEP to explore how to solve this issue. /assign

Wow. Keda. Gracias, @gsGabriel Here is a YouTube video from the DevOps Toolkit about Keda https://youtu.be/3lcaawKAv6s?si=qWZ2as6AixzH_6EN

leave a trace here…

got same issue with this, in GKE 1.28

the fix is to update the deployments .spec.selector.matchLabels as mentioned in the below comment

If it is caused by spec.selector.matchLabels labels of Deployment/application-one-ar matching pods outside of that deployment, then this is quite disappointing:

  • It’s very poor UX to see the metric presented as way under the target but still desiredReplicas=maxReplicas. This makes no sense to a user.
  • This issue seems to be over 4 years old, constant comments in that issue also
  • I think it’s mentioned in the docs here but I think many users are unlikely to fully understand what is written and the implication of it

As I said here (3 years ago!):

The HPA scaleTargetRef uses deployment by name and that should be enough without having to worry about selectors.

I think this comment is still valid because from a user perspective a deployment is specified by name but underneath the pods are selected by something (potentially) totally different. This is kind of an obfuscation.

At a minimum, do you think a feature request to show this situation loud and clear in the status of the HorizontalPodAutoscaler would be valid?

hopefully help and clarify others that jumping here recently…

Same issue here… The pods are below 80%, but they are not scaling down. 80% of 6GiB is approximately 4915.2MB, which should trigger scaling up. However, since the pods are below this value, the HPA (Horizontal Pod Autoscaler) should be scaling down.

image

I moved from k8s to EKS on AWS, with 3 clusters, one of them 1.28 and two 1.29 hpa autoscaling/v2, same behaviour on all three

To maybe help the conversation, I was investigating on that matter as well for the last 4 hours. I’m using minikube and I’m fairly new to k8s. For my case I have an app that scaled on CPU utilization only. It needed 5-10 minutes to scale back to minimum replicas but eventually it did.

Commenting on my previous statement - the moment the deployment scales up, the hpa does not scale it down until the spec.replicas is removed again

So it’s not resolved for you then.