PRACTITIONERCHAPTER 09

Performance and load testing

A load test is an experiment against an SLO: a workload model, an arrival rate, production-shaped data, thresholds that fail the build, and an honest statement of what it does not prove

45 MINQA AND QUALITY ENGINEERINGUPDATED 2026-11-05
PREDICT

Your k6 test runs 50 virtual users in a loop with no think time against an endpoint that answers in 250 ms, which is 200 requests a second. One minute into the test the service stalls for 10 seconds, then recovers. In production, traffic arrives at 200 a second whatever the service does. What does the p99 for that minute look like in the test report?

Performance testing is the umbrella for any test whose question is “how fast, how much, and for how long” rather than “does it work”. Load testing is the most common kind: put a known amount of traffic on the system and check that it stays inside its objectives. As a QA engineer or SDET you will be asked to write load tests, and more often to say whether someone else’s load test supports a release. Both jobs depend on the same three things: a workload model that resembles production, a way of measuring latency that does not hide the tail, and a pass criterion that is the service level objective rather than a number somebody liked.

This chapter assumes you know what a percentile is and why the tail matters. If not, read the tail latency lesson and the Observability course chapter on histograms and percentiles first.

What a load test is for

Every load test answers one question. Write the question down before you write the script, because the question decides the shape of the traffic, the length of the run and what counts as a pass. The k6 documentation names six test types, and the names are now common across tools.

Type Question it answers Shape Typical length
Smoke Does the script work and is the system alive under minimal load? A handful of requests One to two minutes
Average load Does the system meet its SLO at normal production traffic? Ramp to the normal peak hour, hold 15 to 60 minutes
Stress Does it meet the SLO at the forecast peak plus headroom? Ramp above the forecast, hold 15 to 60 minutes
Spike Does it survive a sudden jump, and recover after? Near-vertical ramp, short hold, drop Minutes
Soak Does anything degrade over time: memory, connections, disk? Average load, held Hours
Breakpoint Where does it stop meeting the SLO, and how does it fail? Ramp until it breaks Until it breaks

Most release questions are stress questions: “on the day of the big on-sale, at the traffic we forecast, will 99% of payment requests finish inside 800 ms?” Most capacity questions are breakpoint questions. A soak test finds the bugs nobody else finds, the leaked file handle, the connection pool that never shrinks, the log volume that fills a disk at hour six, and it is the one teams skip because it is slow.

Open and closed workload models

The most consequential choice in a load test is one most scripts make by accident. In a closed model, a fixed number of virtual users each send a request, wait for the response, optionally pause, and send the next. The number of requests in flight can never exceed the number of users. In an open model, new requests arrive at a rate you set, whether or not earlier ones have finished. Bianca Schroeder, Adam Wierman and Mor Harchol-Balter showed in 2006 that the two models give very different answers about the same system, especially near saturation, and that the choice is usually made without anyone noticing.

The difference is a feedback loop. When a closed-model system slows down, the users wait longer between requests, so the load falls. Fifty looping users against an endpoint that answers in 250 ms generate 200 requests a second. If it slows to 2.5 seconds, the same fifty generate 20 a second. The tool has politely backed off at exactly the moment the real world would not. Customers arriving for a ticket on-sale, phones requesting a one-time passcode, webhooks from a card network: none of these wait for your last response before sending the next. Public, internet-facing traffic is open. A closed model is right for a small, fixed population such as a call-centre application with 300 agents or a batch of workers pulling from a queue.

The tool that sizes an open-model test is Little’s law: the average number of requests in the system, L, equals the arrival rate, λ, multiplied by the average time each spends in the system, W. At 200 requests a second and 300 ms each, 60 requests are in flight on average. In k6 terms, an arrival-rate executor needs enough virtual users to hold that many iterations at once, and it needs headroom for when the system slows: if latency degrades to 2 seconds at 300 requests a second, you need 600. If the tool runs out of virtual users, it cannot start iterations on time, and the test quietly becomes closed again. k6 reports these as dropped_iterations; treat any as a failed run.

Measuring latency honestly

