System Design

Core Concepts

Capacity Planning and Autoscaling

Autoscaling saves money in the ordinary hours. The capacity plan is what the fleet holds for the worst few minutes: a zone gone, load still climbing, and no new machine ready yet. And for data tiers whose nodes you run, autoscaling isn't the answer at all.

Why you are doing this at all

In 2013 Netflix listed the cases its reactive autoscaling handled badly. Reactive means it adds or removes instances in response to a metric it has just measured, such as CPU. Two of those cases explain most of this page.

The first was a fast rise in demand. Netflix's instances took 10 to 45 minutes to start, and until they were ready, the servers already running carried all the extra load.

The second was an outage. During an outage, incoming traffic can drop sharply. The autoscaler sees less load and removes instances. When the fault is fixed, a retry storm can follow, and it arrives at a fleet that has just been made smaller.

In both cases the autoscaler did what it was built to do. It acted on what it had just measured, and new capacity took minutes to arrive. So the question that sets a fleet's size isn't how many machines the average hour needs. It's what the fleet survives in the minutes before help arrives.

Size a fleet for its worst few minutes: a zone gone, load still climbing, and no new machine ready yet. Autoscaling saves money in every other minute, and adds nothing until its lag has passed.

Back-of-envelope estimation ends with a peak load and a rough figure for what one machine does. This page starts there. It turns the peak into a measured capacity per instance, a utilisation target, a reserve for failures and a scaling policy. It also covers the tiers where autoscaling doesn't work: data tiers whose nodes you run.

Back of envelopeWhat following the daily curve saves
The question is whether autoscaling is worth building for
an API whose busiest minute runs at 24,000 requests a
second, in the evening. It falls to 4,000 at night and
averages 10,000. A load test shows one instance serves
1,000 a second within its latency target.

Fixed fleet, sized for the peak
  target 67% of tested capacity, the zone reserve
  instances     24,000 / 670              ≈    36
  per day       36 × 24 hours             =   864 instance-hours

Autoscaled fleet, following the curve
  target 60%, from the first worked example
  instances     10,000 / 600, on average  ≈  16.7
  per day       16.7 × 24 hours           ≈   400 instance-hours
  saving        1 − 400 / 864             ≈   54%

The same service on a flat day: peak 12,000, average 10,000
  fixed         12,000 / 670 ≈ 18, × 24   =   432 instance-hours
  autoscaled    before rounding up         ≈   400 instance-hours
  saving        1 − 400 / 432             ≈    7%
  ─────────────────────────────────────────────────────
  With a peak 2.4 times the average, autoscaling halves
  the fleet. On a flat day it saves under 10 percent, and
  you still have to plan for its lag.

The autoscaled figure is a little low, because each hour rounds up to a whole instance and the night has a floor. Cost as a design constraint turns instance-hours into a bill.

When you don't need autoscaling

Skip it when the floor is the fleet. If surviving the loss of a machine or a zone already needs more instances than the peak does, the fleet never changes size.

Skip it when the load is flat. The worksheet's flat day saves under 10 percent, and less once each hour rounds up to whole instances. You still pay for the lag reserve and a policy to maintain.

Don't use it for data tiers whose nodes you run: databases, caches, brokers and search indexes. Plan those from a forecast, as tiers that hold data explains.

Utilisation, headroom and lag

Why you never plan for 100 percent busy

Little's law gives the number of busy workers: the arrival rate times the time each request takes. At 800 requests a second and 10 ms of work each, 8 workers are busy on average. With 10 workers, utilisation is 80 percent. Circuit breakers, bulkheads and backpressure builds its whole treatment of overload on the same law.

Latency numbers that matter shows what utilisation costs a single worker. Response time is the work divided by one minus utilisation, so at 90 percent busy a request takes 10 times its work. That model has one worker with its own queue.

Most servers have many workers taking from one queue, such as a pool of threads or a set of cores. With more workers on the queue, the bend moves to the right, because an arriving request is more likely to find a worker free. The Erlang C formula, the standard result for several workers sharing one queue, gives the numbers.

Response time against utilisation, by workers per queue
Each curve is the mean response time as a multiple of the work itself, for workers sharing one queue. One worker, in red, is the curve from latency numbers that matter: 10 times at 90 percent busy. Four workers, in teal, reach 3 times there. Sixteen, in green, reach 1.4 times. The model assumes random arrivals and random work times.Each curve is the mean response time as a multiple of the work itself, for workers sharing one queue. One worker, in red, is the curve from latency numbers that matter: 10 times at 90 percent busy. Four workers, in teal, reach 3 times there. Sixteen, in green, reach 1.4 times. The model assumes random arrivals and random work times.
The more workers share a queue, the later the wait climbs. Each curve is the mean response time as a multiple of the work itself, for workers sharing one queue. One worker, in red, is the curve from latency numbers that matter: 10 times at 90 percent busy. Four workers, in teal, reach 3 times there. Sixteen, in green, reach 1.4 times. The model assumes random arrivals and random work times.

So the bend isn't at one fixed utilisation. It depends on how many workers share the queue that fills first. That might be a server's 16 cores, a pool of 4 database connections, or a lock, which is a queue with one worker. The narrowest queue sets the knee, the load past which latency climbs steeply. You usually can't tell from the code which queue that is.

That's why the number you plan with is a request rate measured by a load test, not a CPU percentage. You then plan below that rate, because of failures and lag.

Finding the knee with a load test

Back-of-envelope estimation gives a web service that makes one database call per request 1,000 to 5,000 requests a second. That's a first guess. The number you plan with comes from a load test of your own service.

Raise the load on one instance in steps, with its real dependencies behind it. At each step, record throughput, the p99 latency (the time 99 requests in 100 beat) and how busy each resource is. The tested capacity is the highest load at which the instance still meets its latency target. Every share on this page is a share of it. Google's Site Reliability Engineering (SRE) book makes the same link: capacity planning has to be coupled with performance testing, to find the load at which the service fails.

Then keep going past the knee, to see how the service fails. Google's advice is to load test components until they break. A well-built service rejects some requests and keeps serving the rest. A badly built one crashes or starts failing a large share of requests. The book also says a gradual ramp and a sudden step can give different results, so test both. And check that the service recovers by itself when the load drops.

The same test finds the bottleneck. If CPU sits at 40 percent at the knee, some other queue filled first: a connection pool, a lock or a downstream service. Latency numbers that matter works through a service stuck at 500 requests a second with CPU at 30 percent, where Little's law points at a pool of 50 connections. Read each resource's saturation, its queue of waiting work, the way the USE method (utilisation, saturation and errors) in observability does.

Two habits make a load test overstate what the service can do. A warm cache answers from memory, while production also has to start cold. And a test client that waits for each reply before sending the next request hides the tail, as latency numbers that matter explains.

Headroom for losing a machine, a zone or a region

A fleet has to keep its latency target after something fails. The failure it must survive sets how much of its tested capacity it can use.

For a small fleet, that's one machine. With two instances, the survivor of a failure carries both shares, so neither can run above 50 percent.

Larger fleets spread across availability zones. A zone is one or more datacentres with their own power, cooling and network, as multi-region and disaster recovery explains. With three zones, a zone failure moves a third of the load onto the other two, so each surviving instance carries 1.5 times its share. That caps planned load at two-thirds of tested capacity, however large the fleet.

Back of envelopeWhich failure sets the reserve
The question is how much of each instance's tested
capacity the fleet may use, given the failure it must
survive. A survivor's load grows by the share it absorbs.

Losing one instance of N
  N = 2      survivor carries 2/1          →  max 50%
  N = 4      survivors carry 4/3           →  max 75%
  N = 10     survivors carry 10/9          →  max 90%

Losing one zone of 3
  any fleet size: survivors carry 3/2      →  max 67%

Google's example, N + 2, counted in clusters
  peak 19,000 / 5,000 per cluster          =  3.8 → 4
  plus 2 that may be out at once           =  6 clusters
  ─────────────────────────────────────────────────────
  From three instances spread over three zones, the zone
  sets the reserve, not the single machine.

Regions follow the same rule. Multi-region and disaster recovery works out the ceiling of (N − 1) / N for N regions, and shows two regions at 70 percent failing into 140 percent behind a cold cache.

Deploys take capacity out too. A rolling deploy needs spare capacity for each batch it replaces, as blue-green and canary deployments explains, so count the largest batch in the reserve.

You don't have to hold the whole reserve. If you hold less, the survivors run past their knee until autoscaling adds capacity, so decide in advance what they stop doing in the meantime.

Peak, seasons and forecasts

Load repeats. It has a daily cycle, a weekly one and a yearly one, with events on top.

Google's SRE book splits growth into two kinds. Organic growth comes from people adopting the product. Inorganic growth comes from launches, marketing campaigns and other business decisions, which no history predicts. A forecast needs both. It also has to reach further ahead than the time it takes to get capacity. For a stateless instance that's minutes. For a database that has to be split, it can be months.

Forecast the demand, not the utilisation. Netflix found load average a poor thing to predict, because load average is partly a result of the autoscaling itself. It also changes with every deploy, as the code gets faster or slower. Requests per second do neither, so Netflix predicted requests and divided by what one server handles to get the fleet size.

The estimation page multiplies the average up to a peak, because a fixed fleet has to be sized for its peak. On this page the peak is the busiest minute, since the scaler here reads one-minute metrics. Bursts shorter than a minute come out of the gap between the target and tested capacity. If your busiest second runs well above your busiest minute, measure the ratio and multiply it into the target with the other reserves.

An autoscaled fleet is sized differently. Target tracking keeps the fleet near its target in every hour, so the peak itself needs no extra reserve. The steepest climb does. The fleet trails the load by one lag, so during a climb it runs above its target.

Scale-up lag

Autoscaling adds an instance some minutes after load starts to rise. Those minutes have three parts.

Detection. The scaler reads a metric at intervals and waits for several readings past the target, so that one noisy minute doesn't move it.

Boot. The cloud launches a machine, the operating system starts, the image is pulled and the process starts.

Warm-up. A new instance is slow at first. Its caches are empty, its just-in-time (JIT) compiler hasn't optimised the hot code yet, and its connection pools aren't open. AWS's autoscaler and Kubernetes's Horizontal Pod Autoscaler (HPA) both leave a new instance's metrics out of the scaling decision while it warms up. Load balancing also ramps its share of traffic up over tens of seconds.

Back of envelopeHow much load arrives during the lag
The question is how far a fleet at its target gets
pushed before new instances carry load, and whether to
shorten the lag or hold more reserve. Lines marked
"assumed" are round figures, not measurements.

The lag
  detect: 1-minute metrics, 3 readings       3 min  assumed
  launch, boot, start the process            4 min  assumed
  warm up, metrics ignored meanwhile         3 min  assumed
  ─────────────────────────────────────────────────────
  total                                     10 min

The steepest climb of the day: 1% a minute, assumed
  over 10 minutes        1.01^10            ≈  1.10
  highest safe target    1 / 1.10           ≈   90%

With a 30-minute boot, inside Netflix's range
  lag 3 + 30 + 3                            =  36 min
  over 36 minutes        1.01^36            ≈  1.43
  highest safe target    1 / 1.43           ≈   70%
  ─────────────────────────────────────────────────────
  With the zone reserve as well, the 10-minute lag allows
  a 60 percent target and the 36-minute lag allows 47.
  That is about 28 percent more instances, all day.

So a slow boot costs instances in every hour, not only during the climb. A warm pool shortens it: instances are booted and initialised in advance, then stopped, and you pay only for their disks while they wait. The other fix is to launch ahead of a forecast, so the lag has passed before the climb arrives.

An instance may carry its tested capacity divided by the zone reserve and by the climb during the lag.

Autoscaling policies

Which signal to scale on

A target-tracking scaler needs a metric that falls when instances are added. AWS puts it as a rule: the value must rise or fall in proportion to the number of instances. Three signals meet it.

  • CPU utilisation. Use it when CPU is the resource that fills first.
  • Requests per instance. Use it when the knee shows up somewhere other than CPU, and requests cost about the same.
  • Backlog per worker. Use it for consumers of a queue: messages waiting, divided by workers running.

CPU is the usual default, because every scaler reads it without extra code. It fails when another queue fills first. A service whose knee comes from a pool can reach it at 40 percent CPU, below a 60 percent CPU target, so the scaler never fires.

Requests per instance takes its target straight from the load test: tested capacity times the target share. It drifts if the mix of requests changes, because the knee moves with the mix.

Backlog per worker suits queue consumers, and the second worked example derives its target.

Three tempting metrics don't move with fleet size, and AWS lists all three. The total request count at the load balancer is set by users, so more instances don't lower it. Latency rises with load but not in proportion, and it also rises when a dependency slows down, where more instances only send that dependency more calls. A raw queue length ignores how many workers are draining it, so a scaler that targets it keeps adding workers while the queue is already shrinking.

Reacting or forecasting

With a signal chosen, the policy decides when to add capacity and how much. Take the API from the first worksheet in its busiest minute: 40 instances across three zones, serving 600 requests a second each against a tested 1,000. A zone fails and takes 13 instances with it. The 27 left each serve about 900. How fast does the policy get back to 40, and could it have been ready before the load arrived?

Naive

Simple rules on a CPU alarm

Add two instances when CPU stays above 80 percent for five minutes, and remove one when it falls below 30. Each rule is easy to read, which is why teams start here.

The alarm stops at the wrong place. Say an instance runs at 80 percent CPU when it serves 800 requests a second. Near 30 instances, 24,000 / 30 = 800 each, CPU falls to 80 and the rules stop adding. The fleet never gets back to 40, so it has no zone reserve left. That's because 80 percent is past the 67 percent a zone loss allows.

It's also slow. Two instances is 20 percent of a fleet of 10 and 5 percent of a fleet of 40, so the step is smallest when the fleet is largest. And each step waits out a cooldown, a fixed pause that starts only after the new instances finish launching. AWS's own documentation recommends against these simple policies and cooldowns.

Senior

Target tracking on a per-instance metric

Set a target for the metric and let the scaler work out the fleet size. The HPA's rule is desired = ceil(current × measured / target). So 27 instances at 900 requests a second, against a target of 600, ask for ceil(27 × 1.5) = 41 in one step.

Scaling in is slow on purpose. AWS's target tracking removes capacity more gradually than it adds it, and the HPA scales in only to the highest count it computed over the last five minutes. Most teams run this, and it's the right default.

The cost is that it only reacts. The fleet holds the lag reserve in every hour of every day: the 7 points between the zone reserve's 67 percent and the 60 percent target. And it reads any fall in load as a reason to shrink, including the fall during an outage that comes before a retry storm.

Staff

Forecast the demand, launch ahead of it, and react only to surprises

Question the idea that capacity should follow what the fleet measures. Most load repeats, so a forecast can launch instances before the climb, at least one lag ahead of it.

Netflix built Scryer to do this. It predicted requests per second from past weeks, divided by one server's throughput, and scheduled the fleet size ahead of time. Netflix kept its reactive autoscaler running as a safety net for surges the forecast missed.

AWS offers the same split as predictive scaling. It sets each hour's count from a forecast, launches ahead of the hour by a buffer you set, and never scales in on the forecast. When both kinds of policy run, the fleet takes the larger of their counts.

The trade is clearest with a slow boot. With a 36-minute lag, the reactive target is 47 percent once the zone reserve is included. A forecast that leads by the lag only has to cover its own error. If that error stays within 3 percent, an assumption to check by running the forecast without letting it scale, the target is 1 / (1.5 × 1.03), about 65 percent. That's 37 instances at the evening peak instead of 52.

The saving is at the peak. During a climb, each hour's count is that hour's highest need, so the forecast fleet carries spare instances for most of the hour.

What you give up: the forecast needs history. AWS's needs 24 hours before it starts and two weeks to work well. Anything not in the history, such as a launch, a sale or a viral post, needs a scheduled action from a calendar. The Ticketmaster breakdown scales the line's servers up when the waiting room opens, 30 minutes before the sale.

A morning climb, reacting and forecasting
The blue line is the number of instances an assumed load curve needs at the target. The lag is 36 minutes, the slow-boot case. The red steps are a reactive fleet: each addition arrives one lag after the load that asked for it, so the fleet sits below the blue line through the climb. The green steps are an hourly forecast, launched one lag early so that each hour's count is serving when the hour starts. They stay above the line, and during the climb they hold spare instances for most of each hour.The blue line is the number of instances an assumed load curve needs at the target. The lag is 36 minutes, the slow-boot case. The red steps are a reactive fleet: each addition arrives one lag after the load that asked for it, so the fleet sits below the blue line through the climb. The green steps are an hourly forecast, launched one lag early so that each hour's count is serving when the hour starts. They stay above the line, and during the climb they hold spare instances for most of each hour.
A reactive fleet trails the climb by its lag, and a forecast fleet runs ahead of it with instances to spare. The blue line is the number of instances an assumed load curve needs at the target. The lag is 36 minutes, the slow-boot case. The red steps are a reactive fleet: each addition arrives one lag after the load that asked for it, so the fleet sits below the blue line through the climb. The green steps are an hourly forecast, launched one lag early so that each hour's count is serving when the hour starts. They stay above the line, and during the climb they hold spare instances for most of each hour.

Flapping and scaling in

An autoscaler flaps when its instance count keeps going up and down while the load barely changes. Kubernetes calls this thrashing or flapping. Each cycle starts instances that are removed before they've warmed up, so part of the fleet is always cold.

Two things cause it. A noisy metric crosses the target and comes back. And a new instance burns CPU while it starts, which reads as load unless warming instances are left out, as the scale-up lag section describes.

Two fixes stop it, and the second makes scaling in slower than scaling out.

  • A dead band, a range around the target where nothing happens. The HPA ignores a ratio within 10 percent of 1.
  • A stabilization window. Before scaling in, the HPA takes the highest count it computed over the last five minutes, which works like a rolling maximum. Scaling out has no window.
Instance count from a noisy metric
The grey dashed line is the count a scaler computes each minute from a noisy metric, while the real load falls slowly. Acting on each value, in red, the fleet changes size 29 times in 30 minutes. Taking the highest value of the last five minutes before scaling in, in green, the fleet holds at 12 and steps down three times. The metric is invented to show the mechanism.The grey dashed line is the count a scaler computes each minute from a noisy metric, while the real load falls slowly. Acting on each value, in red, the fleet changes size 29 times in 30 minutes. Taking the highest value of the last five minutes before scaling in, in green, the fleet holds at 12 and steps down three times. The metric is invented to show the mechanism.
A rolling maximum turns a zigzag into a few late steps down. The grey dashed line is the count a scaler computes each minute from a noisy metric, while the real load falls slowly. Acting on each value, in red, the fleet changes size 29 times in 30 minutes. Taking the highest value of the last five minutes before scaling in, in green, the fleet holds at 12 and steps down three times. The metric is invented to show the mechanism.

The asymmetry is deliberate. Too few instances costs errors now, and too many costs a few minutes of instance time.

Scaling to zero, and cold starts

The floor can be zero. A consumer of a queue that's empty at night, an internal tool and a preview environment don't need an instance while nothing arrives.

That first request pays a cold start: the time to start an environment and run the code's initialisation. AWS says cold starts happen in under 1 percent of Lambda invocations and take from under 100 ms to over a second. They're more common on functions that are called rarely, which describes anything that scales to zero.

On a queue with a 60-second budget, a second doesn't matter. On a user-facing path with a p99 target of 200 ms, cold starts fall in the slowest 1 percent that the p99 measures, and once they reach 1 percent of requests, the p99 is a cold start.

The fix is a floor of warm capacity, which brings back some of the cost you scaled to zero to avoid. Lambda's provisioned concurrency keeps environments initialised and bills for them whether or not they're used. AWS sizes it with Little's law: concurrency is requests per second times duration. 300 requests a second of 100 ms each need 30.

So scale to zero where a second's delay on the first request is acceptable, and keep a floor wherever a latency target applies.

Tiers that hold data

Autoscaling assumes that a new instance holds nothing the others need. An API server is like that. A database, a cache, a search index and a Kafka broker aren't. If you run their nodes, adding one means moving data onto it, and the move is extra load on the nodes already running. A managed database does any moving itself, out of your sight, though its scaling still has a lag, as DynamoDB's does below.

So how should a data tier whose nodes you run grow when traffic grows?

Naive

Put it behind the same autoscaler as the web tier

One policy for everything is simpler, and managed databases offer autoscaling, so it seems safe.

A new node arrives empty. In the distributed cache breakdown, a 76th memcached node takes over 130,000 hits a second, and each one becomes a miss that goes to databases with 100,000 a second to spare. An empty memcached server takes a few hours to reach 90 percent of its peak hit rate, so the extra load lasts hours.

A new database replica copies the dataset before it serves a read. Scaling in is worse, because it removes data the next peak will need back.

Adding a stateless instance and adding a cache node
On the top lane, a new API instance boots, warms up and carries its full share within minutes, in green. On the bottom lane, a new cache node joins empty (1). Every request for its keys misses, and the misses send about 130,000 reads a second to the databases, above their 100,000 of headroom, in red (2). The node's hit rate climbs over a few hours before the extra reads fade (3).On the top lane, a new API instance boots, warms up and carries its full share within minutes, in green. On the bottom lane, a new cache node joins empty (1). Every request for its keys misses, and the misses send about 130,000 reads a second to the databases, above their 100,000 of headroom, in red (2). The node's hit rate climbs over a few hours before the extra reads fade (3).
A new API instance adds capacity in minutes, and a new cache node adds load first. On the top lane, a new API instance boots, warms up and carries its full share within minutes, in green. On the bottom lane, a new cache node joins empty (1). Every request for its keys misses, and the misses send about 130,000 reads a second to the databases, above their 100,000 of headroom, in red (2). The node's hit rate climbs over a few hours before the extra reads fade (3).

Managed autoscaling of a database's throughput still has a lag. DynamoDB's acts once consumed capacity has been above the target for two consecutive minutes, and the change then takes several minutes. Requests above the old capacity are throttled meanwhile.

Senior

Plan it from a forecast, with the data move in the plan

Treat capacity for a data tier as a project with a lead time. Forecast further ahead than that lead time, which Google's SRE book makes a requirement.

Add capacity in the trough of the day. Move data in steps small enough that each step's extra load fits the headroom. Distributed cache moves 100 slots at a time, and fills each new node from the old owner with a warm-up route. Hold a larger reserve than the stateless tier, because a stateless tier recovers in minutes and this one in hours or months.

Most teams do this. The cost is that capacity is bought weeks before it's used, and a wrong forecast costs money in one direction and an incident in the other.

Staff

Ask what sets the tier's size, and keep traffic growth out of it

Question the idea that the data tier has to grow with traffic at all. Ask which resource sets its size. In the key-value store breakdown, disk sets the storage fleet at 107 nodes, while peak throughput needs only 72 to 101, even with headroom. So the daily peak already fits inside a fleet that grows with the data, and data grows slowly and predictably. The storage tier gets a plan. The routers in front of it hold no data, so they scale on request rate behind a load balancer.

Do the same in any design. Sort the tiers into those sized by data and those sized by requests, and keep state out of the second group. Then, of the tiers whose nodes you run, only stateless ones autoscale.

What you give up: the data tier carries throughput headroom it uses only at the peak. And if traffic ever outgrows what the data requires, you're back to a planned expansion, with its lead time.

The method

1. Start from the shape of the load, not one number. Take the busiest minute, the night trough, the steepest climb and the seasonal peak from history. Without history, back-of-envelope estimation gives the busiest hour and the busiest second.

2. Load test one instance to its knee. The highest load that still meets the latency target is the tested capacity. Note which resource filled first.

3. Set the target from the worst few minutes. Multiply the zone reserve by the climb during the lag, and by the busiest instance's load over the average. The target is 1 divided by the result.

4. Sort the tiers. Tiers sized by requests and holding no data autoscale. Data tiers whose nodes you run get a forecast that reaches past their lead time.

5. Write the policy for each autoscaled tier. Name the metric, the target, the warm-up, a slow scale-in, the floor and the maximum. The floor comes from the zones and the forecast, and the maximum from whatever sits downstream. The maximum also caps what a flood of bad traffic can cost, and security in system design covers stopping that traffic before it reaches the fleet.

6. Get ahead of what you can predict. Schedule the known events, forecast the daily cycle, and keep reactive scaling as the net.

7. Test it. Load test past the knee, take a zone out in a game day, and time a real scale-up.

Worked examples, start to finish

Each example breaks a different obvious answer.

An API with a morning climb, where 70 percent is too high

The API from the first worksheet runs at 24,000 requests a second in its busiest minute and falls to 4,000 at night. It runs in three zones. One instance has a tested capacity of 1,000 a second. The lag is 10 minutes, and the steepest climb is 1 percent a minute. The obvious answer is a 70 percent target, the top of the range the latency curve allows.

Back of envelopeWhere the 60 percent comes from
The question is the highest target that survives the
worst few minutes: a zone failing during the steepest
climb, before new instances carry load.

At a 70% target
  a zone fails           0.70 × 1.5               = 105%
  with the climb         0.70 × 1.5 × 1.10        ≈ 116%

What the worst few minutes need
  zone reserve                                    × 1.5
  climb during the 10-minute lag                  × 1.10
  busiest instance ÷ average, assumed even        × 1.0
  highest safe target    1 / (1.5 × 1.10 × 1.0)   ≈  61%
  chosen target                                      60%

The fleet at 60%, or 600 requests a second each
  busiest minute         24,000 / 600             =   40
  night                   4,000 / 600             ≈ 6.7 → 7
  floor: 3 per zone, even across zones            =    9
  worst minute           0.60 × 1.5 × 1.10        ≈  99%

With round robin's 2× spread, loads spread evenly
from 40% to 80% around the 60% average
  the busiest one's worst minute
                         0.80 × 1.5 × 1.10        ≈ 132%
  ─────────────────────────────────────────────────────
  At 70 percent a zone loss overloads the fleet at once.
  At 60 the worst minute reaches 99 percent of tested
  capacity, and only if every instance carries about
  the average.

The floor of 9 matters at night. Seven instances can't split evenly across three zones, and losing the zone that holds three of them leaves four instances at 1,000 a second each, with nothing to spare.

The × 1.0 is the assumption to check. Target tracking holds the average at the target, and the busiest instance reaches its knee first. If the busiest runs 10 percent above the average, the target drops to 1 / (1.5 × 1.10 × 1.10), about 55 percent. Planning on the average instance shows how far round robin spreads the load, and what narrows it.

The decision is target tracking on requests per instance at 600, with a floor of 9 instances, behind a balancer that keeps instances even. A forecast would only raise the target from 60 to about 65 percent with a 10-minute lag, so it waits until the bill makes it worth adding. If the team chooses to hold less reserve, it writes down what the survivors stop doing during a zone loss.

Thumbnail workers on a queue, where CPU never moves

Uploads put a message on a queue such as Amazon SQS. A worker takes one image at a time: it downloads it, resizes it, uploads the thumbnail and writes a status row. That takes 2 seconds, of which about 0.4 seconds is CPU. The product wants each thumbnail within 60 seconds of the upload. Uploads run at 50 a second, and 200 at the evening peak. A marketing email can push them to 220 a second for 10 minutes. The obvious answer copies the API's policy and targets 60 percent CPU.

A worker's CPU is busy for 0.4 seconds out of every 2, so even a worker that never stops sits at 20 percent. A 60 percent CPU target never fires, however long the queue gets.

CPU and backlog during an upload burst
The fleet stays at 400 workers, as it would under a CPU target, through an assumed burst of 220 uploads a second for 10 minutes. The backlog per worker, in blue, starts at the steady 15, a 30-second wait. It reaches 30 after 5 minutes, where waits pass the 60-second budget, in red, and 45 when the burst ends. CPU on each worker, in grey, stays at 20 percent, because every worker is already busy and most of its time is spent waiting on storage. The 60 percent CPU target, the dashed yellow line, is never reached.The fleet stays at 400 workers, as it would under a CPU target, through an assumed burst of 220 uploads a second for 10 minutes. The backlog per worker, in blue, starts at the steady 15, a 30-second wait. It reaches 30 after 5 minutes, where waits pass the 60-second budget, in red, and 45 when the burst ends. CPU on each worker, in grey, stays at 20 percent, because every worker is already busy and most of its time is spent waiting on storage. The 60 percent CPU target, the dashed yellow line, is never reached.
The queue grows while CPU stays flat, so a CPU target never fires. The fleet stays at 400 workers, as it would under a CPU target, through an assumed burst of 220 uploads a second for 10 minutes. The backlog per worker, in blue, starts at the steady 15, a 30-second wait. It reaches 30 after 5 minutes, where waits pass the 60-second budget, in red, and 45 when the burst ends. CPU on each worker, in grey, stays at 20 percent, because every worker is already busy and most of its time is spent waiting on storage. The 60 percent CPU target, the dashed yellow line, is never reached.
Back of envelopeA target for backlog per worker
The question is what number to give the scaler instead
of CPU, and what sets the maximum. One worker handles one
image at a time, for 2 seconds.

Workers busy, by Little's law
  normal          50/s × 2 s                 =   100
  evening peak   200/s × 2 s                 =   400

Target: half the 60 s budget, the other half for the lag
  30 s / 2 s per image                       =    15 per worker
  steady backlog at the peak   400 × 15      = 6,000

A burst of 220 uploads/s, before new workers start
  room before waits reach 60 s   400 × 15    = 6,000 images
  time to fill it       6,000 / (220 − 200)  =   300 s
  waiting then          6,000 + 6,000        = 12,000
  backlog per worker    12,000 / 400         =    30
  desired              ceil(400 × 30 / 15)   =   800

The maximum comes from downstream
  each worker holds 1 database connection
  connections the database gives this service    500
  most images a second       500 / 2 s       =   250/s
  wait at the back of 12,000 at 250/s        =    48 s
  ─────────────────────────────────────────────────────
  The target leaves 5 minutes to detect this burst and
  start new workers before it breaks the budget. The
  scaler asks for 800, the database allows 500, and 500
  workers bring the wait back to 48 seconds.

The target follows AWS's method for queues: an acceptable wait divided by the time per message, compared with messages waiting divided by workers in service. Spending the whole 60 seconds would give a target of 30. But target tracking removes workers whenever the backlog is below its target, so the backlog settles near the target. Waits would then sit near 60 seconds, with nothing left for the lag.

A target of 15 holds the steady wait near 30 seconds, by Little's law: 15 images cleared at one every 2 seconds. The other 30 seconds are room for the backlog to grow while new workers start, which at 220 uploads a second is 5 minutes.

Those 5 minutes are the workers' whole lag. Detection alone takes 3 of them in the lag worksheet, so the 60-second budget holds only if a worker starts in under about 2 minutes, such as a container on a node that's already running. With the API's 10-minute lag, 18,000 would be waiting: 90 seconds at 400 workers and 72 at 500. A marketing email is also a known event, so its workers can be scheduled before the send.

The queue also changes the reserve. A request can wait only milliseconds, so a request-serving fleet keeps its reserve in spare instances. A queue holds a burst for seconds, so here the reserve is half the time budget, and the workers can run close to fully busy.

The decision is backlog per worker with a target of 15, and a maximum of 500 set by the database. Above 250 uploads a second, 500 workers fall behind whatever the scaler asks for, so a bigger burst needs a change to the database first.

A database primary, where the holiday sets the deadline

An orders service runs on one Postgres primary, with a standby in another zone. Reads already go to replicas, so the primary's load is writes. A load test showed its p99 crossing the target above 70 percent CPU. The busiest week now runs at 40 percent. Load has grown 5 percent a month for a year, and last year's holiday week ran at 1.8 times a normal busy week. Sharding the database by customer would take the team about six months. The obvious answer reads 40 percent against 70 at 5 percent a month, calls that a year of room, and starts the sharding work in six months.

Back of envelopeWhen the primary runs out
The question is when the busiest week crosses 70 percent
CPU, and so when the work has to start. Month 0 is now.
The holiday week falls in month 8, and again in month 20.

The trend alone
  40% × 1.05^n = 70%     n = ln 1.75 / ln 1.05 ≈ 11.5 months

The holiday week, this year
  40% × 1.05^8 × 1.8                           ≈  106%

After moving to an instance with twice the cores,
assuming CPU is what binds
  this holiday     20% × 1.05^8 × 1.8          ≈   53%
  next holiday     20% × 1.05^20 × 1.8         ≈   96%
  ─────────────────────────────────────────────────────
  The trend says a year. The holiday says 8 months, and
  only the larger instance gets through it. Sharding has
  to ship before month 20, so it starts by month 14.

A primary can't add instances the way the API fleet can. It can move to a larger machine: resize the standby, switch to it in a planned failover, then resize the old primary. Replication and leader election covers what a failover risks. Partitioning and sharding lists the other cheaper steps to try before splitting a database.

The decision is the larger instance before month 8, and the sharding work started by month 14. The forecast gets checked every month, because a faster trend moves month 14 earlier.

Where it goes wrong

These are ordered by how often they come up.

1. Calling autoscaling the capacity plan

"We'll autoscale" with no target, lag or floor leaves the worst few minutes unplanned: a zone lost during a climb, before any new instance is ready. State the target and show what it survives.

2. Autoscaling a data tier whose nodes you run

A new cache node arrives empty and a new replica copies the data first, so the scale-up adds load before it adds capacity. Plan data tiers from a forecast that reaches past their lead time.

3. A signal that doesn't move with the fleet

Total requests, latency and raw queue length don't fall in proportion as instances are added, so a scaler that targets them overshoots or runs to its maximum. Use CPU, requests per instance or backlog per worker, whichever matches the resource that filled first in the load test.

4. Planning on the average instance

Google's SRE book reports that simple round robin can leave the busiest task using twice the CPU of the least busy one. Its illustration is a service that reserves 1,000 CPUs and can't use more than about 700. The zone reserve assumed every instance at the target, and the busiest ones reach the knee first.

Twelve instances averaging 60 percent
Twelve instances behind round robin average 60 percent of tested capacity, the dashed yellow line, and the busiest uses twice what the least busy does. When the load on each rises by half, as it does on the survivors of a zone loss, the average reaches 90 percent, but the four busiest pass 100, in red.Twelve instances behind round robin average 60 percent of tested capacity, the dashed yellow line, and the busiest uses twice what the least busy does. When the load on each rises by half, as it does on the survivors of a zone loss, the average reaches 90 percent, but the four busiest pass 100, in red.
The busiest instance uses up the reserve first. Twelve instances behind round robin average 60 percent of tested capacity, the dashed yellow line, and the busiest uses twice what the least busy does. When the load on each rises by half, as it does on the survivors of a zone loss, the average reaches 90 percent, but the four busiest pass 100, in red.

Google's least-loaded round robin still left a 2x spread. Google's weighted round robin, re-weighted from each backend's reported load (not the fixed weights load balancing describes), is what narrowed it, and load balancing covers the algorithms. If the spread stays wide, set the target from the busiest instance rather than the average.

5. Shrinking during an outage

An outage cuts incoming traffic, and a reactive scaler removes instances. Netflix described the result: when the fault is fixed, the retry storm meets a fleet too small to absorb it.

A fleet that shrinks during an outage
An outage starts at (1), and requests reaching the fleet, in blue, drop. After its window, the reactive scaler removes instances (2), so capacity, in purple, falls with the load. The fault is fixed at (3), and retries arrive on top of the normal load, far above the smaller fleet's capacity, in red. New instances take a full lag to arrive (4). The shapes are assumed.An outage starts at (1), and requests reaching the fleet, in blue, drop. After its window, the reactive scaler removes instances (2), so capacity, in purple, falls with the load. The fault is fixed at (3), and retries arrive on top of the normal load, far above the smaller fleet's capacity, in red. New instances take a full lag to arrive (4). The shapes are assumed.
The scaler reads an outage as a quiet hour. An outage starts at (1), and requests reaching the fleet, in blue, drop. After its window, the reactive scaler removes instances (2), so capacity, in purple, falls with the load. The fault is fixed at (3), and retries arrive on top of the normal load, far above the smaller fleet's capacity, in red. New instances take a full lag to arrive (4). The shapes are assumed.

Scale in slowly, and keep a floor from the forecast, which an outage doesn't lower. When a forecast policy runs beside a reactive one, the fleet takes the larger of their counts, so the forecast's count holds through the drop.

If you memorise nothing else

factwhy it matters
Size a fleet for its worst few minutesa zone gone, load climbing, nothing new ready
Plan against tested capacity from a load testthe knee where p99 breaks, not a CPU percentage
Busy workers = arrival rate × time per requestLittle's law turns load into a worker count
One worker at 90 percent busy is 10× slower; 16 sharing a queue, 1.4×the narrowest queue sets the knee
Losing one of three zones multiplies load by 1.5so the zone reserve alone caps you at 67 percent
Lag = detect + boot + warm-upthe reserve covers the climb during it
A fixed fleet is sized by its peak; an autoscaled one by its steepest climbtarget tracking holds every hour at the target
60 percent covers a zone loss during a 1 percent-a-minute climb and a 10-minute lag0.60 × 1.5 × 1.10 ≈ 99 percent, if instances are even
Scale on a metric that falls as instances are addedCPU, requests per instance, backlog per worker
Backlog target = part of the latency budget ÷ time per itemthe backlog settles at its target, so keep the rest of the budget for the lag
Scale out fast, scale in slowlythe HPA scales in to the highest count of the last five minutes
Forecast requests, not utilisationutilisation is partly a result of the scaling
A reactive scaler shrinks during an outagethen meets the retry storm too small
Cold starts: under 1 percent of calls, up to over a secondfine for a queue, wrong for a 200 ms p99
Data tiers whose nodes you run are planned, not autoscaledadding a node moves data, and the move is load

What is expected at each level

Mid-level

Know that a fleet is sized for the peak, not the average, and that you never plan for 100 percent busy. Know N + 1: losing one instance mustn't take the rest past their limit. Describe autoscaling on CPU with a minimum and a maximum.

You aren't expected to raise the scale-up lag, zone reserves or stateful tiers without being asked. If the interviewer asks "what happens when traffic doubles?", a good mid-level answer says the autoscaler adds instances, and that new instances take a few minutes to be ready.

Senior

You lead this part of the discussion, and three things must come up without prompting.

A target with its reasons. The tested capacity from a load test, then the zone reserve and the lag reserve that bring the target down to about 60 percent, and lower for any spread between instances.

The lag as a number, and what covers it. Detection, boot and warm-up add up to minutes, and the reserve or a forecast has to carry the climb during them.

Which tiers don't autoscale. Databases, caches and brokers on nodes you run are sized from a forecast, because adding a node moves data.

Two things are disqualifying: "the database autoscales" with nothing about the data move, and a 90 percent target on a latency-sensitive fleet.

Staff+

Producing a correct design is still the bar. A staff answer stands out by putting the reserve only where the worst minutes need it.

Forecast the demand and launch ahead of it. Predict requests, schedule capacity one lag ahead, keep reactive scaling as the net, and put known events on a calendar.

Size data tiers by what binds them. If disk or data size sets the fleet, the traffic peak fits inside it, and of the tiers you run, only stateless ones need to scale.

Design the scale-in. Slow scale-in, a floor from the forecast, and a maximum set by the tier downstream.

Decide what to shed during the lag. Hold less reserve on purpose and write down what the fleet drops while capacity catches up.

And say what you would not build. Each of these can cost a team a quarter.

One is a custom forecasting engine for a service with a flat day, where autoscaling saves under 10 percent. Another is autoscaling on a cache cluster or a database you run yourself. A third is scale-to-zero on a path with a 200 ms p99.

Another is a warm pool for instances that boot in under a minute. And the last is per-minute schedules written by hand, when target tracking follows the daily curve on its own.

Sources

The engine behaviour, defaults and published figures below come from these documents. The fleet sizes, lags and growth rates in the worksheets are assumptions, stated where they're used.

  • Google's SRE book: Introduction on organic and inorganic growth, forecasts beyond the lead time and load testing. Addressing Cascading Failures for the N + 2 example, coupling capacity planning to performance tests, testing until failure with ramps and steps. Handling Overload for CPU as the provisioning signal, and Load Balancing in the Datacenter for the 2x spread, the 1,000 against 700 CPUs and weighted round robin.
  • Netflix, Scryer: part 1 and part 2, 2013, with archived copies of part 1 and part 2. The 10 to 45 minute starts, the scale-down before a retry storm, predicting requests rather than load average, and reactive scaling kept as a safety net.
  • Amazon EC2 Auto Scaling docs: target tracking, scaling on SQS, predictive scaling, cooldowns and warm pools. Proportional metrics, warm-up, gradual scale-in, backlog per instance, predictive scaling's hourly counts and history, cooldowns and warm pools.
  • Kubernetes, Horizontal Pod Autoscaling. The replica formula, the 10 percent tolerance, the five-minute scale-down window, CPU from pods that aren't ready, and scaling to zero, a beta feature, only on external metrics.
  • AWS Lambda docs: the execution environment for cold start frequency and duration, and provisioned concurrency for its billing and sizing.
  • DynamoDB auto scaling, for two minutes to trigger, several minutes to apply, and throttling meanwhile.
  • The M/M/c queue, for the Erlang C formula behind the curves for several workers sharing one queue.
  • Marc Brooker, Latency Sneaks Up On You, 2021, on high-percentile latency as an early sign of overload.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.