Skip to content

Generate a k6 Load Test Script with AI

Performance TestingUpdated 2026-10-21intermediate
TL;DR

Reads an endpoint description and returns a ready-to-run k6 script with `options.scenarios` (ramping-arrival-rate), thresholds for p95/p99/error rate, realistic think times, and a `handleSummary()` for exporting to Grafana / InfluxDB or k6 Cloud.

When to use it

  • Adding a new endpoint to your load test suite.
  • Migrating from JMeter or Locust to k6 for one or many endpoints.
  • Bootstrapping load tests from an OpenAPI spec.
  • Onboarding engineers to k6: the script is annotated for learning.

The prompt

XML-tagged: works best with Claude
k6-script-generator.claude.mdprompt
<role>You are a k6 specialist. You use modern k6 patterns: scenarios with executor, thresholds on percentiles + error rate, handleSummary() for output, check() inside requests. You reject the old "flat VUs + duration" pattern.</role> <context>k6 v1.x recommends scenarios for any non-trivial test. Use `ramping-arrival-rate` for RPS targets, `ramping-vus` for VU-based loads. Thresholds belong in `options.thresholds`, NOT inline in check(). Always implement `handleSummary()` for exporting (default text output is unstructured).</context> <task>For the endpoint below, generate a k6 script that includes:1. `options.scenarios` block with the requested profile (ramp, spike, or steady)2. `options.thresholds` for p95, p99, and error rate3. The HTTP request with realistic headers (Content-Type, Authorization placeholder)4. `check()` inside the request body for status + payload sanity5. Pacing that fits the executor: `sleep()` with jitter for VU-based executors; NO sleep for arrival-rate executors (the executor sets the pace, and sleep only burns VUs)6. `handleSummary()` exporting JSON + a brief text summary</task> <input>Endpoint description (method, URL, payload): {endpoint}Load profile (steady, ramp, spike, soak): {profile}Target RPS or VUs: {target}SLA thresholds (p95, p99, error rate): {sla}</input> <constraints>- k6 v1.0+ syntax: scenarios block, NOT flat VUs.- Thresholds in options block, not inline.- handleSummary() is MANDATORY.- Think time: `sleep(jitter)` with random variation (1-3s default) only in VU-based executors. Arrival-rate executors get no sleep; size `maxVUs` ≈ target RPS × p99 latency in seconds × 1.5, or k6 drops iterations.- Custom `Rate` metrics must record every iteration (`rate.add(!ok)`), not only failures; otherwise the rate reads 100%.- No `http.get('/some/url')` without options: always include headers.- Add SharedArray for any test data (don't load JSON inline).</constraints> <output_format>A single TypeScript/JavaScript code block with the full k6 script. Followed by a "Running it" section with: the exact `k6 run` command, expected output snippet, and 2-3 bullets on how to feed results to Grafana / k6 Cloud.</output_format> <approach>Before writing, decide which scenarios executor matches the requested profile.</approach>

Example

Input
Endpoint description: POST /api/orders. Body: { customerId: string, items: [{ sku: string, qty: number }] }. Requires Authorization: Bearer header.
Load profile: ramp to 500 RPS over 5 min, hold 20 min, ramp down.
Target RPS: 500 sustained, 2000 peak (separate spike test).
SLA: p95 < 800ms, p99 < 2000ms, error rate < 0.5%
Output
```javascript
import http from 'k6/http';
import { check } from 'k6';
import { SharedArray } from 'k6/data';
import { Rate, Trend } from 'k6/metrics';

const errorRate = new Rate('errors');
const checkoutLatency = new Trend('checkout_latency_ms');

const customers = new SharedArray('customers', () =>
  JSON.parse(open('./fixtures/customers.json'))
);

export const options = {
  scenarios: {
    sustained_load: {
      executor: 'ramping-arrival-rate',
      startRate: 50,
      timeUnit: '1s',
      preAllocatedVUs: 200,
      maxVUs: 1000,
      stages: [
        { target: 500, duration: '5m' },
        { target: 500, duration: '20m' },
        { target: 0, duration: '2m' },
      ],
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<800', 'p(99)<2000'],
    http_req_failed: ['rate<0.005'],
    errors: ['rate<0.005'],
  },
};

const BASE_URL = __ENV.BASE_URL || 'https://api.staging.example.com';
const TOKEN = __ENV.AUTH_TOKEN || '';

export default function () {
  const customer = customers[Math.floor(Math.random() * customers.length)];
  const payload = JSON.stringify({
    customerId: customer.id,
    items: [
      { sku: customer.preferredSku, qty: 1 },
      { sku: 'SKU-WIDGET', qty: 2 },
    ],
  });

  const res = http.post(`${BASE_URL}/api/orders`, payload, {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${TOKEN}`,
    },
    tags: { name: 'POST /api/orders' },
  });
  checkoutLatency.add(res.timings.duration);

  const ok = check(res, {
    'status 201': (r) => r.status === 201,
    'has order id': (r) => {
      try {
        return Boolean(JSON.parse(r.body).id);
      } catch {
        return false;
      }
    },
  });

  // Record every iteration: add(1) only on failure would make the rate 100%.
  errorRate.add(!ok);
  // No sleep(): ramping-arrival-rate sets the pace; sleeping here only ties up VUs.
}

export function handleSummary(data) {
  return {
    'summary.json': JSON.stringify(data, null, 2),
    stdout: `
=== Run summary ===
Total requests: ${data.metrics.http_reqs.values.count}
p95 duration:   ${data.metrics.http_req_duration.values['p(95)'].toFixed(0)}ms
p99 duration:   ${data.metrics.http_req_duration.values['p(99)'].toFixed(0)}ms
Failure rate:   ${(data.metrics.http_req_failed.values.rate * 100).toFixed(2)}%
`,
  };
}
```

## Running it

```
k6 run --env BASE_URL=https://api.staging.example.com --env AUTH_TOKEN=$STAGING_BEARER orders.k6.js
```

Expected output: thresholds reported pass/fail at the end. Run produces `summary.json` for downstream tooling.

- **Grafana / InfluxDB**: add `--out influxdb=http://influxdb:8086/k6` to stream metrics live for dashboarding.
- **Grafana Cloud k6**: `k6 cloud run orders.k6.js` to run distributed and get cloud dashboards.
- **Prometheus remote write**: `k6 run --out experimental-prometheus-rw orders.k6.js` (k6 v1.0+).

Common pitfalls

  • Model uses old VUs+duration syntax instead of scenarios: re-prompt with an explicit k6 v1.x reminder.
  • Model adds `sleep()` to an arrival-rate scenario: each VU then handles fewer requests and k6 runs out of VUs before reaching the target RPS (watch for `dropped_iterations`).
  • Thresholds get embedded in check() instead of options.thresholds: they have different semantics. Demand options.thresholds for SLA gates.
  • handleSummary gets omitted; default output is hard to consume downstream.
  • Test data loaded inline as a literal array: fine for trivial cases, kills the script at scale. Use SharedArray for any non-trivial data.

Tips

  • Always parameterize BASE_URL and AUTH_TOKEN via env vars; never commit creds.
  • Add `tags` to requests so you can slice the dashboard by endpoint when you have multiple.
  • Run with `--summary-trend-stats=avg,min,med,max,p(95),p(99),p(99.9)` for fuller percentile coverage.
  • Pair with `design-load-test-strategy` to ensure the script's profile matches your overall strategy.

FAQ

k6 Cloud vs self-hosted?

Cloud: faster setup, dashboards included, distributed runs out of the box, $$$. Self-hosted: free but you wire Grafana yourself and run k6 from your own infra. Most teams should start with self-hosted + InfluxDB; move to Cloud when distributed runs become necessary.

Integrating with CI?

Run k6 as a GitHub Actions / GitLab CI step on every PR. Let handleSummary() write summary.json and upload it as an artifact; k6 exits non-zero when a threshold fails. Block merge if thresholds fail.

When to use SharedArray?

Always for any test data larger than ~10 items. SharedArray parses the data once and shares one read-only copy across all VUs; without it, every VU holds its own copy, which kills memory at high VU counts.

k6 vs Artillery vs JMeter in 2026?

k6 has won for code-first load testing. Artillery still common in Node-first shops. JMeter dominates legacy/enterprise. Pick k6 for new work unless your team has deep JMeter institutional knowledge.