🚀 Modern Performance Engineering as Pure Code in Version Control
Traditional GUI-heavy load testing suites generate bloated XML files, struggle with Git-based collaboration, and consume heavy memory overhead per virtual user thread. Grafana k6 redefines enterprise load testing by marrying a high-performance execution engine written in Go with an accessible, modern ES6 JavaScript scripting interface. In k6, test scenarios, lifecycle hooks, data parametrization, checks, and Service Level Objectives (SLOs) are declared entirely as clean, version-controllable code. By decoupling virtual user concurrency from OS thread limits and providing advanced multi-scenario executors (such as open-model arrival rates to defeat coordinated omission), k6 allows performance engineering teams to shift load testing left directly into developer workflows, pull requests, and automated deployment pipelines.
K6 RUNTIME ARCHITECTURE & EXECUTION TOPOGRAPHY:
┌───────────────────────────────────────────────────────────────────────────────────────────────────┐
│ GO-BASED RUNTIME ENGINE │
│ - Ultra-lightweight goroutines handle thousands of Virtual Users (VUs) with low memory footprint │
│ - Goja JS Engine: Compiles ES6 JavaScript code directly to bytecode without Node.js runtime │
│ - Open-Model Architecture: Schedules requests independently of target response latency │
└───────────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼
FOUR-STAGE TEST LIFECYCLE PIPELINE:
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ 1. INIT CODE (Executed ONCE per VU during script compilation) │
│ - Imports libraries (http, check, sleep) │
│ - Declares custom Trend / Counter / Rate metrics │
│ - Loads SharedArray datasets from JSON/CSV into immutable shared memory │
│ - Exports test options & threshold SLA rules │
├───────────────────────────────────────────────────────────────────────────────────────────────┤
│ 2. SETUP CODE (Optional: export function setup() - Executed ONCE globally) │
│ - Performs administrative tasks: seeds test database, mints master OAuth tokens │
│ - Passes returned data dictionary directly to all worker VUs │
├───────────────────────────────────────────────────────────────────────────────────────────────┤
│ 3. VU CODE (Mandatory: export default function(data) - Executed REPEATEDLY across VUs) │
│ - Simulates user journey: POST /students, GET /courses, asserts status and latency │
│ - Collects telemetry metrics; loops for assigned iterations or duration │
├───────────────────────────────────────────────────────────────────────────────────────────────┤
│ 4. TEARDOWN CODE (Optional: export function teardown(data) - Executed ONCE globally at end) │
│ - Cleans up provisioned tenant resources, purges test database records, flushes logs │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
setup() to the default function, and executing cleanup in teardown().
import http from 'k6/http';
import { check, sleep } from 'k6';
// 1. INIT STAGE: Configure test execution options and global constants
export const options = {
vus: 10,
duration: '30s',
thresholds: {
http_req_duration: ['p(95)<300'], // 95% of requests must complete below 300ms
http_req_failed: ['rate<0.01'], // Error rate must be under 1%
},
};
const BASE_URL = 'https://api.nikita-infotech.com/v1';
// 2. SETUP STAGE: Runs once before any VU begins
export function setup() {
console.log('[*] Initializing Global Test Run: Acquiring Master Auth Token...');
const loginRes = http.post(`${BASE_URL}/auth/token`, JSON.stringify({
clientId: 'k6_perf_runner_01',
clientSecret: 'PerfSecret#2026',
}), {
headers: { 'Content-Type': 'application/json' },
});
check(loginRes, { 'Master auth token acquired': (r) => r.status === 200 });
const authToken = loginRes.json('access_token');
// Return context dictionary passed directly to default() and teardown()
return { token: authToken, batchId: `BATCH-${Date.now()}` };
}
// 3. VU STAGE: Executed concurrently across all 10 VUs for 30 seconds
export default function (data) {
const params = {
headers: {
'Authorization': `Bearer ${data.token}`,
'Content-Type': 'application/json',
'X-Batch-ID': data.batchId,
},
};
const res = http.get(`${BASE_URL}/students/catalog?limit=10`, params);
check(res, {
'Catalog status is 200': (r) => r.status === 200,
'Returned students array': (r) => Array.isArray(r.json('students')),
});
sleep(1); // 1-second pacing delay
}
// 4. TEARDOWN STAGE: Runs once after all VUs complete
export function teardown(data) {
console.log(`[*] Tearing down performance run for Batch: ${data.batchId}`);
http.post(`${BASE_URL}/auth/revoke`, JSON.stringify({ token: data.token }), {
headers: { 'Content-Type': 'application/json' },
});
}
scenarios. Combines a constant arrival-rate workload with a staged ramping-VU profile targeting distinct API endpoints simultaneously.
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
scenarios: {
// Scenario 1: Open-Model Constant Arrival Rate (Defeats Coordinated Omission)
constant_rate_catalog_browsers: {
executor: 'constant-arrival-rate',
rate: 50, // Exactly 50 iterations started per timeUnit
timeUnit: '1s', // 50 RPS target
duration: '1m',
preAllocatedVUs: 20, // Pool size allocated before test starts
maxVUs: 100, // Ceiling if server slows down
exec: 'browseCatalog', // Specific function target
},
// Scenario 2: Closed-Model Ramping Virtual Users (User Journey)
ramping_enrollment_users: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '20s', target: 15 },
{ duration: '30s', target: 30 },
{ duration: '10s', target: 0 },
],
startTime: '10s', // Staggered: Starts 10 seconds after Scenario 1
exec: 'enrollStudent', // Specific function target
},
},
thresholds: {
'http_req_duration{scenario:constant_rate_catalog_browsers}': ['p(95)<150'],
'http_req_duration{scenario:ramping_enrollment_users}': ['p(95)<400'],
},
};
const BASE_URL = 'https://api.nikita-infotech.com/v1';
// Target for Scenario 1
export function browseCatalog() {
const res = http.get(`${BASE_URL}/courses`);
check(res, { 'Catalog OK': (r) => r.status === 200 });
}
// Target for Scenario 2
export function enrollStudent() {
const payload = JSON.stringify({
fullName: `Candidate-${__VU}-${Date.now().toString().slice(-4)}`,
courseCode: 'API-PRO-101',
credits: 4,
});
const res = http.post(`${BASE_URL}/enrollments`, payload, {
headers: { 'Content-Type': 'application/json' },
});
check(res, { 'Enrollment created': (r) => r.status === 201 });
sleep(0.5);
}
Trend (timings and distributions), Counter (cumulative totals), Rate (success/failure percentages), and Gauge (instantaneous values).
import http from 'k6/http';
import { check } from 'k6';
import { Trend, Counter, Rate, Gauge } from 'k6/metrics';
// 1. Declare Custom Metrics
const enrollmentLatencyTrend = new Trend('waiting_time_enrollment_ms', true);
const totalStudentsEnrolled = new Counter('total_students_enrolled_count');
const validationFailureRate = new Rate('validation_failure_percentage');
const activeConcurrentVUsGauge = new Gauge('active_vu_gauge');
export const options = {
vus: 20,
duration: '45s',
thresholds: {
// Assert on default metrics
http_req_failed: ['rate<0.02'], // Max 2% network/HTTP failures
// Assert on custom metrics
waiting_time_enrollment_ms: [
'p(50)<100', // Median latency < 100ms
'p(95)<250', // 95th percentile < 250ms
'p(99)<450', // 99th percentile < 450ms
],
validation_failure_percentage: ['rate<0.05'], // Max 5% validation rejects
total_students_enrolled_count: ['count>500'], // Mandate minimum throughput volume
},
};
export default function () {
activeConcurrentVUsGauge.add(__VU); // Track current VU identifier
const payload = JSON.stringify({
fullName: `Perf Student ${__VU}`,
courseCode: 'API-PRO-101',
credits: 4,
});
const res = http.post('https://api.nikita-infotech.com/v1/students', payload, {
headers: { 'Content-Type': 'application/json' },
});
// Track raw network latency inside our custom Trend metric
enrollmentLatencyTrend.add(res.timings.waiting);
const isSuccess = check(res, { 'Status 201': (r) => r.status === 201 });
if (isSuccess) {
totalStudentsEnrolled.add(1); // Increment counter on success
validationFailureRate.add(0);
} else {
validationFailureRate.add(1); // Record failure in rate metric
}
}
k6/data.SharedArray. Loads the file into memory once, sharing it across all virtual users with zero heap memory duplication.
import http from 'k6/http';
import { check } from 'k6';
import { SharedArray } from 'k6/data';
// SharedArray reads and parses the JSON file ONCE across all VUs
// In standard JS arrays, 100 VUs would duplicate the dataset 100 times in memory!
const candidateDataset = new SharedArray('student_seed_data', function () {
const data = JSON.parse(open('../data/candidate_records.json'));
return data; // Array of objects: [{ id: "STU-1", name: "Nikita", course: "API-101" }, ...]
});
export const options = {
vus: 50,
duration: '1m',
};
export default function () {
// Partition records cleanly across VUs and iterations
const recordIndex = (__VU * 1000 + __ITER) % candidateDataset.length;
const candidate = candidateDataset[recordIndex];
const payload = JSON.stringify({
studentId: candidate.id,
fullName: candidate.name,
courseCode: candidate.course,
});
const res = http.post('https://api.nikita-infotech.com/v1/enrollments', payload, {
headers: { 'Content-Type': 'application/json' },
});
check(res, {
'Enrollment successful': (r) => r.status === 201,
});
}
import http from 'k6/http';
import { check, group, sleep } from 'k6';
export const options = {
vus: 15,
duration: '45s',
};
const BASE_URL = 'https://api.nikita-infotech.com/v1';
export default function () {
let userToken = '';
let generatedStudentId = '';
// STEP 1: Authentication Handshake
group('01_User_Authentication', function () {
const authRes = http.post(`${BASE_URL}/auth/login`, JSON.stringify({
username: `user_${__VU}@nikita-infotech.com`,
password: 'SafePassword#2026',
}), { headers: { 'Content-Type': 'application/json' } });
check(authRes, { 'Login 200 OK': (r) => r.status === 200 });
userToken = authRes.json('token');
});
const authHeaders = {
headers: {
'Authorization': `Bearer ${userToken}`,
'Content-Type': 'application/json',
},
};
// STEP 2: Create Subordinate Student Record
group('02_Create_Student_Record', function () {
const createRes = http.post(`${BASE_URL}/students`, JSON.stringify({
fullName: `Correlated Student ${__VU}`,
courseCode: 'API-PRO-101',
credits: 4,
}), authHeaders);
check(createRes, { 'Created 201': (r) => r.status === 201 });
generatedStudentId = createRes.json('id');
});
// STEP 3: Retrieve Newly Created Record by Extracted ID
group('03_Verify_Created_Record', function () {
const getRes = http.get(`${BASE_URL}/students/${generatedStudentId}`, authHeaders);
check(getRes, {
'Fetch 200 OK': (r) => r.status === 200,
'ID matches created entity': (r) => r.json('id') === generatedStudentId,
});
});
sleep(1);
}
handleSummary() and the k6-reporter library, alongside exporting raw JSON metrics for external consumption.
// Add this function at the bottom of any k6 script to export HTML & JSON:
import { htmlReport } from 'https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js';
import { textSummary } from 'https://jslib.k6.io/k6-summary/0.0.1/index.js';
export function handleSummary(data) {
return {
'reports/performance_summary.html': htmlReport(data), // Generates interactive HTML dashboard
'reports/summary_metrics.json': JSON.stringify(data), // Machine-readable JSON metrics for CI
stdout: textSummary(data, { indent: ' ', enableColors: true }), // Pretty-print to terminal console
};
}
# CLI EXECUTION WITH MULTIPLE OUTPUT DESTINATIONS:
# 1. Standard execution with handleSummary exporting HTML:
k6 run scripts/k6_custom_metrics.js
# 2. Stream real-time metrics directly to InfluxDB / Grafana:
k6 run --out influxdb=http://localhost:8086/k6_metrics scripts/k6_custom_metrics.js
# 3. Export detailed CSV stream of every single HTTP request:
k6 run --out csv=reports/raw_samples.csv scripts/k6_custom_metrics.js
name: k6 API Performance Quality Gate
on:
pull_request:
branches: [ "main" ]
workflow_dispatch:
jobs:
load-test-gate:
runs-on: ubuntu-latest
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
- name: Setup k6 CLI Engine
uses: grafana/setup-k6-action@v1
- name: Execute k6 Performance Test Suite
env:
API_BASE_URL: ${{ secrets.STAGING_API_BASE_URL }}
run: |
mkdir -p reports
k6 run --quiet \
--env BASE_URL=${API_BASE_URL} \
scripts/k6_student_api_load.js
- name: Publish Performance HTML Dashboard
if: always()
uses: actions/upload-artifact@v4
with:
name: k6-html-dashboard
path: reports/performance_summary.html
retention-days: 14
import http from 'k6/http';
import { check, sleep } from 'k6';
// Stress test profile: Step-up stages to determine breakpoint capacity
export const options = {
stages: [
{ duration: '1m', target: 50 }, // Below normal load
{ duration: '2m', target: 100 }, // Normal anticipated peak
{ duration: '2m', target: 200 }, // Stress level 1: 2x peak
{ duration: '2m', target: 350 }, // Stress level 2: 3.5x peak (Determine breakpoint)
{ duration: '1m', target: 0 }, // Scale down to verify system recovery
],
thresholds: {
// If error rate crosses 10% during stress run, abort immediately
http_req_failed: [{ threshold: 'rate<0.10', abortOnFail: true }],
},
};
export default function () {
const res = http.get('https://api.nikita-infotech.com/v1/students/catalog');
check(res, {
'Server healthy': (r) => r.status === 200,
'Not rate-limited': (r) => r.status !== 429,
});
sleep(0.2);
}
K6 CAPABILITIES & EXECUTOR QUICK REFERENCE MATRIX:
┌─────────────────────────┬──────────────────────────────┬──────────────────────────────────────────────────┐
│ EXECUTOR / DIRECTIVE │ CONFIGURATION EXAMPLE │ PRIMARY PURPOSE & OPERATIONAL USE CASE │
├─────────────────────────┼──────────────────────────────┼──────────────────────────────────────────────────┤
│ shared-iterations │ vus: 10, iterations: 100 │ Fixed number of total iterations shared by VUs │
│ per-vu-iterations │ vus: 10, iterations: 50 │ Each VU executes exact number of iterations │
│ constant-vus │ vus: 50, duration: '2m' │ Flat concurrency load over fixed duration │
│ ramping-vus │ stages: [{ target: 100 }] │ Gradual scaling up and down of virtual users │
│ constant-arrival-rate │ rate: 100, timeUnit: '1s' │ Enforces strict RPS open model (defeats CO) │
│ ramping-arrival-rate │ stages: [{ target: 200 }] │ Smoothly ramps requested arrival rate (RPS) │
│ Trend / Counter / Rate │ new Trend('metric_name') │ Custom telemetry tracking and threshold gating │
│ SharedArray │ new SharedArray('name', fn) │ Memory-optimized immutable CSV/JSON data sharing │
│ handleSummary(data) │ export function handle.. │ Generates HTML dashboards and JSON report files │
│ abortOnFail: true │ threshold: [{ abortOnFail }] │ Halts test immediately if error ceiling breached │
├─────────────────────────┴──────────────────────────────┴──────────────────────────────────────────────────┤
│ TOP 5 K6 LOAD TESTING BEST PRACTICES: │
│ 1. Defeat coordinated omission: Use arrival-rate executors for strict requests-per-second targeting. │
│ 2. Use SharedArray for large datasets: Prevents duplicate JSON/CSV memory allocation per virtual user. │
│ 3. Group and tag metrics: Wrap steps in group() and tag requests to inspect endpoint-specific latency. │
│ 4. Always declare thresholds: Define p(95) and error rate limits so CI/CD pipelines can gate merges. │
│ 5. Clean up with teardown(): Always revoke tokens and delete created test data in teardown(). │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────┘