☁️ Cloud

KEDA

Kubernetes Event-driven Autoscaling

A Kubernetes component for event-driven autoscaling

📖 Detailed Explanation

KEDA (Kubernetes Event-driven Autoscaling) is an open-source component that scales Kubernetes workloads based on external event sources. It was jointly developed by Microsoft and Red Hat, and has Graduated status as a CNCF project. Unlike the default HPA, which supports only CPU/memory, KEDA supports more than 60 event sources (Scalers).

Key features include Scale to Zero. When there are no events, it reduces Pods to 0 to cut costs. When a message arrives in a message queue, it creates Pods, and when processing is finished, it scales back down to 0. This makes it possible to implement an operating model similar to serverless on Kubernetes.

Supported event sources are very diverse. Message queues: Kafka, RabbitMQ, AWS SQS, Azure Service Bus, Google Pub/Sub. Databases: PostgreSQL, MySQL, MongoDB, Redis. Metrics: Prometheus, Datadog, New Relic. Cloud services: AWS CloudWatch, Azure Monitor, GCP Stackdriver. Schedule: Cron-based scaling is also possible.

The architecture consists broadly of three components. keda-operator watches the ScaledObject and ScaledJob CRDs and creates/manages HPAs. keda-metrics-apiserver exposes external metrics as the Kubernetes metrics API. Scaler collects metrics from each event source.

💻 Code Example

# KEDA 설치 (Helm)
helm repo add kedacore https://kedacore.github.io/charts
helm repo update
helm install keda kedacore/keda \
    --namespace keda \
    --create-namespace \
    --set prometheus.metricServer.enabled=true

# Kafka Consumer ScaledObject
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: kafka-consumer-scaler
  namespace: production
spec:
  scaleTargetRef:
    name: order-processor          # Deployment 이름
  pollingInterval: 15              # 메트릭 확인 주기 (초)
  cooldownPeriod: 300              # 스케일 다운 대기 시간
  minReplicaCount: 0               # Scale to Zero 활성화
  maxReplicaCount: 50              # 최대 Pod 수
  fallback:
    failureThreshold: 3            # 스케일러 오류 시
    replicas: 2                    # 폴백 replica 수
  triggers:
    - type: kafka
      metadata:
        bootstrapServers: kafka-cluster:9092
        consumerGroup: order-consumer-group
        topic: orders
        lagThreshold: "100"        # Consumer Lag 임계값
        offsetResetPolicy: earliest
      authenticationRef:
        name: kafka-credentials

---
# Kafka 인증 정보
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
  name: kafka-credentials
  namespace: production
spec:
  secretTargetRef:
    - parameter: sasl
      name: kafka-secrets
      key: sasl-mechanism
    - parameter: username
      name: kafka-secrets
      key: username
    - parameter: password
      name: kafka-secrets
      key: password

---
# Consumer Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-processor
  namespace: production
spec:
  replicas: 0                      # KEDA가 관리하므로 0으로 시작
  selector:
    matchLabels:
      app: order-processor
  template:
    metadata:
      labels:
        app: order-processor
    spec:
      terminationGracePeriodSeconds: 60
      containers:
        - name: processor
          image: myapp/order-processor:v1.2.0
          resources:
            requests:
              cpu: "200m"
              memory: "256Mi"
            limits:
              cpu: "500m"
              memory: "512Mi"
          env:
            - name: KAFKA_BROKERS
              value: "kafka-cluster:9092"
            - name: CONSUMER_GROUP
              value: "order-consumer-group"
# AWS SQS ScaledObject
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: sqs-processor-scaler
  namespace: production
spec:
  scaleTargetRef:
    name: sqs-processor
  minReplicaCount: 0
  maxReplicaCount: 30
  triggers:
    - type: aws-sqs-queue
      metadata:
        queueURL: https://sqs.ap-northeast-2.amazonaws.com/123456789/order-queue
        queueLength: "5"           # 메시지 5개당 Pod 1개
        awsRegion: ap-northeast-2
        scaleOnInFlight: "true"    # 처리 중 메시지도 카운트
      authenticationRef:
        name: aws-credentials

---
# IRSA (IAM Roles for Service Accounts) 인증
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
  name: aws-credentials
  namespace: production
spec:
  podIdentity:
    provider: aws-eks              # EKS Pod Identity 사용

---
# ScaledJob: 일회성 작업에 적합
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
  name: image-processor-job
  namespace: batch
spec:
  jobTargetRef:
    parallelism: 1
    completions: 1
    backoffLimit: 3
    template:
      spec:
        restartPolicy: Never
        containers:
          - name: processor
            image: myapp/image-processor:v2.0
            resources:
              requests:
                cpu: "1"
                memory: "2Gi"
  pollingInterval: 10
  minReplicaCount: 0
  maxReplicaCount: 100
  successfulJobsHistoryLimit: 5
  failedJobsHistoryLimit: 5
  triggers:
    - type: aws-sqs-queue
      metadata:
        queueURL: https://sqs.ap-northeast-2.amazonaws.com/123456789/image-queue
        queueLength: "1"           # 메시지 1개당 Job 1개
        awsRegion: ap-northeast-2
      authenticationRef:
        name: aws-credentials

