Sub topic 11
Autoscaling based on load
This chapter assumes you know the difference between vertical and horizontal scaling. It also assumes you know what a load balancer does and why application servers should be stateless. Autoscaling builds on all three.
What autoscaling does
Autoscaling changes the amount of capacity automatically as load changes. Instead of a person adding servers before a sale and removing them afterward, a controller watches a metric and adjusts the number of instances.
Most autoscaling is horizontal. It works because of two earlier ideas:
- A load balancer sends traffic to new instances as soon as they are registered.
- Stateless servers can be added or removed without losing user sessions.
If either is missing, new instances either receive no traffic or break user sessions when they disappear.
The control loop
An autoscaler repeats a simple cycle: measure, compare to a target, decide, act, wait.
The wait at the end matters. A new instance takes time to start, warm up, and pass health checks. If the autoscaler measures again too soon, it still sees high load and adds more instances than it needs.
Choosing a metric
The metric should rise when the system needs more capacity and fall when it has too much.
| Metric | Good for | Caution |
|---|---|---|
| CPU utilization | CPU-bound web or API servers | Misleading for I/O-bound work |
| Requests per instance | Web services behind a load balancer | Needs a sensible per-instance limit |
| Queue length | Background workers | Scale on backlog per worker, not raw size |
| Latency | Protecting user experience | Lags behind the load that caused it |
Use the bottleneck you found earlier to pick the metric. If the database is the bottleneck, scaling on web server CPU adds servers that only increase pressure on the database.
Example: Kubernetes HorizontalPodAutoscaler
Kubernetes expresses this policy declaratively. The following HorizontalPodAutoscaler keeps the web Deployment between 2 and 10 replicas, aiming for average CPU utilization of 70%.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70The core calculation is a ratio:
desired replicas = ceil(current replicas × current metric / target metric)
If 4 replicas average 90% CPU against a 70% target, the result is ceil(4 × 90 / 70) = ceil(5.14) = 6 replicas. If load drops and 6 replicas average 35%, the result is ceil(6 × 35 / 70) = 3.
CPU utilization here is measured against each pod's CPU request. If the Deployment sets no CPU request, the autoscaler cannot compute utilization.
Setting the bounds
minReplicas and maxReplicas are safety limits.
- Minimum: Keep at least 2 for availability. With one instance, a single failure takes the service down while a replacement starts.
- Maximum: This is a cost cap and a protection for downstream systems. Without it, a traffic flood or a bug that burns CPU can scale you into a very large bill.
Set the maximum with the data tier in mind. Ten web replicas each opening 20 database connections need 200 connections. If the database allows 100, autoscaling will push you into failure rather than away from it.
Common errors
- Flapping. The autoscaler adds instances, load per instance drops, it removes them, load rises again, and the cycle repeats. Use cooldown periods and a stabilization window, and scale in more slowly than you scale out.
- Scaling too late. Startup can take minutes. Spikes that arrive faster than that cause errors before new capacity is ready. Keep a higher minimum, use scheduled scaling for predictable peaks, or choose a lower target such as 50% to leave headroom.
- Scaling on the wrong signal. CPU stays low on a service that waits on a slow dependency, so it never scales while users see delays.
- Ignoring stateful parts. Autoscaling the web tier is routine. Databases usually cannot scale this way, because adding a replica or shard involves data movement and replication.
- Cutting off in-flight requests. When removing an instance, stop sending it new requests and let existing ones finish (connection draining) before shutting it down.
Exercise
A service has 5 replicas averaging 40% CPU against a 60% target, with minReplicas 2 and maxReplicas 10. How many replicas does the Kubernetes formula choose, and why might you still be cautious about letting it scale in that far?
Show answer
ceil(5 × 40 / 60) = ceil(3.33) = 4 replicas. Removing a replica shrinks headroom, so a sudden spike could arrive before new replicas are ready. A slower scale-in policy or stabilization window avoids flapping and keeps capacity for short bursts.
Exercise
Your web tier autoscales up to 20 replicas, each holding 10 database connections, and the database accepts 150 connections. What is the problem, and what are two ways to fix it?
Show answer
At 20 replicas the service needs 200 connections, which exceeds the 150 limit, so new replicas will fail or starve. Fixes include lowering maxReplicas to 15 or fewer, reducing per-replica pool size, adding a connection pooler in front of the database, or raising the database limit if it has the resources.