Event-driven autoscaling with KEDA

Advanced · 28 min

Scaling workers on queue depth, lag or a schedule with KEDA: how a ScaledObject becomes an HPA on an external metric, activation, and scaling to zero.

Before thisThe Horizontal Pod AutoscalerJobs and CronJobs

CNCF [Cloud Native Computing Foundation] · 28 min

Event-driven autoscaling with KEDA

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CNCF [Cloud Native Computing Foundation]Report a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Queue workers should scale on the work waiting, not on CPU. A queue can grow for minutes while the busy workers' CPU stays flat.
  • KEDA doesn't replace the HPA. A ScaledObject makes KEDA create an HPA (keda-hpa-<name>) on an External metric that KEDA's metrics server answers from the event source.
  • For an AverageValue target the HPA wants ceil(metric / value) replicas: 42 messages at 5 per Pod is 9 Pods, reached in steps limited by the scale-up policy.
  • KEDA's own loop handles activation: it scales between 0 and 1 using activationValue and cooldownPeriod (300 s by default), and the HPA handles 1 to N.
  • A ScaledJob starts one Job per batch of events instead of scaling a Deployment, which suits long, interruptible-hostile tasks.
  • Credentials for event sources go in a TriggerAuthentication, which reads Secrets or workload identity rather than embedding passwords in the ScaledObject.

CPU is the wrong signal for a queue worker

An order-processing worker pulls messages from a queue, handles each in about a second, and pulls the next. At 3 a.m. the queue is empty. At 9 a.m. a batch import drops 40,000 messages into it. The workers keep going at exactly the same pace, so their CPU barely moves, and an HPA on CPU sees nothing to fix while the backlog takes hours to clear.

What you want to scale on is the work waiting: queue length, Kafka consumer lag, the number of pending jobs in a database, or the time of day. And when there is no work at all, ideally zero workers. KEDA (Kubernetes Event-driven Autoscaling), a CNCF graduated project, does both.

KEDA builds on the HPA

KEDA is an operator plus a metrics server. It doesn’t scale Pods itself between 1 and N. Instead:

  1. You create a ScaledObject naming a workload and one or more triggers.
  2. The KEDA operator creates an HPA for it, named keda-hpa-<name>, with an External metric per trigger.
  3. KEDA’s metrics server registers as external.metrics.k8s.io and answers the HPA’s queries by asking the event source, for example RabbitMQ’s management API.
  4. The normal HPA controller does the arithmetic and sets replicas.

A ScaledObject for the order worker, following KEDA 2.21’s docs:

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: worker
spec:
  scaleTargetRef:
    name: worker            # a Deployment
  minReplicaCount: 0
  maxReplicaCount: 20
  pollingInterval: 30       # seconds, the default
  cooldownPeriod: 300       # seconds, the default
  triggers:
  - type: rabbitmq
    metadata:
      queueName: orders
      mode: QueueLength
      value: "5"            # messages per replica
      activationValue: "0"
    authenticationRef:
      name: rabbitmq-auth   # a TriggerAuthentication holding the host URL

Watching the HPA half work

KEDA itself wasn’t installed here, but its second half is ordinary Kubernetes. I created the HPA KEDA generates for that ScaledObject and served the external metric from a small stand-in for KEDA’s metrics server, then let the lab’s real HPA controller act:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: keda-hpa-worker
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: worker}
  minReplicas: 1
  maxReplicas: 20
  metrics:
  - type: External
    external:
      metric:
        name: s0-rabbitmq-orders
        selector: {matchLabels: {scaledobject.keda.sh/name: worker}}
      target:
        type: AverageValue
        averageValue: "5"

With the queue at 42:

keda-hpa-worker   Deployment/worker   10500m/5 (avg)   1     20    4     16s
keda-hpa-worker   Deployment/worker   5250m/5 (avg)    1     20    8     32s
keda-hpa-worker   Deployment/worker   4667m/5 (avg)    1     20    9     48s

An AverageValue target divides the metric by the replica count: 42 messages over 4 Pods is 10.5 each, shown as 10500m. The goal is ceil(42 / 5) = 9. The steps 1 → 4 → 8 → 9 are the HPA’s scale-up limit, max(2 × current, 4) per sync with no behavior set.

Zero is KEDA’s job, mostly

