Education › OSS Deep Dives › Stage 1: GitOps & platform engineering

KEDA: event-driven autoscaling

ScaledObjects and ScaledJobs, scalers and triggers, scale to zero, and how KEDA plugs into the Horizontal Pod Autoscaler.

Intermediate ~30 min read Module 2 of 10

The Horizontal Pod Autoscaler scales on CPU and memory, but a queue worker is busy when its queue is long, not when its CPU is hot, and an idle worker should cost nothing. KEDA, a graduated CNCF project in kedacore/keda, adds event-driven scaling to Kubernetes: scale on queue length, consumer lag, a Prometheus query or a schedule, all the way down to zero and back up. This lesson covers how it works, the two resources you write, and the settings that decide whether scaling is smooth or flappy.

After this module you can
  • Explain how KEDA's operator and metrics server cooperate with the HPA
  • Write a ScaledObject that scales a Deployment on queue lag or a Prometheus query
  • Choose between a ScaledObject and a ScaledJob for long-running work
  • Set activation thresholds, cooldown and fallback so scaling is predictable
  • Authenticate scalers with TriggerAuthentication instead of inline secrets

How KEDA works: it feeds the HPA, it does not replace it

The cmd/ folder of the repository builds three binaries. The operator watches your KEDA resources, creates a normal HPA for each one, and handles the special case the HPA cannot: scaling between zero and one replica. The metrics adapter (the KEDA metrics server) registers as a Kubernetes external metrics API, so when the HPA asks "what is the value of this metric?" the answer comes from KEDA. The admission webhooks reject invalid objects, such as two ScaledObjects targeting the same Deployment.

The knowledge of each event source lives in pkg/scalers/: one Go file per scaler, about seventy of them covering Kafka, RabbitMQ, SQS, Azure Service Bus, Redis streams, PostgreSQL queries, Prometheus, Cron and many more. A scaler answers two questions: is there any work at all (activation), and how much (the metric value).

  • Activation phase (0 to 1, 1 to 0): the operator decides, using the scaler's activation check.
  • Scaling phase (1 to N): the HPA decides, using the metric KEDA exposes and the target you set.
  • Because the HPA does the 1-to-N maths, everything you know about HPA behaviour, stabilization windows and policies still applies.
pollactivate 0 to 1read metricmetric value?scale 1 to NEvent sourcequeue, lag, PromQLKEDA operatorscalers, 0 to 1Deployment0 .. N podsMetrics serverKEDA, external APIHPAkeda-hpa-NAME
KEDA wakes a workload from zero itself, then hands one-to-N scaling to an ordinary HPA that reads the event metric through KEDA's metrics server.
Note

Install with Helm: helm repo add kedacore https://kedacore.github.io/charts, then helm install keda kedacore/keda --namespace keda --create-namespace. You get the CRDs, the operator, the metrics server and the webhooks.

ScaledObject: scale a Deployment on events

A ScaledObject points at a Deployment, StatefulSet, or any custom resource with a /scale subresource, and lists one or more triggers. Here an order processor scales on Kafka consumer lag: one replica per 50 pending messages, up to 30, and zero when the topic is drained.

Scale on Kafka lag, down to zero
yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: orders-worker
spec:
  scaleTargetRef:
    name: orders-worker
  minReplicaCount: 0
  maxReplicaCount: 30
  pollingInterval: 15
  cooldownPeriod: 300
  triggers:
    - type: kafka
      metadata:
        bootstrapServers: kafka.data.svc:9092
        consumerGroup: orders
        topic: orders
        lagThreshold: "50"
        activationLagThreshold: "5"

The defaults matter: pollingInterval is 30 seconds (how often KEDA checks the source while idle), cooldownPeriod is 300 seconds (how long after the last activity before scaling back to zero), minReplicaCount is 0 and maxReplicaCount is 100. cooldownPeriod only governs the step to zero; scale-in between N and 1 follows the HPA's own stabilization window.

The Prometheus scaler makes KEDA useful far beyond queues. For LLM serving, the right signal is usually requests waiting in the engine's queue, not GPU utilisation, which is high whenever a GPU is in use at all.

Scale an inference Deployment on queued requests
yaml
triggers:
  - type: prometheus
    metadata:
      serverAddress: http://prometheus.monitoring.svc:9090
      query: sum(vllm:num_requests_waiting{model_name="chat"})
      threshold: "4"
      activationThreshold: "1"

ScaledJob: one Job per piece of work

Scaling a Deployment down kills pods, possibly in the middle of a message. For long-running tasks such as video transcoding, batch inference or a nightly training run, that is unacceptable. A ScaledJob creates Kubernetes Jobs instead: each Job takes one or a few items, runs to completion and exits, and nothing is killed to scale in.

Spawn transcoding Jobs from an SQS queue
yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
  name: transcode
spec:
  jobTargetRef:
    backoffLimit: 2
    template:
      spec:
        restartPolicy: Never
        containers:
          - name: worker
            image: ghcr.io/example/transcode:2.3.1
  pollingInterval: 20
  maxReplicaCount: 50
  successfulJobsHistoryLimit: 5
  failedJobsHistoryLimit: 5
  triggers:
    - type: aws-sqs-queue
      authenticationRef:
        name: sqs-auth
      metadata:
        queueURL: https://sqs.eu-west-1.amazonaws.com/123456789012/videos
        queueLength: "1"
        awsRegion: eu-west-1

