Observability and SREVol. 9 · Part IX
0 / 0

Shelves / Observability and SRE

OB·105

Production Performance Engineering

Performance from first principles: latency, throughput, utilisation and saturation; queueing theory (the utilisation curve, M/M/1, why latency explodes near 100%), Little's law and its uses, Amdahl's law and the Universal Scalability Law, bottleneck analysis, a profiling methodology across Java, Go, Python, Rust, C++ and Node, load generation done right (open versus closed models, coordinated omission, test types and tools: k6, Gatling, Locust, wrk2, Vegeta, JMeter), and capacity planning with headroom and forecasting.

29 topics · ~20 min read · 30-question quiz
Updated Suggest a correction

Start here: why systems get slow long before they're "full"

Latency explodes as utilisation approaches 100%

Text
 load   achieved   p50 ms   p99 ms
  30%      119/s      8.4     49.4
  50%      189/s      9.2     47.8
  70%      272/s     12.0     52.7
  80%      314/s     16.5     67.4
  90%      347/s     32.1    157.8
  95%      370/s    251.5    414.7

Each request still needed only 10 ms of work. The extra time is waiting in a queue: requests arrive at random, so sometimes several arrive together and the later ones wait. The busier the server, the more often that happens, and the curve isn't a straight line. Going from 80% to 95% busy multiplied the median latency by 15. That's why services are run at well under 100% utilisation and why "the CPU is only at 80%" can still mean users are waiting.

Little's law: a rule you can always use

average number in the system = arrival rate × average time in the system (L = λ × W)

At 80% load the lab measured, on average, 6.0 requests inside the server; 314 requests/s × 19.8 ms = 6.3. It holds for any stable system: a checkout queue, a thread pool, a Kafka consumer. Uses: how many threads or connections a service needs (rate × latency), and how much latency a backlog implies.

When load exceeds capacity, say no early

At 120% of capacity, a queue only grows. With an unbounded queue the server served everything eventually, and everything late:

Text
120% load, unbounded queue                 p50 2920 ms   p99 4843 ms   answered within 500 ms:   0 per second
120% load, queue limit 40 (shed the rest)  p50  110 ms   p99  169 ms   answered within 500 ms: ~366 per second

Rejecting the excess immediately ("503, try later") kept the requests it accepted fast. That's load shedding: it turns an outage for everyone into a degraded service for some.

Measure first, then optimise

A profiler shows where the time goes. In the lab, a menu-rendering job took 18.9 ms; the sampling profiler py-spy showed 58% of the time inside a function checking whether each dish was sold out by scanning a list. Changing that list to a set (one line) made the job take 7.8 ms. Guessing would probably have blamed the JSON encoding (4%).

How deep to go in production performance engineering

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain latency, throughput, utilisation, percentiles and why queues form
L2 Run a load test and a profiler; read a flame graph
L3 Apply Little's law and queueing intuition; design load tests that avoid coordinated omission
L4 Diagnose bottlenecks and tail latency in production with profiles, traces and metrics
L5 Plan capacity and performance budgets for a system; design for overload
L6 Run performance engineering as a practice: continuous profiling, regression gates, cost-performance

The vocabulary

Term Definition Unit
Latency (response time) Time from request sent to response received, as experienced by the caller. Includes waiting (queueing) and service time ms, s (as a distribution: p50, p99)
Service time Time actually spent working on the request, excluding waiting ms
Throughput Completed work per unit time requests/s, MB/s, messages/s
Utilisation Fraction of time a resource is busy %
Saturation Degree to which a resource has more work than it can serve (queued work) queue length, wait time
Concurrency Requests in progress at once count
Goodput Throughput of useful, successful work (excluding retries, timeouts, errors) requests/s

Latency and throughput are related but different: a system can have high throughput and terrible latency (big batches, long queues), or low latency and low throughput (one fast worker). Most performance work is about getting enough throughput while keeping tail latency within the SLO.

Queueing theory in one chapter

Why latency explodes near full utilisation

Any resource that serves requests (a CPU core, a thread pool, a disk, a database connection pool, a single-threaded event loop) behaves like a queue plus a server. When requests arrive randomly, some arrive while the server is busy and must wait.

For the simplest model, M/M/1 (random Poisson arrivals, exponential service times, one server):