An HPA historically couldn’t go below one replica, and with zero Pods there are no Pod metrics to compute from. KEDA covers that gap with its own loop: every pollingInterval it checks each trigger against activationValue. If any is active and the workload is at zero, KEDA scales it to one and lets the HPA take over. When every trigger has been inactive for cooldownPeriod, KEDA scales back to zero. The two thresholds are separate on purpose. activationValue decides whether to run at all, and value decides how many.

Upstream is catching up. The HPA’s minReplicas: 0 for Object and External metrics is beta and on by default in 1.37. On the lab cluster, with minReplicas: 0 and the queue empty, the plain HPA scaled worker to 0. When the queue went back to 42 it scaled 0 → 4 → 8 and stopped there: 42/8 = 5.25, within the 10% tolerance of 5. During the scale from zero, kubectl get hpa printed the per-Pod average as 9223372036854775807m, the largest 64-bit integer, because there were no Pods to divide by. KEDA still adds what the HPA lacks: dozens of scalers (the 2.21 docs list about 80) that know how to query brokers, databases and clouds, activation thresholds, and ScaledJobs.

ScaledJobs for long tasks

Scaling a Deployment down removes Pods, and a Pod halfway through a 40-minute video transcode loses its work. A ScaledJob creates Jobs instead, one per batch of pending events up to a limit, and each runs to completion. Nothing scales them down mid-task.

Practical notes

  • Credentials go in a TriggerAuthentication, which pulls values from Secrets, environment variables of the target or a cloud workload identity, never in trigger metadata.
  • Pick value from measured throughput. If one worker handles 5 messages a second and you want backlogs cleared in a minute, queue length divided by replicas should be about 300, not 5.
  • Several triggers, say queue length and a cron trigger for business hours, each produce a metric, and the HPA takes the largest desired count.
  • Scale-from-zero has latency: up to one polling interval plus Pod start-up. Keep a minimum of one replica for anything latency-sensitive.

About the video

The embed is Zbynek Roubalik and Jorge Turrado’s KubeCon Europe 2025 talk “KEDA: Unlocking Advanced Event-Driven Scaling for Kubernetes”, cut before the Q&A, about 28 minutes. Both are KEDA maintainers. Going by its chapters, it covers autoscaling with KEDA, a RabbitMQ scaling demo, the architecture, ScaledObjects and ScaledJobs, new features, best practices, a scaling-modifiers demo, production challenges and the HTTP add-on. I judged it from chapters and description only, since transcripts couldn’t be fetched. English was judged from the title, speakers and English caption track. The page shows no audio-language flag. KEDA has moved on to 2.21 since, so check new fields against the docs. Abhishek Veeramalla’s longer video in deeper starts from why the HPA isn’t enough and builds two demos.

What was run: the HPA outputs above, including scale to zero and back, came from the real HPA controller in a local Kubernetes v1.37.3 control plane whose nodes run no containers, with the external metric served by a small stand-in registered as external.metrics.k8s.io. KEDA’s operator was not run. The ScaledObject is from KEDA’s 2.21 docs. Defaults and the activation and polling logic were read from scaledobject_types.go and the scale executor in KEDA’s source (v2.21.1 was the latest release), checked 2026-11-28.

Where this fits

More Pods eventually need more nodes. Next: the Cluster Autoscaler and Karpenter.

Check yourself

  1. 01A RabbitMQ trigger has value: 5 and the queue holds 42 messages. How many replicas does the HPA aim for, and why might it get there in steps?

    ceil(42 / 5) = 9. The HPA caps how fast it scales up. With no behavior set that cap is max(2 × current, 4) per sync, so from 1 it goes 4, 8, 9.

  2. 02Your ScaledObject has minReplicaCount: 0. Who moves the Deployment from 0 to 1 when the first message arrives?

    KEDA's operator. It polls the trigger every pollingInterval, and when the metric exceeds activationValue it scales the target to 1 (or minReplicaCount). After that the HPA it created takes over.

  3. 03Why are workers scaled on CPU often slow to react to a backlog?

    Workers pulling from a queue run at a steady rate whatever the queue length, so their CPU barely changes while the backlog grows. The metric that tracks unmet demand is the queue depth or consumer lag.

  4. 04When would you choose a ScaledJob over a ScaledObject?

    When each unit of work is long-running and shouldn't be killed by a scale-down, such as video transcoding. A ScaledJob creates Jobs that run to completion, instead of resizing a Deployment whose Pods can be removed mid-task.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark