> ## Documentation Index
> Fetch the complete documentation index at: https://docs.komodor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Autoscale agents

> Koperator scales an agent from its queue, with no KEDA, whether koperator deploys the agent or Argo CD, Flux, Helm or kubectl deploys it.

Koperator in your cluster scales an agent from the queue of the agent. It does this whether
koperator deploys the agent, or your own tool deploys it:

| Who deploys the agent | What you do |
| - | - |
| Koperator, on a management cluster | Set the run behaviour and the scaling settings of the agent in the Komodor Agentic Operation Platform (KAOP). Install koperator with the chart value `autoscaler.mode: native`, so that koperator scales the agent itself. With the default mode, KEDA can scale it. See [Deploy agents](https://docs.komodor.com/manage-your-agents/build/koperator/deploy-agents.md). |
| Your own tool: Argo CD, Flux, Helm or `kubectl` | Set the same settings in KAOP. Koperator always scales these agents itself, in every mode. Then opt the Deployment in with two labels, and make sure that your chart does not render `spec.replicas`. An ignore rule in your tool is optional. |

In both cases, the scaling settings are on the agent in KAOP, not in git (see [Set the scaling in
KAOP](#set-the-scaling-in-kaop)). Koperator sets the replica count of the Deployment from the queue
of the agent:

* When the agent is idle, it can go to 0 replicas.
* When a run arrives for an agent at 0, koperator usually wakes it in about one second. If that fast
  wake is not available, koperator wakes the agent at its next poll. The first run then waits until
  the pod is ready.
* When more runs wait, koperator adds replicas, up to the maximum that you set.
* When the queue is empty, koperator removes replicas after a cooldown.

For an agent that you deploy, you do not need KEDA or a HorizontalPodAutoscaler. Koperator changes
only `spec.replicas` and one annotation on that Deployment. It does not change the pod template, so it
does not restart pods.

## How it works for an agent that you deploy

When your own tool deploys the agent, the Deployment and the agent must both opt in. If only one of them opts in, nothing scales.

| Where | What to do |
| - | - |
| The Deployment, in your git repository or your chart | Add two labels: `agentops.komodor.io/autoscale: "true"` and `agentops.komodor.io/agent-id: <agent ID>`. |
| The agent, in KAOP | Set the run behaviour to **Scale to zero**, or set **Always on** with autoscaling on. |

1. Koperator finds each Deployment that opts in, in the namespaces that it scales. It reports each
   one to KAOP at least one time each minute.
2. KAOP binds the agent to the management cluster that reports it. One management cluster scales an
   agent. If another management cluster already scales the agent, KAOP does not change the binding.
3. Koperator reads the queue and the scaling settings of each bound agent from KAOP. It then sets
   the replica count through the scale subresource of the Deployment.

## Before you start

You need:

* **A management cluster.** This is a cluster where koperator is installed and connected to KAOP.
  The Deployment must be in a namespace that koperator scales.
* **A self-hosted agent in KAOP.** Copy its **Agent ID** from the agent page. KAOP must not also
  deploy the agent to a management cluster: an agent that KAOP deploys is scaled by KAOP already.
* **No other scaler on the Deployment.** Remove each HorizontalPodAutoscaler or KEDA ScaledObject that
  targets it.

## Install koperator for scaling only

If koperator is already on the cluster and its namespaces include the namespace of the Deployment,
you can use that install. Go to [Do you need an ignore rule?](#do-you-need-an-ignore-rule).

To scale agents and deploy nothing, install koperator with only the autoscaling module on:

**1. Create a management cluster**

In KAOP, create a management cluster. Keep the install key: KAOP shows it one time.

**2. Create the Secret for the install key**

```bash theme={null}
kubectl create namespace agentops-scaling
kubectl -n agentops-scaling create secret generic koperator-credential --from-literal=key='<install key>'
```

**3. Install the chart**

Set `namespaces` to the namespaces of your agent Deployments:

```bash theme={null}
helm upgrade --install koperator-scaling oci://ghcr.io/komodorio/charts/koperator \
  --namespace agentops-scaling \
  --set controlPlane.url=https://agentops.komodor.com \
  --set credential.existingSecret=koperator-credential \
  --set modules.workloads.enabled=false --set modules.config.enabled=false \
  --set-json 'namespaces=["team-a"]'
```

The page of the management cluster also shows the install command. Add the two `modules` values
to it.

A scaling-only install does not need KEDA, whatever the value of `autoscaler.mode` is. It claims no
namespace, so it can run in the same namespaces as another koperator install. `helm uninstall` does
not change the replica counts.

> [!WARNING]
>
> Do not use `helm upgrade` to turn the workloads module off on an install that has it on. That install
> keeps its claims on the namespaces. Uninstall it, then install it again for scaling only.

### Permissions of a scaling-only install

In each namespace in `namespaces`, the chart gives koperator only these permissions:

| Resource | Verbs | Why |
| - | - | - |
| Deployments | `get`, `list`, `watch`, `patch` | Find the Deployments that opt in. `patch` writes the `agentops.komodor.io/autoscaler-state` annotation. |
| `deployments/scale` | `get`, `update` | Set the replica count. |
| HorizontalPodAutoscalers, KEDA ScaledObjects | `list`, `watch` | Find another scaler. Koperator does not scale a Deployment that another scaler targets. |

Koperator also gets a Role for leader election in its own namespace. Its only cluster-wide
permissions are read-only and limited by name: the two KEDA CRDs and the `kube-system` namespace. It
gets no access to Secrets, ConfigMaps, Services, ServiceAccounts, Pods or Events in the scaled
namespaces. It cannot create or delete an object. With `namespaces: ["*"]`, the chart gives the same
permissions in one ClusterRole.

Koperator connects out to KAOP over HTTPS. Nothing connects in to your cluster.

## Do you need an ignore rule?

The ignore rule in your deploy tool is optional. You need it only when your tool applies a
`replicas` value to the Deployment. With the recommended installation, the KAOP agent chart with
`autoscaling.native.enabled: true`, you do not need it.

| Your chart | Ignore rule (step 1) |
| - | - |
| Does not render `replicas`, and never did. For example, a new agent from the KAOP agent chart with `autoscaling.native.enabled: true`. | Not necessary. Koperator keeps its replica count after a scale and after a sync. |
| Renders `replicas` now, and you will remove it. | Necessary for the change that removes `replicas`. Add the rule, and let it sync, before that change. If you do not, Argo CD sets each agent to 1 replica at that sync. |
| Renders `replicas`, and you keep it. | Necessary. If you do not add it, the deploy tool resets each scale. |

We tested Argo CD with no ignore rule only with server-side apply (`ServerSideApply=true`). If your
Application uses client-side apply, add the rule.

After the change that removes `replicas`, the rule is only a safety net: if a later chart change
renders `replicas` again, the rule stops a reset. You can keep it or remove it.

## Do the steps in this order

| Step | Change | Why this order |
| - | - | - |
| 1 | Only if your chart renders `replicas` now: tell your deploy tool to ignore `spec.replicas`. | While your chart renders `replicas`, the tool resets each scale. The change that removes `replicas` can also reset each agent to 1 replica. |
| 2 | Add the two labels to the Deployment. | Koperator starts to scale when KAOP binds the agent. |
| 3 | Remove `replicas` from your chart or manifest. | With Argo CD, if your chart rendered `replicas` and step 3 comes before step 1, the sync sets each agent to 1 replica. |

If you do step 1, let it sync before you do step 2. You can do step 2 and step 3 in the same change.
If you deploy the KAOP agent chart, one chart value does step 2 and step 3 (see [If you deploy the
KAOP agent chart](#if-you-deploy-the-kaop-agent-chart)).

## Step 1: tell your deploy tool to ignore spec.replicas

Do this step only if your chart renders `replicas` now. See [Do you need an ignore
rule?](#do-you-need-an-ignore-rule).

### Argo CD Application

Add the ignore rule **and** the sync option `RespectIgnoreDifferences=true`:

```yaml theme={null}
spec:
  ignoreDifferences:
  - group: apps
    kind: Deployment
    jsonPointers:
    - /spec/replicas
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
    - ServerSideApply=true
    - ApplyOutOfSyncOnly=true
    - CreateNamespace=true
    - RespectIgnoreDifferences=true
```

* `ignoreDifferences` alone stops self-heal. But a sync from a git change still resets `replicas`.
  You must also set `RespectIgnoreDifferences=true`.
* The rule works with server-side apply on or off.
* Use `jsonPointers`. Do not use `managedFieldsManagers`: when your chart does not render
  `replicas`, the scale writes of koperator do not show as a field manager.
* The `autoscaler-state` annotation does not need an ignore rule.

### Argo CD ApplicationSet

Use a `templatePatch`. It needs `goTemplate: true`. Put the full `syncOptions` list in the patch:

```yaml theme={null}
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
  - list:
      elements:
      - name: my-agent
        autoscaling: true
  template:
    # ... your template, with no change
  templatePatch: |
    spec:
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
        - ServerSideApply=true
        - ApplyOutOfSyncOnly=true
        - CreateNamespace=true
        {{- if .autoscaling }}
        - RespectIgnoreDifferences=true
        {{- end }}
    {{- if .autoscaling }}
      ignoreDifferences:
      - group: apps
        kind: Deployment
        jsonPointers:
        - /spec/replicas
    {{- end }}
```

An element with `autoscaling: false` keeps its rendered `replicas`, and self-heal keeps that count.

With `missingkey=error`, each generator element must set `autoscaling` to `true` or `false`. If one
element does not set it, the ApplicationSet does not render any of its elements.

### Flux HelmRelease

Tell drift detection to ignore `/spec/replicas`:

```yaml theme={null}
spec:
  driftDetection:
    mode: enabled
    ignore:
    - paths: ["/spec/replicas"]
      target:
        kind: Deployment
```

This rule stops drift correction. It does not stop an upgrade that renders `replicas`. So you must
also do step 3. Flux upgrades with Helm, so read [Plain Helm or kubectl](#plain-helm-or-kubectl)
too.

### Plain Helm or kubectl

There is no ignore rule to set. A Helm upgrade, and a client-side `kubectl apply`, overwrite a
`replicas` that the chart or the manifest contains. They do not change a field that they never
applied. So you must do step 3. Until you do it, koperator and each upgrade change the replica count
in turn.

The upgrade that removes `replicas` can set each agent to 1 replica one time. Helm deletes a field
that it applied before, and Kubernetes then sets the default, 1. Koperator can see this as another
writer. It then waits up to 10 minutes before it scales the agent again. To decrease the effect, do
step 3 when the agents are idle.

## Step 2: label the Deployment

Add the two labels to the metadata of the Deployment. Do not add them to the pod template:

```yaml theme={null}
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    agentops.komodor.io/autoscale: "true"
    agentops.komodor.io/agent-id: my-agent   # the Agent ID from the agent page in KAOP
```

If a container sets the environment variable `AGENTOPS_AGENT_ID`, it must have the same value as the
label. If it does not, koperator does not scale the Deployment.

If you do step 1 with Argo CD, the ignore rule is on the Application and the labels are on the
Deployment. One commit does not make sure that Argo CD applies the rule first. So make sure that
step 1 has synced before you push the labels.

## Step 3: remove replicas from your chart

Render `replicas` only when autoscaling is off. For example, in a Helm template:

```yaml theme={null}
spec:
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
```

`autoscaling.enabled` is an example. Use the value that your chart has for this.

In a plain manifest, remove the `replicas` line.

## If you deploy the KAOP agent chart

The KAOP agent chart (`oci://ghcr.io/komodorio/charts/agentops-agent-base`, version 0.1.8 or later)
does step 2 and step 3 for you. Set this value:

```yaml theme={null}
autoscaling:
  native:
    enabled: true
```

* The chart adds the label `agentops.komodor.io/autoscale: "true"` to the Deployment, not to the pod
  template. It always sets the `agentops.komodor.io/agent-id` label.
* The chart does not render `replicas`, so `replicaCount` has no effect.
* The chart does not render a KEDA ScaledObject. The chart fails if `autoscaling.keda.enabled` is
  also `true`.

A new agent that you install with this value needs no ignore rule, because the chart never rendered
`replicas`. For an agent that is already deployed, the upgrade that sets the value removes
`replicas`. With Argo CD, do step 1 first. With Helm, Flux or `kubectl`, do the upgrade when the agent
is idle.

## Rollout results

| What you do | Result |
| - | - |
| A new agent from the KAOP agent chart with `autoscaling.native.enabled: true` | No reset. No ignore rule is necessary. |
| Argo CD with server-side apply: a chart that never rendered `replicas`, no ignore rule | Each agent keeps its replica count, after a scale and after a sync. |
| Argo CD: step 1, then step 3 | Each agent keeps its replica count. |
| Argo CD: a chart that rendered `replicas`, step 3 with no ignore rule | The sync that removes `replicas` sets each agent to 1 replica. |
| Argo CD: the ignore rule without `RespectIgnoreDifferences=true` | The next sync from git resets each agent to the rendered count. |
| Labels (step 2) before step 1 | The deploy tool resets each scale. The agent shows `replicas_owned_by_other`. |
| Plain Helm, `kubectl` or Flux: step 3 | The upgrade can set each agent to 1 replica one time. Koperator can then wait up to 10 minutes. |

When Argo CD creates a new Deployment, it does not use the ignore rule. The new agent starts at the
rendered count, or at 1 when the chart has no `replicas`. A **Scale to zero** agent then goes to 0
after its cooldown.

**To stop autoscaling,** remove the `agentops.komodor.io/autoscale` label. Koperator stops, and the
replica count stays as it is.

## Set the scaling in KAOP

The scaling settings are on the agent in KAOP, not in git, whoever deploys the agent. Set them in
the run settings of the agent:

* **Run behaviour.** **Scale to zero**: no replica runs while the agent is idle. **Always on**: at
  least one replica always runs. To scale an **Always on** agent, turn on its autoscaling.
* **Max replicas.** Koperator never sets more replicas than this.
* **Queue depth per replica.** The number of waiting runs for each replica. Koperator sets the
  replicas to the waiting runs divided by this number, rounded up, between the minimum and the
  maximum.
* **Min replicas.** For an **Always on** agent with autoscaling, the replicas that always run. A
  **Scale to zero** agent has a minimum of 0.

A change applies at the next poll of koperator. No pod restarts. You can also set these settings
with the KAOP API or with the co-pilot. See [Scale agents to zero](https://docs.komodor.com/manage-your-agents/build/scale-to-zero.md)
for how to choose between **Scale to zero** and **Always on**.

## Check that it works

**On the agent page.** The **Overview** tab shows a **Scaling** card. It shows the state
(**Bound**, **Not scaled** or **Released**) and a line such as "Deployed by Argo CD, scaled by the
Komodor operator on `<management cluster>`". It also shows the management cluster, the Deployment
(`namespace/name`), how KAOP bound the agent, and when.

The card has two buttons:

* **Move.** Bind the agent to another management cluster. That management cluster must report an
  opted-in Deployment for the agent. You need permission to update the agent and to deploy to that
  management cluster.
* **Release.** Remove the binding. After a release, no koperator scales the agent, and a new report
  does not bind it again. To scale it again, use **Move**. You need permission to update the agent.

**On the management cluster page.** The **Agents on this cluster** section lists each opted-in
Deployment that its koperator reports: the agent, the Deployment, the deploy tool, and the state.

| State | Meaning |
| - | - |
| **Bound here** | This management cluster scales the agent. |
| **Not bound** | The agent has autoscaling off, KAOP deploys it, a person released it, or the `agent-id` label names no agent in your account. |
| **Not scaled** | Koperator reports a reason code. See [Why an agent does not scale](#why-an-agent-does-not-scale). |

**In your deploy tool.** Argo CD shows the Application as `Synced` and `Healthy`, also at 0 replicas.

**In the cluster.** This command shows the state that koperator writes:

```bash theme={null}
kubectl -n <namespace> get deployment <name> \
  -o jsonpath='{.metadata.annotations.agentops\.komodor\.io/autoscaler-state}'
```

**With the API.** `GET /api/v1/agents/<agent ID>` returns the binding in `scaled_by`: `state`, the
management cluster, `namespace`, `object_name`, `deployed_by` (`argocd`, `flux`, `helm` or
`unknown`), and `reason_code` with `message` when koperator does not scale the agent.

## Why an agent does not scale

When koperator does not scale an opted-in Deployment, it reports a reason code. The **Scaling** card
on the agent page shows the reason code, a message and the fix.

| Reason code | Cause | Fix |
| - | - | - |
| `opt_in_invalid` | The `agentops.komodor.io/agent-id` label is missing, or `AGENTOPS_AGENT_ID` in a container names another agent. | Set the label to the Agent ID. Make `AGENTOPS_AGENT_ID` the same value. |
| `scaler_conflict` | A HorizontalPodAutoscaler or a KEDA ScaledObject targets the Deployment. Or another opted-in Deployment in scope has the same Agent ID. Or another management cluster scales the agent. | Remove the other scaler or the duplicate Deployment. To change the management cluster that scales the agent, use **Move** on the agent page. |
| `replicas_owned_by_other` | Another tool sets `spec.replicas`. Usually this is your deploy tool, because step 1 is missing. Koperator stops for 10 minutes, then starts again from the live count. | Do [step 1](#step-1-tell-your-deploy-tool-to-ignore-spec-replicas) and let it sync. Then remove `replicas` from your chart (step 3). After step 3, the rule is optional. |
| `autoscaler_unreachable` | KAOP did not get a poll from koperator for the agent for three polling intervals. A **Scale to zero** agent shows **Autoscaler not polling**. Koperator cannot reach KAOP, or it reports one of the reason codes above. | Make sure that koperator runs and can connect to KAOP. If it goes through a proxy, it needs `HTTPS_PROXY`, `NO_PROXY` and the CA of the proxy. Then fix the reason code above, if there is one. |

Koperator also does not scale a Deployment that KAOP deployed. KAOP scales that agent on its own
path.

If the agent has no binding and no reason code, examine these items:

* Autoscaling is off on the agent in KAOP.
* KAOP deploys the agent to a management cluster.
* A person released the binding. Use **Move** to bind it again.

## Waking from zero needs koperator

When no koperator replica can connect to KAOP, a bound agent does not wake or scale. Pods that run
keep their count. A run that waits for an agent at 0 fails with `cold_start_timeout` at the end of
its hold timeout.

## Security

A person who can label a Deployment in a namespace that koperator scales can bind a free, opted-in
agent. That koperator can then read the queue counts and the run settings of the agent. It cannot
read the runs or the secrets of the agent.

The **Scaling** card on the agent page shows the binding. KAOP writes each bind, move, release and
end to the audit log. A user with permission to update the agent can release the binding.

## Next steps

> [card] [Argo CD and Flux](https://docs.komodor.com/manage-your-agents/build/koperator/gitops.md)
>
> Install and upgrade koperator itself with Argo CD or Flux.

> [card] [Scale agents to zero](https://docs.komodor.com/manage-your-agents/build/scale-to-zero.md)
>
> Choose between Scale to zero and Always on.


## Related topics

- [Scale agents to zero](https://docs.komodor.com/manage-your-agents/build/scale-to-zero.md)
- [Configure koperator](https://docs.komodor.com/manage-your-agents/build/koperator/configure.md)
- [The agent page](https://docs.komodor.com/manage-your-agents/fleet/agent-page.md)
- [Agent catalog](https://docs.komodor.com/manage-your-agents/build/catalog/overview.md)
- [Agent identity](https://docs.komodor.com/security-and-governance/identity-and-access/agent-identity.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.