---
# 멀티 트리거 예제 (SQS + Cron)
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: hybrid-scaler
spec:
  scaleTargetRef:
    name: hybrid-processor
  minReplicaCount: 0
  maxReplicaCount: 20
  triggers:
    # SQS 기반 스케일링
    - type: aws-sqs-queue
      metadata:
        queueURL: https://sqs.ap-northeast-2.amazonaws.com/123456789/tasks
        queueLength: "10"
      authenticationRef:
        name: aws-credentials
    # 업무 시간 최소 유지 (9시~18시)
    - type: cron
      metadata:
        timezone: Asia/Seoul
        start: 0 9 * * 1-5         # 월-금 09:00
        end: 0 18 * * 1-5          # 월-금 18:00
        desiredReplicas: "3"       # 최소 3개 유지
# Prometheus 메트릭 기반 스케일링
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: prometheus-scaler
  namespace: production
spec:
  scaleTargetRef:
    name: api-gateway
  minReplicaCount: 2
  maxReplicaCount: 50
  triggers:
    - type: prometheus
      metadata:
        serverAddress: http://prometheus.monitoring.svc:9090
        metricName: http_requests_per_second
        threshold: "100"           # Pod당 100 RPS
        query: |
          sum(rate(http_requests_total{
            namespace="production",
            service="api-gateway"
          }[2m]))
        ignoreNullValues: "false"

---
# HTTP Request 수 기반 (Prometheus + Ingress 메트릭)
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: ingress-based-scaler
spec:
  scaleTargetRef:
    name: web-frontend
  minReplicaCount: 3
  maxReplicaCount: 100
  advanced:
    horizontalPodAutoscalerConfig:
      behavior:
        scaleDown:
          stabilizationWindowSeconds: 300
          policies:
            - type: Percent
              value: 10
              periodSeconds: 60
        scaleUp:
          stabilizationWindowSeconds: 0
          policies:
            - type: Pods
              value: 4
              periodSeconds: 15
  triggers:
    - type: prometheus
      metadata:
        serverAddress: http://prometheus.monitoring:9090
        threshold: "50"
        query: |
          sum(rate(nginx_ingress_controller_requests{
            namespace="production",
            ingress="web-frontend"
          }[1m])) /
          count(kube_pod_status_ready{
            namespace="production",
            pod=~"web-frontend.*"
          } == 1)

---
# Redis List 기반 스케일링
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: redis-worker-scaler
spec:
  scaleTargetRef:
    name: background-worker
  minReplicaCount: 0
  maxReplicaCount: 20
  triggers:
    - type: redis
      metadata:
        address: redis-master.cache:6379
        listName: job_queue
        listLength: "10"           # 10개 항목당 Pod 1개
        activationListLength: "1"  # 1개 이상이면 스케일업 시작
        databaseIndex: "0"
      authenticationRef:
        name: redis-auth

---
# 스케일링 상태 확인 명령어
# kubectl get scaledobject -A
# kubectl describe scaledobject kafka-consumer-scaler -n production
# kubectl get hpa -n production  # KEDA가 생성한 HPA 확인
# kubectl logs -n keda -l app=keda-operator  # KEDA 로그

💬 How It's Used in Practice

Architecture Design Meeting

PM: "During peak hours, Kafka lag keeps building up in the order processing system. We're using HPA, but since it's CPU-based, the response seems slow."

DevOps: "If we switch to KEDA, we can use Kafka consumer lag directly as a trigger. If the lag is 100 or more, we add Pods, and when it reaches 0, Scale to Zero is also possible. It automatically scales down to 0 at night, which also saves costs. If we configure KEDA to monitor the consumer group lag directly in the current system, it will respond much faster than with CPU-based scaling."

Interview Questions

Interviewer: "Could you explain the differences between KEDA and the default HPA, and when do you choose KEDA?"

Candidate: "The default HPA requires resource metrics such as CPU and memory, or a custom metrics server. The major differences are that KEDA natively supports more than 60 external event sources and can Scale to Zero. I choose KEDA for message-queue-based workers or batch processing, where resources need to be fully reclaimed when there are no events, or when scaling has to be based on metrics from an external service. In practice, I have applied KEDA to an SQS consumer and cut nighttime costs by 80%."

Troubleshooting

Developer: "I deployed a KEDA ScaledObject, but the Pods aren't scaling up. The HPA wasn't created either."

SRE: "First, check the Status with kubectl describe scaledobject. It's likely a Scaler connection failure. Check whether TriggerAuthentication is configured correctly and whether the Secret is in the same namespace. If the KEDA operator logs show an 'unable to get metrics' error, it's an authentication issue. For AWS SQS, check the IRSA configuration, and for Kafka, check the SASL authentication information."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

❌

Ignoring Cold Start with Scale to Zero

When minReplicaCount: 0 is set, the first event is processed with a delay. It can take tens of seconds for Pod startup, container initialization, and connection establishment. If real-time responsiveness matters, set minReplicaCount to 1 or higher, or adjust activationValue.

❌

Applying HPA and KEDA Together

Applying both an HPA and a KEDA ScaledObject to the same Deployment causes a conflict. Since KEDA creates an HPA internally, if an HPA already exists, delete it and use only KEDA. You can customize HPA behavior with advanced.horizontalPodAutoscalerConfig.

✅

Preparing for Failures with Fallback Settings

Scaling may stop when an external event source fails. Use the fallback setting to specify the number of replicas to maintain when a scaler error occurs. Setting failureThreshold and replicas guarantees minimum availability even when metric collection fails.

🔗 Related Terms

📚 Learn More