Course contents

03. Scaling and Load Balancing Lesson 8 of 8

Autoscaling

Watch target tracking add instances during a ramp, why boot and warm-up make it lag, and how cooldowns, draining and schedules prevent errors and flapping.

16 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • An autoscaler is a control loop: measure a metric, compare it with a target, change the instance count within min and max.
  • Target tracking: desired = ⌈running × metric ÷ target⌉.
  • New capacity arrives after detection + boot + health checks + warm-up; the fleet must survive that window.
  • Known peaks are better handled by scheduled or predictive scaling; slow start protects cold instances.
  • Scale out fast, scale in slowly: cooldowns, stabilisation windows and draining prevent errors and flapping.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. A scaling group with two running instances

    Users reach the app through a load balancer. The scaling group may run between 2 and 4 instances; right now two run and slots 3 and 4 are empty (shown offline). Each instance handles about 75 requests per second.

    At 60 requests per second each running instance is about 40% busy. The autoscaler below the balancer watches the fleet’s average utilisation; its policy says: keep it near 60%.

    Scene: Users send 60 requests per second through a load balancer to two running app instances, each about 40% busy. Two more slots are empty. An autoscaler receives utilisation reports from the balancer.

    Key idea: An autoscaler changes the number of instances to keep a metric near a target, between a minimum and a maximum.

  2. 2. A traffic ramp against a fixed fleet

    First, imagine there is no autoscaler. Traffic ramps up: 100 requests per second at 0.3 s, 140 at 0.9 s, 200 at 1.5 s. Two instances can do about 150 in total.

    Utilisation climbs with every step. At 200 the instances are saturated, their queues fill and the balancer’s requests come back as 503 rejections (red packets). Nothing about the instances is broken; there are simply not enough of them.

    Scene: Traffic ramps from 60 to 200 requests per second. The two instances become saturated and some requests are rejected.

    Key idea: A fleet sized for the average fails at the peak.

  3. 3. Target tracking reacts, but late

    Now the autoscaler is on. Its target-tracking rule is: desired instances = ⌈running × utilisation ÷ target⌉.

    The rule looks at a 1-second average, so it lags the traffic a little. At 1.2 s the fleet is about 78% busy: ⌈2 × 0.78 ÷ 0.6⌉ = 3, so it launches App 3. At 2.0 s traffic is at 200 and the two instances are saturated: ⌈2 × 1.0 ÷ 0.6⌉ = 4, so it launches App 4.

    Each launch takes 0.8 s to boot, then the balancer needs two good health checks before it sends traffic. Meanwhile the peak is already here: requests are rejected from about 1.8 s until the new instances have joined and caught up. Afterwards four instances share 200 req/s at about 67% and the errors stop.

    Scene: The same ramp with an autoscaler. App 3 is launched at 1.2 seconds and App 4 at 2.0 seconds. Each boots for 0.8 seconds and must pass two health checks; requests are rejected until they join, then four instances share the load at about two-thirds utilisation.

    Key idea: Scaling reacts to load that has already arrived; boot plus health checks is the window in which users see errors.

  4. 4. New instances start cold

    A freshly booted instance is rarely at full speed. Its caches are empty, connection pools are still opening, and runtimes with a JIT (JVM, .NET) have not optimised the hot code yet. Here a new instance runs at half speed for its first second.

    The balancer does not know that. It gives App 3 an equal share, about 67 req/s, against a cold capacity of about 37. App 3 saturates and keeps rejecting requests after it has joined, so the error window is longer than in the previous step.

    Scene: The same ramp, but new instances run at half speed for their first second. App 3 receives an equal share while cold and becomes overloaded, so requests are rejected for longer.

    Key idea: Capacity arrives only when new instances are warm, not when they pass a health check.

  5. 5. Scale ahead of the peak

    This ramp happens every weekday at 9:00, so we do not have to wait for the metric. A scheduled action (or predictive scaling, which forecasts the daily pattern) starts App 3 and App 4 right away, before traffic rises.

    The balancer’s slow start gives the cold instances half weight until they are warm at 1.4 s. By the time 200 req/s arrives at 1.5 s, four warm instances are ready: no rejections, and P95 stays far below the reactive run.

    Scene: App 3 and App 4 are started before the ramp and get half weight while cold. When traffic reaches 200 requests per second four warm instances share it and nothing is rejected.

    Key idea: For known peaks, scale on the schedule, not on the symptom; use slow start so cold instances are not flooded.

  6. 6. Scaling in: wait, drain, then terminate

    The peak ends: at 0.3 s traffic falls to 60 req/s. Four instances are now 20% busy, and ⌈4 × 0.2 ÷ 0.6⌉ = 2.

    The autoscaler does not act at once. A scale-in cooldown (here 1.5 s, in production typically several minutes) makes sure the drop is real. Then, for each surplus instance, it drains first (the balancer sets its weight to 0, so no new requests go there and in-flight ones finish) and only then terminates it. App 4 drains at 1.8 s and stops at 2.3 s; App 3 drains at 2.6 s and stops at 3.1 s. No request fails, and the two remaining instances settle at about 40%.

    Scene: Traffic drops to 60 requests per second. After a cooldown the autoscaler drains App 4, then stops it, and does the same for App 3. No request fails; two instances remain at about 40% busy.

    Key idea: Scale out fast, scale in slowly: wait out a cooldown, then drain before you terminate.

  7. 7. Flapping: no cooldown, no draining

    A different team removes the cooldown and terminates instances straight away. Traffic wobbles between 110 and 90 req/s, which is normal noise.

    At 110, two instances are 73% busy, so App 3 is launched (0.2 s) and joins after booting. At 90 the fleet drops below target and App 3 is terminated at once (1.8 s), then launched again (2.4 s) and terminated again (4.0 s). Each termination kills the requests it was working on, and the balancer keeps sending it traffic until two health checks fail: red errors every time. Every launch also costs boot time and money.

    Scene: Traffic wobbles between 110 and 90 requests per second. App 3 is launched, terminated, launched and terminated again within five seconds; each abrupt termination makes requests fail.

    Key idea: Without a cooldown or a gap between scale-out and scale-in thresholds, normal noise makes the fleet oscillate.

  8. 8. Hysteresis: easy to add, slow to remove

    Same wobble, sensible policy. Scale-out still reacts within a second; scale-in requires utilisation to stay below target for a whole stabilisation window (longer than this wobble), and drains first.

    App 3 is launched once at 0.2 s and stays. Three instances at 90–110 req/s run at 40–50%, a little below the target, and that is fine: some idle capacity is cheaper than errors and churn. No request fails.

    Scene: The same wobble with a scale-in stabilisation window. App 3 is launched once and stays; three instances run at 40–50% and nothing fails.

    Key idea: Asymmetric policies (fast out, slow in) trade a little extra capacity for stability.

  9. 9. What autoscaling does and does not fix

    Autoscaling turns capacity into a control loop: measure, compare with a target, adjust. It works when instances are stateless, boot quickly and the bottleneck is the tier being scaled.

    It does not help with sudden spikes shorter than the boot time (keep headroom or queue work), with a saturated database behind the tier (more instances add load to it), or with instances that take minutes to warm. Set a minimum that survives a zone failure, a maximum that protects your budget and downstream systems, and alert when the group sits at its maximum.

    Scene: Three app instances serve about 90 requests per second behind the load balancer, with the autoscaler watching. Nothing fails.

    Key idea: Autoscaling follows demand with a delay; headroom, schedules and limits cover what the delay cannot.