QA and Test Automation · Lab 26 of 35

k6 Load Test With Scenarios and Thresholds: ShopRung Lab

Write a k6 load test for ShopRung step by step: checks on every response, a steady arrival rate of browsers, buyers who sign up once and place orders, thresholds that pass or fail the run, and the slow-search bug caught by a p95 goal and by dropped iterations. Plus a nightly CI job.

⏱ 60 minIntermediate💸 Free6 steps

k6 2.4JavaScriptGitHub ActionsShopRung

Overview video

1 / 6

0 of 6 steps done

What you will build

One k6 script, script.js, that puts realistic load on ShopRung and decides by itself whether the result is good enough:

  • browsers: 20 new browsing journeys every second for a minute (product list, a search with a check that it finds the two mugs, one product), with an arrival-rate executor.
  • buyers: up to 10 virtual users who each sign up once, then add a sticker pack and place an order every 1 to 3 seconds.
  • Thresholds: no failed requests, checks above 99%, search p95 under 300 ms, order p95 under 800 ms, fewer than 20 dropped iterations.
  • Real runs: all thresholds green on a normal shop; with slow-search on, two thresholds red and exit code 99. Plus a nightly GitHub Actions job.

Before you start

Setup

S1Install k6

k6 is one program, not a Node package. Install it and check the version.

Run
brew install k6
k6 version
You should seeyour text will differ: the model writes it
k6 v2.4.0 ...

S2Start ShopRung and make a folder

Start ShopRung as in lab 1 with npm start. Make a folder shoprung-load for the script. Run load tests only against your own copy of ShopRung, never against a site you do not own.

Run
curl http://localhost:8080/api/health
mkdir shoprung-load && cd shoprung-load
You should see
{"status":"UP","app":"ShopRung","version":"1.0.0"}
1

One journey with checks

A script that browses ShopRung once and checks every answer.

Create script.js. setup() runs once before the load: it fails fast with a clear message if ShopRung is not running, then resets the shop to its seed data so every run starts the same.

The default function is one iteration of one virtual user: the product list, a search for "mug" and one product page. Each request has a name tag, so results group by journey step, and checks verify the answer, not only the status: the search must find exactly 2 mugs. Run it with one user for three iterations.

script.js
// ShopRung load test, step 1: one browsing journey with checks.
// Run: k6 run --vus 1 --iterations 3 script.js
import http from "k6/http";
import { check } from "k6";

const BASE = __ENV.BASE_URL || "http://localhost:8080";

// Runs once, before any virtual user starts.
export function setup() {
  const health = http.get(`${BASE}/api/health`);
  if (health.status !== 200) {
    throw new Error(`ShopRung is not running at ${BASE}`);
  }
  http.post(`${BASE}/api/test/reset`);
}

export default function () {
  const list = http.get(`${BASE}/api/products`, { tags: { name: "products" } });
  check(list, { "products 200": (r) => r.status === 200 });

  const search = http.get(`${BASE}/api/products?q=mug`, { tags: { name: "search" } });
  check(search, {
    "search 200": (r) => r.status === 200,
    "two mugs": (r) => r.json("count") === 2,
  });

  const one = http.get(`${BASE}/api/products/4`, { tags: { name: "product" } });
  check(one, { "product 200": (r) => r.status === 200 });
}
  1. Pass -e BASE_URL=... to test another copy of ShopRung.line 6
  2. Runs once, before any virtual user starts.line 9
  3. Groups these requests under "search" in the results and thresholds.line 21
  4. A failed check is counted, not fatal. A fast wrong answer is not a success.line 24
Run
k6 run --vus 1 --iterations 3 script.js
You should seeyour text will differ: the model writes it
  █ TOTAL RESULTS
    checks_succeeded...: 100.00% 12 out of 12
    ✓ products 200
    ✓ search 200
    ✓ two mugs
    ✓ product 200
...
default ✓ [ 100% ] 1 VUs  ... 3/3 shared iters
2

A steady arrival rate and thresholds

20 journeys per second for a minute, and goals that decide pass or fail.

Rename the default function to browse and add options. The browsers scenario uses the constant-arrival-rate executor: it starts 20 new iterations every second, whatever the response times, like real visitors who keep arriving when the site is slow. k6 starts with 10 virtual users and may use up to 50 to keep that rate.

Thresholds are the goals: fewer than 1% failed requests, more than 99% of checks passing, search p95 under 300 ms, and fewer than 20 dropped iterations (iterations k6 wanted to start but had no free virtual user for). If any threshold fails, k6 exits with code 99.

script.js 22 new or changed lines
// ShopRung load test: browsing traffic at a steady arrival rate.
// Run: k6 run -e BASE_URL=http://localhost:8080 script.js
import http from "k6/http";
import { check } from "k6";