Gil Tene’s talk “How NOT to Measure Latency” is the single most useful hour you can spend on this topic. Its central idea is coordinated omission: a load generator that waits for a slow response before sending its next request coordinates with the system it is measuring and omits the requests that would have suffered most. The Predict above is the arithmetic. Over a one-hour run at 200 requests a second, 720,000 requests are sent. A 10-second stall under a closed model contributes 50 slow samples, 0.007% of the total. Under an open model it contributes about 2,000 requests that waited between zero and ten seconds, 0.28% of the hour and more than 15% of the minute in which it happened. One report says the system is fine. The other says that for one minute, a sixth of your customers waited several seconds.

Four rules follow from the talk and from how percentiles work.

  1. Use an arrival-rate executor for open traffic, and check that it did not drop iterations. That removes most coordinated omission at the source.
  2. Never average percentiles. The p99 of five servers averaged is not the fleet’s p99, and the p99 of each minute averaged across an hour is not the hour’s p99. Merge histograms, then read the percentile. The Observability chapter on histograms and percentiles explains why.
  3. Report the distribution, not one number. A p50, p95, p99 and max, or better an HDR histogram plot, shows whether you have a slow tail or a bimodal system, such as a cache hit path and a miss path.
  4. Measure where the user is. Client-side latency from the load generator includes queueing in the load balancer and the network; server-side timing does not. When they disagree, believe the client, then find out where the time went.

There is a further trap on the load generator itself. A generator machine that runs out of CPU delays sending and receiving, which looks like server latency. Watch the generator’s CPU in every run alongside dropped_iterations; a run with a saturated generator is a run you discard.

The workload model

The workload model is the description of production traffic the test reproduces. It has five parts, and a missing one is the usual reason a passing test does not predict production.

Arrival rate. Take it from production, not from a guess: the busiest minute of the busiest comparable event in the last year, from your metrics, then multiplied by the business forecast for the event you are testing for, then by a headroom factor. A factor of 1.5 over forecast is a common rule of thumb, not a law; agree it with the SRE who owns the capacity plan. Use the busiest minute, not the busiest hour divided by sixty: the hourly mean hides the spike that breaks you.

Mix. Real users do not call one endpoint. A ticketing checkout is a seat-map read, a hold, a payment authorisation and a confirmation, in proportions you can read off production traces. Tests that hammer only the endpoint that changed miss the contention between it and its neighbours.

Data shape. The size of the tables, the cardinality of keys, and the skew of access. A staging database of 2 GB fits in memory; production’s 900 GB does not, so every index lookup in staging is a cache hit. Ten thousand test customers spread evenly do not reproduce one on-sale where 85% of traffic hits one event’s inventory row. Data shape is how locks, hot partitions and cache misses enter the test, and it is the part most often missing.

Behaviour. Think time between steps, retries, the proportion of requests that fail validation, the share that carry an idempotency key and repeat. A payment retry with the same key exercises a different path from a fresh request; see the idempotency lesson.

Dependencies. Third parties, such as an acquirer, a carrier gateway or a fraud vendor, cannot be load-tested and often charge per call. Stub them, but give the stub production’s latency distribution, not a constant 10 ms. A stub that answers instantly removes the very waiting that fills your connection pools.

Thresholds tied to SLOs

A threshold is a pass or fail condition the tool evaluates at the end of the run, and in CI it sets the exit code. The discipline is that the thresholds are the SLO, translated, rather than numbers invented for the test. If the objective in the Observability course sense, as in SLIs, SLOs and error budgets, is “99% of authorisation requests succeed within 800 ms”, then the test needs a p99 latency threshold of 800 ms and an error-rate threshold on the same endpoint, with the same definition of error. If the production SLI counts a 429 as an error, the test does too.

Here is a short k6 script for a payment authorisation endpoint, with an open model and thresholds.

import http from 'k6/http';
import { check } from 'k6';
import { SharedArray } from 'k6/data';

// Tokenised test cards, generated to match production's mix of card types and countries.
const cards = new SharedArray('cards', () => JSON.parse(open('./cards.json')));

// As in the SLO: a 2xx or a decline (402) is a correct answer; 429, other 4xx and 5xx are failures.
http.setResponseCallback(http.expectedStatuses({ min: 200, max: 299 }, 402));

