Skip to content

KEDA: autoscale Kubernetes workloads on queue depth, not CPU

KEDA (Kubernetes Event-Driven Autoscaling) adds and removes worker pods based on how much work is waiting, such as messages in a RabbitMQ queue or the result of a Prometheus query. Set it up on your cluster, scale a worker Deployment on queue depth, and let it drop to zero replicas when the queue is empty.

KEDA (Kubernetes Event-Driven Autoscaling) is a small add-on that scales your pods on how much work is waiting, not on how busy the CPU is. It suits teams running queue workers or background jobs whose CPU stays low while a backlog grows. KEDA reads the event source directly, such as RabbitMQ queue length, a Prometheus query, Kafka consumer lag or a cron window. It passes that number to the Horizontal Pod Autoscaler (HPA), the built-in Kubernetes controller that adds and removes pods. KEDA can also take a workload down to zero replicas when there is no work. You’ll install KEDA with Helm and write a ScaledObject, the KEDA resource that ties a Deployment to its triggers, to scale a worker on queue depth. Then you’ll add a Prometheus trigger and pass broker credentials through a TriggerAuthentication, which keeps the broker URL out of your manifest. You’ll also learn to read kubectl get scaledobject and tell whether KEDA is working, idle or quietly failing.

What you’ll accomplish

  • Install KEDA with Helm and confirm its metrics adapter is registered with the API server.
  • Scale a Deployment on RabbitMQ queue depth using a ScaledObject instead of CPU.
  • Run at minReplicaCount: 0 and understand why KEDA — not the HPA — owns the 0 ↔ 1 transition.
  • Pass scaler credentials through a TriggerAuthentication instead of embedding a broker URL in the manifest.
  • Tune pollingInterval, cooldownPeriod and activation thresholds so the workload reacts without flapping.

Prerequisites

  • A Kubernetes cluster and an account that can install CRDs, ClusterRoles and an APIService. KEDA is a cluster-scoped install even if you only scale one namespace.
  • A currently supported Kubernetes version, plus Helm 3. Each KEDA 2.x release supports a narrow window of cluster versions, so check the compatibility table in the KEDA documentation before picking a chart version. The API server’s aggregation layer must be enabled; on every managed offering it already is.
  • A pull-based worker Deployment. This guide uses a Deployment named worker in namespace workers, consuming a RabbitMQ queue named jobs. Your workers must tolerate being killed mid-flight: acknowledge messages only after the work is done, and handle SIGTERM by finishing the current message and exiting.
  • Familiarity with the ordinary HPA. KEDA builds on it rather than replacing it, so setting up a Horizontal Pod Autoscaler is worth reading first if autoscaling/v2 is new to you.
  • No existing HPA already targeting that Deployment. KEDA creates and owns its own HPA, and it will refuse to proceed if another one is already attached.

How it works

KEDA is not a replacement autoscaler. It is a metrics source plus a small controller that drives the HPA you already have.

KEDA control loop: the operator polls the event source, the metrics adapter serves an external metric to a managed HPA that scales the Deployment, with a separate direct path for the 0 to 1 activation

Installing the chart gives you two workloads that matter. The operator watches ScaledObject resources and, for each one, connects to the configured event source on every pollingInterval to ask a single question: what is the current value, and is this trigger active at all? The metrics adapter registers itself as the cluster’s provider for external.metrics.k8s.io and republishes those values as external metrics.

When you create a ScaledObject, the operator creates a HorizontalPodAutoscaler named keda-hpa-<scaledobject-name> whose metric is of type: External. From there the arithmetic is the same HPA arithmetic as always: with a RabbitMQ trigger in mode: QueueLength and value: "20", twenty messages per replica is the target, so 1,200 queued messages asks for ceil(1200 / 20) = 60 replicas, clamped to your maxReplicaCount.

The interesting part is the transition a plain HPA cannot make. An HPA’s minReplicas cannot be zero on a stock cluster — scaling to zero sits behind an alpha feature gate that most clusters do not enable. So KEDA sets the managed HPA’s minReplicas to at least 1 and handles the edges itself: when every trigger has reported inactive continuously for cooldownPeriod, the operator sets the Deployment’s replicas to 0 directly; when a trigger crosses its activation threshold, the operator scales it back to 1 and hands control to the HPA for everything above that. That is why minReplicaCount: 0 works here and minReplicas: 0 does not work in a bare HPA.