const BASE = __ENV.BASE_URL || "http://localhost:8080";

export const options = {
  scenarios: {
    browsers: {
      executor: "constant-arrival-rate",
      exec: "browse",
      rate: 20,               // 20 new browsing iterations every second...
      timeUnit: "1s",
      duration: "1m",
      preAllocatedVUs: 10,    // ...with up to 50 virtual users to keep up
      maxVUs: 50,
    },
  },
  thresholds: {
    http_req_failed: ["rate<0.01"],
    checks: ["rate>0.99"],
    "http_req_duration{name:search}": ["p(95)<300"],
    dropped_iterations: ["count<20"],
  },
};

// Runs once, before any virtual user starts.
export function setup() {
  const health = http.get(`${BASE}/api/health`);
  if (health.status !== 200) {
    throw new Error(`ShopRung is not running at ${BASE}`);
  }
  http.post(`${BASE}/api/test/reset`);
}

export function browse() {
  const list = http.get(`${BASE}/api/products`, { tags: { name: "products" } });
  check(list, { "products 200": (r) => r.status === 200 });

  const search = http.get(`${BASE}/api/products?q=mug`, { tags: { name: "search" } });
  check(search, {
    "search 200": (r) => r.status === 200,
    "two mugs": (r) => r.json("count") === 2,
  });

  const one = http.get(`${BASE}/api/products/4`, { tags: { name: "product" } });
  check(one, { "product 200": (r) => r.status === 200 });
}
  1. An open model: arrivals do not slow down when the shop does.line 11
  2. The function this scenario runs.line 12
  3. The most virtual users k6 may use to keep the rate. Little's law: rate x seconds per iteration.line 17
  4. A goal for one tagged request only.line 23
  5. Catches the case where k6 could not keep the rate: a sign the system slowed down.line 24
Run
k6 run script.js
You should seeyour text will differ: the model writes it
    http_req_duration{name:search}
    ✓ 'p(95)<300' ...
    dropped_iterations
    ✓ 'count<20' count=0
...
browsers ✓ [ 100% ] 00/10 VUs  1m0s  20.00 iters/s
3

Buyers who sign up once

A second scenario with its own users, carts and orders.

Add the buyers scenario: a ramping-vus executor that grows to 10 virtual users over 20 seconds, holds for 30 and ramps down. Each buyer adds a sticker pack (they have the most stock, 200 and 150) and places an order, then thinks for 1 to 3 seconds.

Buyers need accounts. let token at the top level of the script exists once per virtual user, so signUpOnce signs each buyer up on its first iteration and reuses the token after that. Every buyer has its own cart: no two virtual users fight over one. Add a threshold for place order too, then run the whole test.

script.js 36 new or changed lines
// ShopRung load test: browsing traffic at a steady arrival rate, plus buyers who sign up once and place orders.
// Run: k6 run -e BASE_URL=http://localhost:8080 script.js
import http from "k6/http";
import { check, sleep } from "k6";

const BASE = __ENV.BASE_URL || "http://localhost:8080";
const JSON_HEADERS = { "Content-Type": "application/json" };

export const options = {
  scenarios: {
    browsers: {
      executor: "constant-arrival-rate",
      exec: "browse",
      rate: 20,               // 20 new browsing iterations every second...
      timeUnit: "1s",
      duration: "1m",
      preAllocatedVUs: 10,    // ...with up to 50 virtual users to keep up
      maxVUs: 50,
    },
    buyers: {
      executor: "ramping-vus",
      exec: "buy",
      startVUs: 0,
      stages: [
        { duration: "20s", target: 10 },
        { duration: "30s", target: 10 },
        { duration: "10s", target: 0 },
      ],
    },
  },
  thresholds: {
    http_req_failed: ["rate<0.01"],
    checks: ["rate>0.99"],
    "http_req_duration{name:search}": ["p(95)<300"],
    "http_req_duration{name:place order}": ["p(95)<800"],
    dropped_iterations: ["count<20"],
  },
};

// Runs once, before any virtual user starts.
export function setup() {
  const health = http.get(`${BASE}/api/health`);
  if (health.status !== 200) {
    throw new Error(`ShopRung is not running at ${BASE}`);
  }
  http.post(`${BASE}/api/test/reset`);
}

export function browse() {
  const list = http.get(`${BASE}/api/products`, { tags: { name: "products" } });
  check(list, { "products 200": (r) => r.status === 200 });

  const search = http.get(`${BASE}/api/products?q=mug`, { tags: { name: "search" } });
  check(search, {
    "search 200": (r) => r.status === 200,
    "two mugs": (r) => r.json("count") === 2,
  });

  const one = http.get(`${BASE}/api/products/4`, { tags: { name: "product" } });
  check(one, { "product 200": (r) => r.status === 200 });
}