export const options = {
  scenarios: {
    onsale: {
      executor: 'ramping-arrival-rate', // open model: start iterations at a rate
      startRate: 20,
      timeUnit: '1s',
      preAllocatedVUs: 150,   // 360/s x 0.3 s mean = 108 in flight
      maxVUs: 800,            // 360/s x 2 s if latency degrades = 720
      stages: [
        { target: 240, duration: '3m' },  // ramp to forecast peak
        { target: 240, duration: '15m' }, // hold at forecast
        { target: 360, duration: '2m' },  // ramp to 1.5x headroom
        { target: 360, duration: '10m' }, // hold at headroom
      ],
    },
  },
  thresholds: {
    'http_req_duration{name:authorise}': ['p(95)<400', 'p(99)<800'],
    'http_req_failed{name:authorise}': ['rate<0.005'],
    dropped_iterations: ['count<1'], // the generator could not hold the rate
  },
};

let previous = null; // per virtual user: the last fresh request it sent

export default function () {
  let body;
  let key;
  if (previous !== null && Math.random() < 0.02) {
    // 2% repeat an earlier request with the same key and body, as a client retry would.
    body = previous.body;
    key = previous.key;
  } else {
    const card = cards[Math.floor(Math.random() * cards.length)];
    body = JSON.stringify({ token: card.token, amount: card.amount, currency: card.currency });
    key = `${__ENV.RUN_ID}-${__VU}-${__ITER}`;
    previous = { body: body, key: key };
  }
  const res = http.post(
    `${__ENV.BASE_URL}/v1/authorisations`,
    body,
    {
      headers: {
        'Content-Type': 'application/json',
        'Idempotency-Key': key,
      },
      tags: { name: 'authorise' },
    },
  );
  check(res, { 'authorised or declined': (r) => r.status === 201 || r.status === 402 });
}

Five details matter. The name tag lets the thresholds apply to one endpoint rather than to every request the script makes. The virtual-user numbers come from Little’s law, with the arithmetic in the comments so the next reader can check it. The dropped_iterations threshold turns a silent switch to a closed model into a red run. A declined card is a correct answer, not an error: by default k6 counts any status of 400 or above as failed, so the response callback marks 402 as expected and the error-rate threshold measures what the SLO measures. And about 2% of iterations resend the virtual user’s previous request with the same idempotency key and body, so the replay path carries load in the proportion production sees.

Reading the result

A passing run is a single point. What you want is the curve: latency and error rate against arrival rate, run in steps. Near the left of the curve latency is flat; at some arrival rate it bends upward sharply, the knee, because a resource is saturating and requests are queueing for it. The latency cliff lesson walks through how one saturated resource turns a 20 ms request into a 2-second one. Your report says where the knee is relative to the forecast, which resource saturated first (CPU, a connection pool, a lock, a downstream rate limit), and what the system did beyond it. A system that sheds load cleanly with fast 503s, as the load shedding lesson describes, fails very differently from one where every request times out at 30 seconds.

For each resource, Brendan Gregg’s USE method is the checklist: utilisation, saturation, errors. The load test tells you the system broke; the USE pass tells you why.

Where practitioners disagree

Staging or production. One camp says load tests belong in a production-like environment, never production. Another, common at large consumer companies, runs controlled load against production itself, off-peak, with synthetic accounts and an abort switch, on the grounds that no staging environment is production-shaped. Both are defensible. The honest middle is to test in a dedicated performance environment with production-shaped data and to treat production testing as a later, separately approved step.

Every build or before big events. Running a short load test in CI on every merge catches regressions early but needs a stable environment and tolerant thresholds, or it becomes the flakiest job you own. Running full tests only before big events catches capacity problems but finds regressions weeks after the change that caused them. Most teams end with both: a five-minute regression test in the pipeline compared against a baseline, and a full stress test before a known peak.

Who owns it. In some organisations performance testing is a QA specialism; in others it belongs to SRE or to the service team. Ownership matters less than one rule: the person who writes the test is not the only person who reads the result.

Day to day

Performance work arrives in bursts tied to the calendar, with a steady trickle between.

Weekly, about an hour. Check the CI regression job: has p95 on the key endpoints drifted against its baseline? A 15% drift over a month is a conversation with the team before it is a problem. Keep the workload model current; when a new endpoint ships, it enters the mix.

