TS·119
Performance Testing
Measuring how a system behaves under load: questions performance tests answer, the vocabulary (throughput, latency percentiles, concurrency, saturation, Little's law), test types (baseline, load, stress, spike, soak, capacity, breakpoint), open versus closed workload models and coordinated omission, writing tests with k6, Gatling, Locust and JMH/criterion/Go benchmarks for micro-benchmarks, realistic workloads and data, environments, thresholds as pass/fail criteria, analysing results with observability, and performance testing in CI.
Start here: how much load before it hurts?
A performance test answers a question about the system under load: how many orders per second can it take while staying fast? What happens just beyond that? Did this change make it slower? The service here is a model kitchen: four cooks, each order takes 20 ms. Its capacity is therefore 4 ÷ 0.020 s = 200 orders per second, so we can check every measurement against a number we know.
The vocabulary, measured
Throughput is completed requests per second; latency is how long each takes, reported as percentiles (p95 = 95% of requests were at least this fast). Concurrency is how many are in progress at once. Driving the kitchen with a fixed number of simulated users, each sending a new request as soon as the last returns:
users throughput avg latency p95
1 47.5/s 20.9 ms 21.2 ms
4 187.3/s 21.2 ms 21.9 ms
10 191.1/s 52.1 ms 63.4 ms
40 191.6/s 207.1 ms 214.2 ms
Up to 4 users, each request found a free cook. Beyond 4, throughput stopped growing at about 191/s (close to the 200/s capacity, minus overhead) and the extra users just queued. Little's law ties the three together: concurrency = throughput × latency. Check it: 191.1 × 0.0521 = 9.96 ≈ 10 users; 191.6 × 0.207 = 39.7 ≈ 40.
Real customers don't wait politely
In that test, the load generator slowed down when the system slowed down: a user waiting 200 ms sent fewer requests. Real customers arrive whenever they like. An open-model test sends requests at a fixed arrival rate, regardless of how the system is coping:
rate achieved p50 p95 dropped threshold p95<100 ms
100/s 99.9/s 21.0 ms 21.9 ms 0 ✓ pass
180/s 179.9/s 21.2 ms 32.0 ms 0 ✓ pass
210/s 191.8/s 596 ms 1.01 s 163 ✗ FAIL (exit code 99)
260/s 191.8/s 1.75 s 2.07 s 973 ✗ FAIL
Below capacity, latency stayed near 20 ms. Just 5% above capacity (210/s), the queue grew without limit for the whole 20 seconds and the median went from 21 ms to 596 ms. That cliff is the most important thing performance testing shows you, and the closed-model test above could never reach it, because it reduces its own load as the system slows.
Thresholds turn a test into a gate
thresholds: { http_req_duration: ['p(95)<100'], http_req_failed: ['rate<0.01'] }
When a threshold is crossed, k6 exits with code 99, so a CI pipeline fails the build. Here the gate passed at 180/s and failed at 210/s.
Catching a regression
A change made each order take 25 ms instead of 20 (a slower query, say). Same test, 150 requests per second:
20 ms version: p50 20.9 ms p95 21.6 ms (capacity 200/s)
25 ms version: p50 26.2 ms p95 57.3 ms (capacity 160/s)
25 ms version at 170/s: p95 1.08 s ✗ FAIL
A 25% slower request meant a 20% lower capacity, a 2.7× worse p95 at the same load, and collapse at a load the old version handled easily (180/s). Per-request benchmarks alone would have reported "5 ms slower".
How deep to go in performance testing
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 throughput, latency percentiles, concurrency and the main test types |
| L2 | Write a k6 (or Gatling, JMeter, Locust) test with scenarios and thresholds and run it in CI |
| L3 | Explain open vs closed models, Little's law, coordinated omission and why latency rises steeply near capacity |
| L4 | Find a system's capacity and bottleneck, and detect performance regressions reliably |
| L5 | Design a performance-testing strategy: workload models, environments, data, budgets and capacity planning |
| L6 | Run performance engineering across an organisation with production-informed models |
What performance tests answer
Performance testing measures how a system behaves under load to answer questions like:
- Does it meet its SLOs (e.g. 99% of checkout requests under 300 ms) at expected peak traffic?
- How much traffic can it handle before latency or errors become unacceptable (capacity)?
- What breaks first under overload, and does it degrade gracefully and recover?
- Does it stay healthy over hours (memory leaks, connection leaks, growing queues)?
- Did this change make it slower (regression)?
Every performance test should start with a question and success criteria; "let's hammer it and see" produces numbers nobody can interpret. Theory (queueing, Little's law, utilisation curves) is in Vol. 9 ch. 105.
Vocabulary
| Term | Meaning |
|---|---|
| Throughput | Completed operations per unit time (requests/s, messages/s) |
| Latency | Time for one operation; measure as a distribution |
| Percentiles | p50 (median), p95, p99, p99.9: the value below which that fraction of samples falls. Tail percentiles reflect what many users experience, since one page load fans out into many requests |
| Concurrency | Operations in flight at once (virtual users, connections) |
| Error rate | Fraction of failed operations; a fast error isn't success |
| Utilisation | Fraction of time a resource is busy (CPU 70%) |
| Saturation | Work waiting for a resource (run queue length, pool waits, queue depth): the signal that you've hit a limit |
| Little's law | L = λ × W: concurrency = arrival rate × time in system. 200 req/s at 0.25 s each means 50 in flight |
Don't average latencies. A mean of 120 ms can hide a p99 of 2 s. And don't average percentiles across instances or time windows (the average of p99s isn't the p99); aggregate from histograms (HdrHistogram, Prometheus native/exponential histograms).
Types of performance tests
| Type | Profile | Question |
|---|---|---|
| Baseline | Low, steady load | What does "normal" look like? Reference numbers to compare against |
| Load | Ramp to expected peak (and a margin), hold | Do we meet SLOs at expected peak? |
| Stress | Keep increasing beyond peak | Where and how does it break? Does it degrade gracefully (shed load, 429/503) and recover afterwards? |
| Breakpoint | Slow continuous ramp until failure | What is the maximum throughput? |
| Spike | Sudden jump (10× in seconds) and drop | Does autoscaling react in time? Do queues and caches cope with a thundering herd? |
| Soak (endurance) | Realistic load for many hours/days | Memory/connection/file-descriptor leaks, log/disk growth, GC degradation, slow drifts |
| Capacity | Measure throughput per instance at SLO-compliant latency | How many instances do we need for next season's traffic, and at what cost? |
| Scalability | Repeat at 1, 2, 4, 8 instances | Does throughput scale linearly, or does a shared bottleneck (DB, lock) cap it? |
Workload models
Closed versus open
- Closed model: a fixed number of virtual users (VUs), each sending a request, waiting for the response, (optionally thinking), then sending the next. When the system slows down, users send fewer requests: load drops automatically, which hides overload.
- Open model: requests arrive at a fixed rate (e.g. 500/s), regardless of how fast the system responds, like real internet traffic from many independent users. When the system slows down, concurrency grows and queues build, exposing real behaviour.
Most public-facing services experience open arrivals; use arrival-rate executors for SLO and capacity tests.
Coordinated omission
A closed-model load generator that waits for slow responses doesn't send the requests that would have arrived during the stall, so those delays are never measured. The tool "coordinates" with the system under test and omits the worst latencies (Gil Tene's term). A 2-second pause might show as one slow sample instead of hundreds of affected requests, making p99 look far better than reality.
Fixes: use open/arrival-rate models (k6 constant-arrival-rate, Gatling open injection profiles, wrk2), tools that correct for it (HdrHistogram's expected-interval correction), and generators with enough capacity that they aren't the bottleneck.
Tools
| Tool | Language for scripts | Notes |
|---|---|---|
| Grafana k6 | JavaScript/TypeScript | Single Go binary; executors for open and closed models; thresholds; browser module; extensions (xk6); Grafana Cloud k6 for distributed runs; on the 2.x line |
| Gatling | Java, Kotlin, Scala, JavaScript/TypeScript | High-performance async engine, rich HTML reports, open/closed injection profiles |
| Locust | Python | Users defined as Python classes; distributed mode; web UI |
| JMeter | GUI/XML | Long-established, many protocols, heavier to maintain as code |
| wrk2, vegeta, oha, hey | CLI | Quick HTTP benchmarks; wrk2 and vegeta use constant rates |
| ghz | CLI | gRPC load testing |
| Artillery | YAML/JS | Includes Playwright-based browser load |
k6
// load-test.js — open model at expected peak, with SLO thresholds as pass/fail
import http from "k6/http";
import { check, sleep } from "k6";
export const options = {
scenarios: {
browse_and_buy: {
executor: "ramping-arrival-rate", // open model: iterations started per second
startRate: 50,
timeUnit: "1s",
preAllocatedVUs: 200,
maxVUs: 2000,
stages: [
{ target: 500, duration: "5m" }, // ramp to expected peak (500 iterations/s)
{ target: 500, duration: "20m" }, // hold
{ target: 0, duration: "2m" },
],
},
},
thresholds: {
"http_req_duration{name:checkout}": ["p(95)<300", "p(99)<800"],
http_req_failed: ["rate<0.001"],
checks: ["rate>0.999"],
},
};
export default function () {
const product = http.get(`${__ENV.BASE_URL}/api/products/${randomSku()}`, { tags: { name: "product" } });
check(product, { "product 200": (r) => r.status === 200 });
sleep(Math.random() * 2); // think time between steps of the journey
const res = http.post(`${__ENV.BASE_URL}/api/checkout`,
JSON.stringify({ sku: product.json("sku"), qty: 1 }),
{ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token()}` }, tags: { name: "checkout" } });
check(res, { "checkout 201": (r) => r.status === 201 });
}
k6 run -e BASE_URL=https://perf.example.com load-test.js exits non-zero if thresholds fail, so the test can gate CI or a release. Tags (name) group URLs with IDs into one metric series.
Gatling
// Gatling Java DSL: open-model injection with assertions
public class CheckoutSimulation extends Simulation {
HttpProtocolBuilder http = http.baseUrl(System.getenv("BASE_URL")).acceptHeader("application/json");
ScenarioBuilder buyer = scenario("browse and buy")
.exec(http("product").get("/api/products/#{sku}").check(status().is(200)))
.pause(Duration.ofSeconds(1), Duration.ofSeconds(3))
.exec(http("checkout").post("/api/checkout")
.body(StringBody("{\"sku\":\"#{sku}\",\"qty\":1}")).asJson()
.check(status().is(201)));
{
setUp(buyer.injectOpen(
rampUsersPerSec(10).to(500).during(Duration.ofMinutes(5)),
constantUsersPerSec(500).during(Duration.ofMinutes(20))))
.protocols(http)
.assertions(
details("checkout").responseTime().percentile(95.0).lt(300),
global().failedRequests().percent().lt(0.1));
}
}
Locust
# locustfile.py
from locust import HttpUser, task, between
class Buyer(HttpUser):
wait_time = between(1, 3)
@task(5)
def browse(self):
self.client.get(f"/api/products/{random_sku()}", name="/api/products/[sku]")
@task(1)
def checkout(self):
self.client.post("/api/checkout", json={"sku": random_sku(), "qty": 1}, name="checkout")
# locust -f locustfile.py --headless -u 2000 -r 50 -t 25m --host https://perf.example.com
# (closed model: 2000 users; use a constant-throughput wait_time to approximate open arrivals)
Micro-benchmarks
System load tests measure services; micro-benchmarks measure a function or data structure. They need frameworks that handle warm-up, JIT, dead-code elimination and statistics:
// JMH: warm-up iterations, forks, and Blackhole to defeat dead-code elimination
@BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5) @Measurement(iterations = 10) @Fork(2)
@State(Scope.Benchmark)
public class ParseBench {
String input = "2026-10-24T10:15:30Z";
@Benchmark public void parse(Blackhole bh) { bh.consume(Instant.parse(input)); }
}
// Go: testing.B with b.Loop (Go 1.24+) — keeps results alive and excludes setup automatically
func BenchmarkParse(b *testing.B) {
input := "2026-10-24T10:15:30Z"
for b.Loop() {
if _, err := time.Parse(time.RFC3339, input); err != nil { b.Fatal(err) }
}
}
// go test -bench=Parse -benchmem -count=10 | tee new.txt ; benchstat old.txt new.txt
// Rust: criterion with statistical analysis and change detection
use criterion::{criterion_group, criterion_main, Criterion};
use std::hint::black_box;
fn bench_parse(c: &mut Criterion) {
c.bench_function("parse rfc3339", |b| {
b.iter(|| chrono::DateTime::parse_from_rfc3339(black_box("2026-10-24T10:15:30Z")).unwrap())
});
}
criterion_group!(benches, bench_parse);
criterion_main!(benches);
# Python: pytest-benchmark (or pyperf for rigorous runs)
def test_parse_benchmark(benchmark):
benchmark(datetime.fromisoformat, "2026-10-24T10:15:30+00:00")
// Zig: no built-in benchmark harness; time with std.time.Timer, build with -OReleaseFast,
// and use std.mem.doNotOptimizeAway to keep results alive
const std = @import("std");
pub fn main() !void {
var timer = try std.time.Timer.start();
var i: usize = 0;
while (i < 1_000_000) : (i += 1) std.mem.doNotOptimizeAway(parse("2026-10-24"));
std.debug.print("{d} ns/op\n", .{timer.read() / 1_000_000});
}
Compare runs statistically (benchstat, criterion's change detection, JMH with multiple forks), on quiet machines with fixed CPU frequency where possible; a 3% difference on a noisy laptop is noise.
Making tests realistic
Workload
- Model the traffic mix from production analytics (90% reads, 8% searches, 2% checkouts), not a single endpoint hammered in a loop.
- Use realistic data volumes in the database (a query fast on 1,000 rows may be slow on 100 million) and realistic key distributions (hot keys, Zipfian popularity), varied payload sizes, and realistic cache hit rates (a test reusing one product ID measures the cache, not the system).
- Include think time between steps of user journeys, and realistic connection behaviour (keep-alive, TLS handshakes, HTTP/2).
- Record and replay production traffic (GoReplay, service-mesh mirroring) for high-fidelity tests, after scrubbing personal data.
Environment
- Production-like environment: same instance types, configuration, data sizes, network topology and dependencies (or carefully scaled-down replicas with known ratios). Results from a laptop or tiny staging environment don't transfer linearly.
- Isolate the test: no other teams' tests running; or, with care, test in production during low traffic with synthetic tenants and kill switches (many large companies do).
- Ensure the load generator isn't the bottleneck (monitor its CPU/network; distribute across machines) and is close to where real traffic enters (or deliberately far, to include network latency).
- Know what's stubbed: a stubbed payment provider removes a real latency source.
Analysing results
A load test produces a few client-side numbers; understanding them requires server-side observability (Vol. 9): RED metrics per endpoint, USE metrics per resource, traces of slow requests, profiles.
- Check validity first: was the intended load actually generated? Error rates? Generator saturated? Coordinated omission?
- Look at latency percentiles over time, not just a summary: when did p99 start rising? (Plot alongside offered load.)
- Find the first saturated resource when latency rises: CPU, memory/GC, connection pool, thread pool, database CPU or locks, network, a downstream dependency's rate limit. The knee of the latency curve shows where queueing begins.
- Use traces and profiles (continuous profiling, flame graphs) to see where time goes in slow requests.
- For stress tests, check behaviour at and after the limit: graceful load shedding vs cascading failure; recovery time once load drops.
- Compare with the baseline and previous runs; record environment, versions and configuration with results so they're reproducible.
Performance testing in the delivery pipeline
- Per pull request: micro-benchmarks for performance-critical code with regression detection; small smoke-load tests (a minute at modest load) to catch gross regressions such as an N+1 query.
- Nightly or pre-release: full load tests at peak against a production-like environment, with thresholds that fail the pipeline.
- Periodically: stress, spike, soak and capacity tests before major events (sales, launches) and after major architecture changes.
- Continuous: production observability and SLO burn-rate alerts are the real performance test; feed real traffic patterns back into test workloads.
- Store results over time (k6 to Prometheus/Grafana, Gatling Enterprise, CI artifacts) to see trends, not just pass/fail.
Lab: load testing a system with known capacity
k6 1.3.0 on the lab machine (2 cores) against a Go service that models a kitchen: a semaphore of SLOTS concurrent orders, each taking WORK_MS. With 4 slots and 20 ms, theoretical capacity is 200 requests per second. Load generator and service share the machine, which caps what the setup can measure; with a real system, run the generator on separate hardware and watch its own CPU.
sem := make(chan struct{}, slots)
http.HandleFunc("/order", func(w http.ResponseWriter, r *http.Request) {
sem <- struct{}{}; time.Sleep(time.Duration(work) * time.Millisecond); <-sem
fmt.Fprintln(w, `{"ok":true}`)
})
Experiment 1: closed model and Little's law
export const options = { vus: __ENV.VUS, duration: '15s' };
export default function () { http.get('http://127.0.0.1:8191/order'); }
| VUs | Requests | Throughput | avg | p95 | p99 | X × R |
|---|---|---|---|---|---|---|
| 1 | 713 | 47.5/s | 20.9 ms | 21.2 ms | 22.6 ms | 0.99 |
| 4 | 2,812 | 187.3/s | 21.2 ms | 21.9 ms | 24.5 ms | 3.97 |
| 10 | 2,875 | 191.1/s | 52.1 ms | 63.4 ms | 65.3 ms | 9.96 |
| 40 | 2,912 | 191.6/s | 207.1 ms | 214.2 ms | 219.5 ms | 39.7 |
The last column multiplies throughput by average latency and recovers the number of VUs every time, which is a quick sanity check on any load-test result. The 191/s plateau is 4% under the theoretical 200/s: HTTP handling, scheduling and timer granularity add a little to each 20 ms.
Experiment 2: open model, through the cliff
scenarios: { load: { executor: 'constant-arrival-rate', rate: __ENV.RATE, timeUnit: '1s',
duration: '20s', preAllocatedVUs: 50, maxVUs: 400 } },
thresholds: { http_req_duration: ['p(95)<100'], http_req_failed: ['rate<0.01'] },
| Rate | Achieved | p50 | p95 | p99 | Dropped | Thresholds | Exit |
|---|---|---|---|---|---|---|---|
| 100/s | 99.9/s | 21.0 ms | 21.9 ms | 42.6 ms | 0 | pass | 0 |
| 180/s | 179.9/s | 21.2 ms | 32.0 ms | 72.5 ms | 0 | pass | 0 |
| 210/s | 191.8/s | 596 ms | 1.01 s | 1.03 s | 163 | fail | 99 |
| 260/s | 191.8/s | 1.75 s | 2.07 s | 2.07 s | 973 | fail | 99 |
Two details matter. First, dropped_iterations: when every one of the 400 VUs was stuck waiting on the slow service, k6 couldn't start new arrivals and dropped them, so the "achieved" rate understates the offered load. Always check this metric; a test that silently stops offering load measures the wrong thing. Second, no request failed (0% errors) even at 2 s latency: the service never times out or sheds load, so overload shows up only as latency. Volume 9's chapter 105 measures what load shedding does instead.
Experiment 3: a regression gate
| Version | Rate | p50 | p95 | p99 | Result |
|---|---|---|---|---|---|
| 20 ms/order | 150/s | 20.9 ms | 21.6 ms | 24.6 ms | pass |
| 25 ms/order | 150/s | 26.2 ms | 57.3 ms | 79.0 ms | pass, but p95 2.7× worse |
| 25 ms/order | 170/s | 648 ms | 1.08 s | 1.11 s | fail |
A CI performance gate needs three things to be trustworthy: a fixed workload (same rate, same data, same duration), a stable environment (dedicated runners; the noise from a shared machine can exceed the regression you're looking for), and a comparison with a baseline from the main branch rather than only an absolute threshold, so a 2.7× p95 change is flagged even while it still passes "p95 < 100 ms". Run each side several times and compare distributions; a single run of each proves little.
Experiment 4: test types as k6 scenarios
The same script supports each test type by changing only the executor:
| Type | Question | k6 executor |
|---|---|---|
| smoke | does the script and system work at all? | vus: 1, duration: '30s' |
| load | is it fine at expected peak? | constant-arrival-rate at peak |
| stress | where and how does it break? | ramping-arrival-rate past capacity |
| spike | can it absorb a sudden burst? | ramping-arrival-rate with a steep stage |
| soak | does it degrade over hours (leaks, growth)? | constant-arrival-rate for 4–12 h |
| breakpoint | what is the maximum? | ramping-arrival-rate until thresholds abort (abortOnFail) |
Try it yourself
- Run a
ramping-arrival-ratestress test from 50/s to 300/s over 2 minutes withabortOnFailon the p95 threshold, and read off the rate where it aborted. - Change the service to reject requests with 503 when more than 20 are queued. Rerun at 260/s: how do latency and error rate change?
- Rerun Experiment 3 five times per version and compare the spread of p95 values. How big must a regression be before one run can detect it?
- Add
SLOTS=8and predict the capacity and the latency at 300/s before measuring.
Revision sheet: performance testing
Key ideas
- Questions first: capacity, latency at expected load, breaking behaviour, regressions, long-run stability.
- Vocabulary: throughput, latency percentiles (not averages), concurrency, utilisation, saturation, errors.
- Little's law: concurrency = throughput × latency; use it to sanity-check results and size pools.
- Open vs closed workload models: open (arrival rate) matches real traffic and reveals overload; closed (fixed users) hides it.
- Near capacity, latency rises steeply; above it, queues grow without bound.
- Test types: smoke, load, stress, spike, soak, breakpoint.
- Tools: k6, Gatling, JMeter, Locust, wrk2/vegeta for HTTP; thresholds make tests gates.
- Trustworthy results: realistic workload and data, production-like environment, separate load generators, warm-up, repeated runs, baselines, and watch for coordinated omission and dropped arrivals.
Numbers to remember
- Lab: capacity 4 slots ÷ 20 ms = 200/s; measured plateau ≈ 191/s.
- Lab: 180/s → p95 32 ms; 210/s → p95 1.01 s (5% over capacity).
- Lab: 20 → 25 ms per request cut capacity 20% and made p95 at 150/s 2.7× worse.
- k6 exits 99 when thresholds fail.
Pitfalls
- Reporting averages; ignoring tail percentiles.
- Closed-model tests that slow down with the system and never find the cliff.
- Load generator on the same busy machine, or itself saturated (dropped iterations).
- Testing with tiny or unrealistic data sets and cold caches without saying so.
- Single runs compared with no baseline; noisy shared CI runners.
- Testing only below capacity.
Glossary
- VU: virtual user in k6.
- Arrival rate: requests started per second in an open model.
- Saturation: a resource at its limit, with work queueing.
- Soak test: long run to find leaks and degradation.
- Coordinated omission: a measurement flaw where slow responses suppress the requests that would have recorded the delay.