// Each virtual user has its own copy of this variable, so each buyer signs up once and keeps its own cart.
let token;

function signUpOnce() {
  if (!token) {
    const email = `k6-${__VU}-${Date.now()}@shoprung.test`;
    const r = http.post(`${BASE}/api/auth/signup`,
      JSON.stringify({ name: `k6 buyer ${__VU}`, email, password: "Load1234!" }),
      { headers: JSON_HEADERS, tags: { name: "signup" } });
    check(r, { "signed up": (x) => x.status === 201 });
    token = r.json("token");
  }
  return { ...JSON_HEADERS, Authorization: `Bearer ${token}` };
}

export function buy() {
  const headers = signUpOnce();
  // the two sticker packs have the most stock (200 and 150): alternate between them
  const productId = __ITER % 2 === 0 ? 11 : 12;

  const add = http.post(`${BASE}/api/cart/items`, JSON.stringify({ productId, quantity: 1 }),
    { headers, tags: { name: "add to cart" } });
  check(add, { "added": (r) => r.status === 200 });

  const order = http.post(`${BASE}/api/orders`, null, { headers, tags: { name: "place order" } });
  check(order, {
    "order 201": (r) => r.status === 201,
    "order PLACED": (r) => r.json("status") === "PLACED",
  });

  sleep(1 + Math.random() * 2); // think time: 1 to 3 seconds
}
  1. A closed model: 10 users, each waiting for its answer before the next step.line 21
  2. One copy per virtual user: sign up once, reuse after.line 64
  3. __VU is the virtual user's number; the time keeps emails unique across runs.line 68
  4. Alternate the two sticker packs so stock never runs out during the test.line 81
  5. Think time between orders, as a real buyer would have.line 93
Run
k6 run script.js
echo "exit code: $?"
You should seeyour text will differ: the model writes it
  █ THRESHOLDS

    checks
    ✓ 'rate>0.99' rate=100.00%

    dropped_iterations
    ✓ 'count<20' count=0

    http_req_duration{name:place order}
    ✓ 'p(95)<800' p(95)=2.12ms

    http_req_duration{name:search}
    ✓ 'p(95)<300' p(95)=604µs

    http_req_failed
    ✓ 'rate<0.01' rate=0.00%

  █ TOTAL RESULTS
    checks_succeeded...: 100.00% 5510 out of 5510
    ✓ products 200  ✓ search 200  ✓ two mugs  ✓ product 200
    ✓ signed up  ✓ added  ✓ order 201  ✓ order PLACED
    http_reqs......................: 4079   66.485315/s
    dropped_iterations.............: 0      0/s

running (1m01.4s), 00/20 VUs, 1433 complete and 0 interrupted iterations
browsers ✓ [ 100% ] 00/10 VUs  1m0s  20.00 iters/s
buyers   ✓ [ 100% ] 00/10 VUs  1m0s
exit code: 0
4

Catch a slow search

Turn on ShopRung's slow-search bug and watch two thresholds fail.

Run the test again with the slow-search bug on. No request fails and every check passes, because a slow search still finds two mugs. Yet two thresholds go red: search p95 is 2.5 s, and k6 dropped 58 iterations.

Why dropped? Little's law: 20 arrivals per second x 2.5 seconds per browsing iteration = 50 virtual users busy at once, exactly the maxVUs limit. With all 50 waiting on slow searches, k6 could not start new iterations on time. On the normal shop, 10 users were enough. k6 exits with 99, so a CI job fails.

Run
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["slow-search"]}'
k6 run script.js
echo "exit code: $?"
You should seeyour text will differ: the model writes it
  █ THRESHOLDS

    checks
    ✓ 'rate>0.99' rate=100.00%

    dropped_iterations
    ✗ 'count<20' count=58

    http_req_duration{name:place order}
    ✓ 'p(95)<800' p(95)=1.95ms

    http_req_duration{name:search}
    ✗ 'p(95)<300' p(95)=2.5s

    http_req_failed
    ✓ 'rate<0.01' rate=0.00%
...
running (1m02.5s), 00/60 VUs, 1376 complete and 0 interrupted iterations
browsers ✓ [ 100% ] 00/50 VUs  1m0s  20.00 iters/s
buyers   ✓ [ 100% ] 00/10 VUs  1m0s
level=error msg="thresholds on metrics 'dropped_iterations, http_req_duration{name:search}' have been crossed"
exit code: 99
5

Read the summary like a tester

What each number means, and what to report.

Thresholds first: the pass or fail answer. Then checks: were the answers right? Then http_req_duration per tag: the median and p95 tell you what most users and the slow tail felt. http_reqs is throughput. dropped_iterations with an arrival-rate executor means the system could not keep up with the arrivals you asked for, even when every request succeeded.

