k6 Carga Testing Cheatsheet¶
Instalación¶
| Platform | Command |
|---|---|
| Ubuntu/Debian | INLINE_CODE_11 |
| RHEL/CentOS/Fedora | INLINE_CODE_12 |
| macOS (Homebrew) | INLINE_CODE_13 |
| macOS (MacPorts) | INLINE_CODE_14 |
| Windows (Chocolatey) | INLINE_CODE_15 |
| Windows (winget) | INLINE_CODE_16 |
| Linux (Snap) | INLINE_CODE_17 |
| Docker | INLINE_CODE_18 |
| Verify Installation | INLINE_CODE_19 |
Comandos básicos¶
| Command | Description |
|---|---|
| INLINE_CODE_20 | Execute a load test script |
| INLINE_CODE_21 | Run test with 10 virtual users |
| INLINE_CODE_22 | Run test for 30 seconds |
| INLINE_CODE_23 | Run with 50 VUs for 5 minutes |
| INLINE_CODE_24 | Run for exactly 1000 iterations total |
| INLINE_CODE_25 | 100 iterations distributed across 10 VUs |
| INLINE_CODE_26 | Display k6 version information |
| INLINE_CODE_27 | Show detailed version and build info |
| INLINE_CODE_28 | Analyze script without executing it |
| INLINE_CODE_29 | Show execution requirements in JSON format |
| INLINE_CODE_30 | Run with ramping stages (ramp up, sustain, ramp down) |
| INLINE_CODE_31 | Enable HTTP request/response debugging |
| INLINE_CODE_32 | Show full HTTP debug including headers and body |
| INLINE_CODE_33 | Disable end-of-test summary |
| INLINE_CODE_34 | Export test summary to JSON file |
Advanced Usage¶
| Command | Description |
|---|---|
| INLINE_CODE_35 | Pass environment variable to test script |
| INLINE_CODE_36 | Pass multiple environment variables |
| INLINE_CODE_37 | Export metrics to JSON file |
| INLINE_CODE_38 | Send metrics to InfluxDB |
| INLINE_CODE_39 | Output to multiple backends simultaneously |
| INLINE_CODE_40 | Export metrics to CSV format |
| INLINE_CODE_41 | Stream results to k6 Cloud (requires authentication) |
| INLINE_CODE_42 | Set pass/fail threshold (95th percentile < 500ms) |
| INLINE_CODE_43 | Multiple thresholds (response time and error rate) |
| INLINE_CODE_44 | Limit requests per second across all VUs |
| INLINE_CODE_45 | Set maximum test duration (hard stop) |
| INLINE_CODE_46 | Allow 30s for VUs to finish current iteration on stop |
| INLINE_CODE_47 | Skip TLS certificate verification (testing only) |
| INLINE_CODE_48 | Set custom User-Agent header |
| INLINE_CODE_49 | Set maximum parallel batch requests per VU |
| INLINE_CODE_50 | Limit parallel requests per host |
| INLINE_CODE_51 | Blacklist IP ranges from being accessed |
| INLINE_CODE_52 | Include only specific system tags in metrics |
| INLINE_CODE_53 | Create test archive with all dependencies |
| INLINE_CODE_54 | Create archive with custom output filename |
| INLINE_CODE_55 | Execute test from archived bundle |
| INLINE_CODE_56 | Execute test in k6 Cloud infrastructure |
| INLINE_CODE_57 | Authenticate with k6 Cloud service |
| INLINE_CODE_58 | Authenticate using API token |
| INLINE_CODE_59 | Run k6 test in Docker with volume mount |
Configuración¶
Configuración de scripts (objeto de opciones)¶
// Basic load test configuration
export let options = {
vus: 10, // Number of virtual users
duration: '30s', // Test duration
iterations: 1000, // Total iterations (alternative to duration)
};
export default function() {
// Test logic here
}
Configuración de etapas (Amplificación)¶
export let options = {
stages: [
{ duration: '2m', target: 10 }, // Ramp up to 10 VUs over 2 minutes
{ duration: '5m', target: 10 }, // Stay at 10 VUs for 5 minutes
{ duration: '2m', target: 50 }, // Ramp up to 50 VUs over 2 minutes
{ duration: '5m', target: 50 }, // Stay at 50 VUs for 5 minutes
{ duration: '2m', target: 0 }, // Ramp down to 0 VUs
],
};
Thresholds Configuration¶
export let options = {
thresholds: {
http_req_duration: ['p(95)<500'], // 95% of requests must complete below 500ms
http_req_failed: ['rate<0.01'], // Error rate must be below 1%
http_reqs: ['rate>100'], // Request rate must be above 100 req/s
checks: ['rate>0.95'], // 95% of checks must pass
'http_req_duration{status:200}': ['p(99)<1000'], // Tagged threshold
},
};
Configuración de escenarios (Advanced)¶
export let options = {
scenarios: {
// Constant VUs scenario
constant_load: {
executor: 'constant-vus',
vus: 10,
duration: '5m',
gracefulStop: '30s',
},
// Ramping VUs scenario
ramping_load: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '2m', target: 50 },
{ duration: '5m', target: 50 },
{ duration: '2m', target: 0 },
],
gracefulRampDown: '30s',
},
// Per-VU iterations
per_vu_iterations: {
executor: 'per-vu-iterations',
vus: 10,
iterations: 100, // Each VU runs 100 iterations
maxDuration: '10m',
},
// Shared iterations
shared_iterations: {
executor: 'shared-iterations',
vus: 10,
iterations: 1000, // 1000 iterations shared across 10 VUs
maxDuration: '10m',
},
// Constant arrival rate
constant_arrival_rate: {
executor: 'constant-arrival-rate',
rate: 100, // 100 iterations per timeUnit
timeUnit: '1s', // per second
duration: '5m',
preAllocatedVUs: 50,
maxVUs: 100,
},
},
};
Environment Variables¶
// Access environment variables in script
import { check } from 'k6';
import http from 'k6/http';
const API_URL = __ENV.API_URL || 'https://default-api.com';
const API_KEY = __ENV.API_KEY;
export default function() {
let response = http.get(`${API_URL}/endpoint`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
check(response, {
'status is 200': (r) => r.status === 200,
});
}
Custom Metrics¶
import { Counter, Gauge, Rate, Trend } from 'k6/metrics';
// Define custom metrics
let myCounter = new Counter('my_custom_counter');
let myGauge = new Gauge('my_custom_gauge');
let myRate = new Rate('my_custom_rate');
let myTrend = new Trend('my_custom_trend');
export default function() {
myCounter.add(1); // Increment counter
myGauge.add(100); // Set gauge value
myRate.add(true); // Add success to rate
myTrend.add(250); // Add value to trend
}
Common Use Cases¶
Use Case: Basic API Load Test¶
# Create a simple test script
cat > api-test.js << 'EOF'
import http from 'k6/http';
import { check, sleep } from 'k6';
export let options = {
vus: 10,
duration: '30s',
};
export default function() {
let response = http.get('https://api.example.com/users');
check(response, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
EOF
# Run the test
k6 run api-test.js
# Run with custom VUs and duration
k6 run --vus 50 --duration 5m api-test.js
Use Case: Spike Testing¶
# Create spike test with sudden load increase
cat > spike-test.js << 'EOF'
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
stages: [
{ duration: '1m', target: 10 }, // Normal load
{ duration: '30s', target: 100 }, // Spike to 100 users
{ duration: '1m', target: 100 }, // Sustain spike
{ duration: '30s', target: 10 }, // Return to normal
{ duration: '1m', target: 10 }, // Recovery
],
thresholds: {
http_req_duration: ['p(95)<2000'], // Relaxed threshold for spike
http_req_failed: ['rate<0.05'], // Allow 5% error rate during spike
},
};
export default function() {
http.get('https://api.example.com/products');
sleep(1);
}
EOF
# Run spike test
k6 run spike-test.js
Caso de uso: API Authentication & Data Posting¶
# Test with authentication and POST requests
cat > auth-test.js << 'EOF'
import http from 'k6/http';
import { check } from 'k6';
export let options = {
vus: 20,
duration: '2m',
};
export default function() {
// Login and get token
let loginRes = http.post('https://api.example.com/auth/login',
JSON.stringify({
username: 'testuser',
password: 'testpass',
}),
{ headers: { 'Content-Type': 'application/json' } }
);
let token = loginRes.json('token');
// Use token for authenticated request
let response = http.post('https://api.example.com/data',
JSON.stringify({ name: 'test', value: 123 }),
{ headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
}}
);
check(response, {
'authenticated request successful': (r) => r.status === 201,
});
}
EOF
# Run with environment variables
k6 run -e USERNAME=myuser -e PASSWORD=mypass auth-test.js
Caso de uso: Prueba de pico (Duración prolongada)¶
# Long-running stability test
cat > soak-test.js << 'EOF'
import http from 'k6/http';
import { check, sleep } from 'k6';
export let options = {
stages: [
{ duration: '5m', target: 20 }, // Ramp up
{ duration: '4h', target: 20 }, // Soak for 4 hours
{ duration: '5m', target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ['p(95)<500', 'p(99)<1000'],
http_req_failed: ['rate<0.01'],
},
};
export default function() {
let response = http.get('https://api.example.com/health');
check(response, {
'status is 200': (r) => r.status === 200,
});
sleep(Math.random() * 5 + 3); // Random sleep 3-8 seconds
}
EOF
# Run soak test with metrics export
k6 run --out json=soak-results.json soak-test.js
Use Case: Multi-Scenario Prueba con diferentes puntos finales¶
# Complex test with multiple user behaviors
cat > multi-scenario.js << 'EOF'
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
scenarios: {
// Scenario 1: Browse products
browsers: {
executor: 'constant-vus',
exec: 'browseProducts',
vus: 30,
duration: '5m',
},
// Scenario 2: Search functionality
searchers: {
executor: 'constant-vus',
exec: 'searchProducts',
vus: 10,
duration: '5m',
},
// Scenario 3: Checkout process
buyers: {
executor: 'constant-arrival-rate',
exec: 'checkoutFlow',
rate: 5,
timeUnit: '1s',
duration: '5m',
preAllocatedVUs: 10,
},
},
};
export function browseProducts() {
http.get('https://shop.example.com/products');
sleep(2);
}
export function searchProducts() {
http.get('https://shop.example.com/search?q=laptop');
sleep(3);
}
export function checkoutFlow() {
http.post('https://shop.example.com/cart/add', { productId: 123 });
sleep(1);
http.post('https://shop.example.com/checkout', { cartId: 456 });
sleep(2);
}
EOF
# Run multi-scenario test
k6 run multi-scenario.js
Buenas prácticas¶
-
Inicie la pequeña escala. Comience con bajos conteos de VU y corta duración para validar su script funciona correctamente antes de realizar pruebas a gran escala. Use
--vus 1 --iterations 1para validación inicial. -
Use Realistic Think Time: Add
sleep()entre solicitudes para simular el comportamiento real del usuario. Los tiempos de sueño aleatorios (__INLINE_CODE_62_) crean patrones más realistas que los intervalos fijos. -
Set Appropriate Thresholds: Definir criterios de pase/fail claros utilizando umbrales. Supervisar ambos tiempos de respuesta (p95, p99) y las tasas de error para captar la degradación del rendimiento temprano.
-
Pruebe sus peticiones: Use etiquetas para agrupar solicitudes relacionadas para un mejor análisis:
http.get(url, { tags: { name: 'user_login' } }). Esto permite filtrar métricas por operaciones específicas. -
Monitor System Resources: Ver CPU, memoria y red tanto en el generador de carga k6 como en el sistema de destino. k6 puede convertirse en un cuello de botella con recursos insuficientes.
-
Use Escenarios para Pruebas Complejos: Escenarios de Leverage en vez de simple VU/duración cuando usted necesita diferentes patrones de carga, múltiples comportamientos de usuario, o control preciso sobre las tasas de solicitud.
-
Metrices de exportación para el análisis: Siempre exportar resultados a sistemas externos (InfluxDB, JSON, CSV) para la comparación histórica y el análisis detallado. El resumen terminal es útil pero limitado.
-
Version Control Your Tests: Almacene scripts de prueba en Git junto con el código de aplicación. Esto permite el seguimiento de los cambios de rendimiento a través de versiones y pruebas en tuberías CI/CD.
-
** Datos separados de los scripts**: Use variables de entorno (
-eflag) o archivos de datos externos para la configuración de pruebas. Esto hace que los scripts sean reutilizables en entornos (dev, estancamiento, producción). -
Del CI/CD Pipelines: Integrar pruebas k6 en su tubería de implementación para capturar regresiones de rendimiento automáticamente. Utilice umbrales para fallar construye cuando el rendimiento se degrada.
Troubleshooting¶
| Issue | Solution |
|---|---|
| High memory usage on load generator | Reduce VUs, use INLINE_CODE_65 to limit concurrent requests, or distribute load across multiple k6 instances. Check for memory leaks in test scripts. |
| "context deadline exceeded" errors | Increase timeout values in HTTP requests: INLINE_CODE_66. Check network connectivity and target system capacity. |
| Inconsistent results between runs | Ensure consistent test environment, use fixed seed for random data, run longer tests for statistical significance, and check for external factors (network, other traffic). |
| TLS/SSL certificate errors | Use INLINE_CODE_67 for testing environments only. For production, ensure proper certificates or use INLINE_CODE_68 and INLINE_CODE_69 for client certificates. |
| Script import errors ("module not found") | Verify module paths, ensure k6 supports the module (limited Node.js compatibility), use k6 archive (INLINE_CODE_70) to bundle dependencies, or use remote modules with full URLs. |
| Rate limiting by target system | Implement proper INLINE_CODE_71 intervals, use INLINE_CODE_72 to limit request rate, distribute requests across multiple IPs, or coordinate with target system owners for testing. |
| Metrics not appearing in output | Check output configuration (INLINE_CODE_73), verify backend connectivity (InfluxDB, Grafana), ensure custom metrics are properly defined, and validate metric names don't conflict with built-ins. |
| Docker container exits immediately | Mount script volume correctly: INLINE_CODE_74. Use INLINE_CODE_75 flag for piping scripts: INLINE_CODE_76. |
| Thresholds failing unexpectedly | Review threshold definitions for typos, check if target system can handle expected load, analyze metrics to understand actual performance, and adjust thresholds to realistic values. |
** El proceso k6 cuelga o no termina** ← Uso --grace-stop para permitir que VUs termine las iteraciones limpiamente, compruebe los bucles infinitos en scripts de prueba, asegure que las dependencias externas (API) sean sensibles, o use --max-duration como parada dura. Silencio |