Step-by-step

1. Install KEDA with Helm. The chart installs the CRDs, the operator, the metrics adapter and the admission webhooks into a dedicated namespace.

helm repo add kedacore https://kedacore.github.io/charts
helm repo update
helm install keda kedacore/keda --namespace keda --create-namespace
NAME: keda
LAST DEPLOYED: Tue Aug  4 09:12:44 2026
NAMESPACE: keda
STATUS: deployed
REVISION: 1

Confirm all three components reached Running:

kubectl get pods -n keda
NAME                                               READY   STATUS    RESTARTS   AGE
keda-admission-webhooks-6d8b7c9f4d-hq2vr           1/1     Running   0          58s
keda-operator-5f7c4b8d9c-t7wnl                     1/1     Running   0          58s
keda-operator-metrics-apiserver-79c8d5b7c8-4rz9k   1/1     Running   0          58s

2. Verify the metrics adapter is registered. This is the step people skip, and it is the reason a ScaledObject can look perfectly healthy while no scaling happens. Only one component in a cluster can serve external.metrics.k8s.io:

kubectl get apiservice v1beta1.external.metrics.k8s.io
NAME                              SERVICE                                AVAILABLE   AGE
v1beta1.external.metrics.k8s.io   keda/keda-operator-metrics-apiserver   True        71s

If SERVICE names something other than KEDA — monitoring/prometheus-adapter, most often — you have a conflict to resolve before going further.

3. Store the broker credentials and reference them from a TriggerAuthentication. Do not put an AMQP URI with a password inside the ScaledObject; that resource is read by anyone with list access to the namespace. Put it in a Secret:

kubectl create secret generic rabbitmq-conn -n workers \
  --from-literal=host='amqp://worker:CHANGE_ME@rabbitmq.messaging.svc.cluster.local:5672/'
secret/rabbitmq-conn created

Then map the Secret key onto the scaler parameter it satisfies. For the RabbitMQ scaler that parameter is named host:

apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
  name: rabbitmq-auth
  namespace: workers
spec:
  secretTargetRef:
    - parameter: host
      name: rabbitmq-conn
      key: host
kubectl apply -f rabbitmq-auth.yaml
kubectl get triggerauthentication rabbitmq-auth -n workers \
  -o jsonpath='{.spec.secretTargetRef[0].name}{"\n"}'
rabbitmq-conn

A TriggerAuthentication is namespaced and must live in the same namespace as the ScaledObject that references it. If you need one set of credentials shared across namespaces, use a ClusterTriggerAuthentication and set kind: ClusterTriggerAuthentication inside the authenticationRef.

4. Write the ScaledObject. This is the whole configuration: what to scale, between which bounds, and on which signal.

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: worker-scaler
  namespace: workers
spec:
  scaleTargetRef:
    name: worker
  minReplicaCount: 0
  maxReplicaCount: 20
  pollingInterval: 15
  cooldownPeriod: 120
  triggers:
    - type: rabbitmq
      metadata:
        protocol: amqp
        queueName: jobs
        mode: QueueLength
        value: "20"
        activationValue: "5"
      authenticationRef:
        name: rabbitmq-auth
kubectl apply -f worker-scaledobject.yaml
kubectl get scaledobject -n workers
NAME            SCALETARGETKIND      SCALETARGETNAME   MIN   MAX   TRIGGERS   AUTHENTICATION   READY   ACTIVE   FALLBACK   AGE
worker-scaler   apps/v1.Deployment   worker            0     20    rabbitmq   rabbitmq-auth    True    False    False      18s

READY True means KEDA connected to RabbitMQ and the scaler is functioning. ACTIVE False means the queue is below activationValue, so the Deployment is being held at zero. That pair of columns is the fastest health check you have.

5. Confirm the managed HPA exists. KEDA created it for you, and you should never edit it by hand — the operator reconciles it back to whatever the ScaledObject says:

