k6 Reference
Free reference guide: k6 Reference
About k6 Reference
The k6 Reference is a complete, searchable guide to the k6 open-source load testing tool developed by Grafana Labs. It covers all eight major areas of k6 scripting: Basics (default function export, options configuration, staged load with stages[], sleep(), group()), HTTP (GET/POST/PUT/DELETE requests, batch requests, request headers and authentication), Checks (check() with status code, JSON body, response time, and header assertions), Thresholds (http_req_duration percentile rules, http_req_failed rate rules, custom metric thresholds), Scenarios (constant-vus, ramping-vus, constant-arrival-rate, per-vu-iterations, shared-iterations executors), Metrics (Counter, Trend, Rate, Gauge custom metric types, built-in HTTP metrics), Protocols (WebSocket with k6/ws, gRPC with k6/net/grpc, multipart file upload, SharedArray for test data), and CLI (k6 run, --vus, --duration, --out, -e env vars, web dashboard, k6 cloud). Every entry includes a realistic JavaScript example.
k6 is the go-to performance testing tool for developers and SREs who want to write load tests as code using JavaScript or TypeScript. It is widely used in CI/CD pipelines to catch performance regressions, validate SLAs, and run stress and soak tests before deploying to production. Teams using Kubernetes, microservices, REST APIs, GraphQL endpoints, WebSocket servers, and gRPC services all use k6 to verify that their systems perform correctly under realistic traffic loads.
The reference is structured into eight categories that mirror k6's own conceptual organization. Whether you need to recall the exact syntax for a ramping VU scenario, look up which metric type to use for tracking error counts, or find the right CLI flag to send test results to a JSON file, this guide gives you the answer with a working code example you can paste directly into your k6 script.
Key Features
- Core script structure: export default function, export const options, stages-based ramping, sleep() think time, group() for logical grouping
- HTTP request methods: http.get(), http.post(), http.put(), http.del(), http.batch() for parallel requests, and params.headers for auth
- check() function for asserting status codes, JSON response body, response time under threshold, and response headers
- Threshold rules using percentile expressions: p(95)<500, p(99)<1500, http_req_failed rate<0.01, and custom metric thresholds
- Scenario executors: constant-vus, ramping-vus with staged targets, constant-arrival-rate for RPS testing, per-vu-iterations, shared-iterations
- Custom metric types: Counter for cumulative counts, Trend for timing distributions, Rate for pass/fail ratios, Gauge for instantaneous values
- Protocol support: WebSocket with event handlers, gRPC client with proto loading, multipart file uploads, and SharedArray for data-driven testing
- CLI reference: k6 run flags (--vus, --duration, --out json/csv, -e), K6_WEB_DASHBOARD, k6 cloud, and __VU / __ITER built-in globals
Frequently Asked Questions
What is k6 and how is it different from other load testing tools like JMeter or Locust?
k6 is a developer-centric load testing tool that lets you write tests in JavaScript. Unlike JMeter which uses XML configuration and a GUI, or Locust which uses Python, k6 scripts are plain JavaScript files that run in a high-performance Go runtime. k6 integrates naturally with CI/CD pipelines, supports version control, and produces detailed metrics natively compatible with Grafana and InfluxDB.
What is the difference between VUs and arrival rate in k6?
VU-based executors (constant-vus, ramping-vus) control how many concurrent virtual users are running. Each VU loops through your default function as fast as it can. Arrival-rate executors (constant-arrival-rate) control how many iterations start per unit of time (e.g., 30 req/s), regardless of how long each iteration takes. Use arrival rate when you want to simulate a fixed RPS load pattern.
How do I set a performance threshold in k6?
Add a thresholds object to your options export. For example: `thresholds: { "http_req_duration": ["p(95)<500"], "http_req_failed": ["rate<0.01"] }`. k6 will fail the test run (exit code 99) if any threshold is violated, making it easy to integrate with CI/CD pass/fail gates.
How do I use different data for each virtual user in k6?
Use SharedArray from k6/data to load a JSON or CSV file once and share it across all VUs without duplicating memory. Access per-VU data using `users[__VU % users.length]` to distribute records evenly. SharedArray data is read-only and initialized in the init stage, outside the default function.
How do I test WebSocket or gRPC endpoints with k6?
For WebSocket, import ws from "k6/ws" and use ws.connect() with event handlers for open, message, and close events. For gRPC, import grpc from "k6/net/grpc", create a client, load your .proto definitions, then call client.invoke() with the service method and request payload. Both protocols are fully supported in k6 with real-time metric collection.
What custom metrics can I create in k6?
k6 provides four custom metric types: Counter (cumulative sum, e.g., total errors), Trend (min/max/avg/percentiles, e.g., custom response times), Rate (ratio of true/false values, e.g., success rate), and Gauge (tracks the most recent value, e.g., active sessions). Create them with `new Counter("name")`, then call .add() inside your test function.
How do I run k6 tests in a CI/CD pipeline?
Install k6 in your CI environment and run `k6 run --vus N --duration Xs script.js`. Define thresholds in your script so k6 exits with a non-zero code on failure. Use `--out json=results.json` or `--out csv=results.csv` to save metrics for reporting. For cloud-based distributed testing, use `k6 cloud script.js` with a Grafana Cloud k6 account.
How do I gradually ramp up load in k6?
Use the stages array in your options (shorthand) or a ramping-vus scenario executor. Define an array of {duration, target} objects: start at 0 VUs, ramp to your peak load, hold steady for the main test period, then ramp back down to 0. This simulates a realistic traffic pattern and avoids hitting your system with an instant spike.