Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Practice: k6 Exercises with Solutions

Practice k6 with design and analysis exercises: write thresholds, choose executors, size VUs, read result tables and build a test plan, with runnable Node self-checks and worked solutions.

Reading about load testing is not the same as doing it. These exercises train the decisions you make in real projects: which executor, which threshold, how many VUs, what the numbers mean. Try each task on paper (or in a text file) first, then compare with the worked solution.

Honesty note. k6 cannot run on this site, so the k6 answers are read-only text you can run on your own machine. The runnable blocks are Node self-checks: they encode the arithmetic and logic of each exercise so you can verify the reasoning, not k6 itself.

Exercise 1: write the thresholds

A product owner gives you these requirements for a search API:

  • 99 % of requests must succeed.
  • 95 % of requests must be faster than 250 ms, 99 % faster than 600 ms.
  • The slower Export route may take up to 3 seconds at p(95).
  • At least 98 % of your content checks must pass.

Write the thresholds object before reading on.

Solution

JavaScript
export const options = {
  thresholds: {
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<250', 'p(99)<600'],
    'http_req_duration{name:Export}': ['p(95)<3000'],
    checks: ['rate>0.98'],
  },
};

Remember that the global http_req_duration threshold also includes the Export route, so exclude it or loosen the global one if the export traffic is significant: for example tag normal requests with type:api and use 'http_req_duration{type:api}'. Thresholds are the test's definition of success: see CI pipelines for how they gate builds.

Node.js Self-check: evaluate thresholds on a sample result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 2: pick the executor

Choose an executor for each situation (several fit; justify).

Situation Your choice
A. 50 logged-in support agents use an internal tool all day ?
B. A public API receiving 120 independent requests per second at peak ?
C. Run a data-import script exactly 10,000 times as fast as possible, shared among VUs ?
D. Gradually increase visitors from 0 to 300 per second to find the breaking point ?
E. Every VU must replay its own 20 recorded steps once ?

Solution

  • A: constant-vus (a fixed population, closed model) with realistic think time.
  • B: constant-arrival-rate at 120 per second (open model; give it enough maxVUs).
  • C: shared-iterations with iterations: 10000 and some number of VUs.
  • D: ramping-arrival-rate with increasing stages and large maxVUs.
  • E: per-vu-iterations with iterations: 1.

The closed versus open distinction is the heart of Test design and workload models.

Exercise 3: size the VUs

Your analytics show a peak of 25 sessions starting per second. A session is 8 requests with about 1.5 seconds of think time between them, and the server usually answers in 0.2 s. How many VUs does a constant-arrival-rate scenario need? What preAllocatedVUs and maxVUs would you configure?

Solution. Iteration time is about 8 x 0.2 + 7 x 1.5 = 12.1 s. By Little's Law 25 x 12.1 = 302.5, so about 303 VUs. Allocate preAllocatedVUs: 320. Set maxVUs much higher (for example 600), because if responses slow down iterations last longer and more VUs are needed to keep the arrival rate.

Node.js Self-check: Little's Law with and without slowdown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 4: read the table

An engineer posts this end-of-test result and says "all good, average is 90 ms":

TEXT
http_req_duration: avg=90ms  min=12ms  med=60ms  max=8.2s  p(90)=140ms  p(95)=1.1s
http_req_failed:   3.4%
checks:            96.5%
dropped_iterations: 4210

List everything that is not good.

Solution.

  1. p(95) is 1.1 s while the median is 60 ms: a heavy tail; 5 % of requests are more than ten times slower than typical. The average hides it.
  2. max 8.2 s: some requests nearly timed out.
  3. http_req_failed 3.4 % is high for most SLOs, and failed responses are often fast, which makes the latency numbers look better than they are.
  4. checks 96.5 % means roughly 3.5 % of responses had wrong content or status.
  5. dropped_iterations 4210: k6 could not start the planned iterations, so the intended load was not delivered. Either the system saturated or maxVUs was too low or the generator was overloaded. The test did not measure what it was supposed to.

See Analyzing results for the validation steps.

Node.js Self-check: automatic red flags from a summary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 5: spot the script bugs

JavaScript
import http from 'k6/http';
import { Trend } from 'k6/metrics';

export default function () {
  const orders = new Trend('order_time');
  const body = { name: 'Pen', qty: 1 };
  const res = http.post('https://shop.example.test/orders', body);
  const data = open('./products.json');
  orders.add(res.timings.duration);
  http.get(`https://shop.example.test/orders/${res.json('id')}`);
}

How many problems can you find?

Solution.

  1. The Trend is created inside the default function; metrics must be created at init (top level).
  2. body is an object, so k6 sends a form, not JSON: use JSON.stringify and a Content-Type header if the API expects JSON (HTTP requests).
  3. open() is only allowed in the init context, and this file is not even used: load it with a SharedArray (Data).
  4. No check on res.status: a 500 response with no id would produce a confusing error on the next line; use check and fail.
  5. The last request URL contains an id, so it needs a name tag to avoid one series per order.
  6. No sleep or arrival-rate pacing: each VU hammers the server without think time.
  7. No options: there are no thresholds, so the run can never fail a pipeline.
Node.js Self-check: a tiny linter for the same mistakes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exercise 6: plan a full test

You are asked to prepare a launch for a ticket-sales site: normal traffic 30 requests per second, an on-sale moment when traffic is expected to jump to 15 times normal within a minute, then stay high for ten minutes. Write a short test plan with: goals, workload model, scenarios, thresholds, data needs and risks.

A model answer

  • Goals: the site stays available during the on-sale; p(95) under 800 ms for browsing and under 1.5 s for purchase; fewer than 1 % errors; recovery to baseline within two minutes after the peak.
  • Workload model: open model (independent visitors). Mix 80 % browse, 15 % seat selection, 5 % purchase. Think time 2 to 8 seconds between steps.
  • Scenarios: (1) a load test at 30/s for 15 minutes; (2) a spike test: ramping-arrival-rate from 30 to 450 per second over a minute, hold ten minutes, drop and observe a five-minute recovery window; (3) a soak test at 30/s for four hours the night before; (4) a smoke test on every deployment.
  • Thresholds: as in the goals, using sub-metrics for browsing and purchase and a phase:recovery tag.
  • Data: thousands of test accounts and seat inventories reset before each run; purchases go to a payment sandbox, never the real provider.
  • Risks and mitigations: the payment provider or email service rate-limiting (stub or sandbox them); the generator limit (distribute with execution segments, see Docker and Kubernetes); shared environments (reserve a window); cache warm state (decide and document whether the test starts cold).
Node.js Self-check: peak arrival rate and generator capacity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which executor suits 'exactly 10,000 runs of a script, shared among VUs'?

    shared-iterations spreads a fixed total number of iterations over the available VUs.
  2. 2. A run shows avg=90ms but p(95)=1.1s. What does this indicate?

    Averages hide tails; percentiles show what slower users experience.
  3. 3. Why should maxVUs be much larger than the VUs needed at normal speed?

    By Little's Law needed VUs = rate x iteration time, and iteration time grows when the system slows.
  4. 4. Where is a metric such as new Trend('x') allowed to be created?

    Custom metrics must be created in the init context.

Summary

  • Thresholds express requirements; relative and sub-metric thresholds cover slices.
  • Choose executors by the model: VUs for fixed populations, arrival rates for independent visitors, shared iterations for fixed workloads.
  • Size VUs with Little's Law and leave headroom in maxVUs.
  • Read tails, failures, checks and dropped iterations before the average.
  • A good test plan states goals, model, scenarios, thresholds, data and risks.

Back to the k6 Load Testing track.