kubectl get hpa -n workers
NAME                     REFERENCE           TARGETS      MINPODS   MAXPODS   REPLICAS   AGE
keda-hpa-worker-scaler   Deployment/worker   0/20 (avg)   1          20        0          24s

Note MINPODS is 1 even though you asked for minReplicaCount: 0. That is the split described above: the HPA governs 1 and up, KEDA governs the step down to 0 and back.

6. Add a Prometheus trigger next to the queue trigger. A ScaledObject can carry several triggers; KEDA computes a desired replica count for each and takes the highest. This is useful when queue depth alone under-reacts — say, few messages but each one expensive:

  triggers:
    - type: rabbitmq
      metadata:
        protocol: amqp
        queueName: jobs
        mode: QueueLength
        value: "20"
        activationValue: "5"
      authenticationRef:
        name: rabbitmq-auth
    - type: prometheus
      metadata:
        serverAddress: http://prometheus-server.monitoring.svc.cluster.local
        query: sum(rate(job_seconds_total{app="worker"}[2m]))
        threshold: "30"
        activationThreshold: "1"

threshold is the per-replica target for the query result, exactly like value on the queue trigger. activationThreshold is the separate 0 → 1 gate. Apply it and re-check that READY is still True — a typo in a PromQL query shows up here as a scaler failure, not as a silent zero.

7. Tune the timings so it reacts without thrashing. Three settings do almost all the work, and they govern different things.

Timeline comparing a CPU-based HPA stuck at two replicas against KEDA scaling zero to eight and back to zero as queue depth rises and drains

pollingInterval (default 30 seconds) is how often the operator asks the scaler for a value. Dropping it to 10–15 seconds buys faster reaction at the cost of more queries against RabbitMQ or Prometheus. cooldownPeriod (default 300 seconds) applies only to the drop to zero: how long every trigger must stay inactive before the operator removes the last replica. Scaling in from eight replicas to one is not governed by cooldownPeriod at all — that is the HPA’s stabilization window, which you set through the advanced block:

  advanced:
    restoreToOriginalReplicaCount: true
    horizontalPodAutoscalerConfig:
      behavior:
        scaleDown:
          stabilizationWindowSeconds: 180
          policies:
            - type: Percent
              value: 50
              periodSeconds: 60

restoreToOriginalReplicaCount: true makes KEDA put the Deployment back to its pre-KEDA replica count if you delete the ScaledObject, rather than leaving it at zero — worth setting before anyone deletes one in production.

Validate it works

Start from a cold state and confirm the Deployment really is at zero:

kubectl get deployment worker -n workers
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
worker   0/0     0            0           14m

Check the queue agrees:

kubectl exec -n messaging rabbitmq-0 -- rabbitmqctl list_queues name messages
Timeout: 60.0 seconds ...
Listing queues for vhost / ...
name    messages
jobs    0

Now publish work — from your own producer, or from the RabbitMQ management UI’s Publish message form on the queue page. Push a few hundred messages, then watch two things in separate terminals:

kubectl get scaledobject worker-scaler -n workers -w

ACTIVE flips to True within one pollingInterval of the queue crossing activationValue:

NAME            READY   ACTIVE   FALLBACK   AGE
worker-scaler   True    False    False      14m
worker-scaler   True    True     False      14m
kubectl get deployment worker -n workers -w
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
worker   0/0     0            0           14m
worker   0/1     1            0           14m
worker   1/1     1            1           15m
worker   1/8     8            1           15m
worker   8/8     8            8           16m

The single-replica step is the KEDA activation; everything after it is the managed HPA doing the per-replica arithmetic. Confirm the sequence in the event stream:

kubectl get events -n workers --sort-by=.lastTimestamp | tail -5
2m    Normal   ScaledObjectReady          scaledobject/worker-scaler   ScaledObject is ready for scaling
90s   Normal   KEDAScaleTargetActivated   scaledobject/worker-scaler   Scaled apps/v1.Deployment workers/worker from 0 to 1
75s   Normal   SuccessfulRescale          horizontalpodautoscaler/keda-hpa-worker-scaler   New size: 8; reason: external metric above target

Now stop the producer and let the workers drain the queue. Replicas step down under the HPA’s stabilization window, hold at one, and only then — after cooldownPeriod of continuous inactivity — go to zero:

