Part 01 · Thinking About Scale
Load Testing with k6
Write a k6 script for the shop, ramp up traffic, and find the point where p95 shoots up and errors start.
⏱ 9 min · Station 4 of 93
The problem
"The shop handles 500 requests per second" is a claim. Before the Eid sale someone will ask how you know, and "we clicked around and it felt fast" isn't an answer. You need a test that sends a known amount of traffic, records what happened to every request, and can be run again after every change so the numbers are comparable.
We've been running ./k6.sh product.js for two lessons. Today we look at how a k6 script is put together, the one choice that decides whether a load test tells the truth, and how to find the breaking point in a single run.
The idea
A load test sends traffic to a system on purpose and measures latency, throughput and errors. k6 runs a JavaScript function over and over, from many virtual users (VUs) at once, and records every HTTP request it makes.
The important choice is how the load is made:
- Closed model (fixed users). A fixed number of VUs each send a request, wait for the answer, and send the next one. If the server slows down, the VUs send less. This is k6's
constant-vus. - Open model (fixed arrival rate). k6 starts new requests on a schedule, say 600 per second, whether or not earlier ones have finished. If the server slows down, requests pile up, just like real users who keep arriving. This is
constant-arrival-rateandramping-arrival-rate.
Real shoppers behave like the open model: a slow server doesn't stop new people from opening the page. So for capacity questions, use an arrival-rate executor.
How it works
A k6 script has four parts:
options: what load to make. A scenario picks an executor (constant-arrival-rate,ramping-arrival-rate,constant-vus...) and its settings: the rate, how long, and how many VUs k6 may use to keep that rate.- The default function: what one iteration does. Ours fetches one random product page.
check: assertions on each response, like "status is 200". A failed check doesn't stop the test; it's counted.thresholds: pass/fail rules on the results, like "p95 under 50 ms". If one is crossed, k6 exits with code 99, so a CI job or a script can fail on it.
When k6 runs an arrival-rate scenario:
- every second it starts the requested number of iterations, each on a free VU;
- if all VUs are busy waiting on slow responses, it starts new ones, up to
maxVUs; - when it can't start an iteration on time, it counts a dropped iteration. Drops mean the target rate was not delivered, and the latency you see is an underestimate.
For finding a breaking point, ramping-arrival-rate raises the rate in steps within one run. We tag each request with its step, so the summary can show each step separately.
You test with 8 fixed users (constant-vus). During the test the database gets 10 times slower. What does the k6 summary show?
Visual
Common misconception
"A load test with 100 users means 100 requests per second." With fixed users, the rate depends on the server: 100 users and 10 ms responses is up to 10,000 per second; the same 100 users and 1-second responses is 100 per second. Always read the achieved rate (got/s), and test capacity with an arrival rate you choose.
"No errors in the test, so the system is fine." Our overloaded runs had 0% errors and p95 near one second. Latency and dropped iterations show overload long before errors do.
Try it
Measured on the lab (Intel i3-10110U, 4 threads, 7 GB RAM; PostgreSQL and the shop each pinned to one CPU thread; k6 on the other two).
k6/steps.js holds each rate for 20 seconds, from 200 up to 700 requests per second, tags every request with its step, and prints one row per step:
// Find the breaking point in one run: hold each rate in LEVELS for STEP seconds, and report
// throughput and latency per step.
import http from "k6/http";
import { check } from "k6";
import exec from "k6/execution";
const TARGET = __ENV.TARGET || "http://api:8080";
const LEVELS = (__ENV.LEVELS || "200 300 400 500 600 700").split(" ").map(Number);
const STEP = Number(__ENV.STEP || 20);
const stages = [];
for (const l of LEVELS) stages.push({ target: l, duration: "1s" }, { target: l, duration: `${STEP - 1}s` });
const thresholds = {};
LEVELS.forEach((_, i) => {
// k6 only keeps per-tag numbers for metrics named in thresholds; these always pass.
thresholds[`http_req_duration{step:${i}}`] = ["p(95)>=0"];
thresholds[`http_reqs{step:${i}}`] = ["count>=0"];
thresholds[`http_req_failed{step:${i}}`] = ["rate>=0"];
});
export const options = {
scenarios: {
ramp: {
executor: "ramping-arrival-rate",
startRate: LEVELS[0],
timeUnit: "1s",
preAllocatedVUs: 100,
maxVUs: 500,
stages,
},
},
thresholds,
};
export default function () {
const step = Math.min(Math.floor(exec.instance.currentTestRunDuration / 1000 / STEP), LEVELS.length - 1);
const id = 1 + Math.floor(Math.random() * 20000);
const res = http.get(`${TARGET}/products/${id}`, { tags: { step: String(step) }, timeout: "10s" });
check(res, { "status is 200": (r) => r.status === 200 });
}
export function handleSummary(data) {
const m = data.metrics;
const ms = (v) => (v < 10 ? v.toFixed(1) : Math.round(v)) + " ms";
const rows = [" step asked got/s p50 p95 failed"];
LEVELS.forEach((l, i) => {
const d = m[`http_req_duration{step:${i}}`].values;
const n = m[`http_reqs{step:${i}}`].values.count;
const f = m[`http_req_failed{step:${i}}`].values.rate;
rows.push(
`${String(i + 1).padStart(5)}${String(l).padStart(7)}${(n / STEP).toFixed(0).padStart(7)}${ms(d.med).padStart(9)}${ms(d["p(95)"]).padStart(9)}${((f * 100).toFixed(1) + "%").padStart(9)}`,
);
});
const c = m.checks.values;
rows.push(`checks: ${c.passes} passed, ${c.fails} failed dropped: ${m.dropped_iterations ? m.dropped_iterations.values.count : 0}`);
return { stdout: rows.join("\n") + "\n" };
}
Three details in it:
ramping-arrival-ratewith paired stages: a 1-second ramp to each level, then 19 seconds holding it. Without the hold, the rate would climb continuously and no step would be a clean measurement.- The dummy thresholds (
p(95)>=0) never fail. k6 only keeps per-tag numbers for metrics that appear in thresholds, so this is how you get a row per step. checkcounts responses that weren't 200.
step asked got/s p50 p95 failed
1 200 200 2.2 ms 5.8 ms 0.0%
2 300 297 1.7 ms 3.8 ms 0.0%
3 400 398 1.7 ms 5.1 ms 0.0%
4 500 498 1.7 ms 33 ms 0.0%
5 600 598 66 ms 147 ms 0.0%
6 700 600 830 ms 921 ms 0.0%
checks: 51808 passed, 0 failed dropped: 1940
Reading it:
- Steps 1 to 3 (200 to 400 per second): p95 under 6 ms. Plenty of room.
- Step 4 (500): p95 33 ms. Everything got through, but requests are starting to wait.
- Step 5 (600): p95 147 ms, p50 66 ms. Close to the limit, and the queue from this step spills into the next.
- Step 6 (700): only 600 got through per second, p95 921 ms, and 1,940 iterations were dropped. Past capacity.
- All 51,808 checks passed. Not a single error, at a point where users would already be leaving. That's why latency and drops, not errors, are the first signs of overload.
One run, two minutes, and it agrees with the two lessons before: this shop's single server tops out a little under 600 requests per second.
Trade-offs
- Don't load test from the same machine you're testing if you can avoid it. Here k6 has its own CPU threads, so it doesn't steal from the shop. On a shared machine, the load generator becomes part of the bottleneck.
- Warm up first. The first minute after a start includes cold caches and connection setup. We always run 20 to 30 seconds of traffic before measuring.
- Short steps are cheap but noisy. 20 seconds per step is fine for finding the cliff; a real pre-sale test holds the peak rate for many minutes (soak tests are in the Reliability course).
- One URL is not your traffic. Random product pages are a reasonable start for this course. A real test mixes browsing, search, cart and checkout in realistic proportions.
Key takeaway
A useful load test chooses the arrival rate (open model), checks responses, and reports latency percentiles, achieved rate and drops per step. Fixed-user tests slow down with the server and hide overload. Thresholds turn the result into pass or fail, so the same test can guard every change.
Practice
Objective: make a load test fail on its own when latency is too high.
Challenge: product.js accepts -e P95=50, which adds a threshold "p95 must be under 50 ms". Predict which of 500 and 650 requests per second passes, then run both and look at k6's exit code.
Expected result: one run exits with 0, the other with 99 and a message that the threshold was crossed.
Hint 1
Look at the step test: where was p95 below 50 ms?
Hint 2
k6 exits with 99 when a threshold is crossed. In a shell, echo $? right after the command prints the exit code (pipe through grep and you get grep's code instead).
Hint 3
Thresholds are evaluated at the end of the run on the whole run's numbers, not per second.
Solution
$ ./k6.sh product.js -e RATE=500 -e DURATION=20s -e P95=50
requests 10000 (500.0/s)
failed 0.00%
latency avg 5.8 ms p50 1.7 ms p95 28 ms p99 70 ms max 98 ms
vus max 50
exit code: 0
$ ./k6.sh product.js -e RATE=650 -e DURATION=20s -e P95=50
requests 12165 (586.8/s)
failed 0.00%
latency avg 547 ms p50 534 ms p95 862 ms p99 889 ms max 921 ms
dropped 836 (k6 could not start them in time)
vus max 500
level=error msg="thresholds on metrics 'http_req_duration' have been crossed"
exit code: 99
At 500 per second p95 was 28 ms and k6 exited with 0. At 650, the shop completed only 587 per second, p95 was 862 ms, and k6 printed that the threshold was crossed and exited with 99. Put a run like the first one in your deploy pipeline and a change that makes product pages slower fails the build before users see it.
Interview check
Q: A teammate's load test with 200 virtual users shows p95 at 120 ms and 0 errors, and they conclude the service can take Black Friday traffic. What would you ask?
Model answer
What rate did it actually achieve, and was it fixed users or a fixed arrival rate? 200 fixed users at 120 ms is only about 1,600 requests per second and slows down with the server, so it can't show overload. I'd ask for the expected peak rate, then run an arrival-rate test at and above that rate, with a warm-up, realistic request mix, enough duration, and look at p95/p99, achieved rate and dropped iterations, not just errors.
Q: What does it mean when k6 reports dropped iterations?
Model answer
k6 couldn't start iterations on schedule because all its allowed virtual users were busy waiting for responses. The target rate was not delivered, so the system was past capacity (or maxVUs was too low for the latency). The latency numbers under-report the problem, because the requests that would have waited longest were never sent.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →