QA AND TEST AUTOMATION · PART 9 · NON-FUNCTIONAL TESTING · PERFORMANCE · 82 OF 112

k6 Load Testing Tutorial: Scenarios and Thresholds

A k6 load test for ShopRung written step by step in JavaScript: virtual users and iterations, stages for ramping, checks on status and body, logging in once in setup, scenarios with arrival-rate executors for spike and steady load, thresholds that fail the run on p95 and error rate, tags and groups, reading the summary, and running k6 in CI.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Default function
  • stages
  • checks on the body
  • setup login
  • arrival-rate scenarios
  • thresholds fail CI

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.

script.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.

options
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.

Checks on the body
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.

setup and auth
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
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
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.

Running it
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.

The summary, shortened
✓ 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1What is k6?

An open source load testing tool from Grafana Labs; tests are JavaScript scripts run from the command line, with checks and thresholds.

Q2What is the difference between checks and thresholds in k6?

Checks verify individual responses and are counted; thresholds are pass/fail goals on metrics that set the exit code.

Q3What does setup() do in k6?

Runs once before the load; its return value (for example an auth token) is passed to every VU's default function.

Q4Why use an arrival-rate executor?

It starts iterations at a fixed rate regardless of response time, like real users who keep arriving, instead of slowing down with the system.

Q5How do you make a k6 test fail CI?

Define thresholds such as http_req_duration p(95)<500 and http_req_failed rate<0.01; a missed threshold gives a non-zero exit code.

Q6Why tag requests with a name?

URLs with ids or query values would create separate metrics; a name tag groups them for readable results and per-endpoint thresholds.

Q7How are stages used?

They ramp the VU count over time, for example 1 minute up to 50, 5 minutes at 50, 1 minute down.

Q8How do you pass configuration and secrets to k6?

With environment variables (-e NAME=value), read through __ENV in the script.