Load Test Script Generator
Generates realistic, production-equivalent load testing scripts for k6, Locust, or JMeter from OpenAPI specifications, recorded HTTP traffic, or natural-language descriptions — including ramp-up profiles, realistic think times, authentication, and meaningful assertions.
When to Use
- User asks to "create load tests", "write a k6 script", or "simulate traffic"
- API capacity or breaking point needs to be determined before a launch
- Performance SLAs need to be verified (p99 latency < 200ms, 1000 RPS target)
- A deployment change may impact performance and regression testing is needed
- User provides an OpenAPI spec and wants load tests generated for all endpoints
- Production traffic patterns need to be replayed or simulated
Process
Identify the target tool from context or recommend:
- k6 (default for most cases): JavaScript DSL, great for developers, excellent CI integration, detailed metrics
- Locust: Python, highly customizable, good for complex user flow simulation
- JMeter: Java GUI + XML DSL, enterprise standard, extensive protocol support
- Artillery: JavaScript/YAML, simpler scenarios, good for API testing
Gather test parameters:
- Target base URL and authentication method (API key, Bearer token, Basic auth)
- Target RPS or virtual user (VU) count
- Test duration and ramp-up profile
- Acceptable thresholds: P95/P99 latency, error rate, throughput
- Specific endpoints or user flows to test
Parse the input (OpenAPI spec, HAR file, curl commands, or description):
- Extract endpoints, methods, path/query parameters, and request body schemas
- Identify required headers and authentication
- Note endpoints with different load characteristics (read-heavy vs. write-heavy)
Design the load profile (ramp-up → steady state → scale-down):
- Smoke test: 1–5 VUs for 30s to verify the script works
- Load test: ramp to target load, hold for 5–10 minutes, ramp down
- Stress test: gradually increase beyond target until error rate spikes
- Spike test: sudden burst to 10× normal load for 1 minute
- Soak test: target load for 1–4 hours to detect memory leaks or degradation
Add realistic behavior:
- Think time:
sleep(Math.random() * 2 + 1) between requests (1–3s)
- Data variation: parameterize requests with a data set (user IDs, search terms)
- Session simulation: login, perform actions, logout (realistic user flow)
- Correlation: extract tokens/IDs from responses and use in subsequent requests
Add assertions/checks:
- HTTP status code is as expected (200, 201, etc.)
- Response body contains expected fields
- Response time under threshold
- Define
thresholds that cause the test to fail if SLAs are breached
Add parameterization so the script can be run for different environments/load levels via env vars.
Output Format
k6 Script
// load-tests/api.k6.js
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';
// Custom metrics
const errorRate = new Rate('errors');
const productLatency = new Trend('product_request_duration');
// Test configuration — override with K6_VUS, K6_DURATION env vars
export const options = {
stages: [
{ duration: '1m', target: 10 }, // Ramp up to 10 VUs over 1 minute
{ duration: '5m', target: 50 }, // Ramp up to target load
{ duration: '10m', target: 50 }, // Hold at target load
{ duration: '2m', target: 0 }, // Ramp down
],
thresholds: {
http_req_failed: ['rate<0.01'], // Error rate < 1%
http_req_duration: ['p(95)<500'], // 95th percentile < 500ms
http_req_duration: ['p(99)<1000'], // 99th percentile < 1s
},
};
const BASE_URL = __ENV.BASE_URL || 'https://api.example.com';
const API_KEY = __ENV.API_KEY;
// Test data — rotate through to simulate realistic access patterns
const TEST_PRODUCT_IDS = ['prod_001', 'prod_002', 'prod_003', 'prod_004', 'prod_005'];
export default function () {
const productId = TEST_PRODUCT_IDS[Math.floor(Math.random() * TEST_PRODUCT_IDS.length)];
// GET /products/:id
const res = http.get(`${BASE_URL}/products/${productId}`, {
headers: { 'X-API-Key': API_KEY, 'Content-Type': 'application/json' },
});
productLatency.add(res.timings.duration);
errorRate.add(res.status !== 200);
check(res, {
'status is 200': (r) => r.status === 200,
'has product id': (r) => r.json('id') === productId,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(Math.random() * 2 + 1); // 1-3 second think time
}
Examples
Example Input
Generate k6 load tests for our checkout API:
POST /api/orders — create order (authenticated, JWT Bearer)
GET /api/orders/:id — fetch order status
Target: 200 concurrent users, p99 latency < 1s, error rate < 0.5%
Example Output (summary)
load-tests/checkout.k6.js
Stages:
0–2 min: ramp 0→200 VUs
2–12 min: hold at 200 VUs
12–14 min: ramp 200→0 VUs
User flow per VU:
1. POST /api/orders (with randomized order data from 100-item dataset)
2. Extract orderId from response
3. GET /api/orders/:orderId (using correlated ID from step 1)
4. sleep(1-3s)
Thresholds (test fails if breached):
http_req_failed < 0.5%
http_req_duration p(99) < 1000ms
Run commands:
# Smoke test
k6 run --vus 2 --duration 30s load-tests/checkout.k6.js
# Full load test
BASE_URL=https://staging.api.example.com \
JWT_TOKEN=$TOKEN \
k6 run load-tests/checkout.k6.js
Boundaries
- Do NOT run load tests against production without explicit confirmation — always default to a staging/test environment.
- Do NOT hardcode authentication tokens in script files — always read from environment variables.
- Do NOT generate tests that create unrealistic traffic patterns (e.g., 0 think time, all identical requests) — real-world variance is essential.
- Do NOT set thresholds so loose that the test never fails — thresholds should reflect actual SLA requirements.
- Warn if the OpenAPI spec contains endpoints that mutate shared data (user creation, payment processing) — these require careful data isolation to avoid corrupting test/staging environments.
- Do NOT generate JMeter XML without noting that it requires JMeter to be installed and cannot be easily reviewed as code.
1---2name: load-test-script-generator3description: Generates load testing scripts for k6, Locust, or JMeter from an OpenAPI spec or recorded traffic, including ramp-up scenarios. Invoke when asked to create load tests, write performance tests, generate k6 scripts, simulate traffic, or test API capacity.4---56# Load Test Script Generator78Generates realistic, production-equivalent load testing scripts for k6, Locust, or JMeter from OpenAPI specifications, recorded HTTP traffic, or natural-language descriptions — including ramp-up profiles, realistic think times, authentication, and meaningful assertions.910## When to Use1112- User asks to "create load tests", "write a k6 script", or "simulate traffic"13- API capacity or breaking point needs to be determined before a launch14- Performance SLAs need to be verified (p99 latency < 200ms, 1000 RPS target)15- A deployment change may impact performance and regression testing is needed16- User provides an OpenAPI spec and wants load tests generated for all endpoints17- Production traffic patterns need to be replayed or simulated1819## Process20211. **Identify the target tool** from context or recommend:22 - **k6** (default for most cases): JavaScript DSL, great for developers, excellent CI integration, detailed metrics23 - **Locust**: Python, highly customizable, good for complex user flow simulation24 - **JMeter**: Java GUI + XML DSL, enterprise standard, extensive protocol support25 - **Artillery**: JavaScript/YAML, simpler scenarios, good for API testing26272. **Gather test parameters**:28 - Target base URL and authentication method (API key, Bearer token, Basic auth)29 - Target RPS or virtual user (VU) count30 - Test duration and ramp-up profile31 - Acceptable thresholds: P95/P99 latency, error rate, throughput32 - Specific endpoints or user flows to test33343. **Parse the input** (OpenAPI spec, HAR file, curl commands, or description):35 - Extract endpoints, methods, path/query parameters, and request body schemas36 - Identify required headers and authentication37 - Note endpoints with different load characteristics (read-heavy vs. write-heavy)38394. **Design the load profile** (ramp-up → steady state → scale-down):40 - **Smoke test**: 1–5 VUs for 30s to verify the script works41 - **Load test**: ramp to target load, hold for 5–10 minutes, ramp down42 - **Stress test**: gradually increase beyond target until error rate spikes43 - **Spike test**: sudden burst to 10× normal load for 1 minute44 - **Soak test**: target load for 1–4 hours to detect memory leaks or degradation45465. **Add realistic behavior**:47 - **Think time**: `sleep(Math.random() * 2 + 1)` between requests (1–3s)48 - **Data variation**: parameterize requests with a data set (user IDs, search terms)49 - **Session simulation**: login, perform actions, logout (realistic user flow)50 - **Correlation**: extract tokens/IDs from responses and use in subsequent requests51526. **Add assertions/checks**:53 - HTTP status code is as expected (200, 201, etc.)54 - Response body contains expected fields55 - Response time under threshold56 - Define `thresholds` that cause the test to fail if SLAs are breached57587. **Add parameterization** so the script can be run for different environments/load levels via env vars.5960## Output Format6162### k6 Script63```javascript64// load-tests/api.k6.js65import http from 'k6/http';66import { check, sleep } from 'k6';67import { Rate, Trend } from 'k6/metrics';6869// Custom metrics70const errorRate = new Rate('errors');71const productLatency = new Trend('product_request_duration');7273// Test configuration — override with K6_VUS, K6_DURATION env vars74export const options = {75 stages: [76 { duration: '1m', target: 10 }, // Ramp up to 10 VUs over 1 minute77 { duration: '5m', target: 50 }, // Ramp up to target load78 { duration: '10m', target: 50 }, // Hold at target load79 { duration: '2m', target: 0 }, // Ramp down80 ],81 thresholds: {82 http_req_failed: ['rate<0.01'], // Error rate < 1%83 http_req_duration: ['p(95)<500'], // 95th percentile < 500ms84 http_req_duration: ['p(99)<1000'], // 99th percentile < 1s85 },86};8788const BASE_URL = __ENV.BASE_URL || 'https://api.example.com';89const API_KEY = __ENV.API_KEY;9091// Test data — rotate through to simulate realistic access patterns92const TEST_PRODUCT_IDS = ['prod_001', 'prod_002', 'prod_003', 'prod_004', 'prod_005'];9394export default function () {95 const productId = TEST_PRODUCT_IDS[Math.floor(Math.random() * TEST_PRODUCT_IDS.length)];9697 // GET /products/:id98 const res = http.get(`${BASE_URL}/products/${productId}`, {99 headers: { 'X-API-Key': API_KEY, 'Content-Type': 'application/json' },100 });101102 productLatency.add(res.timings.duration);103 errorRate.add(res.status !== 200);104105 check(res, {106 'status is 200': (r) => r.status === 200,107 'has product id': (r) => r.json('id') === productId,108 'response time < 500ms': (r) => r.timings.duration < 500,109 });110111 sleep(Math.random() * 2 + 1); // 1-3 second think time112}113```114115## Examples116117### Example Input118```119Generate k6 load tests for our checkout API:120POST /api/orders — create order (authenticated, JWT Bearer)121GET /api/orders/:id — fetch order status122Target: 200 concurrent users, p99 latency < 1s, error rate < 0.5%123```124125### Example Output (summary)126```127load-tests/checkout.k6.js128129Stages:130 0–2 min: ramp 0→200 VUs131 2–12 min: hold at 200 VUs132 12–14 min: ramp 200→0 VUs133134User flow per VU:135 1. POST /api/orders (with randomized order data from 100-item dataset)136 2. Extract orderId from response137 3. GET /api/orders/:orderId (using correlated ID from step 1)138 4. sleep(1-3s)139140Thresholds (test fails if breached):141 http_req_failed < 0.5%142 http_req_duration p(99) < 1000ms143144Run commands:145 # Smoke test146 k6 run --vus 2 --duration 30s load-tests/checkout.k6.js147148 # Full load test149 BASE_URL=https://staging.api.example.com \150 JWT_TOKEN=$TOKEN \151 k6 run load-tests/checkout.k6.js152```153154## Boundaries155156- Do NOT run load tests against production without explicit confirmation — always default to a staging/test environment.157- Do NOT hardcode authentication tokens in script files — always read from environment variables.158- Do NOT generate tests that create unrealistic traffic patterns (e.g., 0 think time, all identical requests) — real-world variance is essential.159- Do NOT set thresholds so loose that the test never fails — thresholds should reflect actual SLA requirements.160- Warn if the OpenAPI spec contains endpoints that mutate shared data (user creation, payment processing) — these require careful data isolation to avoid corrupting test/staging environments.161- Do NOT generate JMeter XML without noting that it requires JMeter to be installed and cannot be easily reviewed as code.