Before a known peak, two to four weeks out. Agree the forecast with product and the business: expected peak arrival rate, date, duration. Write the load test plan (the artefact below) and review it with the service’s tech lead and the SRE who owns capacity, in a forty-five-minute meeting. The review is where the data-shape gap and the stubbed-dependency gap get named. Book the environment; performance environments are always contended.

Test week. Run the smoke test, then the average-load test, then stress, then a breakpoint run. Run each at least twice; one run is an anecdote. Sit with an engineer during the runs, watching the service dashboards as well as the k6 output, because the explanation for a knee is in the server’s metrics, not the client’s.

The readout. A one-page result against the plan’s exit criteria: pass or fail per threshold, the knee, the saturating resource, what was not covered. It goes to the release sign-off as evidence. The release management chapter in this module covers how that evidence is weighed, and testing in production covers what a staging load test cannot tell you.

After the peak. Compare production’s real peak minute with your forecast and the test’s prediction. If production’s p99 at 200 a second was worse than the test’s at 360, your model is missing something, and finding it is the most valuable hour of the cycle.

BY ORG SIZE
STARTUPunder 30 people

Nobody owns performance and nobody has a performance environment. You test the night before a launch, from a laptop, against staging, and the database has twelve rows. Do the cheap things that matter most: use an arrival-rate executor, write thresholds from whatever latency promise the product makes, and generate a realistic volume of fake data once and keep it. A one-page plan still earns its keep, because the paragraph listing what the test does not cover is the one the founder needs to read before the launch.

SCALE-UP30 to 300

Growth has made peaks predictable and expensive: a marketing launch, a big customer onboarding, a seasonal sale. This is where a performance environment gets built and where you make the case for production-shaped data, masked or synthetic. SLOs exist, or are being written, so thresholds can come from them. You own the plan template and the CI regression job, and you spend real time teaching service teams to read their own results instead of sending them to you.

ENTERPRISE300 and up

There may be a performance engineering team with its own tooling, a shared environment booked weeks ahead, and a change board that wants load test evidence for anything customer-facing. Your problem is not running tests but keeping them honest: models copied from the last release, thresholds that drifted away from the SLOs, environments that differ from production in ways nobody recorded. Expect to negotiate with data protection on masked copies and with SRE on testing in production.

ARTEFACT Write a load test plan tied to SLOs ~60 MIN
YOU PRODUCELoad test plan

Template

# Load test plan: <service> for <event or release>
Owner · Reviewers (tech lead, SRE) · Date · Status

## Question
<The one question this plan answers, e.g. "Does X meet its SLO at forecast peak plus headroom?">
Test types: smoke | average | stress | spike | soak | breakpoint

## SLOs under test
| SLI | Objective | Measured where | Threshold in test |
|---|---|---|---|

## Workload model
**Arrival rate:** <busiest minute, source, date> × <forecast factor> × <headroom> = <rate/s>
**Model:** open (arrival-rate) | closed (<population size and why>)
**Mix:** | Endpoint or journey | Share | Source |
**Behaviour:** think time, retries, idempotent repeats, validation failures
**Virtual users:** rate × mean duration = <n>; rate × degraded duration = <maxVUs>

## Profile
| Stage | Target rate | Duration | Purpose |
|---|---|---|---|

## Environment
<Where, instance types and counts vs production, versions, what differs>

## Data
<Table sizes vs production, key cardinality and skew, how produced, masking>

## Dependencies
| Dependency | Real or stub | Stub latency (p50/p99, source) |
|---|---|---|

## Exit criteria
Pass: <all thresholds green, no dropped iterations, generator CPU < 70%>
Report: knee, saturating resource, behaviour beyond the knee

## Not covered
- <gap> — <risk> — accepted by <name>

## Results
<Empty until run. Then per run: date, build, pass/fail per threshold, knee, notes.>
WORKED EXAMPLE

Gannet is a fictional payments platform for ticketing: it authorises card payments for 300 promoters’ on-sales. A stadium tour goes on sale on 14 March and the payments QA engineer wrote this plan four weeks out.

Question. Does the authorisation service meet its SLO at the forecast on-sale peak plus 50% headroom? Types: smoke, stress, breakpoint, plus a two-hour soak at forecast.

