Autoscaling and Capacity Planning: Signals, Lag, Headroom and Sizing a Fleet
At 20:00 a ticket sale opens. Traffic goes from 2,000 to 18,000 requests per second in 40 seconds. Your autoscaler is configured well by the textbook: target 60% CPU, scale up when above. It notices the spike after its next metrics read, asks for 40 more pods, and those pods need a new node each, which takes about 90 seconds to boot, plus 30 seconds for the JVM to warm up.
For roughly three minutes the existing 10 pods carry 9 times their normal load. Latency climbs from 60 ms to 12 seconds, clients time out and retry, which adds even more load, and by the time the new pods are ready the queue in front of them is so deep they fall over too. The autoscaler did everything right, two minutes too late.
Autoscaling is a control loop with a delay, and capacity planning is deciding how much spare capacity covers that delay. This article covers both: which signal to scale on, how the main autoscalers work, how to avoid flapping, and how to size a fleet from a load test with real arithmetic.
What it is
Autoscaling changes the amount of capacity (pods, instances, functions, nodes) automatically based on a signal, so you pay for roughly what you use and survive load you did not predict.
Capacity planning decides how much capacity you need for a given load and reliability target: how much one instance can handle, how much headroom to keep, how many instances survive losing a zone, and what minimums and maximums to give the autoscaler.
You need both. An autoscaler without capacity planning has no idea what a sensible target, minimum or maximum is. A capacity plan without autoscaling pays for peak all day. Running many copies at all requires the service to be stateless, covered in stateless vs stateful services, and spreading load across them is the job of load balancing.
How it works
The control loop
flowchart LR M["Measure<br/>CPU, RPS, queue depth"] --> C["Compare with target<br/>desired = current x metric / target"] C --> D["Decide<br/>stabilisation, min, max"] D --> A["Act<br/>add or remove pods"] A --> W["Wait for capacity<br/>boot, warm up, pass readiness"] W --> M style M fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style C fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style D fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style A fill:#E1F5EE,stroke:#0F6E56,color:#085041 style W fill:#FAEEDA,stroke:#854F0B,color:#633806
Most autoscalers use proportional control. The Kubernetes Horizontal Pod Autoscaler (HPA), for example, computes:
desired_replicas = ceil(current_replicas x current_metric / target_metric)
10 pods at 90% CPU, target 60%: ceil(10 x 90 / 60) = 15 pods
It ignores changes within a tolerance band (10% by default, and newer Kubernetes releases let you set tolerance per HPA), evaluates every 15 seconds by default, and by default uses a 300 second stabilisation window for scale-down, so it removes pods only if the recommendation has stayed lower for five minutes.
The yellow box in the diagram is the part people forget. Every step adds delay:
gantt title Time from spike to useful new capacity (typical, minutes and seconds) dateFormat ss axisFormat %M:%S section Detect Metrics scrape and aggregation :a1, 00, 30s Autoscaler evaluation :a2, after a1, 15s section Provision New node boots if needed :a3, after a2, 90s Image pull and container start :a4, after a3, 20s section Warm up App start and cache warmup and readiness :a5, after a4, 30s
That is three minutes from spike to relief, which is fine for a lunchtime peak that builds over 30 minutes and useless for a flash sale that arrives in 40 seconds. The whole art is choosing a combination of headroom, faster provisioning and scheduling that covers the lag.
Reactive, scheduled and predictive
- Reactive scaling responds to the current metric. It handles anything, including surprises, but always lags.
- Scheduled scaling raises the minimum before a known event: weekday 08:30, the 20:00 ticket sale, a marketing email. It has no lag, but only covers what you know about.
- Predictive scaling forecasts load from history (daily and weekly cycles) and provisions ahead of it. AWS Auto Scaling groups offer predictive scaling policies alongside target tracking. It helps with regular cycles, not with one-off events.
Mature setups combine them: predictive or scheduled to set the floor, reactive on top for surprises, and load shedding for whatever still exceeds capacity during the lag.
Choosing the signal
The signal must rise when the service needs more copies and fall when it does not. Pick the one closest to what actually saturates.
| Signal | Good for | Watch out for |
|---|---|---|
| CPU utilisation | CPU-bound request handling | I/O-bound services sit at low CPU while queueing; GC and JIT distort it |
| Requests per second per pod | Services with stable cost per request | Changes in request mix change the right target |
| In-flight requests (concurrency) | I/O-bound and long-lived requests | Needs the app or proxy to export it |
| Queue depth or consumer lag | Workers draining a queue or a Kafka topic | Scale on backlog per worker, not total backlog |
| Latency | Rarely as the primary signal | It rises from downstream problems too, and more pods will not fix those |
| Memory | Almost never | It rarely falls after scale-out, so the fleet ratchets up and never comes down |
Queue-driven workers deserve a note. If each worker processes 50 messages per second and you want backlog cleared within 60 seconds, the target is 3,000 messages of backlog per worker. That is what KEDA’s queue scalers compute for you. Queues themselves are covered in message queues.
The tools
Kubernetes HPA scales pod replicas on CPU, memory, or custom and external metrics through the metrics APIs. Vertical Pod Autoscaler adjusts pod CPU and memory requests instead of the count, and should not act on the same metric as an HPA for the same workload. The Kubernetes basics are covered later in containers and Kubernetes.
KEDA (Kubernetes Event-driven Autoscaling, a CNCF graduated project) feeds the HPA from event sources such as queue length, Kafka consumer lag, Prometheus queries or cron schedules, and adds scale to zero: it removes all pods when there is no work and brings one back when work arrives.
Pods need nodes. When pods cannot be scheduled for lack of room, a node autoscaler adds machines:
- Cluster Autoscaler grows and shrinks predefined node groups (for example an Auto Scaling group per instance type) based on pending pods, and removes nodes that have been underused for a while (10 minutes by default).
- Karpenter looks at the pending pods’ requirements and launches right-sized instances directly, choosing among many instance types, and consolidates by replacing or removing underused nodes. It usually provisions faster and packs tighter than fixed node groups.
AWS EC2 Auto Scaling groups support target tracking (keep average CPU or requests per target at a value, the same proportional idea as HPA), step scaling, scheduled actions and predictive scaling. Warm pools keep pre-initialised instances stopped or running on the side, so scaling out resumes an instance that has already booted and installed software instead of launching from scratch. An instance warmup setting stops brand-new instances from counting in the metric before they serve real load.
Cooldowns, stabilisation and flapping
A loop that reacts too fast oscillates: scale out, average CPU drops, scale in, CPU jumps, scale out again. Each cycle costs boot time and cache warmup and may drop connections. The fixes are asymmetric on purpose:
- Scale out fast, scale in slowly. Missing capacity hurts users; extra capacity for ten minutes only costs money.
- Stabilisation windows act on the highest (for scale-in) recommendation over a window, so brief dips do not remove pods.
- Cooldowns and warmup ignore new instances’ metrics until they are actually serving.
- Rate limits on change (at most double, or at most remove 10% per minute) stop a bad metric from scaling to the maximum or to zero in one step.
Scale to zero and cold starts
Scaling to zero removes all cost when idle, which is ideal for internal tools, preview environments and spiky event handlers. The price is a cold start: the first request waits for a pod or function to start. Knative and KEDA bring Kubernetes workloads back from zero; serverless platforms such as AWS Lambda do it per request, and Lambda SnapStart restores from a snapshot of an initialised environment to cut startup for Java, Python and .NET. For user-facing paths with a latency SLO, keep a minimum of at least one warm instance per zone, or pay for provisioned concurrency. The broader trade-offs are in serverless trade-offs.
Capacity planning
Why the target is not 100%
Queueing theory explains why you scale long before a server is busy. As utilisation approaches 100%, the time a request spends waiting grows without bound. In a simple single-server queue the latency multiplier is 1 divided by (1 minus utilisation): 2x at 50%, about 3.3x at 70%, 10x at 90%. The background is in latency vs throughput. Try it: move utilisation from 60% to 85% and see how fast the curve bends.
Real servers with many worker threads tolerate higher utilisation than this single-server model before latency bends, so 60 to 75% CPU targets are common for web services. The point stands: the target must leave room for both queueing and the scaling lag.
Headroom for lag and for failure
Headroom must cover two separate things.
Lag headroom. If traffic can grow by g during the time it takes to add capacity, the target utilisation u must satisfy u x (1 + g) at most equal to the highest utilisation you can tolerate. With a three minute lag, 20% growth possible in that window, and an 85% ceiling: u at most 0.85 / 1.2 = about 71%.
Failure headroom. N+1 means you can lose any one unit (instance, node, zone) and still carry peak. N+2 means you can lose one during a planned outage of another, for example a zone failure during a deploy. For a service spread across three zones, losing a zone removes a third of capacity at once, and the autoscaler takes minutes to replace it, often while every other customer in that region is trying to do the same.
The same arithmetic, scaled up, is what you do in an interview with numbers from back-of-envelope estimation.
Capacity planning from load tests
Load tests give you the per-instance number every plan depends on. Do them properly:
- Test with realistic request mixes and data sizes, not one cheap endpoint.
- Ramp until the SLO breaks and record the knee of the latency curve, then plan below it.
- Test the full path: one pod rarely breaks first; the database, a cache or a third-party API often does.
- Retest after big releases, runtime upgrades and instance type changes, because the per-pod number drifts.
- Compare forecast growth against the plan quarterly and track how long it takes to get more capacity (quota increases, reserved capacity, larger database instances), since some of it takes weeks, not minutes.
Where it breaks
- Scaling on the wrong signal. An I/O-bound service waiting on a slow database shows low CPU, so CPU-based scaling never fires while requests pile up. Scale on concurrency or queue depth instead.
- Scaling the wrong layer. If the database is the bottleneck, adding 40 pods adds 40 times the connections and makes it worse. Autoscaling only fixes the tier it scales.
- Retry storms during lag. Clients that time out and retry immediately multiply load exactly while capacity is short. Backoff with jitter, covered in timeouts, retries and backoff, and load shedding protect the gap.
- Capacity that is not there. Instance types run out in a zone during regional incidents, and account quotas cap growth. Allow several instance types, keep quotas well above your maximum, and reserve capacity for critical services.
- Maximum too low or missing. A bug that makes every request expensive, or a bot attack, scales you to the limit. A sensible maximum and a budget alert stop a bad day from becoming a large bill, a topic for cloud cost engineering.
- Scale-in kills work. Removing a pod mid-request or mid-job loses work unless graceful shutdown and draining are in place.
Real-world systems
- Kubernetes HPA with default 15 second evaluation, 10% tolerance and a 300 second scale-down stabilisation window.
- KEDA for event-driven scaling and scale to zero on Kubernetes.
- Cluster Autoscaler and Karpenter for nodes.
- AWS EC2 Auto Scaling with target tracking, scheduled actions, predictive scaling and warm pools.
- Knative for request-driven scaling of containers, including to zero, using concurrency as the default signal.
- AWS Lambda scales per request by concurrency, with provisioned concurrency and SnapStart to reduce cold starts.
How to apply it
A practical default for a stateless web service:
- Load test one instance and find the safe per-instance throughput below the SLO knee.
- Size for peak plus zone loss (N+1 at zone level), and set that as the scheduled minimum during peak hours.
- Scale reactively on the signal closest to saturation: CPU for CPU-bound, concurrency or RPS per pod for I/O-bound, backlog per worker for queues.
- Target 60 to 70% of the safe per-instance number, then check it against your lag headroom.
- Scale out fast, in slowly, with a stabilisation window of several minutes.
- Add scheduled or predictive scaling for known peaks, and load shedding for the rest.
- Set a maximum, check downstream connection limits at that maximum, and alert when you hit it.
Interview angle
Interview questions
Q1: A flash sale will take traffic from 2,000 to 20,000 RPS in under a minute. How do you handle scaling?
Reactive autoscaling cannot help, because getting new capacity takes minutes and the spike takes seconds. Scale ahead: a scheduled action 20 to 30 minutes before the sale raises the minimum to full peak capacity plus zone headroom, and checks that nodes are actually up and pods ready, not just requested. Pre-warm caches and confirm database and downstream limits at that size. Keep reactive scaling on top for overshoot. Protect the system during any gap: admission control or a waiting room, load shedding of low-priority traffic, and clients that back off with jitter. Afterwards, scale in slowly so a second wave does not catch you short.
Q2: Workers consume from a queue. CPU stays at 20% but the backlog grows. What is wrong and what should you scale on?
The workers are I/O-bound, waiting on a database or an external API, so CPU never crosses the target and the autoscaler never acts. Scale on backlog per worker: if one worker drains 50 messages per second and you want backlog cleared within a minute, target 3,000 messages per worker, which KEDA or a custom metric can drive. Before adding workers, check the dependency they wait on: if it is saturated, more workers add contention and the fix is there (more capacity, batching, or rate limiting the workers to what it can take).
Q3: Size a fleet for 12,000 RPS peak at 80 ms mean latency across three zones.
Little’s law gives concurrency: 12,000 x 0.08 = 960 requests in flight. From a load test, suppose one pod safely does 400 RPS within the SLO, which is 32 in flight per pod. Peak needs 12,000 / 400 = 30 pods. To survive a zone loss, two zones must carry all 30, so 15 per zone and 45 in total. Each pod then runs at about 267 RPS at peak, about two thirds of its safe rate, leaving room for scaling lag. Then check downstream: 45 pods times their database pool size must fit the database, or put a pooler in front.
✅ Key takeaways
- Autoscaling is a delayed control loop. Detection, provisioning and warmup typically take minutes, so headroom, scheduling or load shedding must cover the gap.
- Scale on the signal closest to saturation: CPU for CPU-bound work, concurrency or RPS per pod for I/O-bound, backlog per worker for queues. Almost never memory.
- Kubernetes HPA scales pods proportionally; KEDA adds event sources and scale to zero; Cluster Autoscaler and Karpenter add nodes; AWS ASGs add target tracking, predictive scaling and warm pools.
- Scale out fast and in slowly with stabilisation windows to avoid flapping.
- Size from load tests and Little’s law, then add failure headroom: surviving one of three zones costs 1.5x the bare count.
🧠 Check your understanding
0 / 4-
1An HPA has 10 pods at 90% average CPU and a 60% target. How many pods does it ask for?
desired = ceil(10 x 90 / 60) = 15. Doubling to 20 is a common guess but over-shoots, and adding one at a time is step scaling, not the proportional rule the HPA uses.
-
2Which metric is usually the worst choice as the primary autoscaling signal for a web service?
Memory rarely falls after adding pods, because caches and heaps fill up, so the fleet scales out and never back in. The others track load and drop when capacity is added.
-
3A service needs 30 pods at peak and runs across 3 zones. How many pods survive one zone loss with no SLO breach?
After losing a zone, the remaining two must hold 30 pods, so 15 per zone and 45 total. 33 (adding 10%) treats the loss as a single pod, not a third of the fleet.
-
4A peak of 6,000 requests per second with a mean latency of 50 ms means how many requests are in flight on average?
Little's law: L = lambda x W = 6,000 x 0.05 s = 300. 120 comes from dividing instead of multiplying (6,000 / 50). The number sizes thread pools and connection pools.
Where to go next
- Consistent hashing: when the copies are not interchangeable, scaling them in and out must move as few keys as possible.
- Bulkheads, load shedding and backpressure: what to do with the load that arrives before new capacity does.
- Containers and Kubernetes: the platform most of these autoscalers run on.
- Cloud cost engineering: turning capacity plans into reserved capacity, spot and budgets.
Finished this lesson?
Mark it complete to track your progress across the roadmap.