K6 CODE-BASED LOAD TESTING: SCRIPTING, SCENARIOS & THRESHOLDS

Architect high-concurrency developer-centric load automation: Go-runtime core, ES6 JavaScript test authoring, multi-scenario executors (ramping-arrival-rate, per-vu-iterations), custom Trend & Counter metrics, SLA thresholds, memory-optimized SharedArray datasets, and CI/CD quality gate enforcement.

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

1. k6 Runtime Architecture & Four-Stage Test Lifecycle
Understanding the internal runtime architecture of k6: how Go goroutines execute isolated JavaScript VMs across the init, setup, VU execution, and teardown lifecycles.
k6 Runtime Architecture & Execution Lifecycle Topography
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       │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
Architectural Standard: Code in the 'init' context cannot make HTTP requests. Pre-flight API setup (such as authenticating or generating database fixtures) must execute inside the setup() function, which runs once on a dedicated setup worker before VUs start.
Real-Time Example 1: Full Lifecycle Script (Init, Setup, VU & Teardown)
A complete k6 test script demonstrating all four lifecycle stages, passing shared configuration from setup() to the default function, and executing cleanup in teardown().
JavaScript (scripts/k6_complete_lifecycle.js)
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' },
  });
}
Lifecycle Execution Verification: [*] Initializing Global Test Run: Acquiring Master Auth Token... running (0m30.0s), 10/10 VUs, 270 complete and 0 interrupted iterations default ✓ [======================================] 10 VUs 30s [*] Tearing down performance run for Batch: BATCH-1793524800000 ✓ Master auth token acquired ✓ Catalog status is 200 ✓ Returned students array
Real-Time Example 2: Multi-Scenario Architecture & Advanced Executors
Orchestrating complex, multi-model workloads in a single test using k6 scenarios. Combines a constant arrival-rate workload with a staged ramping-VU profile targeting distinct API endpoints simultaneously.
JavaScript (scripts/k6_multi_scenarios.js)
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);
}
Executor Advantage: Open-model arrival rates (constant-arrival-rate) ensure that even if the backend begins to slow down, k6 continues dispatching 50 requests every second by dynamically scaling VUs up to maxVUs, measuring true latency degradation.
Real-Time Example 3: Defining Custom Telemetry Metrics & Percentile Thresholds
Instrumenting tests with k6 custom metrics: Trend (timings and distributions), Counter (cumulative totals), Rate (success/failure percentages), and Gauge (instantaneous values).
JavaScript (scripts/k6_custom_metrics.js)
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
  }
}
Threshold Summary Output: ✓ waiting_time_enrollment_ms........: p(50)=42ms p(95)=184ms p(99)=312ms [All < Thresholds] ✓ validation_failure_percentage.....: 0.21% [✓ rate<0.05] ✓ total_students_enrolled_count.....: 742 [✓ count>500] ✓ http_req_failed...................: 0.00% [✓ rate<0.02]
Real-Time Example 4: Memory-Efficient Parameterization with SharedArray
Injecting realistic, non-cached datasets from external JSON or CSV files using k6/data.SharedArray. Loads the file into memory once, sharing it across all virtual users with zero heap memory duplication.
JavaScript (scripts/k6_shared_array_param.js)
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,
  });
}
Memory Benchmark: Loading a 10MB CSV with standard JSON.parse() across 500 VUs consumes ~5GB of RAM. Loading the same file via SharedArray consumes ~12MB of RAM total, allowing massive concurrency on single load-generator nodes.
Real-Time Example 5: Correlating Authentication Tokens Across Step Chains
Modeling stateful multi-step user workflows: authenticating, extracting dynamic JWT tokens, passing tokens to create a resource, querying the created entity, and checking out.
JavaScript (scripts/k6_stateful_correlation.js)
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);
}
Group Telemetry: Wrapping steps inside group('name', function(){}) segments k6 summary metrics, reporting separate http_req_duration statistics for 01_User_Authentication, 02_Create_Student_Record, and 03_Verify_Created_Record.
Real-Time Example 6: Generating HTML Reports & Exporting JSON Telemetry
Generating standalone HTML performance dashboards from k6 using handleSummary() and the k6-reporter library, alongside exporting raw JSON metrics for external consumption.
JavaScript & CLI (Custom Summary & HTML Dashboard Export)
// 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
Dashboard Generation Log: Execution finished. Generating report artifacts: Writing HTML report to: reports/performance_summary.html Writing JSON summary to: reports/summary_metrics.json Interactive HTML dashboard contains latency distribution graphs, requests per second timelines, and threshold checks ready for browser viewing.
Real-Time Example 7: CI/CD Performance Regression Gate in GitHub Actions
Automating k6 performance checks in GitHub Actions. Executes during pull request workflows, checks thresholds, archives HTML dashboards, and posts summary tables as PR comments.
YAML (.github/workflows/k6_regression_pipeline.yml)
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
Pipeline Execution Log: ✓ Checkout Source Code (2s) ✓ Setup k6 CLI Engine (1s) ✓ Execute k6 Performance Test Suite (1m 15s) ↳ All 4 thresholds satisfied: p95=142ms (<250ms), errors=0.00% (<1%) ✓ Publish Performance HTML Dashboard (2s) Status: Completed successfully. Quality gate passed; PR approved for merge.
Real-Time Example 8: Stress Testing & Finding Maximum Sustainable Capacity
Designing a stress testing script with gradual stepping stages to identify the exact point where response times degrade and HTTP 5xx errors begin to occur.
JavaScript (scripts/k6_stress_breakpoint.js)
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);
}
Breakpoint Analysis: Setting abortOnFail: true ensures that if the server becomes saturated and errors exceed 10%, k6 aborts execution immediately to protect target infrastructure from persistent crashes.
Real-Time Example 9: k6 Code-Based Load Testing Reference Matrix
A comprehensive reference summary pairing k6 execution options, executors, metric types, CLI commands, and best practices for performance test engineers.
k6 Capabilities & Options Quick Reference Matrix
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().             │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Engineering Best Practice: Adopting k6 allows your team to treat performance testing as code. Storing JavaScript test scripts alongside your application source code, leveraging open-model arrival rates, and enforcing strict threshold gates in CI prevents performance regressions before they reach production.