What it does
k6 (by Grafana) runs virtual users (VUs) that call your service again and again, and measures response times and errors. The test is a JavaScript file. Thresholds turn it into a pass/fail check, for example "95 % of requests under 300 ms and less than 1 % errors" — perfect as a step after a deploy to staging.
Results can go to Prometheus, InfluxDB or Grafana Cloud.
How to write it
k6 run [OPTIONS] SCRIPT.jsMain parts
Commands
runSCRIPT- Run a test.
newFILE- Make an example script.
inspectSCRIPT- Show the options of a script.
cloudSCRIPT- Run in Grafana Cloud.
Options 9
Most used
run options
Nothing matches this filter.
Examples 10
$ run as a normal user# run as root (or with sudo)
1A first test: 10 users for 30 seconds
cat smoke.js import http from "k6/http"; import { check, sleep } from "k6"; export default function () { const res = http.get(`${__ENV.BASE_URL}/health`); check(res, { "status is 200": (r) => r.status === 200 }); sleep(1); } k6 run -u 10 -d 30s -e BASE_URL=https://staging.example.com smoke.js2Thresholds: fail the pipeline when slow
cat load.js export const options = { stages: [ { duration: "1m", target: 50 }, { duration: "3m", target: 50 }, { duration: "30s", target: 0 } ], thresholds: { http_req_duration: ["p(95)<300"], http_req_failed: ["rate<0.01"] }, }; k6 run load.jsIf a threshold fails, k6 exits with code 99 and the CI job fails.
3Ramp up from the command line
k6 run --stage 30s:20,2m:20,10s:0 smoke.js4A POST with JSON and a token
cat api.js import http from "k6/http"; export default function () { http.post(`${__ENV.BASE_URL}/api/cart`, JSON.stringify({ sku: "BA-101" }), { headers: { "Content-Type": "application/json", Authorization: `Bearer ${__ENV.TOKEN}` } }); } k6 run -e BASE_URL=https://staging.example.com -e TOKEN="$TOKEN" api.js5Run in Docker (no install)
docker run --rm -i grafana/k6 run - < smoke.js6In GitHub Actions after a staging deploy
cat .github/workflows/perf.yml - uses: grafana/setup-k6-action@v1 - run: k6 run -e BASE_URL=https://staging.example.com load.js7Save the results
k6 run --summary-export summary.json --out json=raw.json load.js8Send metrics to Prometheus (remote write)
K6_PROMETHEUS_RW_SERVER_URL=http://prometheus:9090/api/v1/write k6 run -o experimental-prometheus-rw load.js9Make an example script
k6 new script.js10Debug one request
k6 run -i 1 --http-debug=full smoke.js
Nothing matches this filter.
Watch out
- Load tests on production can hurt real users; test staging, or agree on a time window.
- The machine that runs k6 can be the limit; watch its CPU too.
Tips to remember
- Start with a small smoke test in every pipeline; run big load tests on a schedule.
Exit codes
0 | All thresholds passed. |
99 | A threshold failed. |
107 | Script error. |