SLOs. 95% of authorisations answered within 400 ms and 99% within 800 ms, measured at the load balancer. 99.5% answered with an authorisation or a decline; any other status, including 429 and 5xx, counts as an error. Thresholds: p95 under 400 ms, p99 under 800 ms, failure rate under 0.5%, with the same error definition.

Arrival rate. Busiest minute last year was 7,200 authorisations, 120 a second, at an arena on-sale on 9 September. The promoter forecasts twice that demand: 240 a second. Headroom of 1.5 gives 360 a second.

Virtual users. Mean authorisation time is 300 ms, so 360 × 0.3 = 108 in flight; preAllocatedVUs 150. If latency degrades to 2 s, 360 × 2 = 720; maxVUs 800.

Data. Performance database restored from a masked 640 GB snapshot, matching production’s size. 2 million tokenised test cards in production’s card-type and country mix. 85% of traffic targets one event, as in last September’s peak, so the event’s inventory ledger row is hot. 2% of requests repeat an earlier request’s idempotency key and body, as a client retry would; the service replays the stored response, so a repeat answers 201 or 402.

Dependencies. Acquirer stubbed with production’s latency from February: p50 120 ms, p99 450 ms. Fraud vendor stubbed at p50 40 ms, p99 150 ms.

Not covered. The acquirer’s own capacity (they confirm 500 a second in writing); the seat-hold service, tested separately. Accepted by the payments tech lead.

First run. Thresholds held to 280 a second. At 300 the p99 reached 2.1 s: writes to the hot event’s ledger row serialised behind a row lock. With 10,000 evenly spread test events the run would have passed.

Now you

You are the QA engineer for Sorrel, a fictional API that sends one-time passcodes by SMS for 400 customer apps. Normal traffic is 900 send requests a second at peak hour. Last month a large bank’s app came back from an outage and every user logged in again: send requests reached 5,400 a second within two minutes, and p99 on the send endpoint went from 180 ms to 4 seconds. The SLO is that 99% of send requests are accepted within 300 ms, and 95% of messages are handed to a carrier within 5 seconds. Carrier gateways cannot be load-tested, and every real SMS costs money. Staging has 50,000 phone numbers, all UK; production sends to 120 countries, and routing differs by country. The passcode check endpoint reads from a Redis store with a five-minute expiry. The product lead wants a plan in a week. Write the load test plan for a spike test and a stress test.

Self-check

DECIDE

You are the QA engineer at Sorrel, an SMS passcode API. A routing change ships on Thursday. The performance environment matches production's instance types, but its database holds 40,000 synthetic UK numbers; production holds 30 million numbers across 120 countries, and the change touches per-country routing. A stress test at 1.5 times the forecast peak passes cleanly. The engineering manager asks you to sign off. What do you do?

READING
  1. TALK
    How NOT to Measure Latency Gil Tene, 2016

    The talk that named coordinated omission and explains why most latency reports understate the tail. Watch it before you trust any load tool's percentiles, including your own.

  2. DOC
    Open and closed models Grafana k6

    The k6 explanation of open and closed executors, with examples. Read it to choose the executor deliberately rather than by default.

  3. DOC
    Constant arrival rate executor Grafana k6

    The options for an arrival-rate scenario, including preAllocatedVUs and maxVUs. Read with Little's law in hand to size them.

  4. DOC
    Thresholds Grafana k6

    How to turn an SLO into a pass or fail check, including tagged submetrics and aborting a run early when a threshold is crossed.

  5. PAPER
    Open Versus Closed: A Cautionary Tale Bianca Schroeder, Adam Wierman, Mor Harchol-Balter, 2006

    The research showing that open and closed models give different results for the same system, and that most benchmarks choose without noticing. Read: NSDI 2006.

  6. HANDBOOK
    Service Level Objectives Google SRE

    Chapter 4 of the SRE book: how SLIs and SLOs are chosen and measured. Your thresholds should come from documents written this way.

  7. PAPER
    The Tail at Scale Jeffrey Dean, Luiz André Barroso, 2013

    Why the slowest one per cent of requests dominates user experience in systems that fan out, and why p99 is the number your thresholds care about. Read: Communications of the ACM 56(2).

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Release management and sign-off →