worker   8/8     8            8           22m
worker   4/4     4            4           25m
worker   1/1     1            1           27m
worker   0/0     0            0           29m

If you watched it go 0 → 1 → 8 → 1 → 0 against a queue you filled and drained, the loop is closed.

Troubleshooting

  • READY is False and nothing ever scales. The scaler cannot reach its event source. Run kubectl describe scaledobject worker-scaler -n workers and read the conditions and events; a KEDAScalerFailed event carries the underlying error verbatim. Then check the operator: kubectl logs -n keda deploy/keda-operator --tail=50. In practice this is a wrong Service DNS name, a missing vhost in the AMQP URI (the trailing / matters), or credentials that are valid for the management API but not for AMQP.
  • The Secret exists but the scaler still fails to authenticate. Three things must line up. The parameter value in the TriggerAuthentication has to be the name the scaler expects — host for RabbitMQ, not url or connectionString. The key has to match the Secret key exactly (kubectl get secret rabbitmq-conn -n workers -o jsonpath='{.data}' will tell you). And the TriggerAuthentication must be in the same namespace as the ScaledObject, unless you deliberately used a ClusterTriggerAuthentication and said so in authenticationRef.kind.
  • KEDA refuses the ScaledObject because an HPA already owns the Deployment. The admission webhook rejects the create with a message that the workload is already managed by another HPA, naming it. Two autoscalers writing the same spec.replicas fight each other, so this is a deliberate block, not a bug. Delete the old HPA — kubectl delete hpa web -n workers — and re-apply the ScaledObject. If you genuinely want CPU as well, express it as a cpu trigger inside the ScaledObject instead of keeping a separate HPA.
  • Replicas flap between zero and the maximum. Usually one of three causes. activationValue is too low, so a single leftover message wakes the whole pool — raise it above your normal background noise. cooldownPeriod is shorter than the gap between producer bursts, so the pool dies just before the next batch arrives. Or in-flight work is inflating the reading: the RabbitMQ scaler counts ready and unacknowledged messages by default, so long-running jobs keep the number high while they are being processed. Set excludeUnacknowledged: "true" on the trigger to count only messages that are actually waiting for a consumer.
  • External metrics are unavailable even though the ScaledObject is ready. Check kubectl get apiservice v1beta1.external.metrics.k8s.io — if AVAILABLE is False, or the backing service is Prometheus Adapter rather than KEDA, the HPA has no metric to read and will sit at MINPODS. Only one APIService can own external.metrics.k8s.io in a cluster; if you need both, move the Prometheus queries into KEDA as prometheus triggers and retire the other adapter. Confirm the API responds with kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1".

When this is the wrong approach

Scale-to-zero has a real cost: the first unit of work after an idle period waits for a Pod to be scheduled, an image to be pulled if it isn’t cached, the container to start and the runtime to warm up. For batch and background work that is a fine trade. For a latency-sensitive HTTP service it is not — keep minReplicaCount at one or more, or use idleReplicaCount to hold a warm floor outside business hours only.

If your workload’s CPU genuinely tracks its load, a plain HPA is fewer moving parts and one less controller to operate; the standard HPA setup is enough and KEDA adds nothing. KEDA earns its place specifically when the signal you care about lives outside the cluster.

KEDA also changes the desired replica count, never the available capacity. If Pods sit Pending because no node has room, you need Cluster Autoscaler or Karpenter underneath — an aggressive maxReplicaCount on a fixed node pool just produces a queue of unschedulable Pods. And for work where each item is a discrete unit that must not be interrupted mid-flight, ScaledJob is the better resource: it creates one Job per item rather than resizing a long-lived Deployment.

Finally, a scaler is a dependency: if RabbitMQ or Prometheus is unreachable, KEDA has no value to act on. The fallback block pins a fixed replica count once a scaler has failed a set number of times in a row — configure it rather than discovering the default behaviour during an incident. Broker resilience matters for the same reason; if your queues are still classic mirrored queues, migrating to quorum queues removes a failure mode that would otherwise take your autoscaling signal down with the broker.

The KEDA documentation carries the full parameter list for every scaler, and the KEDA source repository is where the exact metadata fields live when the docs are ambiguous.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.