Sub topic 11
Autoscaling Based on Load
This chapter assumes you know what horizontal scaling, load balancing, and stateless application servers are, and that you can read latency, throughput, and utilization numbers. Autoscaling automates the decision of how many servers (or how big a server) to run. It adds capacity when load rises and removes it when load falls.
What autoscaling is
Autoscaling is a control loop. A system measures a signal, compares it with a target, and changes the amount of capacity to bring the signal back toward the target.
The loop has four parts:
- Metric source. Something produces a number, such as average CPU utilization, requests per second per instance, or queue depth.
- Policy. A rule says what the metric should be, for example "keep average CPU near 70%".
- Actuator. A component changes capacity by starting or stopping instances, pods, or containers.
- Limits. A minimum and a maximum keep the loop from shrinking to zero or growing without bound.
Autoscaling depends on two earlier chapters. Horizontal scaling needs a load balancer, so new instances can receive traffic. It also needs stateless design, so an instance can disappear without losing user data. If servers keep session data in local memory, scaling in will log users out or lose work.
Horizontal and vertical autoscaling
Most autoscaling is horizontal. The system changes the number of identical instances. This fits the stateless model and has no practical ceiling short of your account quotas and your data tier.
Vertical autoscaling changes the size of one instance, for example by raising its CPU and memory requests. It is used for workloads that cannot be split, such as a single-writer database or a legacy process. Resizing often requires a restart, so it causes a short interruption. Do not combine horizontal and vertical autoscaling on the same metric, such as CPU, for the same workload. The two controllers react to the same signal and fight each other.
A target-tracking example in Kubernetes
A HorizontalPodAutoscaler (HPA) is the Kubernetes object that scales the number of pod replicas of a workload. This one keeps the web Deployment between 2 and 10 replicas, aiming for 70% average CPU utilization.
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 HPA computes the desired replica count with a proportional rule:
desiredReplicas = ceil(currentReplicas * currentMetric / targetMetric)Suppose 4 replicas are running at an average of 105% of their CPU request. The result is ceil(4 * 105 / 70), which is 6. If CPU later drops to 35% across 6 replicas, the result is ceil(6 * 35 / 70), which is 3.
Three details matter in practice:
- Utilization is relative to the CPU request. The percentage is usage divided by the amount the pod requested, not by the machine's total CPU. If pods have no CPU request, the HPA cannot compute utilization for them.
- A tolerance band avoids tiny changes. The controller ignores differences of roughly 10% from the target.
- The
minReplicasvalue is also your availability floor. A value of 2 keeps a second replica running if one fails.
Types of scaling policy
| Policy type | How it decides | Good for | Weakness |
|---|---|---|---|
| Target tracking | Keeps a metric near a target value | Steady, proportional workloads such as web APIs | Reacts only after load has changed |
| Step scaling | Adds or removes fixed amounts when a metric crosses thresholds | Workloads where large spikes need larger responses | More thresholds to tune and maintain |
| Scheduled scaling | Changes capacity at set times | Predictable patterns such as business hours or a planned launch | Wrong if the pattern shifts |
| Queue-based scaling | Sizes workers to backlog or message age | Background jobs and consumers | Needs a good estimate of time per job |
| Predictive scaling | Forecasts load from history and scales ahead | Recurring daily or weekly cycles | Needs enough history, and fails on one-off events |
Target tracking is the usual starting point. Add scheduled scaling when you know a spike is coming, because reactive scaling always lags.
Choosing the metric
The metric decides how well the loop behaves. A good scaling metric has three properties:
- It rises when the system needs more capacity and falls when it has too much.
- It changes roughly in proportion to the number of instances. Doubling instances should roughly halve the per-instance value.
- It is available quickly and reliably.
CPU is the default because it is easy to get and often tracks work done. It fails for workloads limited by something else. A service waiting on a database spends little CPU, so CPU stays low while latency climbs. Better signals for such services are requests per second per instance, active connections, or queue depth.
Latency is a tempting scaling metric, but be careful. If the bottleneck is a shared database, adding application instances does not reduce latency and may increase it by adding more connections. The loop then scales to its maximum and makes things worse. Use the bottleneck analysis from the earlier chapter to confirm that the tier you scale is the tier that is saturated.
For a worker pool that processes a queue, a useful target is backlog per worker:
import math
def desired_workers(queue_depth, seconds_per_job, acceptable_delay_s,
min_workers=1, max_workers=50):
# Jobs one worker can finish within the acceptable delay.
jobs_per_worker = acceptable_delay_s / seconds_per_job
needed = math.ceil(queue_depth / jobs_per_worker)
return max(min_workers, min(max_workers, needed))
print(desired_workers(queue_depth=600, seconds_per_job=2, acceptable_delay_s=60)) # 20
print(desired_workers(queue_depth=0, seconds_per_job=2, acceptable_delay_s=60)) # 1
print(desired_workers(queue_depth=5000, seconds_per_job=2, acceptable_delay_s=60)) # 50With 600 jobs at 2 seconds each and a 60-second delay budget, one worker handles 30 jobs, so 20 workers are needed. The last call shows the cap: the formula asks for 167 workers, and the maximum limits it to 50.
Timing: why autoscaling lags
Autoscaling is never instant. The delay has several parts:
- Metric delay. Metrics are collected and aggregated at intervals, often 15 to 60 seconds, and some cloud metrics are one minute or older.
- Decision delay. The controller evaluates on a schedule, and may require the signal to persist before acting.
- Provisioning delay. A new virtual machine can take minutes to boot. A container on an existing node starts faster, but the node may need to be added first.
- Warm-up delay. The application must start, load caches, open connections, and pass health checks before the load balancer sends it traffic.
The sum is the time during which the system is under-provisioned. A sudden spike that doubles traffic in 30 seconds can overload the existing instances before any new one is ready. Ways to cope include:
- Keep headroom by setting the utilization target lower, such as 50% to 60% instead of 80%.
- Use a higher
minReplicasbefore known events. - Use scheduled or predictive scaling for recurring peaks.
- Make startup fast with small images and lazy initialization.
- Let the load balancer shed or queue excess requests, rather than letting instances collapse.
Scaling in: the dangerous direction
Scaling out costs money if you are wrong. Scaling in can cause outages if you are wrong, so controllers treat the two directions differently.
Flapping is when capacity repeatedly goes up and down because the signal oscillates around the target. Each cycle wastes startup work and can drop requests. Controllers reduce flapping with:
- Cooldown or stabilization windows. After a change, the controller waits before reversing it. Kubernetes HPA uses a default scale-down stabilization window of 300 seconds, picking the highest recommendation seen in that window.
- Asymmetric rates. Scale out quickly and scale in slowly.
- A gap between thresholds. In step policies, add capacity above 75% but remove it only below 40%.
Scale-in must also be graceful. Before an instance stops, the load balancer should stop sending it new requests, and in-flight requests should finish. This is called connection draining. Without it, each scale-in event produces failed requests. Long-running jobs need extra care, because terminating a worker mid-job loses its work unless the job is retried or checkpointed.
The following HPA fragment makes scale-in slower than scale-out:
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: 70
behavior:
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 1
periodSeconds: 60Here the workload can double every minute but loses at most one pod per minute, and only after 5 minutes of lower demand.
Common errors
- No resource requests. The HPA cannot calculate CPU utilization without a CPU request on each container.
- Scaling the wrong tier. Autoscaled web servers can overwhelm a fixed-size database. Check connection limits and pool sizes before raising
maxReplicas. - A maximum that is too high. A bug or an attack can drive the loop to the maximum, and the bill follows. Set a ceiling you can afford and alert when it is reached.
- A minimum that is too low. A minimum of 1 means a single failure removes all capacity until a replacement starts.
- Stateful instances. Local sessions, local file uploads, and in-memory job state do not survive scale-in.
- Slow readiness checks. If new instances count as ready before they can serve traffic, they receive requests too early and fail.
- Ignoring cluster capacity. In Kubernetes, new pods stay pending if no node has room. A separate node autoscaler must add machines, which adds more delay.
- Treating autoscaling as a fix for inefficiency. If one request does wasteful work, more instances hide the problem at higher cost.
Cost and limits
Autoscaling saves money when load varies a lot. If the peak is 5 times the average, running at peak capacity all day wastes most of the spend. When load is flat, autoscaling adds complexity and little saving. Reserved or committed-use pricing for the baseline, with autoscaled capacity on top, is a common mix.
Autoscaling does not remove the limits from the earlier chapters. Amdahl's law still caps the speedup from adding workers when part of the work is serial, and shared resources such as the primary database remain ceilings. The autoscaler only automates how many copies you run.
Exercise
A service has 5 replicas, each averaging 90% CPU against a CPU request. The HPA target is 60% utilization. How many replicas does the proportional rule ask for, and why might the real system still be overloaded for a few minutes after the load rise?
Show answer
The rule gives ceil(5 * 90 / 60) = ceil(7.5) = 8 replicas. The system can still be overloaded because of delays: metrics are collected at intervals, the controller evaluates on a schedule, new pods must be scheduled and started, and they must pass readiness checks before receiving traffic. During that time the existing 5 replicas carry the full load.
Exercise
Your autoscaled web tier reaches its maximum of 40 instances during a traffic spike, yet latency keeps rising. Database CPU is at 95%. What is the likely problem, and what should you do before raising the maximum?
Show answer
The bottleneck is the database, not the web tier. Adding web instances adds more concurrent queries and connections to an already saturated database, so it does not help and can hurt. Before raising the maximum, address the data tier: add caching, read replicas for read-heavy traffic, connection pooling, or query tuning, and consider capping the web tier at a size the database can support.
Exercise
Why do autoscalers usually scale in more slowly than they scale out?
Show answer
Scaling out too much only costs extra money for a short time, while scaling in too much can cause an outage and then force another slow scale-out. Slow scale-in, with stabilization windows and limits on how many instances are removed at once, also prevents flapping when load oscillates around the target.