KEDA (Kubernetes Event-Driven Autoscaling) Cheatsheet¶
Installazione¶
Tabella_108_
Comandi di verifica¶
Tabella_109_
Comandi di base¶
Scaled Gestione degli oggetti¶
Tabella_110
Scaled Gestione del lavoro¶
Tabella_111
Authentication Management¶
Tabella_112_
Monitoraggio e stato¶
Tabella_113_
Uso avanzato¶
Scala avanzata Operazioni di oggetti¶
Tabella_114_
KEDA Gestione dell'operatore¶
Tabella_115
Metrics and Debugging¶
Tabella_116_
Multi-Trigger e Scenari complessi¶
Tabella_117_
Configurazione¶
Scala di base Configurazione degli oggetti¶
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: my-scaledobject
namespace: default
spec:
scaleTargetRef:
name: my-deployment # Target deployment name
minReplicaCount: 0 # Minimum replicas (0 for scale-to-zero)
maxReplicaCount: 10 # Maximum replicas
pollingInterval: 30 # Seconds between metric checks
cooldownPeriod: 300 # Seconds to wait after last trigger
triggers:
- type: prometheus # Scaler type
metadata:
serverAddress: http://prometheus:9090
metricName: http_requests_total
threshold: '100'
query: sum(rate(http_requests_total[2m]))
Scaled Oggetto con Trigger multipli¶
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: multi-trigger-scaler
spec:
scaleTargetRef:
name: api-deployment
minReplicaCount: 1
maxReplicaCount: 50
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus:9090
threshold: '100'
query: sum(rate(http_requests_total[2m]))
- type: cpu
metricType: Utilization
metadata:
value: "70"
- type: memory
metricType: Utilization
metadata:
value: "80"
Scaled Oggetto con Advanced HPA Behavior¶
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: advanced-scaling
spec:
scaleTargetRef:
name: worker-deployment
minReplicaCount: 2
maxReplicaCount: 100
advanced:
restoreToOriginalReplicaCount: true
horizontalPodAutoscalerConfig:
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50 # Scale down max 50% at a time
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100 # Scale up max 100% at a time
periodSeconds: 15
- type: Pods
value: 5 # Or add max 5 pods at a time
periodSeconds: 15
selectPolicy: Max # Use the policy that scales faster
triggers:
- type: kafka
metadata:
bootstrapServers: kafka:9092
consumerGroup: my-group
topic: events
lagThreshold: '10'
Scaled Configurazione del lavoro¶
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
name: batch-processor
spec:
jobTargetRef:
parallelism: 1
completions: 1
backoffLimit: 3
template:
spec:
containers:
- name: processor
image: myapp:latest
command: ["./process"]
restartPolicy: Never
pollingInterval: 30
maxReplicaCount: 10
successfulJobsHistoryLimit: 5
failedJobsHistoryLimit: 5
scalingStrategy:
strategy: "default" # or "custom", "accurate"
triggers:
- type: rabbitmq
metadata:
queueName: jobs
host: amqp://guest:guest@rabbitmq:5672
queueLength: '5'
TriggerAuthentication with Secret¶
apiVersion: v1
kind: Secret
metadata:
name: rabbitmq-secret
type: Opaque
stringData:
connection-string: "amqp://user:password@rabbitmq:5672"
---
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
name: rabbitmq-auth
spec:
secretTargetRef:
- parameter: host
name: rabbitmq-secret
key: connection-string
ClusterTriggerAutorizzazione con Pod Identity¶
apiVersion: keda.sh/v1alpha1
kind: ClusterTriggerAuthentication
metadata:
name: aws-credentials
spec:
podIdentity:
provider: aws-eks # or aws-kiam, azure, gcp
identityId: arn:aws:iam::123456789012:role/keda-role
Helm Installazione Valori¶
# values.yaml for Helm installation
operator:
replicaCount: 2 # HA setup
metricsServer:
replicaCount: 2 # HA setup
serviceAccount:
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::123456789012:role/keda-role
resources:
operator:
limits:
cpu: 1000m
memory: 1000Mi
requests:
cpu: 100m
memory: 100Mi
metricServer:
limits:
cpu: 1000m
memory: 1000Mi
requests:
cpu: 100m
memory: 100Mi
prometheus:
operator:
enabled: true
podMonitor:
enabled: true
metricServer:
enabled: true
podMonitor:
enabled: true
Common Use Cases¶
Use Case 1: RabbitMQ Bilanciatura basata su queue¶
Scale una distribuzione operaia basata su Rabbit Profondità della coda MQ:
# Create secret with RabbitMQ credentials
kubectl create secret generic rabbitmq-secret \
--from-literal=host='amqp://user:password@rabbitmq.default.svc.cluster.local:5672'
# Create TriggerAuthentication
kubectl apply -f - <<EOF
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
name: rabbitmq-auth
spec:
secretTargetRef:
- parameter: host
name: rabbitmq-secret
key: host
EOF
# Create ScaledObject
kubectl apply -f - <<EOF
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: rabbitmq-scaler
spec:
scaleTargetRef:
name: worker-deployment
minReplicaCount: 0
maxReplicaCount: 30
triggers:
- type: rabbitmq
metadata:
protocol: amqp
queueName: tasks
mode: QueueLength
value: '5'
authenticationRef:
name: rabbitmq-auth
EOF
# Monitor scaling
kubectl get scaledobject rabbitmq-scaler -w
kubectl get hpa
kubectl get deployment worker-deployment
Use Case 2: Kafka Consumer Group Lag Scaling¶
I consumatori di Scale Kafka basati sul merletto del gruppo di consumatori:
# Create ScaledObject for Kafka
kubectl apply -f - <<EOF
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: kafka-consumer-scaler
spec:
scaleTargetRef:
name: kafka-consumer
minReplicaCount: 1
maxReplicaCount: 50
triggers:
- type: kafka
metadata:
bootstrapServers: kafka.default.svc.cluster.local:9092
consumerGroup: my-consumer-group
topic: events
lagThreshold: '10'
offsetResetPolicy: latest
EOF
# Check scaling status
kubectl describe scaledobject kafka-consumer-scaler
kubectl get hpa keda-hpa-kafka-consumer-scaler
# View external metrics
kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/s0-kafka-my-consumer-group" | jq
Use Case 3: Prometheus Metrics-Based Scaling¶
Scala basata su personalizzato metriche Prometheus:
# Create ScaledObject with Prometheus trigger
kubectl apply -f - <<EOF
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: prometheus-scaler
spec:
scaleTargetRef:
name: api-server
minReplicaCount: 2
maxReplicaCount: 20
triggers:
- type: prometheus
metadata:
serverAddress: http://prometheus.monitoring.svc.cluster.local:9090
metricName: http_requests_per_second
threshold: '100'
query: |
sum(rate(http_requests_total{job="api-server"}[2m]))
EOF
# Verify Prometheus connectivity
kubectl logs -n keda deployment/keda-operator | grep prometheus
# Test scaling
kubectl get scaledobject prometheus-scaler -o jsonpath='{.status}'
Use Case 4: Cron-Based Scheduled Scaling¶
Carico di lavoro scala in base agli orari:
# Create ScaledObject with cron trigger for business hours
kubectl apply -f - <<EOF
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: scheduled-scaler
spec:
scaleTargetRef:
name: business-app
minReplicaCount: 1
maxReplicaCount: 1
triggers:
- type: cron
metadata:
timezone: America/New_York
start: 0 8 * * 1-5 # 8 AM Mon-Fri
end: 0 18 * * 1-5 # 6 PM Mon-Fri
desiredReplicas: "10"
- type: cron
metadata:
timezone: America/New_York
start: 0 18 * * 1-5 # 6 PM Mon-Fri
end: 0 8 * * 1-5 # 8 AM Mon-Fri
desiredReplicas: "2"
EOF
# Monitor scheduled scaling
kubectl get scaledobject scheduled-scaler -w
kubectl get events --field-selector involvedObject.name=scheduled-scaler
Use Case 5: AWS SQS Elaborazione di queue con lavoro scalato¶
Elaborare messaggi AWS SQS utilizzando lavori batch:
# Create ClusterTriggerAuthentication with AWS IAM
kubectl apply -f - <<EOF
apiVersion: keda.sh/v1alpha1
kind: ClusterTriggerAuthentication
metadata:
name: aws-credentials
spec:
podIdentity:
provider: aws-eks
EOF
# Create ScaledJob for SQS processing
kubectl apply -f - <<EOF
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
name: sqs-processor
spec:
jobTargetRef:
template:
spec:
containers:
- name: processor
image: my-sqs-processor:latest
env:
- name: QUEUE_URL
value: https://sqs.us-east-1.amazonaws.com/123456789012/my-queue
restartPolicy: Never
pollingInterval: 30
maxReplicaCount: 10
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
triggers:
- type: aws-sqs-queue
authenticationRef:
name: aws-credentials
kind: ClusterTriggerAuthentication
metadata:
queueURL: https://sqs.us-east-1.amazonaws.com/123456789012/my-queue
queueLength: '5'
awsRegion: us-east-1
EOF
# Monitor job creation
kubectl get scaledjob sqs-processor
kubectl get jobs -l scaledjob.keda.sh/name=sqs-processor
kubectl logs job/<job-name>
Migliori Pratiche¶
-
Start with Conservative Limits: Inizia con i valori
minReplicaCount: 1e moderatamaxReplicaCount__. Test scale-to-zero (minReplicaCount: 0) solo dopo aver convalidato le maniglie dell'applicazione inizia con grazia. -
Configure Appropriato Polling and Cooldown: Set
pollingInterval(default 30s) basato sulla frequenza di aggiornamento della sorgente metrica. Utilizzare più a lungocooldownPeriod_ (default 300s) per i carichi di lavoro con traffico variabile per evitare il ribaltamento. -
Utilizzare TriggerAuthentication for Secrets: Le credenziali di codice mai duro nelle specifiche di ScaledObject. Utilizzare sempre
TriggerAuthenticationoClusterTriggerAuthenticationcon i segreti Kubernetes o i fornitori di identità pod (AWS IAM, Azure AD, GCP Workload Identity). -
Attuazione delle politiche di comportamento HPA: Per i carichi di lavoro di produzione, configurare
advanced.horizontalPodAutoscalerConfig.behaviorper controllare i tassi di scale-up/scale-down. Prevenire scaling aggressivo con finestre di stabilizzazione e politiche basate sulla percentuale. -
Monitor KEDA Componenti: Distribuisci operatore KEDA e server metrici con almeno 2 repliche per alta disponibilità. Attivare il monitoraggio Prometheus e impostare avvisi per la salute dei componenti KEDA e guasti di scaling.
-
Set Resource Limits: Definire sempre richieste e limiti di risorse sia per i componenti KEDA che per i carichi di lavoro scalati. Questo impedisce la contention delle risorse e assicura il comportamento di scaling prevedibile.
-
Utilizza la configurazione di Fallback: Configure
fallback.replicasefallback.failureThresholdper mantenere la disponibilità di servizio quando non sono disponibili fonti metriche esterne. Ciò previene la scaling a zero durante le interruzioni di sorgente metriche. -
Test Scaling Behavior: Prima dell'implementazione della produzione, testare lo scaling sotto carico utilizzando l' annotazione di pausa (
autoscaling.keda.sh/paused-replicas) per convalidare le soglie di trigger e osservare i modelli di scaling senza influire sul traffico live. -
**Namespace Isolation ** Utilizzare spazi di nome separati per diversi ambienti (dev, staging, prod) e applicare politiche RBAC appropriate. Usa
ClusterTriggerAuthenticationper le credenziali condivise tra namespaces. -
Controllo di curvatura Oggetti: Conservare tutte le risorse KEDA in Git accanto ai manifesti di applicazione. Utilizzare gli strumenti GitOps (ArgoCD, Flux) per gestire le configurazioni KEDA e garantire la coerenza in ambienti.
Risoluzione dei problemi¶
Traduzione: Scaling too aggressive/slow | Adjust __INLINE_CODE_100_ (come spesso vengono controllate le metriche). Configurare H