How-to guide / Package task guides
Autoscale workloads with KEDA
These docs describe Kix's main branch, which can include changes not yet released. Read the docs for the latest release.
Use packages.experimental.keda to deploy KEDA 2.21.1 and autoscale
Deployments, StatefulSets, and Jobs from external metrics and event queues.
The package installs KEDA’s six CustomResourceDefinitions, the operator, the
metrics API server, and the admission webhooks. Upstream tests KEDA 2.21 on
Kubernetes 1.34 to 1.36; kix check warns if your cluster’s k8sVersion is
outside that range and continues the build. Because this package is
experimental, breaking changes may ship in any release.
Each cluster can run only one KEDA instance. kix check rejects a second
instance because Kubernetes serves only one v1beta1.external.metrics.k8s.io
APIService per cluster and the KEDA operator watches all namespaces.
Add KEDA to the cluster
Section titled “Add KEDA to the cluster”Add a keda instance to your cluster definition:
298 instances.keda.keda.package = packages.experimental.keda;This creates a keda instance in the keda namespace
(instances.<namespace>.<name>). Every option has a working default, and no
dependencies are required (the operator generates and rotates its own TLS
certificates, without cert-manager).
When the cluster has a prometheus provider (such as
packages.experimental.prometheus-operator or
packages.victoria-metrics-operator), Kix connects it to KEDA automatically
(deps.prometheus) and creates a metrics Service, a ServiceMonitor, and
Prometheus alert rules for the operator. Set config.metrics.enabled = false on
the KEDA instance to turn them off.
Under config, you can pass extra flags or environment variables with env and
extraArgs for the operator, metricsServer.extraArgs for the metrics API
server, and webhooks.extraArgs for the admission webhooks. kix check rejects
flags and environment variables that the package manages itself, including
Service names, ports, leader election, cluster domain, TLS certificates,
POD_NAMESPACE, and WATCH_NAMESPACE.
Scale a Deployment
Section titled “Scale a Deployment”Leave spec.replicas unset on any Deployment or StatefulSet that KEDA scales
(for example, in scope.mkDeployment). KEDA and its HorizontalPodAutoscaler
update spec.replicas at runtime, including when scaling to or from zero.
Leaving spec.replicas unset keeps Kix from owning that field, so kix deploy
does not reset the live replica count.
Add keda and any trigger source dependencies (here, prometheus and nats)
to your workload package’s build arguments
({ self, keda, prometheus, nats, ... }:). Because a cluster runs one KEDA
instance, Kix connects keda automatically from any namespace. Build the
ScaledObject with scope.mkCR and keda.out.crds.ScaledObject, and include
it in root.requires:
222 scaler = scope.mkCR keda.out.crds.ScaledObject {223 name = "worker";224 # The trigger reads the consumer the Job creates.225 requires = [ self.streams ];226 spec = {227 scaleTargetRef.name = self.worker.out.name;228 minReplicaCount = 1;229 maxReplicaCount = 6;230 triggers = [231 {232 type = "prometheus";233 metadata = {234 # The Service address orders this ScaledObject after235 # Prometheus and opens the KEDA operator's egress to it.236 serverAddress = prometheus.out.serviceUrl;237 query = "vector(3)";238 threshold = "1";239 };240 }241 {242 type = "nats-jetstream";243 metadata = {244 # The monitoring address opens the operator's egress to245 # the NATS servers on port 8222 only, in any namespace.246 natsServerMonitoringEndpoint = "${nats.out.monitoringHost}:${nats.out.monitoringPort}";247 # The global account, as the servers configure none.248 account = "$G";249 stream = "events";250 consumer = "worker";251 lagThreshold = "5";252 };253 }254 ];255 };256 };This snippet creates a ScaledObject named worker in the workload’s
namespace (app). scaleTargetRef.name uses self.worker.out.name to target
the worker Deployment in the same package. KEDA scales the Deployment between
1 and 6 replicas from two triggers:
- Prometheus.
prometheus.out.serviceUrlsetsserverAddressto the Service URL of apackages.experimental.prometheusdependency. When that Prometheus server runs in another namespace (such asmonitoring), wire it on the workload instance withdeps.prometheus = ref.monitoring.prometheus. Replacequery = "vector(3)"andthreshold = "1"with your own PromQL query and scaling threshold. - NATS JetStream.
natsServerMonitoringEndpointtakeshost:portwithout a URL scheme:"${nats.out.monitoringHost}:${nats.out.monitoringPort}"(from apackages.experimental.natsdependency, wired across namespaces withdeps.nats = ref.messaging.nats).out.monitoringHostis the NATS headless Service, which lets KEDA resolve individual pod DNS names (<pod>.<out.monitoringHost>) to find the consumer leader in a NATS cluster. Because the NATS monitoring port (8222) uses no authentication, this trigger needs noTriggerAuthentication. It scales up when pending messages for consumerworkeron streamevents(in the default global account"$G") exceedlagThreshold = "5". See Deploy NATS with JetStream for setting up streams and cross-namespace client credentials.
In the snippet, requires = [ self.streams ] deploys the ScaledObject after a
setup Job in the same package that creates the events stream and worker
consumer. Omit requires when your stream and consumer already exist.
ScaledObjects, ScaledJobs, and authentication
Section titled “ScaledObjects, ScaledJobs, and authentication”keda.out.crds provides handles for ScaledObject, ScaledJob,
TriggerAuthentication, and ClusterTriggerAuthentication. Build each one with
scope.mkCR (for example,
scope.mkCR keda.out.crds.TriggerAuthentication { name = "worker-auth"; spec = { ... }; })
and reference resource names through .out.name so Kix deploys them in order.
At runtime, KEDA copies labels and annotations from each ScaledObject onto the
HorizontalPodAutoscaler it creates, and from each ScaledJob onto the Jobs it
creates. Because those copies carry Kix’s labels,
kix gc --full-scan
lists them under “Copied labels”. Kix sees that it never applied those objects,
so kix deploy --prune, kix gc, and kix gc --full-scan keep them running
unless you pass --include copies.
Network policy for triggers
Section titled “Network policy for triggers”When a ScaledObject, ScaledJob, TriggerAuthentication, or
ClusterTriggerAuthentication uses a Service address from another package’s
out (such as prometheus.out.serviceUrl or
"${nats.out.monitoringHost}:${nats.out.monitoringPort}"), Kix:
- Deploys the KEDA custom resource after that Service.
- Allows traffic from the KEDA operator pods to that Service (both operator egress and Service ingress) when generated network policy is enabled.
Kix cannot detect dependencies in literal address strings or external endpoints.
When generated network policy is enabled, allow those connections by adding an
egress rule for the KEDA operator pods in
networkPolicy.platformIntents.
Check and deploy
Section titled “Check and deploy”Check the cluster configuration:
❱ kix check my-cluster Deploy the cluster:
❱ kix deploy my-cluster During kix deploy, Kix starts the KEDA operator first so it can create the
<instance>-certs Secret (keda-certs when the instance is named keda). Once
the operator is ready and that Secret exists, Kix deploys the metrics API
server, the admission webhooks, their Services, the webhook configuration, and
the v1beta1.external.metrics.k8s.io APIService. On a fresh install, the
metrics API server and webhook pods may restart while the operator finishes
writing TLS certificates into <instance>-certs.
kix deploy waits for the APIService to report Available (confirming the
Kubernetes API server can reach the metrics API server over TLS) and for each
ScaledObject and ScaledJob to report Ready=True.
Verify that the ScaledObject, its HorizontalPodAutoscaler, and the external
metric are active:
❱ kubectl get scaledobject worker --namespace app❱ kubectl get hpa --namespace app❱ kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/app/s0-prometheus?labelSelector=scaledobject.keda.sh%2Fname%3Dworker" KEDA names each ScaledObject metric s<index>-<trigger-type>, so
s0-prometheus is the metric for the first trigger (index 0). Because the
example query is vector(3), this command returns 3.
If a ScaledObject is not Ready or cannot read a trigger, check its events
and the KEDA operator logs:
❱ kubectl describe scaledobject worker --namespace app❱ kubectl logs deployment/keda-operator --namespace keda --since=10m What the package sets up
Section titled “What the package sets up”- Components and replicas. The package runs three Deployments, each with its
own ServiceAccount:
- Operator (
<instance>-operator): ReconcilesScaledObjectandScaledJobresources, creates a HorizontalPodAutoscaler for eachScaledObject, polls trigger sources, and serves metrics over gRPC on TCP port 9666. It uses leader election and runs 1 replica at availability levelsnoneandpod, and 2 replicas atnodeandzone. - Metrics API server (
<instance>-metrics-apiserver): Servesexternal.metrics.k8s.ioto HorizontalPodAutoscalers and reads metric values from the operator over gRPC with mutual TLS. It runs 1 replica atnoneand 2 replicas atpod,node, andzone. - Admission webhooks (
<instance>-admission-webhooks): Validates KEDA custom resources. Webhook rules setfailurePolicytoIgnore, so custom resources applied during a fresh install (before the operator writes the CA bundle) are still admitted. It runs 1 replica atnoneand 2 replicas atpod,node, andzone.
- Operator (
- Certificates. On startup, the operator generates and rotates its own CA
and service certificates in the
<instance>-certsSecret, and writescaBundleonto the webhook configuration andAPIService. Nocert-managerinstance is needed. Kix leavescaBundleunset on both resources so only the operator manages that field. - Permissions. The operator’s ClusterRole (from KEDA’s release manifest)
grants
getaccess to all resources, including Secrets, in every namespace. KEDA needs this access becauseTriggerAuthenticationresources read Secrets in application namespaces and scale targets can be any resource kind with ascalesubresource. - Network policy. When generated network policy is enabled, Kix allows the
metrics API server to connect to the operator on TCP port 9666 (gRPC), and
opens operator egress and Service ingress for any trigger or authentication
address read from a Kix Service
outfield. Kix also allows ingress from the Kubernetes API server on TCP ports 6443 (metrics API server) and 9443 (admission webhooks). Package-level ingress rules apply to all three KEDA Deployments, even though only one component listens on each port. - Metrics. When a
prometheusprovider is connected andconfig.metrics.enabledistrue(the default), the package creates a metrics Service (<instance>-operator-metrics), aServiceMonitor, and three warning alerts:KedaOperatorDown(no operator pod scraped for 10 minutes),KedaScalerErrors(a trigger has failed to read its source for 15 minutes), andKedaOperatorReconcileErrors(high controller reconcile error rate).
Limits
Section titled “Limits”- ScaledJob pod network policy. Job pods started by a
ScaledJobdo not get generated network policies. When generated network policy is enabled, add anetworkPolicy.platformIntentsentry for those Job pods. Any Kix Serviceoutaddress inside aScaledJob(including underjobTargetRef) opens network access only for the KEDA operator pods. - CPU and memory triggers. Deploy a
metrics.k8s.ioprovider (such aspackages.experimental.metrics-server) before usingcpuormemorytriggers.kix checkdoes not verify that the cluster servesmetrics.k8s.iowhen aScaledObjectuses these triggers. - Scale targets without
spec.replicas. Whenspec.replicasis unset on a target workload, Kix treats it as having 1 replica regardless ofminReplicaCounton theScaledObject. Kix does not generatetopologySpreadConstraintsor aPodDisruptionBudgetfor that workload, and counts only 1 pod toward any namespaceResourceQuota. - HorizontalPodAutoscaler conflicts. Do not target the same workload with
both a
ScaledObjectand a separate HorizontalPodAutoscaler.kix checkdoes not catch this conflict. KEDA’s admission webhook rejects the second resource duringkix deploy, unless the webhook is unreachable (failurePolicyisIgnore). - Removing KEDA. Remove KEDA in two deploys: first delete all
ScaledObject,ScaledJob,TriggerAuthentication, andClusterTriggerAuthenticationresources and runkix deploy <cluster> --prune, then remove thekedainstance and deploy again.kix deploy --prunestarts deleting KEDA custom resources before the operator, but does not wait for deletion to finish; removing both in one deploy can leave custom resources stuckTerminatingon thefinalizer.keda.shfinalizer. - CloudEvent sources.
keda.out.crdsdoes not exposeCloudEventSourceorClusterCloudEventSource, soscope.mkCRcannot build them. The package still installs both CustomResourceDefinitions because the KEDA operator watches them at startup. - Updating ScaledObjects and ScaledJobs. When
kix deployupdates an existingScaledObjectorScaledJob, it can finish before KEDA reconciles the new spec. KEDA does not writeobservedGenerationin status, so Kix sees the existingReady=Truecondition immediately.