| name | k6-best-practices |
| description | Guides developers and testers in writing, fixing, and structuring k6 load test scripts using JavaScript or TypeScript. Use this skill whenever the user mentions k6, Grafana k6, load testing with JavaScript, virtual users, VUs, scenarios, executors, thresholds, checks, SharedArray, ramp-up stages, arrival rate, open/closed workload model, or wants to benchmark an API, WebSocket, or gRPC service using k6 โ even if they do not explicitly say "k6" or "load test".
|
| license | MIT |
| compatibility | Claude Code, Cursor, Windsurf. Requires k6 installed (brew install k6 / apt install k6 / choco install k6). Node.js 18+ required only for TypeScript compilation. |
| model | sonnet |
| metadata | {"author":"rcampos","version":"1.4","tags":["k6","load-testing","performance","javascript","typescript"]} |
k6 Scenario Builder
Enforces a consistent, production-ready pattern for k6 load test scripts using
JavaScript or TypeScript, covering HTTP/REST, WebSocket, and gRPC protocols.
Output Format
When producing or fixing a script, always deliver three things:
- A complete, runnable script file โ never a partial snippet.
- The exact run command with the environment variables needed.
- A one-line explanation of the executor chosen and why it fits the load goal.
When fixing any OOM error or open() misuse, cover both failure modes โ even if the user only mentioned one:
- Plain variable at init context โ OOM (data copied per VU). Fix:
SharedArray.
open() inside default() โ immediate runtime error (can't call open() in the VU context). Fix: move to init context.
Step 1 โ Gather Context
Ask only what is unknown:
- Language: JavaScript (default) ยท TypeScript
- Protocol: HTTP/REST ยท WebSocket ยท gRPC
- Goal: New script ยท Fix existing script ยท Specific DSL question
- Workload model: Fixed concurrent users (closed) or fixed arrival rate in RPS (open)?
Only load references/EXECUTORS.md when the user asks about executor types, workload models, scenario configuration, multi-scenario orchestration, or startTime/exec/gracefulStop parameters.
Only load references/PROTOCOLS.md when the user mentions WebSocket or gRPC. Contains connection setup, event handling, streaming DSL, and gotchas.
Only load references/DESIGN-PATTERNS.md when the user asks about folder structure, project architecture, sharing data between VUs, TypeScript setup, scaling beyond a single file, modular structure, reusable helpers, multi-step user flows (e-commerce, checkout, login+browse), or multiple scenarios sharing common logic.
Step 2 โ Apply the 5-Block Pattern
Every k6 script must have these five blocks in order. Generate the complete skeleton first, then fill in details.
Block 1 โ Options scenarios + thresholds (executor, VUs, duration, SLA gates)
Block 2 โ Data SharedArray for parameterized inputs โ loaded once, shared across VUs
Block 3 โ Setup one-time auth or preparation โ runs once before VUs start
Block 4 โ Default fn the VU workload: requests, checks, groups, sleep
Block 5 โ Teardown cleanup (optional โ required for gRPC/WS connection close)
Common Mistakes โ Check Every Script for These
1. No sleep() between requests โ generates unrealistic load
Without think time, VUs hammer the server at maximum speed. Always add sleep() between logical steps.
export default function() {
http.get(`${BASE_URL}/api/products`);
http.get(`${BASE_URL}/api/cart`);
}
import { sleep } from 'k6';
export default function() {
http.get(`${BASE_URL}/api/products`);
sleep(Math.random() * 2 + 1);
http.get(`${BASE_URL}/api/cart`);
sleep(1);
}
2. check() as a test gate โ it never fails the test
check() records pass/fail statistics but never stops or fails the test. This is the most common k6 misconception. Use thresholds to actually fail.
check(res, { 'status is 200': (r) => r.status === 200 });
export const options = {
thresholds: {
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'],
checks: ['rate>0.99'],
},
};
check(res, { 'status is 200': (r) => r.status === 200 });
Three failure mechanisms:
check() โ per-iteration assertion, records stats, never stops the test
threshold โ aggregate SLA gate, fails the test on breach (exit code 99)
fail(msg) โ stops the current iteration immediately, use for unrecoverable errors
3. Hardcoded base URL โ breaks multi-environment usage
const res = http.get('https://hardcoded-prod.example.com/api/users');
const BASE_URL = __ENV.BASE_URL || 'https://staging.example.com';
Run: k6 run --env BASE_URL=https://prod.example.com script.js
4. Storing test data in a plain variable โ multiplied per VU
Any variable declared at init context scope is copied once per VU. For a 50 MB JSON file with 200 VUs, that is 10 GB of RAM. Use SharedArray โ loaded once, shared across all VUs as read-only.
import { open } from 'k6';
const users = JSON.parse(open('./data/users.json'));
import { SharedArray } from 'k6/data';
const users = new SharedArray('users', () => JSON.parse(open('./data/users.json')));
Two open() errors to always explain together:
- Plain variable at init context โ OOM (per-VU copy). Fix:
SharedArray.
open() inside default() โ runtime error (can't call open() in the VU context). Fix: move to init context.
5. Imports not at the top of the file โ breaks convention and readability
All import statements must be the very first lines of the file โ before export const options, before SharedArray, before any other code. ES modules technically hoist imports regardless of position, but placing them anywhere else creates scripts that are hard to read and breaks the init-context mental model.
export const options = { ... };
import { SharedArray } from 'k6/data';
const users = new SharedArray(...);
import http from 'k6/http';
import { check, sleep } from 'k6';
import http from 'k6/http';
import { check, group, sleep, fail } from 'k6';
import { SharedArray } from 'k6/data';
export const options = { ... };
const users = new SharedArray('users', () => JSON.parse(open('./data/users.json')));
export default function() { ... }
6. ramping-vus for a fixed RPS target โ wrong workload model
ramping-vus controls concurrent users (closed model). Throughput varies with response time. For a fixed RPS goal, use constant-arrival-rate.
executor: 'ramping-vus', stages: [{ duration: '5m', target: 100 }]
executor: 'constant-arrival-rate',
rate: 100,
timeUnit: '1s',
duration: '5m',
preAllocatedVUs: 50,
maxVUs: 200,
7. Under-sized preAllocatedVUs โ silent dropped iterations
constant-arrival-rate drops iterations when VUs run out. Monitor dropped_iterations in output.
preAllocatedVUs = ceil(rate ร p95_response_time_in_seconds ร 1.2)
Example: 100 RPS, p95 = 400ms โ ceil(100 ร 0.4 ร 1.2) = 48 โ use 50
8. gracefulStop shorter than p99 response time โ inflated errors
k6 waits gracefulStop duration after the test ends for in-flight iterations to complete. If p99 is 2s and gracefulStop is the default 30s, you are fine. But if p99 is 45s (batch job), set gracefulStop: '60s' explicitly.
scenarios: {
load: {
executor: 'constant-vus',
vus: 100,
duration: '5m',
gracefulStop: '60s',
}
}
9. One shared token for all VUs โ all users share the same identity
setup() runs once before all VUs start. A token returned from setup() is shared by every VU โ they all authenticate as the same user, producing unrealistic server-side behavior (single session, no per-user data isolation).
export function setup() {
const res = http.post(`${BASE_URL}/auth/login`, JSON.stringify({ username: 'admin', password: 'secret' }), ...);
return { token: res.json('access_token') };
}
import { SharedArray } from 'k6/data';
const credentials = new SharedArray('creds', () => JSON.parse(open('./data/users.json')));
export default function() {
const cred = credentials[(__VU - 1) % credentials.length];
const res = http.post(`${BASE_URL}/auth/login`,
JSON.stringify({ username: cred.username, password: cred.password }),
{ headers: { 'Content-Type': 'application/json' } }
);
const token = res.json('access_token');
}
Use setup() only for shared, stateless initialization (e.g., seeding a test dataset via an admin API call).
10. Missing Content-Type on POST โ server returns 415
http.post(`${BASE_URL}/api/users`, JSON.stringify({ name: 'Alice' }));
http.post(`${BASE_URL}/api/users`, JSON.stringify({ name: 'Alice' }), {
headers: { 'Content-Type': 'application/json' },
});
The 5-Block Pattern โ Reference
Block 1: Options
export const options = {
scenarios: {
load: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '2m', target: 50 },
{ duration: '5m', target: 50 },
{ duration: '2m', target: 0 },
],
gracefulRampDown: '30s',
gracefulStop: '30s',
},
},
thresholds: {
http_req_duration: ['p(95)<500', 'p(99)<1000'],
http_req_failed: ['rate<0.01'],
checks: ['rate>0.99'],
},
};
Block 2: Data (SharedArray)
import { SharedArray } from 'k6/data';
const users = new SharedArray('users', () => JSON.parse(open('./data/users.json')));
const csvUsers = new SharedArray('csv-users', () =>
open('./data/users.csv')
.split('\n')
.slice(1)
.filter(line => line.trim().length > 0)
.map(line => {
const [username, password] = line.split(',');
return { username: username.trim(), password: password.trim() };
})
);
const user = users[(__VU - 1) % users.length];
const user = users[Math.floor(Math.random() * users.length)];
Block 3: Setup
const BASE_URL = __ENV.BASE_URL || 'https://staging.example.com';
export function setup() {
const res = http.post(`${BASE_URL}/api/seed`, null, {
headers: { Authorization: `Bearer ${__ENV.ADMIN_TOKEN}` },
});
if (res.status !== 200) {
fail(`Seed failed: ${res.status} โ aborting test`);
}
return { seedId: res.json('id') };
}
Block 4: Default Function (VU workload)
import http from 'k6/http';
import { group, check, sleep } from 'k6';
export default function(data) {
const cred = users[(__VU - 1) % users.length];
const token = login(cred);
group('Browse', () => {
const res = http.get(`${BASE_URL}/api/products`, {
headers: { Authorization: `Bearer ${token}` },
tags: { endpoint: 'products' },
});
check(res, {
'products 200': (r) => r.status === 200,
'products not empty': (r) => r.json('#') > 0,
'products < 500ms': (r) => r.timings.duration < 500,
});
sleep(Math.random() * 2 + 1);
});
group('Checkout', () => {
const res = http.post(`${BASE_URL}/api/orders`,
JSON.stringify({ productId: data.seedId }),
{ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
tags: { endpoint: 'checkout' } }
);
check(res, {
'order created 201': (r) => r.status === 201,
'order has id': (r) => r.json('id') !== undefined,
});
sleep(1);
});
}
Block 5: Teardown
export function teardown(data) {
http.del(`${BASE_URL}/api/seed/${data.seedId}`, null, {
headers: { Authorization: `Bearer ${__ENV.ADMIN_TOKEN}` },
});
}
Executor Selection Guide
Closed model โ controls concurrent users. Use when connection count or session state matters.
| Executor | When to use | Required params |
|---|
constant-vus | Steady-state, fixed concurrency | vus, duration |
ramping-vus | Ramp up/down, standard load test | stages, startVUs |
per-vu-iterations | Each VU runs exactly N iterations | vus, iterations, maxDuration |
shared-iterations | Exactly N total iterations across all VUs | vus, iterations, maxDuration |
Open model โ controls arrival rate. Use for public APIs where RPS is the goal.
| Executor | When to use | Required params |
|---|
constant-arrival-rate | Fixed RPS target | rate, timeUnit, preAllocatedVUs, maxVUs, duration |
ramping-arrival-rate | Escalating RPS (stress test) | stages, timeUnit, preAllocatedVUs, maxVUs |
externally-controlled | Live VU adjustment via REST API | vus, maxVUs, duration |
Default choice: ramping-vus. Switch to constant-arrival-rate when the SLA is expressed in RPS.
Thresholds Reference
export const options = {
thresholds: {
http_req_duration: ['p(95)<500', 'p(99)<1000'],
'http_req_duration{endpoint:checkout}': ['p(99)<2000'],
http_req_failed: ['rate<0.01'],
checks: ['rate>0.99'],
http_reqs: ['rate>50'],
'checkout_duration_ms': ['p(95)<300'],
},
};
export const options = {
thresholds: {
http_req_duration: [
{ threshold: 'p(95)<500', abortOnFail: true, delayAbortEval: '1m' },
],
},
};
Custom Metrics
import { Counter, Gauge, Trend, Rate } from 'k6/metrics';
const checkoutMs = new Trend('checkout_duration_ms');
const authErrors = new Counter('auth_errors_total');
const cacheHits = new Rate('cache_hit_rate');
export default function(data) {
const start = Date.now();
const body = JSON.stringify({ productId: '123' });
const res = http.post(`${BASE_URL}/api/orders`, body, {
headers: { 'Content-Type': 'application/json',
Authorization: `Bearer ${data.token}` },
tags: { endpoint: 'checkout' },
});
checkoutMs.add(Date.now() - start, { step: 'payment' });
if (res.status === 401) authErrors.add(1);
cacheHits.add(res.headers['X-Cache'] === 'HIT');
}
Run Commands
k6 run script.js
k6 run --vus 2 --duration 30s script.js
k6 run --env BASE_URL=https://staging.example.com \
--env USERNAME=perf_user \
--env PASSWORD=secret \
script.js
k6 run --out json=results.json script.js
k6 run --out influxdb=http://localhost:8086/k6 script.js
npx esbuild src/load.ts --bundle --outfile=dist/load.js --target=es2015
k6 run dist/load.js
k6 cloud run script.js
References