# Autoscale an app

Let an app add and remove machines on CPU, memory, requests or a queue's backlog.

With autoscaling on, an app runs between a minimum and a maximum number of machines and the platform
picks the number every minute from one reading per machine and your target for it. Replace
app-id with the app's id.

| Metric     | Reading per machine                                         | Measured by                                   |
| ---------- | ----------------------------------------------------------- | --------------------------------------------- |
| `cpu`      | CPU in use, 0–100 % of the machine, average of 5 minutes    | the provider, 1 to 2 minutes behind           |
| `memory`   | memory in use, 0–100 %, average of 3 minutes                | the machine's agent, each minute              |
| `requests` | requests per second handed to the app, average of 3 minutes | the machine's agent, from the machine's proxy |
| `queue`    | messages waiting in one of your queues, divided by machines | the queue itself, read at every check         |

How the number is picked:

- **Out**: machines = ⌈machines measured × reading ÷ target⌉, up to the maximum. New machines run the
  version that is live: nothing is built, no deployment is started.
- **In**: only when the reading is more than 10 % under the target, and one machine at a time. The
  newest machine leaves the load balancer first; it is deleted once its proxy reports no request in
  flight, or when the drain time is up.
- **Cooldowns**: after a scale-out, the next scale-out waits the scale-out cooldown (default 60 s);
  a scale-in waits the scale-in cooldown (default 300 s) after any change.
- A machine counts once it is 3 minutes old: its boot is not load. While one is younger, the app
  does not scale in.
- Nothing changes while a deployment is rolling out.

An app whose maximum is more than one machine sits behind its own load balancer at every size, so
scaling never changes its addresses or certificates. While autoscaling is on, the platform sets the
app's machine count; changing it by hand is refused with `409`.

**Important:**
Every machine is a compute instance, billed as one. The maximum is the most you pay for
machines. The app's load balancer is charged like the smallest standalone network load balancer:
per started hour, up to the same monthly price, on its own line of the bill (**App load
balancer**, `deploy.load_balancer.hour`). The **Autoscaling** panel shows the price at the minimum
and at the maximum before you save.

## Prerequisites

- Permission for `deploy:PutAutoscaling` on the app (`deploy:DeleteAutoscaling` to turn it off).
- In the console, also `deploy:DescribeApp` to open the app's page (without it the page is not
  found).
- An app on its own machines, with a live deployment. A pooled app starts and stops on its own and
  has no autoscaling.
- For `queue`: `queue:GetQueueAttributes` on the queue.

## Turn on autoscaling

**Console**
1. Open the app, then choose **More** › **Runtime**; the **Autoscaling** section is there.
2. Enter **Minimum machines** and **Maximum machines** (1 to 10).
3. Under **Scale on**, pick the metric, and enter the **Target per machine**. For a queue, pick the
   queue.
4. Change the cooldowns and the drain time if the defaults do not suit the app.
5. Choose **Turn on**. The first check runs at once; **Now** shows the machines, the last reading and
   what it decided, the charts show machines and the reading against the target, and **Decisions**
   lists every change with its reason.

**CLI**
```sh
dcloud deploy autoscaling put app-id --min-replicas 1 --max-replicas 4 \
  --policies '{"metric":"requests","target":50}' --scale-in-cooldown-seconds 120
dcloud deploy autoscaling get app-id
```

**API**
```http
PUT /deploy/api/apps/3f1c2b4a-5d6e-4f70-8a91-b2c3d4e5f601/autoscaling
{
  "minReplicas": 1,
  "maxReplicas": 4,
  "policies": [{ "metric": "requests", "target": 50 }],
  "scaleOutCooldownSeconds": 60,
  "scaleInCooldownSeconds": 120,
  "drainSeconds": 30
}
```

**Terraform**
```hcl
resource "dcloud_app_autoscaling" "web" {
  app_id       = dcloud_app.web.id
  min_replicas = 1
  max_replicas = 4
  policies     = jsonencode([{ metric = "requests", target = 50 }])
}
```

Leave `replicas` out of the app's `dcloud_app` resource, or ignore its changes.

A minimum above the maximum, a percentage target above 100, or `queue` without a queue is refused
with `400`; a queue of another organization with `404`; a pooled app or a preview environment with
`409`.

## Turn autoscaling off

Choose **Turn off** in the **Autoscaling** section of **Runtime**, or `dcloud deploy autoscaling delete
app-id`. The app keeps the machines it has; the count is yours to change again. While a
machine is draining, turning off answers `409`: try again after the drain time.

## Result

Every check is recorded as the app's series `app_replicas`, `app_cpu_percent`, `app_memory_percent`
and `app_requests_per_second` (all machines), and each machine records `memory_percent`,
`requests_per_second` and `requests_in_flight`. You can chart them and set alarms on them like any
other metric. Every change is in the app's activity with the reading that caused it.

## Related

- [Scale an app](scale-an-app.md)
- [Monitoring](monitoring.md)
- `deploy.autoscaling.put` · `dcloud deploy autoscaling put` · `dcloud_app_autoscaling`
