K6 Load Testing Tool – Installation and Sample Test Scripts
Introduction
K6 is an open-source load testing tool used to test the performance and stability of APIs, websites, and applications.
It is lightweight, developer-friendly, and uses JavaScript for writing test scripts.
K6 helps to:
- Test API performance
- Simulate multiple users
- Identify bottlenecks
- Measure response times
- Validate application scalability
Prerequisites
Before installing K6, ensure the following requirements are available:
- Linux / Windows / macOS server
- Internet connection
- Basic terminal knowledge
- Access to the application or API
Example test target:
https://example.com
Implementation
I. K6 Installation
(i) Install K6 on Ubuntu / Debian
sudo apt update sudo apt install -y gnupg software-properties-common curl -fsSL https://dl.k6.io/key.gpg | sudo gpg --dearmor -o /usr/share/keyrings/k6-archive-keyring.gpg echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main" | sudo tee /etc/apt/sources.list.d/k6.list sudo apt update sudo apt install k6 -y
(ii) Verify Installation
k6 version
Example output:
k6 v0.48.0
II. Basic K6 Test Script
Create a file:
test.js
Add the following script:
import http from 'k6/http';
import { sleep } from 'k6';
export default function () {
http.get('https://example.com');
sleep(1);
}III. Run the Test
k6 run test.js
IV. API Load Test Example
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10,
duration: '30s',
};
export default function () {
let response = http.get('https://example.com/api/users');
check(response, {
'status is 200': (r) => r.status === 200,
});
sleep(1);
}V. POST Request Example
import http from 'k6/http';
export default function () {
const payload = JSON.stringify({
username: 'testuser',
password: 'password123'
});
const params = {
headers: {
'Content-Type': 'application/json',
},
};
http.post('https://example.com/api/login', payload, params);
}VI. Stress Test Example
import http from 'k6/http';
export const options = {
stages: [
{ duration: '30s', target: 20 },
{ duration: '1m', target: 100 },
{ duration: '30s', target: 0 },
],
};
export default function () {
http.get('https://example.com');
}VII. Save Test Results
k6 run test.js --out json=result.json
VIII. Generate HTML Report
k6 run test.js --summary-export=summary.json
Notes
| Metric | Description |
|---|---|
| http_req_duration | API response time |
| http_req_failed | Failed requests |
| vus | Virtual users |
| iterations | Total requests executed |
| checks | Validation results |
IX. Advantages of K6
- Easy JavaScript scripting
- Lightweight and fast
- Supports API and website testing
- Good CLI output
- Supports CI/CD integration
- Open-source
Conclusion
K6 is a simple and powerful load testing tool for testing APIs and web applications.
It allows teams to simulate user traffic, monitor application performance, and identify issues before production deployment.
