Notes
First script
A k6 script imports the http module and helpers. The base URL comes from an environment variable, so the same script can target a laptop or staging. The default function is one iteration of one virtual user: here it gets the product list, checks the status, and sleeps one second as think time. Each virtual user repeats this function over and over until the test ends. Run it with k6 run script dot js.
import http from "k6/http";
import { check, sleep } from "k6";
const BASE = __ENV.BASE_URL ||
"http://localhost:8080";
export default function () {
const r = http.get(BASE+"/api/products");
check(r, { ok: (x) => x.status === 200 });
sleep(1); // think time
} Stages
Options control the load. Stages ramp the number of virtual users: one minute up to fifty, five minutes holding fifty, one minute back down to zero. Ramping up gradually lets you see where response times start to rise, and holding gives stable numbers to measure. A quick check with a fixed count also works, using vus and duration options instead.
export const options = {
stages: [
{ duration: "1m", target: 50 },
{ duration: "5m", target: 50 },
{ duration: "1m", target: 0 },
],
};
// 1 minute up to 50 VUs,
// 5 minutes at 50, 1 minute down Checks
Checks verify each answer. Here the search for mug must return status two hundred and a count of two, read from the JSON body. A failed check does not stop the test; k6 counts passes and failures and reports a percentage. The name tag groups all searches under one name in the results, which matters when URLs contain ids or query values.
const r = http.get(
`${BASE}/api/products?q=mug`,
{ tags: { name: "search" } });
check(r, {
"status 200": (x) => x.status === 200,
"two mugs": (x) =>
x.json("count") === 2,
});
// a failed check does NOT stop
// the test; it is counted Log in once
Setup runs once before the load starts, and whatever it returns is passed to every virtual user. Here it logs in to ShopRung with credentials from environment variables and returns the token, so the default function can send it as a bearer header. For carts, each virtual user should usually have its own account, otherwise they all edit one cart, the same shared state problem you saw with parallel tests.
export function setup() {
const r = http.post(
`${BASE}/api/auth/login`,
JSON.stringify({ email: __ENV.EMAIL,
password: __ENV.PASSWORD }),
{ headers: { "Content-Type":
"application/json" } });
return { token: r.json("token") };
}
export default function (data) { /* send
Authorization: Bearer data.token */ } Scenarios
Scenarios let one test run several traffic shapes. Executors decide how. Constant arrival rate starts a hundred iterations per second whatever the response time, which is closer to real traffic: users keep arriving even when the site is slow. Ramping arrival rate can model a sale spike. Pre-allocated virtual users is the pool k6 uses to keep up; if it runs out, k6 reports dropped iterations.
scenarios: {
browse: {
executor: "constant-arrival-rate",
rate: 100, timeUnit: "1s",
duration: "5m",
preAllocatedVUs: 50,
},
sale: {
executor: "ramping-arrival-rate",
startTime: "5m", ... },
} Thresholds
Thresholds turn goals into pass or fail. The ninety fifth percentile of all requests under five hundred milliseconds. Searches, selected by their tag, under three hundred. Failed requests under one percent, and more than ninety nine percent of checks passing. If any threshold is missed, k6 marks it in the summary and exits with a non zero code, so CI fails the job.
thresholds: {
http_req_duration: ["p(95)<500"],
"http_req_duration{name:search}":
["p(95)<300"],
http_req_failed: ["rate<0.01"],
checks: ["rate>0.99"],
},
// any threshold missed →
// k6 exits with a non-zero code Results and CI
Pass environment variables with dash e. At the end, k6 prints a summary: check results, request duration with average and percentiles, the failure rate, iterations, and a tick or cross for each threshold. Export it as JSON to keep with the CI run, or stream results to a time series database and Grafana for graphs. In CI, use Grafana's setup k6 action or the k6 Docker image.
k6 run -e BASE_URL=http://... \ -e EMAIL=... -e PASSWORD=... \ script.js summary: checks, http_req_duration (avg, p90, p95), http_req_failed, iterations, vus, ✓/✗ thresholds --summary-export=summary.json CI: grafana/setup-k6-action, or the grafana/k6 Docker image
Run for real
We ran a version of this script with k6 two point four on a Mac against ShopRung. Every threshold passed: all twenty three thousand checks, a ninety fifth percentile under one millisecond, and no failed requests. But k6 warned it ran out of virtual users and dropped three thousand and nine iterations. Each iteration sleeps one second, so fifty users can start only fifty per second, not the hundred asked. Raise max VUs, or drop the sleep with arrival rate executors.
✓ checks 100% (23,056 of 23,056) ✓ p(95)<500 p95 = 879 µs ✓ search p(95)<300 p95 = 551 µs ✓ http_req_failed 0 of 17,293 WARN Insufficient VUs, reached 50 active VUs dropped_iterations 3,009 50 VUs x 1 iteration/s (sleep 1) = 50/s, not the 100/s asked
Common mistakes
k6 mistakes. No thresholds, so the run is always green. No checks, so fast error pages look like success. No sleep with user based executors, which creates unrealistic load. Every virtual user on one account. Secrets written in the script instead of environment variables. And URLs containing ids without a name tag, which creates thousands of separate metrics nobody can read.
- no thresholds: always green
- no checks: fast errors look like success
- no sleep with VU executors
- every VU on one account
- secrets written in the script
- ids in URLs without a name tag (thousands of metrics)
Say it like this
In the interview: one JavaScript script per journey, with the base URL and secrets from environment variables and the login in setup. Checks verify status and body, and requests are tagged by name. Scenarios use arrival rate executors for steady and spike load. Thresholds on the ninety fifth percentile, error rate and checks make the CI job fail, and results are exported and compared with a baseline.
- "A JavaScript script per journey, base URL and secrets
- from env, login in setup, checks
- on status and body, tagged
- requests. Scenarios with arrival- rate executors for steady and spike load, thresholds on p95, error rate and checks, so the CI
- job fails, and results exported
- and compared with a baseline."