# Autoscale workloads with KEDA

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

Add a `keda` instance to your cluster definition:

<Snippet {...kedaInstance} />

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

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`:

<Snippet {...kedaScaledObject} />

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.serviceUrl` sets `serverAddress` to the
  Service URL of a `packages.experimental.prometheus` dependency. When that
  Prometheus server runs in another namespace (such as `monitoring`), wire it on
  the workload instance with `deps.prometheus = ref.monitoring.prometheus`.
  Replace `query = "vector(3)"` and `threshold = "1"` with your own PromQL query
  and scaling threshold.
- **NATS JetStream.** `natsServerMonitoringEndpoint` takes `host:port` without a
  URL scheme: `"${nats.out.monitoringHost}:${nats.out.monitoringPort}"` (from a
  `packages.experimental.nats` dependency, wired across namespaces with
  `deps.nats = ref.messaging.nats`). `out.monitoringHost` is 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 no `TriggerAuthentication`. It scales up when pending messages for
  consumer `worker` on stream `events` (in the default global account `"$G"`)
  exceed `lagThreshold = "5"`. See
  [Deploy NATS with JetStream](/docs/how-to/package-task-guides/deploy-nats-jetstream/#connect-an-application)
  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

`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`](/docs/how-to/operate-a-cluster/garbage-collect-stale-resources/#scan-the-live-cluster-for-orphans)
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

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](/docs/how-to/platform-capabilities/enable-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`](/docs/how-to/platform-capabilities/declare-platform-intents-for-non-kix-managed-pods/).

## Check and deploy

Check the cluster configuration:

<Command commands={["kix check my-cluster"]} />

Deploy the cluster:

<Command commands={["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:

<Command
  commands={[
    "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:

<Command
  commands={[
    "kubectl describe scaledobject worker --namespace app",
    "kubectl logs deployment/keda-operator --namespace keda --since=10m",
  ]}
/>

## What the package sets up

- **Components and replicas.** The package runs three Deployments, each with its
  own ServiceAccount:
  - **Operator (`<instance>-operator`):** Reconciles `ScaledObject` and
    `ScaledJob` resources, creates a HorizontalPodAutoscaler for each
    `ScaledObject`, polls trigger sources, and serves metrics over gRPC on TCP
    port 9666. It uses leader election and runs 1 replica at
    [availability levels](/docs/explanation/availability-levels/) `none` and
    `pod`, and 2 replicas at `node` and `zone`.
  - **Metrics API server (`<instance>-metrics-apiserver`):** Serves
    `external.metrics.k8s.io` to HorizontalPodAutoscalers and reads metric
    values from the operator over gRPC with mutual TLS. It runs 1 replica at
    `none` and 2 replicas at `pod`, `node`, and `zone`.
  - **Admission webhooks (`<instance>-admission-webhooks`):** Validates KEDA
    custom resources. Webhook rules set `failurePolicy` to `Ignore`, so custom
    resources applied during a fresh install (before the operator writes the CA
    bundle) are still admitted. It runs 1 replica at `none` and 2 replicas at
    `pod`, `node`, and `zone`.
- **Certificates.** On startup, the operator generates and rotates its own CA
  and service certificates in the `<instance>-certs` Secret, and writes
  `caBundle` onto the webhook configuration and `APIService`. No `cert-manager`
  instance is needed. Kix leaves `caBundle` unset on both resources so only the
  operator manages that field.
- **Permissions.** The operator's ClusterRole (from KEDA's release manifest)
  grants `get` access to all resources, including Secrets, in every namespace.
  KEDA needs this access because `TriggerAuthentication` resources read Secrets
  in application namespaces and scale targets can be any resource kind with a
  `scale` subresource.
- **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 `out` field. 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 `prometheus` provider is connected and
  `config.metrics.enabled` is `true` (the default), the package creates a
  metrics Service (`<instance>-operator-metrics`), a `ServiceMonitor`, and three
  warning alerts: `KedaOperatorDown` (no operator pod scraped for 10 minutes),
  `KedaScalerErrors` (a trigger has failed to read its source for 15 minutes),
  and `KedaOperatorReconcileErrors` (high controller reconcile error rate).

## Limits

- **ScaledJob pod network policy.** Job pods started by a `ScaledJob` do not get
  generated network policies. When generated network policy is enabled, add a
  `networkPolicy.platformIntents` entry for those Job pods. Any Kix Service
  `out` address inside a `ScaledJob` (including under `jobTargetRef`) opens
  network access only for the KEDA operator pods.
- **CPU and memory triggers.** Deploy a `metrics.k8s.io` provider (such as
  `packages.experimental.metrics-server`) before using `cpu` or `memory`
  triggers. `kix check` does not verify that the cluster serves
  `metrics.k8s.io` when a `ScaledObject` uses these triggers.
- **Scale targets without `spec.replicas`.** When `spec.replicas` is unset on a
  target workload, Kix treats it as having 1 replica regardless of
  `minReplicaCount` on the `ScaledObject`. Kix does not generate
  `topologySpreadConstraints` or a `PodDisruptionBudget` for that workload, and
  counts only 1 pod toward any namespace `ResourceQuota`.
- **HorizontalPodAutoscaler conflicts.** Do not target the same workload with
  both a `ScaledObject` and a separate HorizontalPodAutoscaler. `kix check` does
  not catch this conflict. KEDA's admission webhook rejects the second resource
  during `kix deploy`, unless the webhook is unreachable (`failurePolicy` is
  `Ignore`).
- **Removing KEDA.** Remove KEDA in two deploys: first delete all
  `ScaledObject`, `ScaledJob`, `TriggerAuthentication`, and
  `ClusterTriggerAuthentication` resources and run
  `kix deploy <cluster> --prune`, then remove the `keda` instance and deploy
  again. `kix deploy --prune` starts deleting KEDA custom resources before the
  operator, but does not wait for deletion to finish; removing both in one
  deploy can leave custom resources stuck `Terminating` on the
  `finalizer.keda.sh` finalizer.
- **CloudEvent sources.** `keda.out.crds` does not expose `CloudEventSource` or
  `ClusterCloudEventSource`, so `scope.mkCR` cannot build them. The package
  still installs both CustomResourceDefinitions because the KEDA operator
  watches them at startup.
- **Updating ScaledObjects and ScaledJobs.** When `kix deploy` updates an
  existing `ScaledObject` or `ScaledJob`, it can finish before KEDA reconciles
  the new spec. KEDA does not write `observedGeneration` in status, so Kix sees
  the existing `Ready=True` condition immediately.