A good report states the load (20 browsing journeys per second plus 10 buyers for 1 minute), the goals, the result per goal, and the evidence: on the normal shop, search p95 was 604 µs and order p95 2.12 ms with 0 dropped iterations; with slow-search, search p95 was 2.5 s and 58 iterations were dropped. Turn the bug off afterwards.

Run
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'
You should seeyour text will differ: the model writes it
{"mystery":false,"active":[],...}
6

A nightly load test in CI

The same script on a schedule, failing the job when goals are missed.

Load tests are too slow for every pull request, so run this one nightly and on demand. In the repository from lab 23, put script.js in a load folder and add the workflow. It starts ShopRung, installs k6 with Grafana's setup action, and runs the script; k6's exit code 99 turns the job red when a threshold fails.

Numbers on GitHub's shared machines are noisier than on a dedicated load environment: use CI runs to catch big regressions (like 2.5 s searches), and a stable environment for capacity numbers.

.github/workflows/load-test.yml
name: load-test

on:
  schedule:
    - cron: "23 4 * * *"   # nightly, 04:23 UTC: load tests are too slow for every pull request
  workflow_dispatch:

permissions:
  contents: read

jobs:
  k6:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Start ShopRung
        working-directory: shoprung
        run: |
          npm start > shoprung.log 2>&1 &
          npx --yes wait-on@8 http-get://localhost:8080/api/health --timeout 60000

      - uses: grafana/setup-k6-action@v1

      - name: Load test with thresholds
        working-directory: load
        run: k6 run --no-color -e BASE_URL=http://localhost:8080 script.js

      - name: Keep the shop's log
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: shoprung-log
          path: shoprung/shoprung.log
  1. Nightly. Load tests do not belong on every pull request.line 5
  2. Installs k6 on the runner.line 28
  3. Exit code 99 on a missed threshold fails the job.line 32
Run
actionlint
git add load/script.js .github/workflows/load-test.yml
git commit -m "Nightly load test" && git push
You should seeyour text will differ: the model writes it
Actions → load-test → Run workflow → k6 ✓

Check it works

Reset ShopRung (POST /api/test/reset, or restart it) and run k6 run script.js: every threshold shows ✓, dropped_iterations count=0, and the exit code is 0.

Switch on slow-search and run again: http_req_duration{name:search} and dropped_iterations show ✗, checks are still 100%, and the exit code is 99. Turn the bug off.

Test
k6 run script.js; echo "exit code: $?"
You should see
    http_req_duration{name:search}
    ✓ 'p(95)<300' p(95)=604µs
...
    dropped_iterations.............: 0      0/s
...
exit code: 0

Troubleshooting

ShopRung is not running at http://localhost:8080 from setup.

Start ShopRung, or pass the right address with -e BASE_URL=http://....

"Insufficient VUs, reached 50 active VUs and cannot initialize more".

The system is slower than the rate needs, or maxVUs is too low. Little's law: rate x seconds per iteration. Find out which before raising it.

Buyers fail with 409 on sign-up.

The email already exists. Keep Date.now() in the email so every run creates new accounts.

"order 201" checks fail with 409 or 400 after a long run.

Stock ran out. Reset ShopRung before each run (setup does), or lower the buyers' rate.

Thresholds pass on your laptop but fail in CI.

Shared CI machines are slower and noisier. Set CI goals that catch regressions, and measure capacity on a stable environment.

What changes in production

  • Teams keep k6 scripts in the repository, one per journey or service, with goals as thresholds agreed with the product owner.
  • Arrival-rate scenarios model real traffic; ramping scenarios find the breaking point in stress tests.
  • Results stream to Grafana or another time-series store so runs can be compared over weeks.
  • Load runs happen against a production-like environment with monitoring on, never against production without a plan and approval.

Interview angle

“Walk me through a load test you wrote.”

A k6 script against our shop. Setup checks the app is up and resets data. A browsers scenario with a constant arrival rate of 20 journeys a second, each tagged and checked, including the body. A buyers scenario where each virtual user signs up once and places orders with think time, so no two users share a cart. Thresholds on failed requests, checks, p95 per tagged request and dropped iterations. With a slow-search bug, every request still succeeded but search p95 hit 2.5 seconds and 58 iterations were dropped, because 20 per second times 2.5 seconds needed all 50 virtual users. k6 exited 99, which fails our nightly CI job.

Clean up

Practice

These run in your browser and check your answer.

How many virtual users?

Little's law: virtual users needed = arrival rate x seconds per iteration. Write vus_needed(rate, seconds) that returns the whole number of virtual users needed (round up: you cannot run 6.2 users).

Exercise
def vus_needed(rate, seconds):
    return int(rate * seconds)
Hint

Use math.ceil, and watch out for tiny floating-point errors such as 100.00000000000001.

The full project

Every file from this lab, as it is after the last step.

Download k6 project (.zip)