Average response time R = S / (1 − U)

where S is the average service time and U the utilisation. At U = 50%, R = 2S; at 80%, R = 5S; at 90%, R = 10S; at 95%, R = 20S; at 99%, R = 100S. Response time grows without bound as utilisation approaches 100%, and tail latency grows even faster.

utilisationR / S 0%50%80%90%100% comfortable zone 2×5×10×20×
Response time versus utilisation for a single queue (M/M/1). Latency stays near the service time at low utilisation, then curves sharply upward: doubling at 50%, five times at 80%, ten times at 90%. Running hot leaves no headroom for bursts, which is why capacity targets usually stay well below 100%.

Consequences:

  • Headroom is not waste: running CPUs or pools at 90% means queueing dominates latency and any burst causes a pile-up. Typical targets: 50–70% average utilisation for latency-sensitive services.
  • Variability hurts: the more variable arrivals and service times are (bursty traffic, occasional slow requests, GC pauses), the worse the queueing (Kingman's formula: waiting time scales with the variability of both). Reducing variance (batching smoothly, removing slow outliers) improves latency even at the same utilisation.
  • More servers per queue help (M/M/c): one shared queue feeding several workers has far less waiting than separate queues per worker (why a single bank queue beats one queue per teller, and why work stealing and least-request load balancing beat random assignment).
  • Overload: when arrival rate exceeds capacity, queues grow until something breaks (memory, timeouts). Clients time out and retry, adding load: congestion collapse. Hence bounded queues and load shedding (chapter 104).

Little's law

Little's law holds for any stable system, regardless of distributions:

L = λ × W

average number in the system = average arrival rate × average time in the system

Uses:

  • Concurrency sizing: 2,000 req/s × 0.05 s average latency = 100 requests in flight. A thread pool, connection pool or Kubernetes concurrency limit must accommodate that (plus headroom).
  • Detecting problems: if latency to a dependency doubles at the same request rate, the number of in-flight requests (threads, connections) doubles too, which is how a slow dependency exhausts a pool.
  • Database pools: at 500 queries/s with 4 ms each, about 2 connections are busy on average; a pool of 100 is pointless (and harmful to the database). Size pools from Little's law plus burst headroom.
  • Queues: a Kafka consumer group processing 1,000 msg/s with 2 s average time in system holds about 2,000 messages in flight (lag).
  • Load testing: closed-loop testers with N virtual users and think time Z produce throughput X = N / (R + Z) (the interactive response time law).

The utilisation law and bottlenecks

  • Utilisation law: U = X × S (throughput × service time per request at that resource). At 400 req/s and 2 ms of CPU per request, CPU utilisation = 0.8 cores.
  • The bottleneck is the resource with the highest utilisation (highest demand per request relative to capacity). System throughput can't exceed 1 / (largest service demand): improving anything else doesn't raise maximum throughput.
  • Bottlenecks move: fix the database and the next limit appears (connection pool, network, a lock).

Scalability laws

Amdahl's law

If a fraction p of the work can be parallelised and the rest is serial, the maximum speedup with N processors is:

Speedup(N) = 1 / ((1 − p) + p / N)

With 95% parallel work, the speedup can never exceed 20×, however many cores you add. Serial sections (a global lock, a single-threaded coordinator, a shared database row) cap scalability.

Universal Scalability Law

Neil Gunther's USL adds coherency (crosstalk) costs: keeping shared state consistent (cache coherence, distributed locks, chatty coordination) costs grow with N²:

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

  • α = contention (serialisation, like Amdahl's serial fraction)
  • β = coherency (crosstalk between nodes)

With β > 0, throughput peaks and then declines as you add nodes: adding servers makes things slower. Fitting USL to load-test data at a few concurrency levels predicts where your system peaks.

N (nodes / threads)throughput linear (ideal) Amdahl (contention) USL peakcoherency: more nodes hurt
Scalability curves. Linear scaling is the ideal; Amdahl's law (contention) flattens toward a ceiling; the Universal Scalability Law adds coherency costs, so throughput reaches a peak and then falls as more nodes or threads are added.

Practical lessons: reduce shared mutable state and coordination (partitioning, single-writer ownership, Vol. 5 ch. 65), avoid global locks and hot rows, batch coordination, and measure scalability instead of assuming it.

Bottleneck analysis

A disciplined approach to "it's slow":

  1. Define the problem precisely: which operation, which percentile, since when, under what load, compared with what baseline or SLO?
  2. Check the obvious: recent changes (deploys, config, data growth), resource limits (cgroup throttling, pool exhaustion, file descriptors), errors and retries.
  3. USE method for every resource on the request path (Vol. 6 ch. 79): utilisation, saturation, errors for CPU, memory, disks, network, and software resources (thread pools, connection pools, locks, queues, rate limits).
  4. Trace slow requests to find where the time goes (chapter 101); compare with fast requests.
  5. Profile the component that owns the time to find why (below).
  6. Form a hypothesis, change one thing, measure again. Keep notes; performance work is empirical.

Common culprits by symptom:

Symptom Likely causes
High latency, low CPU Waiting: locks, I/O, connection pool exhaustion, slow dependency, DNS, GC pauses, CPU throttling
High CPU, throughput flat Inefficient code (hot loops, regex compiles, serialisation), GC churn from allocations, spin locks, too many threads (context switching)
Latency grows with load Queueing near saturation; contention on a shared resource; pool sizes
Periodic latency spikes GC, cron jobs, cache expiry stampedes, log rotation, compaction, autoscaling events, noisy neighbours
Tail latency much worse than median Head-of-line blocking, occasional slow dependency calls, retries, cold caches, uneven load balancing
Slow only for some tenants/endpoints Data skew (hot partitions, huge accounts), N+1 queries on large collections, missing indexes

Profiling

Methodology

  • Profile in production (continuous profiling, chapter 97) or under realistic load in a test environment; micro-benchmarks lie about real workloads.
  • Choose the right profile type:
  • CPU (on-CPU): where cycles go.
  • Off-CPU / wall-clock: where threads wait (I/O, locks, sleeps), essential for latency problems.
  • Allocation / heap: who allocates and what retains memory (GC pressure, leaks).
  • Lock / mutex contention.
  • Goroutine / thread dumps: what everyone's doing right now (deadlocks, pool starvation).
  • Read flame graphs (chapter 97); compare differential flame graphs between versions.
  • Fix the biggest thing first; re-measure.

Tools by language

# Java: async-profiler (low overhead, CPU/alloc/lock/wall), JFR (built into the JVM), jcmd
asprof -d 30 -e cpu   -f /tmp/cpu.html   <pid>          # CPU flame graph
asprof -d 30 -e wall  -f /tmp/wall.html  <pid>          # wall-clock (includes waiting threads)
asprof -d 30 -e alloc -f /tmp/alloc.html <pid>          # allocation profile
jcmd <pid> JFR.start duration=60s filename=/tmp/app.jfr settings=profile   # open in JDK Mission Control
jcmd <pid> Thread.print                                  # thread dump: blocked threads, pool starvation
jcmd <pid> GC.heap_info

Common optimisations that pay off

  • Algorithmic: O(n²) loops over growing data, N+1 queries, scanning instead of indexing (Vol. 4).
  • Avoid repeated work: cache compiled regexes, templates, serializers, prepared statements; memoise expensive pure functions; cache remote results with TTLs.
  • Reduce allocations in hot paths (pooling, reusing buffers, avoiding boxing/temporary strings): less GC.
  • Batch and pipeline I/O: batch DB writes, Redis pipelining, bulk APIs, HTTP/2 multiplexing.
  • Concurrency where it helps: parallelise independent downstream calls (the critical path); but bound it.
  • Right-size pools (Little's law) and remove contention (lock striping, lock-free structures, single-writer partitions).
  • Tune runtimes: GC choice and heap sizing (JVM G1/ZGC, GOGC/GOMEMLIMIT), JIT warm-up (CDS/AOT caches), worker counts.
  • Serialisation formats: JSON parsing can dominate CPU; consider faster libraries or binary formats (Protobuf) on internal hot paths.

Load generation

Open versus closed models

How the load generator issues requests changes the results:

Model How Represents Pitfall
Closed N virtual users, each sends a request, waits for the response (and think time), then sends the next A fixed population of users (internal tools, batch clients) When the system slows, users send fewer requests, so load drops as latency rises, hiding overload
Open Requests arrive at a target rate (e.g. 500/s) regardless of responses Internet traffic: new users keep arriving whether or not you're slow Needs enough generator capacity; reveals queueing and collapse realistically

Use open (arrival-rate) models for internet-facing services. In k6 that's the constant-arrival-rate / ramping-arrival-rate executors; in Gatling, open injection profiles (constantUsersPerSec, rampUsersPerSec).

Coordinated omission

Gil Tene's coordinated omission: if a load generator waits for slow responses before sending the next request (closed loop, or a fixed schedule that stalls), it doesn't send the requests that would have arrived during the stall, so those requests' latencies are never measured. Reported percentiles look far better than what users would experience. Fixes: open-model generators that keep the schedule (wrk2, k6 arrival-rate executors, Vegeta), and correcting latency to the intended send time (HdrHistogram supports this).

Test types

Test Purpose
Smoke Tiny load to verify the script and system work
Load Expected peak traffic; verify SLOs are met with headroom
Stress Increase load beyond expectations to find the breaking point and how it fails (graceful shedding or collapse?)
Spike Sudden jumps (marketing push, retry storm); test autoscaling and shedding
Soak / endurance Sustained load for hours; find leaks, slow degradation, log/disk growth, connection churn
Breakpoint / capacity Ramp until SLOs break: the measured capacity per instance
Scalability Measure throughput at several instance counts; fit USL

Tools

JavaScript
// k6 (JavaScript, Go engine): open-model arrival rate with SLO thresholds that fail the test
import http from "k6/http";
import { check } from "k6";

export const options = {
  scenarios: {
    checkout: {
      executor: "ramping-arrival-rate",
      startRate: 50, timeUnit: "1s", preAllocatedVUs: 200, maxVUs: 2000,
      stages: [
        { target: 500, duration: "5m" },   // ramp to peak
        { target: 500, duration: "20m" },  // hold
        { target: 0,   duration: "2m" },
      ],
    },
  },
  thresholds: {
    http_req_failed: ["rate<0.001"],                     // availability SLO
    "http_req_duration{name:checkout}": ["p(95)<300", "p(99)<1000"],
  },
};

export default function () {
  const res = http.post(`${__ENV.BASE_URL}/checkout`, JSON.stringify({ cart: "c-123" }),
    { headers: { "Content-Type": "application/json" }, tags: { name: "checkout" } });
  check(res, { "status 200": (r) => r.status === 200 });
}
Tool Language / style Notes
k6 (Grafana) JavaScript scripts, Go engine Open and closed executors, thresholds as pass/fail, cloud and distributed runs, browser module
Gatling Scala/Java/Kotlin/JS DSL Efficient (async), strong open-model injection, detailed HTML reports
Locust Python Code-defined user behaviour, distributed workers; mainly closed model
wrk2 C, Lua scripts Constant throughput with coordinated-omission correction; great for raw HTTP benchmarks
Vegeta Go CLI/library Constant-rate HTTP load, HdrHistogram output
JMeter Java GUI/XML Long-established, many protocols; heavier
ghz, k6 gRPC gRPC gRPC benchmarking

Realism matters more than tool choice: production-like data volumes, traffic mix (from real access logs), cache states (cold and warm), think times, dependencies (real or realistic stubs with realistic latency), and a test environment whose capacity relationship to production is understood. Run the generator from outside the system under test, and watch the generator itself (CPU-bound generators produce bogus results). Integrate performance tests into CI for critical paths, and compare against baselines to catch regressions.

Capacity planning

Capacity planning ensures enough resources for future demand at acceptable cost:

  1. Measure demand drivers: requests per second per endpoint, active users, data growth, messages per second, and their relationship to business metrics (orders per day).
  2. Measure capacity: from load tests (breakpoint per instance, per database) and production telemetry (resource demand per request: CPU-ms per request, DB queries per order).
  3. Forecast: growth trends, seasonality (daily, weekly, festive seasons, sales events), planned launches and marketing campaigns. Simple models (linear or exponential trend plus seasonality, e.g. Prophet or seasonal decomposition) are often enough.
  4. Plan with headroom: - N+1 / zone loss: capacity to lose a zone (or a region) at peak. - Burst headroom: utilisation targets that keep queueing low (50–70%). - Lead times: reserved instances, quota increases, hardware for on-premises, database scaling operations that take hours.
  5. Identify the next bottleneck at 2× and 5× load: which component breaks first (database writes, a single-threaded consumer, a third-party rate limit)?
  6. Review regularly (quarterly, plus before major events) and compare forecasts with reality.

A worked example: an orders API peaks at 1,200 req/s today, growing 8% per month; one pod sustains 150 req/s at p99 within SLO (from a breakpoint test at 70% CPU). In 6 months, peak ≈ 1,200 × 1.08⁶ ≈ 1,900 req/s → 13 pods at peak, plus zone-loss headroom across 3 AZs (×1.5) → about 20 pods and matching database capacity. The database handles 6,000 queries/s and each request does 3 queries → 5,700 queries/s at forecast peak: the database is the next bottleneck, so plan read replicas, caching, or query reduction now.

Lab: queues, overload, measurement traps and a profile

An aiohttp 3.14 server on one machine with c = 4 workers (an asyncio.Semaphore) and exponentially distributed service times averaging 10 ms (a sleep, so the machine's CPU isn't the bottleneck): capacity 400 requests per second. An open-loop generator sends requests at random (Poisson) times at a set rate, regardless of whether earlier ones have finished, which is how independent users behave. Runs last 12–20 s; the first sixth of each run is discarded as warm-up.

Experiment 1: the latency curve against queueing theory

Text
 load   achieved   p50 ms   p99 ms   mean ms  M/M/4 mean ms   L (measured)  λ×W (Little)
  30%      119/s      8.4     49.4     11.8        10.1           1.3           1.4
  50%      189/s      9.2     47.8     12.3        10.9           2.1           2.5
  70%      272/s     12.0     52.7     14.9        13.6           3.8           4.2
  80%      314/s     16.5     67.4     19.8        17.5           6.0           6.3
  90%      347/s     32.1    157.8     43.6        29.7          14.8          15.7
  95%      370/s    251.5    414.7    248.4        54.6          91.5          94.4

The M/M/4 column is the textbook prediction (Erlang C) for random arrivals and exponential service with 4 servers. Up to 80% the measurement tracks it, about 1.5–2 ms higher: that's Python's HTTP handling on both sides, real work the model doesn't include. That overhead also means the server's true utilisation is higher than the nominal load, and near saturation a few percent matters enormously: at a nominal 95% the real system was at or beyond capacity, and the queue grew for the whole run instead of settling. Practical lessons: plan capacity from measured service times including overhead, keep headroom (a target of 60–75% for latency-sensitive services is common), and treat any model as a guide to the curve's shape, not its exact numbers.

Little's law held at every load: the sampled average number of requests inside the server (L) matched arrival rate × mean latency to within the sampling error, including in the unstable 95% run.

Experiment 2: overload, with and without shedding

120% of capacity (480 requests per second) for 15 s:

Text
120% load, unbounded queue               : served  7160, shed    0, p50   2920 ms, p99   4843 ms, within 500 ms deadline     0/s
120% load, queue limit 40 (shed the rest): served  5538, shed 1581, p50    110 ms, p99    169 ms, within 500 ms deadline  ~366/s

The unbounded queue "served" more requests, but every one of them after its deadline: if callers time out at 500 ms, the server did 15 seconds of useless work while users saw a total outage. That's congestion collapse: throughput looks fine, goodput (useful work) is zero. Bounding the queue at 40 (about 100 ms of work for 4 workers) and rejecting the rest kept accepted requests well inside the deadline and delivered close to full capacity as goodput. Production versions: queue-length or concurrency limits (Netflix's concurrency-limits, Envoy's adaptive concurrency), dropping requests whose deadline has already passed, LIFO under overload, and prioritising critical traffic (checkout over recommendations).

Experiment 3: coordinated omission

The server freezes for 1 s every 5 s (think of a garbage-collection pause or a lock held during a flush) and otherwise answers in ~2 ms. Two ways of measuring it for 20 s:

Text
closed loop (10 workers, each sends the next request when the last returns):
    39017 requests, p50 3.9 ms, p90 4.7 ms, p99 7 ms, share over 100 ms 0.12%
open loop (200 requests/s on a fixed schedule, latency measured from the scheduled send time):
    p50 3.7 ms, p99 996 ms, share over 100 ms 19%

The server was frozen 20% of the time, so about 20% of users arriving at random would wait. The closed-loop tester reported a p99 of 7 ms because during each freeze its 10 workers were stuck and stopped sending: it recorded 10 slow requests per freeze instead of the ~200 that real users would have sent. This is coordinated omission (Gil Tene's term): the load generator coordinates with the system under test and omits exactly the measurements that matter. Use open-model tools or modes for latency testing (wrk2's -R rate, k6's constant-arrival-rate executor, Gatling's open injection profiles, Vegeta), measure from the intended send time, and be suspicious of a "p99" from any closed-loop benchmark.

Experiment 4: finding a hot spot with a sampling profiler

py-spy 0.4.2 (a sampling profiler that reads a running Python process's stacks from outside, without changing its code) recorded the menu-rendering job at 200 samples per second:

Text
40 renders: 18.9 ms each
samples 201
   96.0% inclusive  render
   57.7% inclusive  is_sold_out          ← `d["id"] in SOLD_OUT`, where SOLD_OUT is a list of 572 ids
   24.9% inclusive  price_text           ← a regex substitution per dish
    4.0% inclusive  _compile
    4.0% inclusive  encode               ← JSON encoding
after SOLD_OUT = set(SOLD_OUT):  40 renders: 7.8 ms each

The profile pointed straight at a linear search repeated 4,000 times per render; a one-line change to a set (constant-time lookups) cut the time by 59%, as the 57.7% share predicted. Inclusive time is time spent in a function and everything it calls; self time excludes callees. A flame graph shows both at once (py-spy record -o profile.svg). Equivalent tools: async-profiler and JFR for the JVM, pprof for Go, perf and eBPF-based profilers for native code and whole hosts, and continuous profilers (Pyroscope/Grafana, Parca, Datadog, Elastic) that keep profiles from production over time.

Try it yourself

  1. Rerun experiment 1 with constant (not exponential) service times. Which percentiles change most, and why?
  2. In experiment 2, replace the queue limit with "drop requests that have already waited longer than 200 ms". Compare goodput.
  3. Run wrk against the freezing server and compare its latency distribution with both generators. Then read about how wrk2 corrects for coordinated omission.

Revision sheet: production performance engineering

Key ideas

  • Vocabulary: latency (percentiles), throughput, utilisation, saturation, goodput, headroom.
  • Queueing: waiting time grows non-linearly with utilisation (roughly ρ / (1 − ρ)); variability makes it worse.
  • Little's law L = λW; utilisation law U = X × S; the bottleneck is the resource with the highest demand.
  • Scalability: Amdahl (serial fraction caps speed-up), USL (contention and coherence make throughput fall at high concurrency).
  • Method: USE for resources, RED for services, then profile; optimise the biggest share first.
  • Load testing: open vs closed models, coordinated omission, test types (load, stress, soak, spike), realistic data and think times.
  • Capacity planning: forecast demand, measure per-instance capacity at target latency, keep headroom, plan for failures (N+1 / N+2).

Numbers to remember

  • Lab: 4 workers × 10 ms → 400/s capacity; p50 8.4 ms at 30% load, 16.5 ms at 80%, 251 ms at 95%.
  • Overload at 120%: unbounded queue goodput 0; queue limit 40 kept p99 at 169 ms.
  • Coordinated omission: closed loop p99 7 ms vs open loop p99 996 ms on the same server.
  • Profiling: list → set took a job from 18.9 to 7.8 ms.

Pitfalls

  • Running near 100% utilisation; scaling on averages.
  • Unbounded queues and no admission control.
  • Closed-loop benchmarks quoted as latency results; tests from one region with tiny data sets.
  • Optimising without profiles; micro-optimising code that's 4% of the time.
  • Forgetting overhead (serialisation, network, GC) in capacity models.

Glossary

  • Goodput: useful throughput (within deadline, correct).
  • Coordinated omission: missing measurements because the load generator waits for the system.
  • Open / closed model: arrivals independent of / dependent on responses.
  • Inclusive / self time: with / without callees.
  • Congestion collapse: throughput maintained but goodput falling to zero under overload.