|

k6 Performance Testing From Zero to Production: A JavaScript Developer’s Complete Guide

k6 is a modern performance testing tool that uses JavaScript (ES6). If JMeter feels like piloting a 747 for a neighborhood flight, k6 is the sports car — lightweight, fast, and developer-friendly.

Contents

Why k6 Over JMeter?

Featurek6JMeter
LanguageJavaScript (ES6)XML/GUI
Startup timeMillisecondsSeconds
CI/CD integrationNativeRequires plugins
Resource usageLightweight (Go binary)Heavy (Java)
ScriptingCode-firstGUI-first
Real-time monitoringGrafana nativeRequires setup

Your First k6 Load Test

import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  stages: [
    { duration: '30s', target: 20 },   // Ramp up to 20 users
    { duration: '1m', target: 20 },    // Stay at 20 for 1 minute
    { duration: '10s', target: 0 },    // Ramp down
  ],
  thresholds: {
    http_req_duration: ['p(95)<500'],  // 95% of requests under 500ms
    http_req_failed: ['rate<0.01'],    // Less than 1% failures
  },
};

export default function () {
  const res = http.get('https://api.example.com/products');
  
  check(res, {
    'status is 200': (r) => r.status === 200,
    'response time OK': (r) => r.timings.duration < 500,
    'has products': (r) => JSON.parse(r.body).length > 0,
  });
  
  sleep(1);
}

Test Types with k6

// STRESS TEST - find the breaking point
export const options = {
  stages: [
    { duration: '2m', target: 100 },
    { duration: '5m', target: 100 },
    { duration: '2m', target: 200 },
    { duration: '5m', target: 200 },
    { duration: '2m', target: 300 },  // Push beyond expected load
    { duration: '5m', target: 300 },
    { duration: '2m', target: 0 },
  ],
};

// SPIKE TEST - sudden traffic surge
export const options = {
  stages: [
    { duration: '10s', target: 100 },   // Normal
    { duration: '1m', target: 100 },
    { duration: '10s', target: 1400 },   // SPIKE!
    { duration: '3m', target: 1400 },
    { duration: '10s', target: 100 },    // Recovery
    { duration: '3m', target: 100 },
    { duration: '10s', target: 0 },
  ],
};

k6 in GitHub Actions

name: Performance Tests
on:
  schedule:
    - cron: '0 2 * * *'  # Nightly at 2 AM

jobs:
  load-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: grafana/setup-k6-action@v1
      - run: k6 run tests/load-test.js --out json=results.json
      - uses: actions/upload-artifact@v4
        with:
          name: k6-results
          path: results.json

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.