Set the history limits: both default to 100, and a busy queue otherwise leaves hundreds of finished Job objects behind. The scalingStrategy block (default, custom, accurate, eager) controls how pending messages and already-running Jobs are counted, which matters when your Jobs take items off the queue slowly.

Credentials, thresholds and failure modes

Scalers need to read the queue, so they need credentials. Never put them in trigger metadata. A TriggerAuthentication (namespaced) or ClusterTriggerAuthentication maps scaler parameters to Kubernetes Secrets, or better, to workload identity on your cloud so no long-lived key exists.

Credentials from a Secret, referenced by the trigger
yaml
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
  name: rabbitmq-auth
spec:
  secretTargetRef:
    - parameter: host
      name: rabbitmq-conn
      key: url
  • Flapping between 0 and 1: set an activation threshold above zero so a single stray message does not wake the workload, and lengthen cooldownPeriod.
  • Source unreachable: without a fallback, an erroring scaler leaves you at whatever count you had. With fallback: {failureThreshold: 3, replicas: 6}, KEDA holds a safe replica count after three failed checks.
  • Maintenance: the autoscaling.keda.sh/paused: "true" annotation freezes scaling; paused-replicas pins a fixed count.
  • Two autoscalers: do not also create your own HPA for the same target. KEDA owns the HPA it generates, named keda-hpa- plus the ScaledObject name.
  • Cold start: scaling from zero takes pod scheduling plus image pull plus app start. If the first request must be fast, keep minReplicaCount: 1.
Hands-on practice

Scale a worker to zero and back with a Redis list

  1. Create a kind or k3d cluster and install KEDA with the Helm commands above; check that the operator and metrics server pods are Running in the keda namespace.
  2. Deploy Redis (kubectl create deployment redis --image=redis:7 and expose it as a Service on port 6379).
  3. Deploy a worker Deployment that runs redis-cli -h redis BLPOP jobs 0 in a loop with sleep 2 after each item.
  4. Apply a ScaledObject with a redis trigger with address: redis.default.svc:6379, listName: jobs, listLength: "5", minReplicaCount: 0, cooldownPeriod: 60.
  5. Run kubectl get deploy worker -w in one terminal, push 100 items with redis-cli RPUSH in a loop in another, and watch replicas rise.
  6. Run kubectl get hpa and find the HPA that KEDA generated for you.
  7. Stop pushing and watch the worker drain the list, then return to zero about a minute later.
Cheat sheet

KEDA: event-driven autoscaling — at a glance

Main things to focus on

  • KEDA does 0 to 1 itself and hands 1 to N to a normal HPA it creates.
  • Pick the signal that measures waiting work: queue length, consumer lag, queued requests.
  • ScaledObject for long-lived consumers; ScaledJob when work must not be interrupted.
  • Activation threshold decides waking up; threshold decides how many replicas.
  • Keep credentials in TriggerAuthentication, ideally backed by workload identity.
  • Plan for the scaler failing: set fallback replicas.

Install and inspect

helm repo add kedacore https://kedacore.github.io/chartsAdd the KEDA chart repository
helm install keda kedacore/keda -n keda --create-namespaceInstall operator, metrics server, webhooks
kubectl get scaledobject,scaledjob -AList KEDA resources and their READY/ACTIVE state
kubectl get hpa keda-hpa-NAMEThe HPA KEDA generated for a ScaledObject
kubectl logs -n keda deploy/keda-operatorScaler errors and scaling decisions

ScaledObject fields (defaults)

pollingInterval: 30Seconds between checks of the event source
cooldownPeriod: 300Seconds after last activity before scaling to zero
minReplicaCount: 0 / maxReplicaCount: 100Replica bounds
fallback: {failureThreshold: 3, replicas: 6}Replicas to hold when the scaler keeps failing
advanced.horizontalPodAutoscalerConfig.behaviorPass HPA scale-up/scale-down policies through

Common triggers

type: kafka lagThreshold: "50"Consumer group lag per replica
type: rabbitmq mode: QueueLength value: "20"Messages per replica
type: prometheus query: ... threshold: "4"Any PromQL that returns one value
type: cron start: 0 8 * * 1-5 end: 0 18 * * 1-5Scheduled capacity (plus timezone, desiredReplicas)

Annotations

autoscaling.keda.sh/paused: "true"Freeze scaling at the current count
autoscaling.keda.sh/paused-replicas: "0"Scale to a fixed count and freeze
autoscaling.keda.sh/paused-scale-in: "true"Allow scale out but block scale in

Common pitfalls

  • Creating your own HPA for a workload KEDA already scales, so two controllers fight.
  • Scaling queue consumers on CPU, which stays low while the backlog grows.
  • Using a ScaledObject for hour-long tasks and killing them mid-run on scale-in.
  • Leaving activation thresholds at zero so a single message wakes the whole fleet.
  • Hard-coding broker passwords in trigger metadata instead of a TriggerAuthentication.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →