Skip to content

Capacity Planning and Load Testing

Advanced 57 min read Part 14 of 18

Forecast demand, size every tier with headroom, use queueing and USL intuition, and prove it with load tests, traffic replay and cost-aware autoscaling.

Summary#

Capacity planning answers: how much infrastructure will we need, when, and at what cost, to meet our latency and availability goals? Load testing answers: does the system actually behave the way the plan assumes? Together they stop two expensive failures: outages from running out of capacity at peak, and waste from paying for idle machines.

The core ideas covered on this page:

  • Demand forecasting: model growth (linear, compound, seasonal and event-driven), plan for peaks rather than averages, and look ahead at least as far as your procurement and scaling lead time.
  • Headroom and utilisation targets: never plan to run at 100%. Leave room for failures (losing a zone or region), bursts, deploys and forecast error. Typical CPU targets are 40–70%, depending on how bursty the load is and how fast you can add capacity.
  • Queueing intuition: Little's law (L = λW) links concurrency, throughput and latency. Latency stays flat until utilisation nears the knee (around 70–80% for a single queue), then explodes.
  • The Universal Scalability Law (USL): adding nodes gives diminishing and eventually negative returns because of contention (α) and coherency costs (β).
  • Per-component capacity models: each tier (load balancers, app servers, caches, databases, queues, network, third-party APIs) has its own limiting resource. The system's capacity is set by the first one to saturate.
  • Load test types: load, stress, soak, spike and breakpoint tests each answer a different question. Common tools are k6, Gatling, JMeter and Locust.
  • Coordinated omission: a measurement flaw that makes many load tests report wildly optimistic latency percentiles, and how open-model, constant-arrival-rate tools fix it.
  • Production traffic replay and shadowing: the most realistic tests use real traffic, mirrored or replayed into the new system (as Slack did when moving its job queue to Kafka).
  • Autoscaling vs provisioned capacity: what reacts fast enough, what must be pre-provisioned (databases, spikes faster than scale-out), and predictive or scheduled scaling for known events.
  • Cost-aware capacity: unit economics (cost per request or per user), the pricing mix (reserved, spot, on-demand), rightsizing, and how utilisation targets trade money for safety.

Why It Exists#

Systems fail at capacity limits in ugly, nonlinear ways. A service at 60% CPU looks healthy. At 85%, its queues grow, latency doubles, and timeouts start. Timeouts trigger client retries, which add load, so at 95% it can tip into a metastable failure and stay down even after the original spike passes. Database connection pools exhaust, caches thrash, and garbage-collection pauses lengthen. Teams that don't plan capacity find their limits during their biggest day: the product launch, the Black Friday sale, the breaking-news event or the ticket on-sale, when failure is most costly and most public.

Over-provisioning "just to be safe" has its own cost. Cloud bills are often a top-three expense for software companies. Running every service at 10% utilisation can mean paying 5× more than necessary, and money spent on idle servers isn't spent on features.

Capacity planning also has a time dimension. Some capacity is quick to get: a container autoscales in seconds, a VM in a minute or two. Some takes much longer:

  • Database capacity involves resharding, adding replicas, or migrating to a bigger instance class, which takes hours to months.
  • Reserved cloud capacity for specific GPU or large instance types can be unavailable in a region on short notice.
  • Physical data-centre capacity (racks, power, network) takes months to years.

You have to forecast at least as far ahead as your slowest lever.

Finally, intuition about performance is unreliable. Engineers routinely misjudge where the bottleneck is: "the app servers", when it's actually a lock in the database, a connection limit on a load balancer, a third-party API rate limit, or a single hot Kafka partition. Load tests turn assumptions into evidence. Slack is a good example. Before moving its job queue to Kafka, the team sized the cluster with load tests at expected production rates. Then it drilled failures (broker loss, forced unclean leader elections, full cluster restarts), and ran the new path in shadow mode on real traffic before any customer depended on it.

How It Works#

The capacity planning loop#

Capacity planning is a continuous loop, not a one-off spreadsheet:

The inputs are business forecasts (marketing plans, sales pipeline, launches) and engineering telemetry (see observability). The output is a plan with dates and triggers: "Add 2 shards to the orders database before September; raise the autoscaling maximum for checkout to 400 pods before Black Friday; buy a 1-year savings plan for the baseline 60% of compute".

Demand forecasting and growth models#

Start by choosing a demand driver, a business metric that resources scale with: daily active users, orders per day, messages sent, GB uploaded, model tokens generated. Then express resource demand per unit of driver: "each 1,000 DAU generates 0.8 peak QPS on the feed service", "each order writes 6 KB to the orders table and 3 Kafka events". Forecast the driver, and multiply through.

Growth models:

  • Linear: a constant absolute increase, e.g. +50k users per month. Typical of mature products and storage that accumulates at a steady rate.
  • Compound / exponential: a constant percentage growth, e.g. 8% month over month, which doubles in about 9 months (rule of 72: 72 / 8 ≈ 9). Typical of fast-growing products. Small errors in the rate compound into large errors in the forecast: 8% vs 10% monthly growth differ by 26% after a year (1.08^12 ≈ 2.52 vs 1.10^12 ≈ 3.14).
  • S-curve (logistic): fast growth that saturates as the market fills. Most products eventually follow it. Extrapolating exponential growth past the inflection over-provisions badly.
  • Seasonal: daily cycles (an evening peak 2–3× the overnight trough for consumer apps; weekday business-hours peaks for B2B), weekly cycles, and yearly cycles (Black Friday and holiday retail, tax season, back to school, sports finals).
  • Event-driven: launches, marketing campaigns, ticket on-sales, breaking news, celebrity posts, outages of a competitor. These aren't predictable from trend data, so they need explicit inputs from the business, and the ability to absorb unplanned ones.

Forecasting techniques:

  • Plain trend extrapolation with regression on the log of the metric (for compound growth).
  • Holt–Winters (triple exponential smoothing: level + trend + seasonality).
  • Seasonal decomposition (STL).
  • Tools like Meta's Prophet (Taylor and Letham, "Forecasting at Scale", 2017), which handles trend changes, multiple seasonalities and holidays.

Whatever the technique, forecast ranges, not single numbers: P50 and P90 demand. Plan hard-to-change capacity (databases, reservations, hardware) against P90, and let elastic tiers handle the variance.

Peaks, not averages. Infrastructure must serve the peak minute, not the daily mean. Useful ratios:

  • Peak-to-average ratio: often 2–3× for consumer traffic over a day, and higher (5–10×) for spiky workloads such as sports, ticketing or flash sales.
  • Peak of the year vs a normal peak: retail Black Friday can be several times a normal day.
  • Burst within the minute: per-second peaks are higher than per-minute averages. Size queues and autoscaling for this.

Worked example. A social app has 10M DAU, each making 40 requests a day: 400M requests/day ≈ 4,600 QPS average. The peak-to-average ratio is 3, so peak ≈ 14,000 QPS. Growth is 5% per month, so in 12 months the peak is 14,000 × 1.05^12 ≈ 14,000 × 1.80 ≈ 25,000 QPS. The holiday event multiplier is 1.5×, so 37,500 QPS. Tested capacity is 600 QPS per app pod at the target latency and a 60% CPU target. That means about 63 pods of pure demand, and about 94 after the 1.5× AZ-loss headroom below. That's the autoscaling maximum to configure and to verify with a load test. Similar arithmetic is covered in back-of-the-envelope estimation.

Headroom and utilisation targets#

Headroom is the gap between expected peak load and the capacity at which you'd breach SLOs. It exists for several reasons, which stack:

  1. Failure domains (N+1, N+2). If you run in 3 availability zones and one fails, the other two must carry 100% of traffic. Each zone must therefore be sized at peak / 2, so at most 2/3 ≈ 67% utilised at peak in normal operation. For region failover in active–active across 2 regions, each region must absorb the other's load, so it runs at ≤50% at peak. With N regions, each runs at ≤(N−1)/N. Google's SRE practice describes provisioning for N+2: tolerate one planned outage (maintenance) and one unplanned failure at the same time.
  2. The latency knee. Beyond about 70–80% utilisation of a contended resource, queueing delay grows sharply (next section). The target must sit below the knee even after a failover shifts load.
  3. Burst and reaction time. Autoscaling needs minutes to add capacity (detection plus boot plus warm-up), so the current fleet must absorb the burst in the meantime.
  4. Forecast error. Your P90 forecast will sometimes be exceeded.
  5. Operational events. Deploys (rolling updates temporarily remove capacity: 25% maxUnavailable means 25% less fleet), cache flushes, reindexing, backups and compactions all consume capacity.

Typical targets (tune them with your own measurements):

ResourceCommon steady-state target at peakWhy
CPU (stateless services)50–70%Below the latency knee; headroom for an AZ loss and bursts
CPU (latency-critical, bursty)30–50%Tail latency degrades earlier under bursts
Memory70–85%No graceful degradation: crossing the limit means OOM kills or swapping
Disk spaceAlert at 70–80%, act before 85%Compaction and maintenance need free space (LSM stores, Kafka segment cleanup); full disks corrupt and crash
Disk IOPS / throughput60–70%Queueing at the device; cloud volumes throttle at provisioned limits
Network bandwidth50–70% of NIC or instance limitMicrobursts drop packets; replication and rebalancing spikes
DB connections70–80% of maxSpikes from retries, deploys and pool misconfiguration
Kafka partition / consumerLag recovers within the SLO after the peakConsumers need spare throughput to catch up after incidents

High utilisation targets save money but cut safety margins. Low targets waste money. The right number depends on how fast you can add capacity, how bursty the load is and how costly an SLO breach is. You'll see that same trade-off repeatedly in the sections below.

Queueing intuition: Little's law and the utilisation knee#

Little's law (John Little, "A Proof for the Queuing Formula: L = λW", 1961) says that in any stable system, over the long run:

L = λ × W: the average number of items in the system = arrival rate × average time each spends in the system.

It holds regardless of arrival distribution, service distribution or scheduling order, which makes it the most useful equation in capacity planning:

  • Concurrency sizing. A service handles λ = 2,000 requests/s with an average latency W = 50 ms. On average L = 2,000 × 0.05 = 100 requests are in flight. With 10 instances, that's 10 concurrent requests each, so a thread pool of 10 would be fully busy and leave no headroom. Size it at 30–50, and investigate if in-flight counts creep up.
  • Connection pools. An app does 500 DB queries/s at 4 ms each, so 500 × 0.004 = 2 connections busy on average. A pool of 10 per instance is plenty, and 200 per instance is just wasteful load on the database. If latency rises to 40 ms during a slowdown, you need 20 connections, which is why pools exhaust during DB incidents.
  • Queue backlog to latency. A Kafka consumer group processes 10,000 messages/s, and lag is 600,000 messages. A new message waits about 600,000 / 10,000 = 60 s.
  • Load testing sanity check. A closed-model tester with 200 virtual users and a 1 s think time, against 100 ms responses, generates at most 200 / 1.1 ≈ 182 requests/s. If you wanted 2,000/s, the tool configuration, not the system, is the limit.

Utilisation and the knee. Utilisation is ρ = λ / μ, the arrival rate divided by the service rate. For the simplest single-server queue with random arrivals and service times (M/M/1), the average time in the system is:

W = S / (1 − ρ), where S = 1/μ is the service time.

So response time multiplies as utilisation rises:

Utilisation ρW / S (response time ÷ service time)With S = 10 ms
50%2×20 ms
70%3.3×33 ms
80%5×50 ms
90%10×100 ms
95%20×200 ms
99%100×1 s

The curve is flat-ish until roughly 70–80%, and then shoots up. This is the knee. Tail latencies are worse still: in M/M/1 the response time is exponentially distributed, so p99 ≈ 4.6 × the mean. At 90% utilisation that's 460 ms for a 10 ms operation.

The practical lessons:

  • Don't run contended resources near 100%. "We're only at 85% CPU" can already mean latency 6× its unloaded value.
  • Variability makes it worse. Kingman's formula (an approximation for general single-server queues) scales waiting time by (ca² + cs²) / 2, the average of the squared coefficients of variation of inter-arrival times and service times. Bursty arrivals (ca > 1) or erratic service times (GC pauses, cache misses, cs > 1) move the knee left. Smoothing arrivals (queues, rate limits) or service times (caching, avoiding long-tail queries) raises safe utilisation.
  • Pooling helps. M/M/c (c servers sharing one queue) tolerates much higher utilisation than c separate M/M/1 queues at the same ρ. That's why a load balancer using least-connections or power-of-two-choices beats random assignment when servers are busy, and why one shared worker pool is better than many tiny ones (see load balancing).
  • Overload is a cliff. When λ > μ, the queue grows without bound, and latency grows linearly with time until timeouts and retries take over. Load shedding and back pressure (see resilience patterns) keep the system on the right side of the cliff.

The Universal Scalability Law#

Adding servers doesn't give linear throughput forever. Neil Gunther's Universal Scalability Law (developed in the 1990s and popularised in Guerrilla Capacity Planning, 2007) models relative capacity with N nodes (or threads, or cores) as:

C(N) = N / (1 + α(N − 1) + βN(N − 1))

  • α (contention / serialisation): the fraction of work that must be done one at a time. Think of a global lock, a single leader, a hot row, or a shared queue. With β = 0 this is Amdahl's law: throughput approaches the ceiling 1/α. With α = 5%, you can never exceed 20× a single node.
  • β (coherency / crosstalk): the cost of keeping nodes consistent with each other: cache invalidation broadcasts, distributed locking, gossip, two-phase commits, all-to-all communication. It grows with N(N−1), the number of node pairs, so beyond a point adding nodes decreases total throughput (retrograde scaling).
  • The peak is at N* = √((1 − α) / β).

Worked example. A load test measures throughput at 1, 4, 8, 16 and 32 nodes, and the USL fit gives α = 0.03 and β = 0.0005:

  • N = 8: C = 8 / (1 + 0.21 + 0.028) ≈ 6.5× (81% efficiency).
  • N = 16: C = 16 / (1 + 0.45 + 0.12) ≈ 10.2× (64% efficiency).
  • N = 32: C = 32 / (1 + 0.93 + 0.50) ≈ 13.2× (41% efficiency).
  • N* = √(0.97 / 0.0005) ≈ 44 nodes, where C ≈ 13.7×. Beyond that, throughput falls.

If the business needs 20× single-node throughput, no amount of horizontal scaling of this design gets there. You must reduce α or β: partition the hot lock, shard so nodes don't coordinate, or replace broadcast invalidation with partitioned ownership. That's the deeper reason sharding beats "add more replicas of a shared-everything system" (see scaling up vs scaling out).

Using the USL in practice:

  1. Measure throughput at 5–8 concurrency or node levels, under load tests at saturation.
  2. Fit α and β with nonlinear regression (a spreadsheet solver works).
  3. Look at α and β separately. A large α points to a serial bottleneck, and a large β to coordination chatter.
  4. Predict the safe scaling range, and never extrapolate far beyond the measured points.

It also works for threads within one machine: database throughput vs client concurrency often fits the USL, showing where adding connections stops helping. That's one more reason to size pools from Little's law rather than "max connections = 1,000".

Per-component capacity models#

A system's capacity is the capacity of its first saturated component, and different components saturate on different resources. Build a simple model for each tier: limiting resource → per-unit capacity → demand per request → units needed.

Load balancers and the edge. Load balancers have their own limits, which are easy to forget:

  • Connections: concurrent connections, new connections per second, and TLS handshakes per second. TLS handshakes are CPU-heavy, and session resumption and keep-alive reduce them.
  • Requests per second and bandwidth.
  • L4 vs L7 cost. A Layer 4 balancer (AWS NLB, IPVS, Maglev-style) forwards TCP/UDP flows without parsing requests. It's cheap per packet and good for persistent connections like WebSockets, but every request on a connection goes to the same backend. A Layer 7 balancer (ALB, Envoy, NGINX, HAProxy) terminates connections and routes per HTTP request. It's more flexible, but more CPU per request.
  • Long-lived connection services (WebSockets, SSE) are sized by concurrent connections per node and memory per connection, not QPS. Use least-connections balancing so new nodes fill up instead of old ones accumulating everything. Plan for reconnect storms: when a node dies, its 100k clients reconnect elsewhere within seconds.
  • Cloud load balancers scale automatically, but not instantly. For very sudden step increases (a planned event at 10× normal traffic), providers historically recommended "pre-warming" via a support request. Enterprise hardware balancers (F5 BIG-IP class) handle very high rates. Software balancers scale horizontally behind DNS or anycast.
  • Client-side load balancing (gRPC with a service registry, Redis Cluster clients that hash keys to shards and follow MOVED redirects, and DNS rotation) removes the middle hop. Then the capacity question becomes per-backend balance and how fast clients learn about new nodes. DNS TTLs limit how quickly new capacity gets used.

Stateless application servers. These are limited by CPU (most common), memory (per-request allocations, caches), thread or connection pools, or downstream latency (if each request holds a thread while waiting). Measure QPS per instance at the target p99 with a load test, rather than computing it from CPU per request alone. Most tiers degrade before 100% CPU, as the knee predicts. Account for warm-up: JIT compilation, connection pools and local caches make a fresh JVM or .NET instance much slower for its first minutes. Autoscaling must take that into account.

Caches. Caches are limited by memory for the working set, network throughput per node (a 25 Gbps NIC moves about 3 GB/s, so 50 KB values at 60k ops/s saturate it), and CPU per operation (Redis runs commands single-threaded per shard: roughly 100k+ simple ops/s per core). The critical capacity interaction is the hit ratio. If the cache absorbs 95% of reads, the database sees 5%. A drop to 90% (a cache node failure, a cold restart, a key-schema change) doubles database read load. Size the database to survive a realistic degraded hit ratio, or protect it with request coalescing and warm-up (see caching strategies).

Databases. These are the hardest tier to scale quickly, so they deserve the most careful model:

  • CPU for query execution. Watch for a few expensive queries dominating.
  • Disk IOPS and throughput: random reads for cache misses, WAL and commit-log writes, compaction for LSM stores, checkpoints. Cloud volumes have provisioned limits (gp3 baseline 3,000 IOPS; io2 much higher) and throttle hard at them.
  • Buffer pool / page cache hit rate: when the working set outgrows RAM, latency jumps from microseconds to milliseconds per read. That's a capacity cliff, not a slope.
  • Write throughput: single-leader databases are bounded by one machine's write capacity, and replication must keep up (replica lag).
  • Connections: PostgreSQL forks a process per connection, so thousands of connections cost memory and context switches. Use a pooler.
  • Storage growth: rows per day × row size × index overhead (often 1.5–3× raw data) × replication factor, plus backups.
  • Lock contention: hot rows (a global counter, a popular item's inventory) give a high α in USL terms. No hardware fixes it.

Message queues and streams. Kafka, for example, is limited by partition count (consumer parallelism is capped at one consumer per partition per group), per-broker disk and network throughput (replication multiplies writes by the replication factor), and retention storage (ingest rate × retention × replication factor). Model catch-up capacity: after a 30-minute consumer outage at 20k messages/s, the backlog is 36M messages. Consumers that can process 30k/s drain it at a net 10k/s, taking an hour. Is that within your SLO? (See message queues.)

Network and egress. Per-instance bandwidth caps, cross-AZ traffic (charged per GB on major clouds), NAT gateway throughput and cost, and internet egress. Media-heavy systems are often bandwidth-bound long before they're CPU-bound.

Third-party and internal dependencies. Payment gateways, SMS providers, email providers, LLM APIs and partner APIs all impose rate limits and quotas. An internal shared service (auth, feature flags) may also have a capacity budget. These are capacity constraints you can't scale yourself, so negotiate quotas ahead of events, and design queues and back-off around them.

A useful artefact is a capacity table per service, reviewed quarterly:

ComponentLimiting resourceTested max per unitUnits nowPeak demand next quarter (P90)Utilisation at peak after N+1Action
checkout-apiCPU at p99 300 ms600 req/s per pod60 pods (max 120)45k req/s (75 pods)94% of the 80 pods left after an AZ lossRaise HPA max to 160
orders-db primaryWrite IOPS8k writes/s1 primary6.5k writes/s81%Shard split in Q3
redis-sessionsMemory50 GB per shard6 shards260 GB87%Add 2 shards
SMS providerContract quota200 msg/s1 contract150 msg/s75%Negotiate 400 msg/s before campaign

Load test types: load, stress, soak, spike and breakpoint#

Different tests answer different questions. Name the question first, then choose the test:

TestLoad shapeQuestion it answersTypical duration
SmokeTiny load (1–5 users)Does the script and environment work at all?Minutes
Load (average/peak load)Ramp to expected peak, then holdDo we meet SLOs at the expected peak, with headroom?30–60 min hold
StressRamp beyond peak (1.5–3×)How does it degrade? Graceful shedding, or a collapse? Does it recover?30–60 min
SpikeJump from baseline to many times baseline in secondsCan autoscaling, caches and pools absorb a sudden surge (breaking news, an on-sale)?Minutes per spike
Soak (endurance)Steady, realistic load for hoursMemory leaks, connection leaks, log or disk growth, GC degradation, slow drift4–72 hours
Breakpoint (capacity)Increase load in steps until SLOs failWhat's the maximum sustainable throughput, and which component breaks first?Until failure
ScalabilityRepeat breakpoint tests at different node countsHow does capacity scale with nodes? (Fit the USL.)Several runs

Workload models: open vs closed.

  • Closed model: a fixed number of virtual users (VUs). Each sends a request, waits for the response, "thinks", and repeats. Arrival rate drops when the system slows, because users are waiting. That's realistic for a fixed population of users in a session, but it hides overload: the system quietly gets less load as it struggles.
  • Open model: requests arrive at a fixed arrival rate regardless of how fast the system responds. That's realistic for internet traffic from millions of independent users, where new users keep arriving even when you're slow. Open models expose queueing and overload honestly.

For capacity planning of public services, prefer open, arrival-rate based tests (k6's constant-arrival-rate or ramping-arrival-rate executors, Gatling's open injection profiles, wrk2's -R rate).

Making tests realistic:

  1. A traffic mix that matches production: the endpoint ratio (70% reads, 20% searches, 10% writes), payload sizes and query parameters drawn from real distributions. Hot keys follow Zipf-like popularity. A test that hits the same product ID 1M times measures your cache, not your system.
  2. Realistic data volume. The database should be production-sized (or scaled proportionally), because a 1 GB test database fits in RAM and hides I/O behaviour.
  3. Environment parity. Same instance types, same configuration, same topology, including the load balancers, TLS, WAF and service mesh. Otherwise test in production carefully (below).
  4. Warm-up before measuring, and long enough runs to see GC cycles, cache churn and autoscaling.
  5. Pass/fail criteria tied to SLOs (p99 under 300 ms, error rate below 0.1%) checked automatically, so tests can run in CI/CD as performance regression gates.
  6. The load generators must not be the bottleneck. Monitor their CPU and network, and distribute them across machines and regions for large tests.
  7. Observe the system under test with full telemetry. Each test's purpose is to find which resource saturates, not just "the max QPS".
  8. Dependencies. Stub third parties (payment, SMS) with realistic latency simulators, or coordinate with them. Don't load-test someone else's production API without permission.

Tools:

ToolLanguage / modelFits when
k6 (Grafana)JavaScript scripts, Go engine; open and closed executors; thresholdsDeveloper-friendly scripted tests in CI, HTTP/gRPC/WebSocket, with good arrival-rate support
GatlingScala/Java/Kotlin DSL; async engine; open injection profilesHigh-throughput HTTP tests from one generator, with detailed HTML reports
Apache JMeterGUI plus XML test plans; thread-based (closed) by default; pluginsBroad protocol coverage (JDBC, JMS, LDAP, FTP) and teams preferring GUI authoring
LocustPython user classes; distributed controller/worker; closed model by defaultPython teams, complex user logic, easy distributed runs
wrk2 / Vegeta / heyCLI; constant-rate HTTPQuick, accurate latency benchmarking of a single endpoint at a fixed rate
Artillery, TsungYAML scenarios (Artillery, Node.js) / Erlang (Tsung)Many concurrent connections, e.g. WebSocket and XMPP
Cloud and managed services (Grafana Cloud k6, Azure Load Testing, Distributed Load Testing on AWS)Hosted generatorsVery large or geo-distributed load without running generator fleets
// k6: open-model spike + peak test with SLO thresholds
import http from "k6/http";
import { check } from "k6";
 
export const options = {
  scenarios: {
    peak_with_spike: {
      executor: "ramping-arrival-rate",       // open model: fixed arrival rate
      startRate: 2000, timeUnit: "1s",
      preAllocatedVUs: 2000, maxVUs: 20000,
      stages: [
        { target: 14000, duration: "10m" },    // ramp to forecast peak
        { target: 14000, duration: "30m" },    // hold at peak
        { target: 42000, duration: "30s" },    // 3x spike (breaking news)
        { target: 42000, duration: "5m" },
        { target: 14000, duration: "2m" },     // recovery: does latency return?
      ],
    },
  },
  thresholds: {
    http_req_failed: ["rate<0.001"],           // <0.1% errors
    "http_req_duration{endpoint:feed}": ["p(99)<300"],
    dropped_iterations: ["count<100"],         // generator kept up with the rate
  },
};
 
export default function () {
  const id = Math.floor(Math.pow(Math.random(), 3) * 1e6); // skewed key popularity
  const r = http.get(`https://staging.example.com/feed?user=${id}`,
                     { tags: { endpoint: "feed" } });
  check(r, { "status 200": (res) => res.status === 200 });
}

Coordinated omission#

Coordinated omission is a measurement error named by Gil Tene (Azul Systems, in his talk "How NOT to Measure Latency", around 2013, and the HdrHistogram and wrk2 projects). It makes many load tests and monitoring systems report latency percentiles that are far too optimistic, sometimes by orders of magnitude.

How it happens. A closed-loop load generator sends a request, waits for the response, then sends the next. Suppose it's meant to send 100 requests/s (one every 10 ms), and the server stalls for 1 second (a GC pause, a lock, a failover):

  • The generator sends one request at t = 0, which takes 1,000 ms. It records one slow sample.
  • During that second, the generator didn't send the 99 other requests it should have sent, because it was waiting. Real users (an open system) would have sent them, and they'd have waited 990, 980, … 10 ms.
  • So the test records 1 slow sample and thousands of fast ones, and the p99 looks like 10 ms. The true distribution, with the missing 99 requests counted, has about 1% of requests above 500 ms, so the true p99 is about 500 ms or worse.

The load generator has "coordinated" with the system under test: it backs off precisely when the system is slow, and omits exactly the samples that would reveal the problem.

Worked example. A test runs 100 req/s for 100 s (10,000 requests). The service is 1 ms normally, except for one 2-second freeze.

  • Naive (coordinated) measurement: 9,999 samples at 1 ms and one sample at 2,000 ms. The p99 and p99.9 are both 1 ms. Even the mean is only about 1.2 ms.
  • Corrected measurement: during the 2-second stall, 200 requests should have been issued, with latencies from about 2,000 ms falling linearly to 0. That's 2% of all requests delayed by an average of about 1 s. The true p99 is about 1,000 ms, and the p99.9 about 1,900 ms.

Fixes:

  • Use an open-model, constant-arrival-rate generator that schedules requests on a fixed timeline regardless of responses: wrk2, k6 arrival-rate executors, Gatling open injection, Vegeta.
  • Measure latency from the intended send time, not the actual send time. wrk2 and HdrHistogram's recordValueWithExpectedInterval correct for missed intervals.
  • Watch for dropped iterations (the generator falling behind schedule). In k6, dropped_iterations means the test didn't deliver the intended load, so its results understate the problem.
  • Apply the same thinking to production monitoring. Server-side latency measured after the request reaches the handler misses time spent queued in the accept backlog, the load balancer or a thread pool. Measure at the client or the edge too (RUM, LB request time).
  • Never average percentiles across hosts or time windows. Merge histograms (HdrHistogram, t-digest, Prometheus native histograms) and compute percentiles from the merged distribution.

Production traffic replay and shadowing#

Synthetic scripts never fully capture real traffic: the long tail of weird requests, real key distributions, real payload sizes, real client behaviour. The most convincing evidence comes from real production traffic, used safely:

  • Traffic replay. Capture production requests (from access logs, a proxy tap, or tools like GoReplay), sanitise them (strip credentials and PII, rewrite auth tokens), and replay them against a test environment. You can replay at multiples of the original speed (2×, 5×) to test future load with today's real mix. Replay at the HTTP or RPC level, because packet-level tools like tcpreplay can't re-establish TLS sessions or handle stateful protocols. Caveats: writes may fail or duplicate (replays need an isolated data copy), time-dependent requests go stale, and sessions don't match.
  • Shadowing (mirroring, "dark traffic"). Duplicate live requests in real time to the new system, and discard its responses. Users only see the old system's responses. Envoy and Istio support request mirroring (a percentage of traffic sent fire-and-forget to a shadow cluster), as do NGINX's mirror module and service-mesh traffic policies. Diffy (open-sourced by Twitter in 2015) compares shadow responses with production responses to find behavioural differences, using a second production instance to filter out noisy, non-deterministic fields.
  • Dual writes plus shadow reads during migrations. When Slack moved its job queue from Redis to Kafka, every job was written to both the old and the new path. The new relay ran in shadow mode, reading everything from Kafka and then dropping it. That put real production volume through every new component with zero user impact. The team counted jobs at every hop (web app → Kafkagate → Kafka → Redis) to detect loss, and ran heartbeat canaries: one synthetic job per partition per minute across 1,600 partitions, with alerts on end-to-end flow and timing. The new path served Slack internally for a few weeks before rolling out to customers one job type at a time. The migration also turned up a subtle bug: Go and PHP JSON encoders escape different characters, so "identical" jobs produced different bytes. That's the kind of thing only real traffic reveals.
  • Load tests in production. Some organisations test capacity using live traffic itself:
    • Facebook's Kraken ("Kraken: Leveraging Live Traffic Tests to Identify and Resolve Resource Utilization Bottlenecks in Large Scale Web Services", Veeraraghavan et al., OSDI 2016) shifts real user traffic toward a target cluster or region by adjusting load-balancer weights, while watching health metrics. It finds each cluster's true capacity, and the bottlenecks that appear first.
    • Squeeze tests: progressively remove instances behind a load balancer while observing latency. Netflix has described this practice for finding per-instance capacity.
    • Game days and failover drills: deliberately fail an AZ or region during business hours, which tests both resilience and whether the survivors have enough headroom.

Safety rules for shadowing:

  • No double side effects. Shadow traffic must not charge cards, send emails or mutate shared state. Route the shadow's writes to an isolated store, run it in dry-run mode, or stub outbound calls.
  • Protect shared dependencies. Mirroring 100% of traffic doubles the load on any dependency both paths share. Mirror a fraction, and budget for it.
  • Treat mirrored data as production data (PII rules apply).
  • Make the shadow path "fire-and-forget", with timeouts, so it can't slow down the primary path.

Autoscaling vs provisioned capacity#

Autoscaling adds and removes capacity automatically, in response to metrics or schedules:

  • Horizontal pod or instance autoscaling on CPU, requests per second per target, queue depth, or custom metrics: the Kubernetes HPA, AWS Auto Scaling target tracking, KEDA for queue-driven scaling (see containers and Kubernetes).
  • Cluster or node autoscaling (Cluster Autoscaler, Karpenter) adds nodes when pods can't be scheduled.
  • Serverless (Lambda, Cloud Run) scales per request, up to concurrency limits, but with cold starts and account-level concurrency quotas.
  • Predictive scaling forecasts load from history (daily and weekly patterns) and scales ahead of it. AWS EC2 Auto Scaling offers predictive scaling policies.
  • Scheduled scaling raises minimums before known events: business hours, a 20:00 match kickoff, a ticket on-sale at 10:00.

Autoscaling has limits you must plan around:

  1. Reaction time. Metrics need time to reflect load (scrape interval plus averaging window), the scaler adds instances, instances boot (seconds for containers on warm nodes, 1–5 minutes for new VMs), and then the app warms up (JIT, caches, connections). Total: often 2–10 minutes. A spike that goes 1× → 5× in 30 seconds overwhelms the existing fleet long before help arrives, so the minimum fleet must absorb the burst, or a queue or load shedding must buffer it.
  2. Stateful tiers don't autoscale like stateless ones. Adding a database shard, a Kafka partition or a Cassandra node means data movement, which consumes capacity while it happens. Scale these tiers ahead of need, by plan, not by reaction. Managed "serverless" databases (Aurora Serverless v2, DynamoDB on-demand, Cosmos DB autoscale) scale within limits. DynamoDB on-demand, for example, accommodates up to double the previous peak instantly and scales further over time, so a sudden 10× still needs pre-warming or provisioned capacity.
  3. Dependency limits. Scaling the app to 400 pods also scales DB connections, third-party calls and log volume. Make sure downstream tiers can take it, or autoscaling just moves the bottleneck.
  4. Scale-in risks. Aggressive scale-in drops warm caches and connections, and causes oscillation (flapping). Use stabilisation windows and slower scale-in.
  5. Quotas and stock-outs. Cloud accounts have instance and vCPU quotas per region, and specific instance types (especially GPUs) can be unavailable. Raise quotas ahead of events, and diversify instance types (Karpenter, mixed instance policies).

Provisioned capacity (fixed fleets, reserved instances, provisioned database throughput) gives predictability and lower unit cost, and is mandatory for things that can't scale fast. The practical blend:

  • A baseline of provisioned or reserved capacity for the always-on load (often the daily trough to median).
  • Autoscaling for the daily peak and moderate bursts.
  • Scheduled or pre-provisioned capacity for known big events, raised hours or days ahead and load-tested.
  • Load shedding, queues and graceful degradation for the unknown spike beyond everything, so the system degrades instead of collapsing.

Breaking news and other spikes. A news aggregator sees traffic multiply within minutes when a major story breaks. Everyone hits the same few articles and the same "top stories" feed, so the spike is concentrated as well as large. The defences are mostly about making the spike cheap rather than provisioning for it:

  • Serve the hot feed from CDN and edge caches with short TTLs (even 5–30 seconds absorbs almost all reads; see CDNs).
  • Use request coalescing, so a cache miss triggers one backend fetch rather than thousands.
  • Keep a precomputed top-stories feed in an in-memory cache, replicated so no single node is hot.
  • Hold enough minimum capacity and autoscaling headroom on the uncacheable paths (personalised feeds, search).
  • Prepare degradation switches (serve non-personalised feeds, drop expensive widgets) if those paths saturate.

The news aggregator case study works through this, and ticket booking handles a scheduled spike with a virtual waiting room.

Cost-aware capacity#

Capacity is a financial decision as much as a technical one. Cost-aware planning makes the trade-offs explicit:

Unit economics. Track cost per unit of the demand driver: cost per 1,000 requests, per active user per month, per order, per GB stored, per 1M LLM tokens. A growing bill is fine if users grow faster. A rising unit cost is a signal of waste or a design problem. Unit costs also feed pricing decisions (does a free tier cover its infrastructure?) and architecture choices (does caching this response pay for its memory?).

The pricing mix (terms from AWS, with equivalents on GCP and Azure):

  • On-demand: full price, no commitment. Use it for unpredictable peaks.
  • Reserved instances and savings plans (1 or 3 years): often 30–60% cheaper for the steady baseline you're confident about. Commit to the trough-to-median demand, not the peak.
  • Spot / preemptible: often 60–90% cheaper, but can be reclaimed with about 2 minutes' notice (AWS) or 30 seconds (GCP). Ideal for stateless, fault-tolerant work: batch jobs, CI, stateless web tiers with diversified instance pools, and load-test generators.
  • Committed throughput for managed services (provisioned DynamoDB capacity, reserved database instances, committed CDN egress).

Rightsizing. Many fleets are over-provisioned per instance: 16 vCPU instances running at 8% CPU, or containers requesting 4 GB and using 600 MB. Kubernetes requests determine bin packing and therefore cost. Inflated requests waste node capacity even when actual usage is low. Use vertical pod autoscaler recommendations, or usage percentiles, to set requests. Newer instance generations, and ARM-based instances (AWS Graviton, Google Axion, Azure Cobalt), often give better price-performance, so measure with a load test before switching.

Utilisation vs safety. Raising the CPU target from 40% to 60% cuts compute cost by a third (40/60). But it reduces failover headroom, and moves latency closer to the knee. Make the trade-off deliberately, per service: run latency-critical checkout at 45%, and batch analytics at 85% on spot.

Hidden costs often dominate capacity bills (see cloud architecture):

  • Data transfer: internet egress, cross-AZ traffic (chatty services spread across AZs pay per GB both ways), cross-region replication, NAT gateway processing.
  • Idle resources: dev environments running 24/7, unattached volumes, forgotten load-test fleets.
  • Observability volume: logs and high-cardinality metrics that grow with traffic.
  • Over-replication: three replicas plus backups of data nobody reads.

Cost as a capacity constraint. Sometimes the cheapest capacity is not serving the load:

  • Cache more.
  • Batch requests.
  • Reduce polling frequency.
  • Compress payloads.
  • Downsample old data (see data lifecycle).
  • Rate-limit abusive clients (see rate limiting).

A 10% reduction in demand per request is a 10% capacity increase for free.

FinOps practice. Tag every resource by team and service, show each team its cost and unit cost, review it monthly with engineering and finance, and set budgets and anomaly alerts. A sudden 3× jump in a team's NAT gateway bill is often a capacity bug (a retry loop, a misrouted data pipeline).

When to Use It#

  • Before any launch, major event or migration where traffic will be new or much larger: product launches, marketing campaigns, ticket on-sales, Black Friday, sports finals, a database or queue migration (like Slack's Kafka move).
  • When growth is fast (more than about 5% per month). Last quarter's capacity won't hold next quarter, and stateful tiers need months of lead time.
  • When you have strict latency or availability SLOs. Headroom and knee-avoidance are how you keep them, and error budgets burn fastest at capacity limits.
  • When cloud cost is a significant budget line. Rightsizing, reservations and utilisation targets typically save 20–40% of compute spend.
  • After architecture changes that alter the cost per request: a new ORM, a serialisation change, a new dependency, a language runtime upgrade. Run a performance regression test in CI on every significant release.
  • For stateful systems whose scaling needs data movement (databases, Kafka, search clusters, caches). Plan splits and expansions before the 70% mark.

Pick something else instead when:

  • Pure serverless or managed services with no capacity knobs (and acceptable cost) need only quota checks and spike tests, not detailed per-instance models.
  • Tiny internal tools with dozens of users don't need formal capacity models. Basic monitoring and generous instance sizes are cheaper than the analysis.
  • When the real question is resilience to failure rather than load, chaos engineering (fault injection) is the better tool, though failover drills and capacity overlap (see high availability design).

When NOT to Use It#

  • Don't load-test production dependencies you don't own (payment providers, partner APIs) without permission. Use sandboxes or simulators.
  • Don't trust a load test against a tiny, unrealistic environment (a 1 GB database, one instance, no TLS) to predict production capacity. Results won't transfer.
  • Don't plan from averages. Daily-average QPS is useless for sizing. Plan from peak-minute or peak-second demand with headroom.
  • Don't extrapolate linear scaling from a 2-node test to 50 nodes. Measure several points and fit the USL.
  • Don't run closed-model load tests and report their percentiles as SLO evidence without checking for coordinated omission.
  • Don't rely on reactive autoscaling alone for spikes faster than your scale-out time, or for stateful tiers.

How to Implement It#

  1. Pick demand drivers for each service (requests, users, orders, GB) and instrument them alongside resource metrics. Measure the per-driver resource cost from production data.
  2. Forecast the drivers with a seasonal model (Holt–Winters, Prophet or regression on logs) plus explicit business events. Produce P50 and P90 forecasts over a horizon longer than your slowest scaling lever.
  3. Build per-component capacity models: for each tier, the limiting resource, the tested capacity per unit at the SLO, and the current units. Keep them in a reviewed capacity table.
  4. Set headroom policies: failure-domain sizing (N+1 AZ, N+1 region if active–active), utilisation targets per resource below the knee, and minimum fleet sizes that absorb bursts during scale-out lag.
  5. Validate with load tests in a production-like environment using open-model tools: a load test at P90 peak plus headroom, stress and breakpoint tests to find the first bottleneck, spike tests for events, and soak tests for leaks. Automate a smaller regression test in CI.
  6. Use real traffic where possible: replay sanitised captures at multiples of the original rate, shadow new systems, and run failover drills that also verify headroom.
  7. Configure scaling: autoscaling metrics, minimums and maximums from the model; scheduled and predictive scaling for known patterns; quotas raised ahead of events; and stateful-tier expansions scheduled by plan.
  8. Optimise cost: rightsize requests and instances, reserve the baseline, use spot for fault-tolerant work, and track unit costs per service with FinOps reviews.
  9. Review quarterly, and after every incident or major event: compare forecast with actual, and update models and headroom.
# Minimal capacity model: pods needed for a service at forecast peak
import math
 
def pods_needed(peak_rps: float,           # P90 forecast peak, incl. event multiplier
                rps_per_pod_at_slo: float, # load-tested at target CPU and p99
                zones: int = 3) -> int:    # survive the loss of one zone
    base = peak_rps / rps_per_pod_at_slo
    # Deploy with maxSurge (extra pods) rather than maxUnavailable,
    # so rollouts don't eat into this headroom.
    return math.ceil(base * zones / (zones - 1))
 
def littles_law_concurrency(rps: float, latency_s: float) -> float:
    return rps * latency_s  # average in-flight requests: size pools above this
 
def kafka_drain_minutes(backlog: int, consume_rate: float, produce_rate: float) -> float:
    net = consume_rate - produce_rate
    return math.inf if net <= 0 else backlog / net / 60
 
print(pods_needed(37_500, 600))                  # 94 pods with zone-loss headroom
print(littles_law_concurrency(2_000, 0.05))       # 100 in flight
print(kafka_drain_minutes(36_000_000, 30_000, 20_000))  # 60 minutes
TechnologyFits when
k6Scripted, open-model HTTP/gRPC/WebSocket tests in CI, with thresholds as pass/fail gates
GatlingHigh-throughput tests from few generators; JVM teams; rich reports
JMeterMany protocols (JDBC, JMS, LDAP), GUI-based test authoring
LocustPython teams; complex user flows; easy distributed workers
wrk2, VegetaAccurate constant-rate latency benchmarks free of coordinated omission
GoReplay, Envoy/Istio mirroring, NGINX mirrorReplaying or shadowing real production traffic
Diffy-style response diffingChecking a rewrite behaves identically under real traffic
HdrHistogram, t-digest, Prometheus native histogramsAccurate, mergeable latency percentiles
Prometheus + Grafana, Datadog, CloudWatchUtilisation, saturation and demand-driver dashboards for models
Prophet, statsmodels (Holt–Winters), BigQuery ML / cloud forecastingDemand forecasting with seasonality and events
Kubernetes HPA, KEDA, Karpenter, Cluster AutoscalerReactive pod and node autoscaling, including queue-driven scaling
AWS predictive and scheduled scaling, GCP/Azure equivalentsScaling ahead of daily patterns and known events
AWS Cost Explorer, GCP Billing, Kubecost / OpenCostUnit costs, rightsizing, Kubernetes cost allocation

Trade-offs#

OptionProsConsPick when
High utilisation targets (70%+)Lower costLittle failover headroom; near the latency knee; burst-sensitiveBatch, async or fault-tolerant work with fast scaling
Low utilisation targets (30–50%)Safe tails, absorbs failover and burstsExpensiveLatency-critical, revenue-critical, slow-to-scale tiers
Reactive autoscalingPays for what you use; handles gradual growth2–10 minute lag; flapping; doesn't fit stateful tiersStateless tiers with gradual daily curves
Predictive / scheduled scalingCapacity ready before the peakWrong forecasts waste money or under-provisionStrong daily or weekly patterns, known events
Provisioned / reserved capacityLowest unit cost; predictable; no lagCommitment risk; idle when demand dropsSteady baseline; stateful tiers
Spot capacity60–90% cheaperInterruptions; capacity not guaranteedFault-tolerant stateless work, batch, CI, load generators
Synthetic load testsControlled, repeatable, any load levelUnrealistic traffic mix unless carefully modelledPre-launch, regression gates, breakpoint finding
Traffic replayReal request mix, can multiply rateSanitisation work; stateful writes are hardValidating capacity with today's real mix at future scale
ShadowingReal traffic in real time, zero user impactDouble load on shared dependencies; side-effect isolationMigrations and rewrites (Slack's Kafka move)
Live-traffic tests (Kraken, squeeze tests)True production capacityRisk to users; needs excellent monitoring and fast rollbackLarge fleets with mature traffic control

Common Pitfalls#

  • Sizing from averages, ignoring peak-to-average ratios and per-second bursts.
  • Forgetting failure-domain headroom. A fleet that's fine at 80% across 3 AZs is at 120% after losing one.
  • Closed-model tests with coordinated omission, reporting a p99 of 10 ms for a system that freezes for seconds.
  • A load-generator bottleneck: the generator machine maxes its CPU, or the tool silently drops iterations, so the test never delivers the intended load.
  • Cache-friendly test data (one user ID, one product) that measures the cache instead of the system. Or the opposite, all-uncached random keys that under-estimate capacity.
  • Ignoring warm-up and cold caches after deploys, scale-outs and failovers. Capacity is lowest exactly when you need it most.
  • Autoscaling the app tier into a database meltdown, because more pods means more connections and queries on a tier that didn't scale.
  • Hitting cloud quotas or instance stock-outs during an event because nobody raised limits beforehand.
  • Retry storms. Clients retrying on timeout multiply load at the worst moment. Capacity plans must assume retry behaviour, and resilience patterns (retry budgets, jitter) must cap it.
  • Soak tests skipped, so memory leaks surface after 3 days in production.
  • Capacity models never revisited after an architecture change altered the cost per request.
  • Treating cost and capacity separately: engineering over-provisions "for safety" with no visibility of unit cost, or finance cuts reservations without knowing the headroom requirements.

Real-World Examples#

  • Slack's job queue migration (2017). Slack moved its Redis-based job queue to a Kafka-backed design after an outage in which backlog and dispatch state competed for the same Redis memory. The new Kafka cluster (16 brokers, 32 partitions per topic, replication factor 3) was sized with load tests at expected production rates. It was validated with failure drills (broker loss, a forced unclean leader election, a full cluster restart) and rolled out via dual writes, a shadow-mode relay, per-hop job counting and per-partition heartbeat canaries, before serving customers one job type at a time.
  • Facebook Kraken (OSDI 2016). It uses live traffic shifting to load web and service clusters toward their limits, identifying bottlenecks and true capacity. The paper reports finding and fixing many capacity issues, and raising the utilisation the fleet could safely sustain.
  • Google SRE practice. The Site Reliability Engineering book (Beyer, Jones, Petoff and Murphy, O'Reilly, 2016) describes N+2 provisioning, demand forecasting, load testing as part of launch reviews, and intent-based capacity planning. Its Auxon tool turned high-level intent ("serve with 5 nines from 3 regions") into resource allocations via a solver.
  • Amazon Prime Day / retail peaks. Amazon publicly discusses preparing for Prime Day with large-scale load testing, and its AWS posts report the peak scale its services handle during the event. The general lesson is that the yearly peak is planned and rehearsed months ahead, not autoscaled on the day.
  • Ticketing on-sales. Ticket platforms facing millions of users at a fixed on-sale time combine pre-provisioned capacity, virtual waiting rooms (queue-it style admission control) and spike tests. Pure autoscaling can't react in seconds to a step from 0 to millions.
  • Netflix. Netflix's engineering blog has described squeeze testing (narrowing a cluster's instances under real traffic to find per-instance limits), predictive autoscaling (its Scryer system), and regional evacuation drills, which require each remaining region to absorb a failed region's traffic.
  • Gil Tene and coordinated omission. His HdrHistogram library and wrk2 fork are now standard tools for honest latency measurement, and k6 and Gatling's open models follow the same principle.

Case studies that use this pattern#

In the Interview#

Common follow-ups:

  • "Why not run servers at 90% CPU to save money?" Queueing: at 90% utilisation, M/M/1 response time is 10× the service time. Losing an AZ pushes the survivors above 100%. Bursts during autoscaling lag have nowhere to go.
  • "How many connections should the DB pool have?" Little's law: queries/s × query latency = average busy connections. Add headroom for latency spikes, then cap so all instances together stay under the DB's efficient concurrency (often a small multiple of its cores), not its max_connections.
  • "We doubled the nodes and throughput went up 20%. Why?" Contention (α) or coherency costs (β) in USL terms: a shared lock, a hot partition, a single leader, broadcast invalidations. Measure, fit the USL, and fix the serialisation point.
  • "Your load test shows p99 of 20 ms but users complain of seconds-long stalls. Why?" Likely coordinated omission in a closed-model test, or server-side timing that misses queueing. Re-test with a constant arrival rate and measure from the intended send time.
  • "How would you test a rewrite before switching traffic?" Shadow production traffic to it with side effects isolated, diff the responses, compare capacity metrics, then canary.
  • "How do you prepare for a 10× event next month?" Forecast with the business, load-test at 10× plus headroom, pre-provision stateful tiers, raise quotas, set scheduled minimums, cache and degrade aggressively, add a waiting room if needed, and run a game day.
Deep Dive: Queueing Beyond M/M/1 (Erlang C, Square-Root Staffing and Fan-out Tails)Show

The M/M/1 knee explains why one busy server gets slow. Real services are pools: a pod with 12 worker threads, a database with 16 cores, a fleet of 100 pods behind a load balancer. The right model is M/M/c: Poisson arrivals, exponential service times, c identical servers sharing one queue. Its key output is the Erlang C formula (A. K. Erlang, early 1900s, originally for telephone exchanges). It gives the probability that an arriving request finds every server busy and has to wait.

Define the offered load a = λ × S, measured in "Erlangs". This is just Little's law: the average number of servers that would be busy. With λ = 900 req/s and S = 10 ms, a = 9. You need at least 10 workers just to be stable. But how many do you need for good latency? Erlang C answers that directly:

Workers cUtilisationP(request waits)Mean waitP(wait > 20 ms)
1090%67%6.7 ms9%
1182%43%2.2 ms0.8%
1275%27%0.9 ms0.07%
1369%16%0.4 ms0.01%
1560%5%0.08 ms~0

Two lessons stand out. First, the tail improves dramatically with each added server near saturation. Going from 10 to 12 workers (20% more cost) cuts the chance of a 20 ms queueing delay by over 100×. Second, mean wait is a poor guide: at 90% utilisation the mean wait is still under one service time, but 9% of requests wait more than two service times, and those are what your p99 sees.

Pooling gets better with scale. Now take a = 90 (ten times the traffic, same service time):

Servers cUtilisationP(request waits)Mean wait
9595%50%1.0 ms
10090%22%0.2 ms
10586%8%0.06 ms

At a = 90, 90% utilisation gives better queueing than 75% did at a = 9. This is the economy of scale behind big shared pools. The rule of thumb that captures it is square-root staffing (Halfin and Whitt, Heavy-Traffic Limits for Queues with Many Exponential Servers, Operations Research, 1981):

c ≈ a + β √a

β is a quality-of-service knob. With β ≈ 1, about 20–25% of requests wait at all, at any scale. For a = 9 that's 9 + 3 = 12 servers (75% utilised). For a = 90 it's 90 + 9.5 ≈ 100 (90% utilised). For a = 9,000 it's 9,000 + 95 ≈ 9,095 (99% utilised!). The headroom needed to absorb randomness grows only with the square root of the load. That's why large, pooled fleets can run hotter than small ones, for randomness alone. It doesn't remove the need for failure-domain headroom (zone loss) or forecast error, which grow linearly with load.

The practical consequences:

  • Don't fragment pools. Ten tenants each with a dedicated 10-worker pool need far more total capacity, for the same tail, than one shared 100-worker pool. This is a real argument for shared fleets (with isolation guarded by quotas and bulkheads), and against per-customer clusters unless isolation demands them. See Multi-Tenancy.
  • Small, hot pools are the tail-latency danger. A pod with 4 worker threads at 80% busy has a high wait probability. Thread-per-request servers with small pools, and databases with few cores, show queueing early.
  • Load balancing matters. M/M/c assumes one shared queue: any idle server takes the next request. A load balancer that assigns requests randomly to per-server queues behaves like c separate M/M/1 queues, which is much worse. Join-shortest-queue or power of two choices (Mitzenmacher, The Power of Two Choices in Randomized Load Balancing, IEEE TPDS, 2001) gets close to the pooled ideal at low cost: sample two servers, send to the less loaded one. This is one reason least-outstanding-requests balancing beats round-robin for variable-cost requests; see Load Balancing.

Service-time variability. M/M/c assumes exponential service times, which have a coefficient of variation (CV, standard deviation divided by mean) of 1. Real services vary: a cache hit takes 1 ms and a miss takes 40 ms, giving a CV well above 1. For a single server with general service times (M/G/1), the Pollaczek–Khinchine formula gives the mean wait:

W = ρ / (1 − ρ) × S × (1 + CV²) / 2

At CV = 1 this reduces to M/M/1. At CV = 3 (common for mixed cheap/expensive requests) the mean wait is 5× higher at the same utilisation. Kingman's approximation, mentioned earlier, extends this to variable arrivals too. The design lesson is that variance is a capacity cost. Separating cheap and expensive requests into different pools (a "fast lane"), capping request sizes, paginating, and moving expensive work to async queues all lower CV and let you run hotter safely.

Fan-out tail amplification. A request that fans out to N backends in parallel is as slow as the slowest one. If each backend has a 1% chance of being slower than its p99, the chance that at least one of N is slow is 1 − 0.99^N:

Fan-out NP(at least one backend above its p99)
11%
109.6%
10063%

With a fan-out of 100, the backend's p99 becomes the frontend's median. Even at the p99.9 level, 9.5% of requests with a fan-out of 100 hit at least one backend slower than its p99.9. Dean and Barroso described this in The Tail at Scale (Communications of the ACM, 2013) and proposed hedged requests: send to one replica, and if no reply arrives within, say, the p95 latency, send a second copy to another replica and use whichever replies first. That costs only about 5% extra load while cutting the tail sharply. Their paper reports a Google BigTable benchmark where hedging after 10 ms cut the p99.9 for reading 1,000 keys from 1,800 ms to 74 ms, with only about 2% more requests. Tied requests go further, enqueueing on two servers that cancel each other when one starts work.

For capacity planning, this means fan-out services need more headroom per backend than their own SLO suggests. Hedging consumes a few percent extra capacity that must be budgeted. Fan-out width is a capacity parameter too: halving it (by better sharding, or by partial results with a deadline) can matter more than adding servers.

Deep Dive: The Statistics of Load Testing (Percentiles, HdrHistogram and Fitting the USL)Show

A load test produces numbers that people treat as facts: "p99 is 180 ms", "we max out at 4,200 req/s per pod". Most of those numbers have error bars nobody has computed, and some are just wrong. This deep dive covers how to make them trustworthy.

You cannot average percentiles. If pod A reports p99 = 100 ms and pod B reports p99 = 300 ms, the fleet p99 is not 200 ms. It depends on each pod's whole distribution and request count. It could be anything from about 100 ms to 300 ms. Dashboards that average per-host p99s (or take the "max of p99") routinely misreport. The fix is to collect mergeable summaries, meaning histograms, and compute percentiles after merging:

  • HdrHistogram (Gil Tene) records values into buckets that are exponential in magnitude, with linear sub-buckets inside each. You choose the number of significant digits. With 3 significant digits, every recorded value is accurate to within 0.1%, across a range from 1 microsecond to an hour, in a few tens of kilobytes. Recording is a fixed-cost array increment (nanoseconds), and two histograms merge by adding their counts. That makes it ideal for load generators and for merging across workers.
  • t-digest (Ted Dunning) clusters values adaptively, so it's most accurate at the extreme tails, where you care most. It merges approximately and is used in many databases and metrics systems.
  • DDSketch (Masson, Rim and Lee, VLDB 2019, from Datadog) guarantees relative error (for example, every percentile within 1% of the true value). Like HdrHistogram it uses logarithmic buckets, and it merges exactly.
  • Prometheus histograms with fixed buckets are mergeable, but their accuracy is only as good as the bucket boundaries. A p99 inside a bucket spanning 250–500 ms is an interpolation. Native (exponential) histograms in newer Prometheus versions improve this considerably.

How many samples do you need? A percentile estimate from n samples is an order statistic, and its uncertainty follows the binomial distribution. The rank of the true p-quantile among n samples has mean np and standard deviation √(np(1 − p)). For a 95% interval, take ±1.96 standard deviations:

  • n = 10,000, p99: np = 9,900, sd ≈ 10, so the interval spans ranks 9,880–9,920. The true p99 lies between your measured p98.8 and p99.2. That's reasonably tight.
  • n = 10,000, p99.9: only 10 samples lie beyond it, and the interval spans ranks 9,984–9,996, between your measured p99.84 and p99.96. On a heavy tail, that's a wide latency range.
  • The rule of thumb: to estimate the p(1 − 1/k) percentile you want at least 10–100 × k samples. For p99.9 that's at least 10,000 and preferably 100,000; for p99.99, a million.

A 5-minute test at 50 req/s yields 15,000 samples, which is fine for p99 and shaky for p99.9. Short or low-rate tests that report p99.99 are reporting noise.

Comparing runs. Performance numbers vary run to run: noisy neighbours on shared cloud hosts, JIT warm-up, GC timing, cache state, network jitter. Run-to-run variation of 5–10% in throughput is common on cloud VMs. To claim "the new version is 8% faster", you need:

  1. Several runs per variant (at least 3–5), interleaved (A, B, A, B) so drifting conditions affect both equally.
  2. Warm-up excluded. Discard the first few minutes, or ramp before measuring.
  3. A comparison of distributions, not single numbers. Non-parametric tests such as Mann–Whitney U don't assume normality, which latency data never has.
  4. Fixed environment variables: same instance types, same data size, same region, and dedicated hosts if the variance is too high.

Continuous benchmarking systems that run performance tests on every commit (MongoDB, for example, has published its use of change-point detection on CI performance results: Daly et al., ICPE 2020) exist because single-run comparisons generate a flood of false alarms.

Correcting for coordinated omission. If you're stuck with a closed-model tool, HdrHistogram supports a correction: recordValueWithExpectedInterval(value, expectedInterval). When a recorded latency exceeds the expected interval between requests, it back-fills the samples that should have been sent during the stall, with linearly decreasing latencies. This approximates what an open-model test would have recorded. It's a repair, not a substitute; prefer generating load at a constant arrival rate (wrk2, k6's arrival-rate executors, Gatling's open injection) and measuring from the intended send time.

Watch the generator. A test is only valid if the generator delivered the intended load. Check: generator CPU stays below about 70%; the achieved rate matches the target; k6's dropped_iterations (or the equivalent) is zero; the generator's network isn't saturated; there are enough source ports and connections (ephemeral port exhaustion caps tests at tens of thousands of new connections per second per source IP). Distribute generators across hosts and zones when needed. Spot instances are fine for this.

Fitting the USL to measurements. The USL from earlier is useful precisely because you can fit it to a handful of measurements and extrapolate. The method (from Neil Gunther's Guerrilla Capacity Planning, Springer, 2007):

  1. Measure throughput X(N) at several concurrency levels or node counts, for example N = 1, 2, 4, 8, 16, 32. Each point is a steady-state run at saturation.
  2. Compute relative capacity C(N) = X(N) / X(1).
  3. Rewrite the USL as a quadratic: N / C(N) − 1 = α (N − 1) + β N (N − 1). Fit α and β by least-squares regression, with no intercept.
  4. Compute the peak at N* = √((1 − α) / β) and the predicted X(N) beyond your measurements.
import numpy as np
 
N = np.array([1, 2, 4, 8, 16, 32])
X = np.array([1000, 1940, 3640, 6300, 9200, 10100])  # measured req/s
C = X / X[0]
y = N / C - 1
A = np.column_stack([N - 1, N * (N - 1)])            # columns for alpha, beta
(alpha, beta), *_ = np.linalg.lstsq(A, y, rcond=None)
n_star = np.sqrt((1 - alpha) / beta)
print(f"alpha={alpha:.3f} beta={beta:.5f} N*={n_star:.0f}")  # 0.028, 0.00130, 27

Interpret the fitted values, not just the curve. A large α (for example 0.05+) points to serialisation: a global lock, a single-writer partition, a leader. A non-trivial β points to cross-talk: cache coherency, all-to-all gossip, distributed locks, broadcast invalidation. Each has a different fix, and the fit tells you which to look for. Two cautions: extrapolate modestly (at most 2× beyond the largest measured N), and re-fit after any architecture change.

Deep Dive: Capacity at Hyperscale (Failover Headroom, Metastable Failures and Intent-Based Planning)Show

At large scale, capacity planning stops being "how many servers" and becomes a set of interacting constraints: failure domains at several levels, a fleet shared by thousands of services, multi-month supply chains for hardware, and failure modes in which the system loses capacity exactly when load peaks.

Stacking failure-domain headroom. Survive-the-loss-of-one rules compound. With R active regions sharing load evenly, each region must be able to absorb its share of a failed region's traffic, so it can run at no more than (R − 1)/R of its capacity in steady state. Inside each region, with Z zones, each zone must absorb a lost zone's share: (Z − 1)/Z. If you require both, the factors multiply:

Regions × zonesRegional factorZonal factorMax steady-state utilisation
2 × 31/22/333%
3 × 32/32/344%
5 × 34/52/353%

Then you also need queueing headroom (stay below the knee) and forecast error. That's why naive "N+1 everywhere" plans look shockingly expensive, and why large operators make deliberate choices:

  • Don't require simultaneous region and zone loss. Plan for one or the other, accept degraded mode (shed low-priority traffic) for the double failure, and get much higher utilisation.
  • More, smaller failure domains. Going from 2 regions to 5 raises the regional factor from 50% to 80%. Cells and shuffle sharding apply the same principle inside a region (see Designing for High Availability).
  • Priority-aware capacity. Not all traffic needs failover capacity. Batch jobs, prefetching, analytics and other preemptible work fill the headroom in normal times and get evicted during failover. Google's Borg (Verma et al., Large-scale cluster management at Google with Borg, EuroSys 2015) reports reclaiming unused reservation for lower-priority work this way; the headroom isn't idle, it's lent out.

Metastable failures. The most dangerous capacity events aren't slow overloads but metastable failures: a trigger pushes the system into a bad state that sustains itself after the trigger is gone. Bronson, Aghayev, Charapko and Zhu named and described these in Metastable Failures in Distributed Systems (HotOS 2021), and Huang et al. analysed real incidents in Metastable Failures in the Wild (OSDI 2022). Typical feedback loops:

  • Retry amplification. A brief slowdown causes timeouts. Clients retry, so load goes up, so latency goes up, so more timeouts happen. With 3 retries per layer across 3 layers, worst-case amplification is 4³ = 64×. The system stays down even after the original slowdown ends.
  • Cache-loss collapse. If the cache serves 95% of reads, the database sees 5%. A cache restart or mass expiry sends 100% of reads to the database: a 20× load jump. Even a drop in hit rate from 95% to 90% doubles database load. A cold cache under peak load may never warm, because the database is too overloaded to serve the fills.
  • Work that grows with backlog. Slack's Redis queue, described earlier, had a dequeue path whose cost grew with queue length. Long queues made draining slower, exactly when draining mattered most.
  • GC or swapping death spirals. Higher load means more allocation, longer GC pauses, more queueing, and more in-flight objects, so more GC.

Classic capacity planning sizes for the stable state at peak. Metastability means you must also consider the vulnerable state: the system has spare capacity in normal operation, but a trigger (deploy, zone loss, cache flush, upstream retry storm) can tip it into a sustained overload. Defences that capacity planners should insist on:

  • Retry budgets and circuit breakers (retries capped at around 10% of requests) and jittered backoff, so retries can't multiply load; see Resilience Patterns.
  • Admission control and load shedding that rejects work early (cheaply) instead of letting it queue (expensively). Work is shed by priority, and queues are bounded with LIFO or deadline-based dropping, so stale requests aren't served.
  • Plan the database for cache-miss scenarios, or protect it with request coalescing, warm-up procedures (warm a new cache from a peer before taking traffic), and staggered TTLs; see Caching Strategies.
  • Load-test the recovery, not just the steady state. Kill the cache under peak load; drop a zone at peak; restart the fleet while traffic flows. If the system can't recover without manual traffic reduction, you've found a metastable state.

Capacity as an organisation-wide system. At hyperscale, capacity is managed as a shared resource with its own processes:

  • Quotas and budgets per service. Teams request capacity against forecasts. A central capacity team aggregates, applies pooling (square-root effects across services), and orders hardware months ahead.
  • Intent-based planning. Google's SRE book describes Auxon. Teams state intent, such as dependencies, SLOs, failure tolerances ("N+2 in each region") and location constraints. A solver (linear programming) computes the cheapest resource allocation that satisfies them all. Plans then update automatically when forecasts or constraints change, instead of being redone by hand in spreadsheets.
  • Continuous production capacity testing. Facebook's Kraken shifts real traffic to deliberately load clusters toward target utilisation, measuring where latency or errors start to rise. That gives an up-to-date, empirical capacity number for every cluster and exposes regressions that load tests in staging miss.
  • Disaster-readiness exercises. Draining an entire region or data centre on a schedule proves the failover headroom actually exists. Many large operators run such drills regularly; see Disaster Recovery and Backups.
  • Efficiency programmes with unit-cost targets (cost per 1,000 requests, per active user, per GB stored). They're often the biggest lever: a 20% efficiency gain across a large fleet is worth more than any rightsizing.

Worked example: a region evacuation plan. Three regions serve 300k req/s at peak, 100k each. Each region has 3 zones and runs 1,500 pods at 200 req/s each (load-tested at SLO), for 300k req/s of capacity per region.

  • Normal: 100k / 300k = 33% utilisation per region.
  • One region lost: the two survivors carry 150k each: 50% of capacity. Fine.
  • One region lost, plus a zone in a surviving region: that region has 1,000 pods (200k req/s) for 150k req/s: 75%. Survivable, near the knee.
  • Cache warm-up: the traffic moving into the surviving regions belongs to users whose data isn't in those regions' caches. If the hit rate there drops from 95% to 85% for an hour, database read load triples. The plan must check database headroom for this, not just pods. Gradual traffic shifting, and pre-warming caches with the moving users' hot keys, are the fixes.

The pods were never the hard part. The database and the cache were, which is the recurring lesson of capacity planning at every scale.

Key Takeaways#

  • Capacity planning is a loop: measure demand drivers, forecast (P50/P90 plus events), model each tier, add headroom, provision, verify with load tests, and repeat as traffic and code change.
  • Size from peaks (per second, during events), not averages, and plan headroom for failure domains: N+1 zones means about 67% maximum steady utilisation with 3 zones.
  • Little's law (L = λW) sizes concurrency: threads, connections, in-flight requests. The utilisation knee (response time ∝ 1/(1 − ρ)) explains why 90% busy is dangerous and why variance makes it worse.
  • The USL explains why adding nodes stops helping, or even hurts: contention (α) and coherency (β). Fit it from measurements to find the real limit and the serialisation point.
  • Bottlenecks hide in shared tiers: databases, hot partitions, connection limits, third-party quotas, single Kafka partitions. Model every component, not just the app servers.
  • Load-test with an open model at forecast peak plus headroom. Use realistic data and mixes, run soak, spike and breakpoint tests, and measure percentiles with HdrHistogram-style mergeable histograms, free of coordinated omission.
  • Real traffic is the best test. Replay, shadowing (Slack's dual writes and shadow mode), response diffing and live capacity tests (Kraken, squeeze tests) find what synthetic tests miss.
  • Autoscaling handles gradual change, not instantaneous spikes or stateful tiers. Pre-provision, schedule minimums, raise quotas and keep caches, queues and waiting rooms ready for known events.
  • Watch for metastable failures (retry storms, cache-loss collapse): test recovery under peak load, cap retries, shed load early.
  • Capacity is a cost decision too: track unit economics, mix reserved, on-demand and spot capacity, rightsize continuously, and make headroom an explicit, justified number rather than an accident.