Performance and load tests as part of the suite
A test that fails when the service gets slow is a test with a budget: count the work, open the load, and set thresholds you can defend
Ojaline's checkout API takes 50 new orders a second in a test. Each order calls the payment provider, and the provider is slow: every charge takes 1 second, which is under the API's 2-second timeout, so nothing fails. The API serves plain endpoints from a pool of about 40 worker threads. /cart/price never calls the provider. What do you expect the load test to show?
A functional test asks whether the answer is right. A performance test asks how long it took, how much work it did, and what happened when many requests came at once. Those are three different questions, and a suite needs a different tool for each. This chapter teaches the testing side: what to put in the suite, what to run on a schedule, how to set a threshold, and how to read a breach. Load testing in depth, with capacity planning, soak tests and tools beyond one script, belongs to the Performance course (planned: Load testing with k6, Tail latency and Catching performance regressions in CI). Here you learn enough to put one honest load test next to your unit and integration tests, and to know when to distrust it.
Three questions, three tools
| Question | Tool | Runs | Deterministic? |
|---|---|---|---|
| Did this change make a request do more work? | A cost budget: count queries, connections, calls | Every commit, in the normal suite | Yes |
| Does the service still meet its latency and error targets at the expected load? | A load test with thresholds | On a schedule, or on a pull request in a short form | No: it measures a noisy system |
| Where is the limit, and what breaks first? | A stress run: raise the load until a threshold breaks | By hand, before a big event | No |
The first row is the one teams skip, and it is the cheapest. A request that opens 40 database connections instead of 20 is slower on every machine, and you can see that without a clock. The second row is the one teams build first, and it needs the most care, because a threshold on a measurement that wobbles produces the flaky-test problem all over again, at a cost of minutes per run. The third is a human activity. You do it, and you read the output.
The shape of a suite chapter argued that each tier has a cost and a purpose. Performance tests follow the same rule. Put the deterministic ones low and run them often. Put the noisy ones high and run them rarely, where a failure means something.
Count the work instead of timing it
The tempting first performance test is assert elapsed < 0.05. It fails on a busy runner, passes on a quiet one, and teaches the team to rerun. You learned the cause in flaky tests: the assertion is a guess about speed, and the machine’s speed is not yours to control.
Count the work instead. The checkout service prices a cart in quote_lines in checkout/orders.py, which looks up each product with db.get_product, and Database opens a short connection for every call. So pricing a cart opens one connection per line. That is today’s cost, and you can pin it:
@pytest.mark.parametrize("n_lines", [1, 5, 20])
def test_pricing_a_cart_opens_at_most_one_connection_per_line(db, payments, clock, connections, n_lines):
client = TestClient(create_app(db, payments, clock, SearchIndex()))
connections.clear()
lines = [{"product_id": 1 + i % 3, "qty": 1} for i in range(n_lines)]
resp = client.post("/cart/price", json={"lines": lines, "distance_km": 3})
assert resp.status_code == 200
assert len(connections) <= n_lines
The connections fixture wraps sqlite3.connect and records each call. It does not care how fast the machine is. If a developer adds a second look-up per line, a log line or a permission check, the count doubles and the test fails with 40 connections for 20 lines, on a laptop, in CI or on a train. This is a regression test for cost, and it has no flake rate.
There are limits. The budget says “no more than one per line”, which is the current cost and not the ideal one: a single query for all lines would be better, and the test would let you lower the budget to a constant when you make that change. It also measures only what you choose to count. Pick counts that track real cost: database round trips, outbound calls, bytes written, rows read. Elapsed time stays out of the commit-time suite.
Load is not many tests at once
A load test fires many requests and watches latency and errors. The decision that matters most is how it fires them.
A closed model has a fixed number of virtual users. Each sends a request, waits for the reply, thinks for a moment and sends the next. The arrival rate is decided by the service: when it slows, the users wait longer and send fewer requests. An open model starts requests on a schedule, 50 a second, whether or not earlier ones have finished. The arrival rate is decided by the world.
Real customers behave like the open model. A flash sale’s shoppers do not coordinate with your checkout service. They arrive at a rate set by an email campaign, and if you are slow, they pile up. Schroeder, Wierman and Harchol-Balter showed in 2006 that closed and open generators give very different results on the same system, and that designers rarely say which one they chose. The k6 documentation puts the consequence plainly: in a closed model, a slow target reduces the load, and that is what some of the literature calls coordinated omission.
Gil Tene named the effect for latency measurement. A tool that sends a request, waits for the reply and only then takes its next timestamp has left out the requests it should have sent during the stall. Suppose the service freezes for 5 seconds and the tool was meant to send 50 requests a second. A closed tool sends one request, waits 5 seconds, and records one slow sample. The 249 requests that should have waited behind it are never sent, never timed and never counted. Your p99 looks fine. The fix is to measure from when each request was due, and to use an open model so the due times do not move.
// wait for every shard
const parts = await Promise.all(shards.map((s) => s.query(q)));
// latency = the slowest of N callsasync function hedged(q, replicas, delayMs) {
let done = false;
const first = replicas[0].query(q).finally(() => { done = true; });
// send the backup only if the primary is still silent after delayMs
const backup = sleep(delayMs).then(() => (done ? first : replicas[1].query(q)));
return Promise.any([first, backup]); // first answer wins
}
const parts = await Promise.all(shards.map((s) => hedged(q, s.replicas, P95_MS))); Watch the p99 column in the simulation, not the mean. A p99 is the latency that 1 request in 100 is slower than, and under fan-out it becomes the typical experience. The tail latency lesson explains why a backend that is slow 1% of the time makes a page that calls 100 of them slow 63% of the time. For a load test, the point is the choice of statistic. Thresholds on averages hide the stall; thresholds on p95 or p99 catch it.
Thresholds: a pass or a fail you can defend
A load test without a verdict is a report, and reports are not read after the first week. A threshold turns a metric into a pass or fail. In k6 you write it next to the scenario:
thresholds: {
http_req_failed: ['rate<0.01'],
'http_req_duration{name:order}': ['p(95)<300'],
},
When any threshold is crossed, k6 ends the run with a failed status and exits non-zero (99 in the runs below), so a pipeline step fails without anyone reading a graph. A threshold can also stop a run early: { threshold: 'p(95)<300', abortOnFail: true, delayAbortEval: '10s' } aborts when the limit is crossed, after waiting 10 seconds for enough samples. Use it for stress runs where continuing to hammer a broken service is a waste. The {name:order} part is a tag: you give each request a name, and the threshold applies to that endpoint only. Without it, a fast endpoint’s samples dilute a slow one’s.
Where do the numbers come from? Not from a round figure. Take them from the target you have promised, the service-level objective, and add what the test environment costs you. The SLIs, SLOs and error budgets chapter covers how a target is chosen. Ojaline’s promise is p95 under 300 ms for orders; if the test runs on a smaller machine than production, the limit may be tighter or looser, and you have to measure which.
Three things make a threshold honest.
- A spread. Run the test ten times on the same commit and look at the p95 of each run. If they range from 9 ms to 14 ms, a limit of 300 ms is generous and will not flake; it is also too loose to catch a change from 10 ms to 100 ms. Choose a limit slightly above what you saw and review it when the machine changes.
- A fixed environment. A shared laptop that is also compiling is not a load-test machine. The lab runs everything on one machine, so its numbers say what the code does under this load on this machine, not what production would do. Use the same kind of runner every time or compare nothing.
- Enough samples. A p99 over 20 requests is the maximum. A p95 over 2,000 is stable enough to be worth a threshold. k6’s own testing guide warns that a quality gate can give false assurance when it is the only check: a pass says these thresholds held, on this scenario, and nothing more.
Reading a breach
A red threshold tells you something broke and not what. The skill is reading what broke first.
Start with the error rate. If http_req_failed is up, requests are failing outright, and the status codes say why: 502 means the provider call failed, 409 means stock ran out and the test data was too small. If errors are zero but latency is up, something is queueing. Look at which endpoints slowed. If only the endpoint that calls a dependency slowed, the dependency is the cause. If unrelated endpoints slowed too, a shared resource is saturated: a thread pool, a connection pool, a lock, the database file.
The checkout API is built so you can watch this. Its plain endpoints run on a pool of about 40 threads. An order that calls a provider taking 1 second holds a thread for that second, so the pool can finish about 40 such orders a second. Offer 50 and the queue grows without limit while the test runs. The timeouts lesson shows the general case.
// Every worker thread runs:
const token = await auth.verify(req); // no timeout
const row = await db.query(sql, params); // no timeout: hangs forever if db does
return render(row);// One deadline per request, shrinking per hop.
// The timeout must cancel the call (abort signal, driver statement timeout),
// not just stop waiting for it, or the connection stays held.
const deadline = Date.now() + 1000;
const left = () => deadline - Date.now();
const token = await auth.verify(req, { signal: AbortSignal.timeout(left()) });
if (left() <= 0) throw new DeadlineExceeded();
const row = await db.query(sql, params, { signal: AbortSignal.timeout(left()) });
return render(row); The simulation’s pool fills when the dependency hangs, and the healthy requests starve with it. A timeout is the cure, and it works by converting a slow failure into a fast one: a shorter client timeout releases threads sooner, and the problem moves from latency to errors. Neither is good; the second is easier to see and to alert on. That move is the last step of the lab.
Last, check the load generator. k6 reports dropped_iterations when it could not start an arrival on time because it ran out of virtual users, and a generator that is itself saturated measures itself. Run it on a different machine from the target when you can, and never read a result without checking that the tool delivered the rate you asked for.
Make the load honest
Before you trust a number, check that the load looks like the real thing. Four mistakes recur.
Reused keys. Every order needs an Idempotency-Key. Send the same key 4,000 times and the service replays the first order, a cheap read, and reports a wonderful latency for work it never did. The lab script builds a key from the virtual user, the iteration and the clock, so each order is new. The idempotency chapter explains what the replay does.
Stock that runs out. A test that sells the same 100 units of shea butter gets 409 out_of_stock after a few seconds, and from then on it measures how fast the service says no. The script’s setup() creates its own product with 10 million units. Decide whether you are testing the happy path or the sell-out, and set the data to match.
No warm-up. The first requests pay for connections, imports and cold caches. A 20-second run with no warm-up gives them a large share of the samples. For a longer run, start at a low rate and ramp, or throw away the first minute. For the lab, the maximum shows it: the slowest request in the clean 50-a-second run was 107 ms against a median of 4 ms.
The wrong arithmetic about capacity. There is a rule that helps you check the output. The number of requests in flight is the arrival rate times the time each takes (Little’s law). Fifty orders a second at 1 second each is 50 in flight, and a pool of 40 cannot hold them. You can predict the breach in step 5 before you run it, and a prediction that matches the run is a better sign that you understand the system than a green tick. When the run and the prediction disagree, find out why before you set a threshold.
Where each test runs
| Test | Where | Length | On failure |
|---|---|---|---|
| Cost budgets | Unit and integration job, every commit | Under a second | Blocks the merge |
| A smoke load test | Pull request or merge to main, on a runner of fixed size | 30 to 60 seconds at a modest rate with loose thresholds | Blocks the merge: it catches a service that is plainly broken |
| The flash-sale scenario | Nightly or before a release, against a staging environment | 10 to 20 minutes at the expected peak | Opens an issue with an owner; blocks the release |
| A stress run | By hand, before an event | Until something breaks | A report, and a decision |
A load test on every commit looks thorough and is not. It is slow, it needs a stable environment, and a noisy threshold on every pull request teaches people to ignore it. Keep the per-commit gate to the deterministic checks and a smoke run, and run the realistic load on a schedule. For slow drift, where every run passes and the p95 creeps from 10 ms to 25 ms over a month, a fixed threshold is the wrong tool; Daly and colleagues at MongoDB describe change-point detection on the series of results, and the Performance course returns to it.
What a load test here does not prove
The lab’s numbers are real and small. The database is one SQLite file with four products. The provider is a fake that answers instantly or sleeps. The generator shares the machine. So the test shows how this code behaves, not how Ojaline’s production behaves with its real catalogue, its network and its real provider’s long tail. It still earns its place, because it finds the class of problem that is in the code: a thread pool that fills, a query per line, a missing timeout. Say what the test covers when you report a pass, and never promise a capacity from it.
You add four files: a test, two k6 scripts and a small Python load tool. Numbers below were taken on a 12-core Mac that was busy with other work, on 2026-11-24, with the load generator on the same machine. Yours will differ. The shapes will not.
1. Start the two services. Check the ports, then start the provider and the API in two terminals, from labs/testing.
lsof -i :8094 -i :8095
export CHECKOUT_DB=/tmp/perf-lab.sqlite
.venv/bin/uvicorn fake_provider.app:app --port 8095In the second terminal (with the same CHECKOUT_DB):
export CHECKOUT_DB=/tmp/perf-lab.sqlite
.venv/bin/uvicorn checkout.api:app --port 8094Uvicorn running on http://127.0.0.1:<port>. Check with curl -s localhost:8094/products, which lists three published products. If a port is busy, stop what holds it before you go on; do not use the other labs’ ports.2. Add a cost budget to the suite. Create tests/integration/test_cost_budgets.py.
"""Cost budgets: count the work a request does instead of timing it."""
import sqlite3
import pytest
from fastapi.testclient import TestClient
from checkout.api import create_app
from checkout.search_index import SearchIndex
@pytest.fixture
def connections(monkeypatch):
"""A list that gains one item every time the code opens a database connection."""
opened = []
real_connect = sqlite3.connect
def counting_connect(*args, **kwargs):
opened.append(args)
return real_connect(*args, **kwargs)
monkeypatch.setattr(sqlite3, "connect", counting_connect)
return opened
@pytest.mark.parametrize("n_lines", [1, 5, 20])
def test_pricing_a_cart_opens_at_most_one_connection_per_line(db, payments, clock, connections, n_lines):
client = TestClient(create_app(db, payments, clock, SearchIndex()))
connections.clear() # forget what building the app cost
lines = [{"product_id": 1 + i % 3, "qty": 1} for i in range(n_lines)]
resp = client.post("/cart/price", json={"lines": lines, "distance_km": 3})
assert resp.status_code == 200
assert len(connections) <= n_lines, f"{len(connections)} connections for {n_lines} lines"Run it.
.venv/bin/pytest tests/integration/test_cost_budgets.py -q -p no:randomly3 passed in about 0.3 s. It never reads a clock. Now open checkout/orders.py, and in quote_lines add one line before product = db.get_product(item["product_id"]): a second call, db.get_product(item["product_id"]). Run the test again: it fails for every case, and the 20-line case says AssertionError: 40 connections for 20 lines. Take the extra line out again.3. Write the load test and run it at a modest rate. Create the folder perf and the file perf/checkout.js.
// k6 script: a flash sale against the checkout API.
import http from 'k6/http';
import { check } from 'k6';
const BASE = __ENV.BASE || 'http://127.0.0.1:8094';
const RATE = Number(__ENV.RATE || 50); // new orders started per second
const JSON_HEADERS = { 'Content-Type': 'application/json' };
export const options = {
scenarios: {
flash_sale: {
executor: 'constant-arrival-rate', // open model: arrivals do not wait for replies
rate: RATE,
timeUnit: '1s',
duration: __ENV.DURATION || '20s',
preAllocatedVUs: 50,
maxVUs: 400,
},
},
thresholds: {
http_req_failed: ['rate<0.01'],
'http_req_duration{name:price}': ['p(95)<300'],
'http_req_duration{name:order}': ['p(95)<300'],
},
};
export function setup() {
// A product with plenty of stock, so the test measures speed and not a sell-out.
const res = http.post(`${BASE}/products`, JSON.stringify({
seller_id: 'perf', name: `Load-test item ${Date.now()}`, price_kobo: 100000, stock: 10000000,
}), { headers: JSON_HEADERS });
return { productId: res.json('id') };
}
export default function (data) {
const cart = { lines: [{ product_id: data.productId, qty: 1 }], distance_km: 3 };
const quote = http.post(`${BASE}/cart/price`, JSON.stringify(cart),
{ headers: JSON_HEADERS, tags: { name: 'price' } });
check(quote, { 'priced': (r) => r.status === 200 });
const order = http.post(`${BASE}/orders`, JSON.stringify(cart), {
headers: { ...JSON_HEADERS, 'Idempotency-Key': `k6-${__VU}-${__ITER}-${Date.now()}` },
tags: { name: 'order' },
});
check(order, { 'order placed': (r) => r.status === 201 });
}k6 run --quiet perf/checkout.js; echo "exit: $?"{name:order} p(95)=12.42ms, {name:price} p(95)=3.15ms and http_req_failed rate=0.00%, then iterations: 1001 50.0/s, and exit: 0. The scenario is an open one: 50 iterations a second, each a price request and an order. The job created its own product with 10 million units, so stock cannot run out.4. Find where it breaks, and read the exit code. Raise the rate.
RATE=200 k6 run --quiet perf/checkout.js; echo "exit: $?"
RATE=400 k6 run --quiet perf/checkout.js; echo "exit: $?"{name:order} p95 120.56ms, {name:price} 37.93ms, exit: 0); the generator reports dropped_iterations of 18 of 4,000, because it started a few arrivals late. At 400 both latency thresholds fail (p95 1.34s for price, 1.46s for orders), http_req_failed still passes at 0.00%, only about 210 iterations a second complete (dropped_iterations is over 3,000 and vus_max reaches 400), and the exit code is 99. The limit on this machine is near 200 orders a second, and the first sign of it is latency, with no errors. A pipeline step that runs this command goes red on exit 99.5. Slow the provider and read what breaks first. Set the provider’s mode through its admin route, run at 50 a second, then clear it.
curl -s -X POST localhost:8095/_admin/mode -H 'Content-Type: application/json' -d '{"mode":"slow"}'
k6 run --quiet perf/checkout.js; echo "exit: $?"
curl -s -X POST localhost:8095/_admin/mode -H 'Content-Type: application/json' -d '{"mode":null}'{name:order} p95 2.55s and {name:price} p95 1.95s, with http_req_failed 0.00% and exit: 99. About 38 iterations a second finish. Orders were always going to be slow, because each waits a second for the provider. The price endpoint is the finding: it never calls the provider, and it slowed from 3 ms to nearly 2 s. All 40 worker threads were waiting on charges, so a price request waited for a thread. The error rate shows nothing wrong.6. Show coordinated omission. Create perf/stall.js. It runs 20 seconds, makes the provider slow from second 5 to second 10, and offers the same traffic either as 10 closed-loop users or as an open 50-a-second arrival rate.
import http from 'k6/http';
import { sleep } from 'k6';
import { Counter } from 'k6/metrics';
const slow = new Counter('orders_over_300ms');
const BASE = __ENV.BASE || 'http://127.0.0.1:8094';
const PROVIDER = __ENV.PROVIDER || 'http://127.0.0.1:8095';
const JSON_HEADERS = { 'Content-Type': 'application/json' };
const closed = (__ENV.MODEL || 'open') === 'closed';
export const options = {
scenarios: {
traffic: closed
? { executor: 'constant-vus', vus: 10, duration: '20s', exec: 'shopper' }
: { executor: 'constant-arrival-rate', rate: 50, timeUnit: '1s', duration: '20s',
preAllocatedVUs: 100, maxVUs: 400, exec: 'shopper' },
stall: { executor: 'per-vu-iterations', vus: 1, iterations: 1, startTime: '5s', exec: 'stall' },
},
thresholds: { 'http_req_duration{name:order}': ['max>=0'] }, // always true; it makes k6 print this metric
summaryTrendStats: ['med', 'p(95)', 'p(99)', 'max'],
};
export function setup() {
const res = http.post(`${BASE}/products`, JSON.stringify({
seller_id: 'perf', name: `Stall item ${Date.now()}`, price_kobo: 100000, stock: 10000000,
}), { headers: JSON_HEADERS });
return { productId: res.json('id') };
}
export function shopper(data) {
const cart = { lines: [{ product_id: data.productId, qty: 1 }], distance_km: 3 };
const res = http.post(`${BASE}/orders`, JSON.stringify(cart), {
headers: { ...JSON_HEADERS, 'Idempotency-Key': `st-${__VU}-${__ITER}-${Date.now()}` },
tags: { name: 'order' },
});
if (res.timings.duration > 300) slow.add(1);
if (closed) sleep(0.18); // think time, so 10 VUs offer about 50 orders a second
}
export function stall() {
http.post(`${PROVIDER}/_admin/mode`, JSON.stringify({ mode: 'slow' }), { headers: JSON_HEADERS });
sleep(5);
http.post(`${PROVIDER}/_admin/mode`, JSON.stringify({ mode: null }), { headers: JSON_HEADERS });
}MODEL=closed k6 run --quiet perf/stall.js
MODEL=open k6 run --quiet perf/stall.js{ name:order } med=8.99ms p(95)=1.01s p(99)=1.01s max=1.03s and orders_over_300ms about 50 to 90. Open: med=2.08s p(95)=3.56s p(99)=3.72s max=3.85s and orders_over_300ms about 700. The two runs ran the same code against the same stall. In the closed run the 10 users each waited a second and sent nothing, so only the few requests in flight were slow, and the median stayed at 9 ms. In the open run the arrivals kept coming at 50 a second into a pool that finished 40, and a queue formed. The open numbers vary a lot on a busy machine (p95 from 1.7 s to 4.2 s over five runs), the closed numbers do not, and the open ones were always far worse. The closed test could not see the queue because it never made one.7. The same thing without k6. Create perf/load.py, an open-model tool that records latency from when a request was sent and from when it was due.
"""A small open-model load test with httpx. No k6 needed."""
import argparse
import os
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
import httpx
API = os.environ.get("BASE", "http://127.0.0.1:8094")
PROVIDER = os.environ.get("PROVIDER", "http://127.0.0.1:8095")
def pct(values, q):
values = sorted(values)
return values[min(len(values) - 1, int(q * len(values)))]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--rate", type=float, default=50)
ap.add_argument("--seconds", type=float, default=20)
ap.add_argument("--workers", type=int, default=200)
ap.add_argument("--stall", action="store_true", help="provider slow from second 5 to second 10")
args = ap.parse_args()
client = httpx.Client(timeout=30, limits=httpx.Limits(max_connections=args.workers))
product = client.post(f"{API}/products", json={"seller_id": "perf", "name": "Load item",
"price_kobo": 100000, "stock": 10000000}).json()["id"]
cart = {"lines": [{"product_id": product, "qty": 1}], "distance_km": 3}
results = []
def one(due):
sent = time.perf_counter()
r = client.post(f"{API}/orders", json=cart, headers={"Idempotency-Key": str(uuid.uuid4())})
done = time.perf_counter()
results.append((done - sent, done - due, r.status_code))
def stall():
time.sleep(5)
client.post(f"{PROVIDER}/_admin/mode", json={"mode": "slow"})
time.sleep(5)
client.post(f"{PROVIDER}/_admin/mode", json={"mode": None})
if args.stall:
threading.Thread(target=stall, daemon=True).start()
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=args.workers) as pool:
for i in range(int(args.rate * args.seconds)):
due = start + i / args.rate
time.sleep(max(0.0, due - time.perf_counter()))
pool.submit(one, due)
sent, due, codes = zip(*results)
print(f"orders {len(results)} errors {sum(c != 201 for c in codes)}")
for name, values in (("from sent", sent), ("from due ", due)):
print(f"{name} p50 {pct(values, .5)*1000:7.0f} ms p95 {pct(values, .95)*1000:7.0f} ms max {max(values)*1000:7.0f} ms")
main().venv/bin/python perf/load.py --rate 50 --seconds 20 --workers 200 --stall
.venv/bin/python perf/load.py --rate 50 --seconds 20 --workers 20 --stallfrom sent p50 14 ms p95 1663 ms max 1981 ms and from due p50 17 ms p95 1666 ms max 1981 ms. With 20 workers, the tool itself becomes the queue: from sent p50 10 ms p95 1014 ms max 1140 ms and from due p50 16 ms p95 2859 ms max 3719 ms. The first line is what a naive tool reports, a p95 of about one second, because it starts the clock when a worker picks the request up. The second is what a customer who arrived on time experienced. The difference, 1.8 seconds at p95, is coordinated omission, in about fifty lines of Python.8. Stop the services. Press Ctrl-C in both terminals. Clear the mode if a run was interrupted: curl -s -X POST localhost:8095/_admin/mode -H 'Content-Type: application/json' -d '{"mode":null}'. Delete /tmp/perf-lab.sqlite. Then put the lab back, because later chapters count tests from the starter state: git checkout checkout/orders.py (in case the extra line from step 2 is still in), then rm -rf perf tests/integration/test_cost_budgets.py.
lsof -i :8094 -i :8095
.venv/bin/pytest -qlsof prints nothing, and pytest shows 23 passed, 1 skipped, 1 deselected, the starter state.CHECKOUT_PROVIDER_TIMEOUT_S=0.5 .venv/bin/uvicorn checkout.api:app –port 8094, set the provider to slow and rerun k6 run –quiet perf/checkout.js at 50 a second. The provider answers in 1 second, so every charge now times out at 0.5 s and every order returns 502. Checked on 2026-11-24: http_req_failed failed at 49.97% (every order, none of the price requests), the order p95 was 509 ms, the price p95 was 3.13 ms and the exit code 99. The problem moved from latency to errors. The price endpoint is fast again because each stuck order frees its thread after half a second, so 50 a second needs about 25 threads and the pool has 40. The test did not get better and the service did not get better, but the failure is now one you can alert on, and the customer sees a clear error and not a spinner. Whether that is the right trade is a product decision. Put the timeout back to its default afterwards.Six weeks before the flash sale, Refilwe wants a performance gate in the checkout pipeline. Kabelo has a k6 script that passes at 50 orders a second on his laptop. The shared CI runners are busy and vary by a factor of two in speed from one run to the next. The sale expects about 200 orders a second at peak. Which gate does the team build first?
- DOC Automated performance testing Grafana k6 documentation
A practical guide to choosing which performance tests to automate, how often to run them in each environment, and how to plan result analysis. Read the sections on choosing tests and on testing frequency; its warning that quality gates in CI can give false assurance is worth keeping. Read in November 2026; the page changes with k6 releases.
- DOC Thresholds Grafana k6 documentation
The reference for the pass-or-fail rules in this chapter's scripts: the metric syntax, tags to scope a threshold to one endpoint, the non-zero exit code on failure, and abortOnFail with delayAbortEval. Read the syntax and the abort sections; skip the long list of metric types on a first read.
- DOC Open and closed models Grafana k6 documentation
A short page on the two ways to generate load and which k6 executors use which. It names coordinated omission as the closed-model risk. Read all of it; it takes five minutes and decides which executor you use.
- TALK How NOT to Measure Latency Gil Tene
The talk that named coordinated omission and showed how most latency charts understate the tail. Watch the parts on percentiles and on the measuring-from-the-wrong-clock problem; the middle is long, and you can skip a section if you already read the k6 page above.
- PAPER Open Versus Closed: A Cautionary Tale Bianca Schroeder, Adam Wierman and Mor Harchol-Balter, 2006
The research behind the open-versus-closed choice: the same system behaves very differently under the two generators, and designers rarely say which they used. Read the abstract and the principles; skip the scheduling-policy simulations unless you design schedulers. Read: the abstract, the introduction and the list of eight principles.
- PAPER Change Point Detection in Software Performance Testing Daly, Brown, Ingo, O'Leary and Bradford, 2020
How a team replaced hand-reviewed graphs and fixed alert thresholds with change-point detection across commits, for noisy performance results. Read it for the problem with fixed thresholds on a series; skip the algorithm's mathematics on a first pass. Read: the abstract, the introduction and the section describing the system in use.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.