What it is
Autoscaling automatically changes the number of instances of a service (VMs, containers, pods, function instances) to follow demand. You give it a metric (average CPU, requests per instance, queue length), a target for that metric, and a minimum and maximum instance count. The autoscaler then runs a control loop: measure, compare with the target, add or remove instances, repeat.
Why it exists
Load is rarely flat. A fleet sized for the daily peak sits mostly idle at night; a fleet sized for the average fails at the peak. Horizontal scaling made capacity a number you can change; autoscaling changes that number for you, faster than a human would and without a page at 3 a.m. In the cloud you pay per instance-hour, so following demand also saves money.
How it works
The loop. Every evaluation period the autoscaler reads the metric aggregated over the group (for example, the 1-minute average CPU across all instances) and computes a desired count. If it differs from the current count, it launches or terminates instances, always staying within min and max.
Target tracking. The most common policy type keeps a metric near a target, like a thermostat. For a metric that scales linearly with load, the rule is
desired = ⌈running × current metric ÷ target⌉
Six instances at 80% CPU with a 50% target → ⌈6 × 0.8 ÷ 0.5⌉ = 10. Kubernetes' Horizontal Pod Autoscaler uses exactly this formula (with a 10% tolerance band); AWS, Azure and Google Cloud offer target tracking for their instance groups.
Other policy types.
- Step scaling: alarm thresholds with fixed steps ("above 70% add 2, above 90% add 4; below 30% remove 1"). Explicit, but you tune several numbers.
- Scheduled scaling: set min/desired by time ("weekdays 08:45 → 10 instances"). Ideal for known patterns.
- Predictive scaling: forecast the daily and weekly pattern from history and launch ahead of it. Works for regular traffic, not for surprises.
- Event or queue-driven (for example KEDA in Kubernetes): scale workers on queue length or lag instead of CPU, including down to zero.
The lag. New capacity arrives only after the metric has crossed the target (aggregation window), the policy has evaluated it, the instance has booted (seconds for a container on a warm node, a minute or more for a VM, longer if a new node must be provisioned first), the load balancer has seen enough good health checks, and the application has warmed up (caches, connection pools, JIT). Until then the existing fleet carries the load.
Scale-in. Removing capacity is the risky direction. Policies scale in more slowly than they scale out (cooldowns, stabilisation windows — the HPA defaults to five minutes for scale-down), and instances are drained before termination: deregistered from the load balancer, so no new requests arrive, while in-flight requests finish.
When to use it
- Stateless tiers behind a load balancer: web and API servers, gRPC services.
- Worker pools that consume a queue, scaled on queue depth or age.
- Traffic with daily or weekly cycles, or growth you cannot predict precisely.
- Batch or bursty workloads where idle capacity is expensive.
When not to
- Stateful nodes such as databases, brokers or caches, where adding a node means moving data. Scale these deliberately (or use a managed service that handles rebalancing).
- Spikes shorter than your boot time: by the time instances are ready, the spike is over. Keep headroom, shed load or queue work instead.
- When the bottleneck is downstream: more API instances only add load to a saturated database.
- Tiny, steady services where a fixed N+1 fleet is simpler and cheap enough.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Lower target (e.g. 50% instead of 75%) | Headroom for spikes during the scale-out lag | More instances, higher cost |
| Fast scale-in | Lower cost after peaks | Flapping, more cold starts, risk of errors when terminating |
| Scheduled / predictive scaling | Capacity ready before the peak | Wasted capacity if the pattern changes; still need reactive scaling |
| Scaling on requests per instance instead of CPU | Tracks load directly for I/O-bound services | Needs a metric pipeline from the load balancer |
| High maximum | Survives large peaks | Can overwhelm downstream systems and the budget |
Alternatives
- Fixed capacity with headroom: size for peak plus N+1. Simple and predictable; you pay for idle capacity.
- Vertical scaling: bigger machines. Easy for stateful systems, but needs a restart and has a ceiling.
- Serverless functions: the platform scales per request, down to zero. Cold starts and concurrency limits replace boot times and group sizes.
- Load shedding and queueing: accept that capacity is fixed and protect it by rejecting or deferring low-priority work.
Failure modes
- Scale-out too late: the error window equals detection + boot + health checks + warm-up. Fix with a lower target, faster images, warm pools or schedules.
- Cold start overload: a new instance gets a full share while still slow and becomes the slowest server in the pool. Use slow start in the load balancer and a warm-up period in the policy so new instances do not count at full weight yet.
- Flapping: instances launched and terminated repeatedly on normal noise; every cycle costs boot time and, without draining, failed requests.
- Terminating without draining: in-flight requests die and the balancer keeps routing to the instance until health checks notice.
- Scaling the wrong tier: more app instances open more database connections and make a database bottleneck worse.
- Stuck at maximum: the group cannot grow further and quietly saturates. Alert on "at max for N minutes".
- Feedback from failures: crashing instances report low CPU, so a CPU policy may scale in during an outage. Combine with health-based replacement and request-based metrics.
In production
Choose the metric that tracks your bottleneck: CPU for compute-bound services, requests or concurrent requests per instance for I/O-bound ones, queue age for workers. Keep the minimum high enough to survive the loss of an availability zone, and spread the group across zones. Make images start fast (pre-baked images, small containers, lazy initialisation off the request path) and use warm pools where boot is slow. Enable connection draining (deregistration delay) with a timeout longer than your slowest normal request. Test scaling with a load test, and watch the group's desired versus running count next to latency and error rate.
Common misconceptions
- "Autoscaling makes capacity instant." It follows demand with a delay of seconds to minutes.
- "Passing the health check means full capacity." Warm-up can take much longer than boot.
- "Scale-in is just scale-out in reverse." Removing capacity needs cooldowns and draining, or it causes errors and flapping.
- "Autoscaling fixes performance problems." It multiplies whatever the instance does, including its load on shared dependencies.
- "Aim for 90% utilisation to save money." Near saturation, queueing makes latency explode and there is no headroom for the scale-out lag.
Interview angle
When you put a stateless tier behind a load balancer, say how it scales: the metric, the target and why, min and max (min covers a zone failure, max protects the database and budget). Interviewers then probe the lag ("traffic doubles in 30 seconds, instances take 2 minutes"): answer with headroom, scheduled or predictive scaling for known peaks, and queueing or shedding for the rest. Mention draining, cooldowns, and that databases and caches are not autoscaled the same way.
Model assumptions
The traffic, queues, rejections and health checks are simulated; the autoscaler itself is not. Its decisions (launch, drain, terminate) are scripted at the moments a target-tracking policy with the stated rule would make them, and the lesson's tests check that the simulated utilisation justified each one. Each instance has 6 workers, an 80 ms mean service time (lognormal, cv 0.35) and room for 12 waiting requests (≈ 75 req/s). A "down" instance is an empty slot of the scaling group. Boot takes 0.8 s, health checks run every 250 ms (2 good checks admit an instance, 2 failures eject it), a cold instance runs at half speed for 1 s, and draining is modelled as a balancer weight of 0. The timeline is compressed: in real clouds these phases take tens of seconds to minutes. Utilisation is the busy-worker fraction averaged over the last second, not CPU. Arrivals are random (Poisson). Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together. Numbers show behaviour, not benchmarks.