k6 부하테스트 [팔복소프트]
\n\n
📌 k6란 무엇인가?
Grafana k6는 Grafana에서 제공하는 오픈소스 부하 테스트 도구로,
서버의 성능과 안정성을 검증하기 위해 사용된다.
간단히 말하면,
👉 여러 명의 사용자가 동시에 접속하는 상황을 가짜로 만들어서
👉 서버가 얼마나 버틸 수 있는지 확인하는 도구다.
🚀 왜 k6를 사용하는가?
실제 서비스에서는 다음과 같은 상황이 자주 발생한다.
이벤트로 인해 갑자기 트래픽이 몰리는 경우
특정 기능(API)이 병목이 되는 경우
서버가 언제 터지는지 미리 알고 싶은 경우
이때 k6를 사용하면
👉 실서비스 전에 미리 부하를 걸어보고 문제를 발견할 수 있다.
⚡ k6의 특징
k6는 기존 부하 테스트 도구들과 비교했을 때 몇 가지 장점이 있다.
1. JavaScript 기반
테스트 코드를 JavaScript로 작성할 수 있어서
👉 백엔드 개발자라면 매우 쉽게 사용할 수 있다.
2. 빠르고 가벼움
Go로 만들어져 있어서 실행 속도가 빠르고
설치도 매우 간단하다.
3. 다양한 시나리오 지원
단순 반복 요청뿐만 아니라
동시 사용자 테스트 (VU 기반)
초당 요청 수 기반 테스트 (RPS/TPS)
점진적 부하 증가 테스트 (Ramp-up)
스파이크 테스트
👉 다양한 상황을 실제처럼 재현할 수 있다.
📌 k6 설치 방법 (https://grafana.com/docs/k6/latest/set-up/install-k6/)
Grafana k6는 다양한 환경에서 간단하게 설치할 수 있다.
운영체제별로 설치 방법을 정리해보면 다음과 같다.
🐧 Linux
✅ Debian / Ubuntu
sudo gpg -k
sudo gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg \
--keyserver hkp://keyserver.ubuntu.com:80 \
--recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69
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-get update
sudo apt-get install k6
✅ Fedora / CentOS
sudo dnf install https://dl.k6.io/rpm/repo.rpm
sudo dnf install k6
CentOS 구버전에서는 yum을 사용할 수도 있다.
🍎 macOS
✅ Homebrew 사용
brew install k6
👉 가장 간단한 방법이며, Mac 사용자에게 추천
🪟 Windows
✅ Chocolatey 사용
choco install k6
✅ winget 사용 (공식 패키지)
winget install k6 --source winget
✅ 설치 파일 직접 다운로드
👉 공식 설치 프로그램을 다운로드해서 실행하는 방법도 가능하다.
🐳 Docker
✅ 기본 이미지
docker pull grafana/k6
✅ 브라우저 테스트 포함 이미지
docker pull grafana/k6:master-with-browser
👉 k6 browser 기능을 사용할 경우 필요
✅ 설치 확인
설치가 완료되면 아래 명령어로 정상 설치 여부를 확인할 수 있다.
k6 version
📌 예제 1
http
get, post, put, del 예제
공식문서 링크 : https://grafana.com/docs/k6/latest/javascript-api/k6-http/
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
vus: 10, // 동시 사용자 10명
duration: '10s' // 10초 동안 테스트
};
export default function () {
// GET 요청
http.get('https://test.k6.io');
// POST 요청
let res = http.post('https://test.k6.io/login', JSON.stringify({
username: 'test',
password: '1234',
}));
console.log(res.json().json.name); // Bert
// PUT 요청
http.put('https://test.k6.io/user/1', JSON.stringify({
name: 'kim',
age: 30,
}), {
headers: { 'Content-Type': 'application/json' },
});
// DELETE 요청
http.del('https://test.k6.io/user/1');
sleep(1);
}
📌 예제 2
- Shared iterations
🔹 개요
shared-iterations는 전체 iteration 수를 VU들이 나눠서 처리하는 방식이다.
즉, 총 요청 수가 고정된 테스트에 적합하다.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
discardResponseBodies: true,
scenarios: {
contacts: {
executor: 'shared-iterations',
vus: 10,
iterations: 200,
maxDuration: '30s',
},
},
};
export default function () {
http.get('https://test.k6.io/contacts.php');
// Injecting sleep
// Sleep time is 500ms. Total iteration time is sleep + time to finish request.
sleep(0.5);
}
🔹 주요 옵션 설명
옵션 설명
executor 실행 방식 (shared-iterations)
vus 동시에 실행되는 가상 사용자 수 (10명)
iterations 전체 실행 횟수 (200번)
maxDuration 최대 실행 시간 (30초)
discardResponseBodies 응답 body를 버려 메모리 절약
🔹 동작 방식
총 200번의 요청(iterations)을
10명의 VU가 나눠서 처리
각 VU가 처리하는 횟수는 균등하지 않을 수 있음
먼저 끝난 VU가 남은 작업을 이어서 수행
📌 예제 3
- Per VU iterations
🔹 개요
per-vu-iterations는
각 VU가 동일한 횟수만큼 반복 수행하는 방식이다.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
discardResponseBodies: true,
scenarios: {
contacts: {
executor: 'per-vu-iterations',
vus: 10,
iterations: 20,
maxDuration: '30s',
},
},
};
export default function () {
http.get('https://test.k6.io/contacts.php');
// Injecting sleep
// Sleep time is 500ms. Total iteration time is sleep + time to finish request.
sleep(0.5);
}
🔹 동작 방식
VU 1 → 20회
VU 2 → 20회
...
VU 10 → 20회
👉 총 요청 수 = 10 × 20 = 200회
📌 예제 4
🔹 개요
constant-vus는
일정한 수의 VU를 유지하면서 계속 요청을 보내는 방식이다.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
discardResponseBodies: true,
scenarios: {
contacts: {
executor: 'constant-vus',
vus: 10,
duration: '30s',
},
},
};
export default function () {
http.get('https://test.k6.io/contacts.php');
// Injecting sleep
// Total iteration time is sleep + time to finish request.
sleep(0.5);
}
🔹 동작 방식
10명의 VU가
30초 동안 계속 반복 요청 수행
👉 요청 수는 정해져 있지 않음 (시간 기반)
📌 예제 5
🔹 개요
ramping-vus는
시간에 따라 사용자(VU)를 점진적으로 늘리고 줄이는 방식이다.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
discardResponseBodies: true,
scenarios: {
contacts: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '20s', target: 10 },
{ duration: '10s', target: 0 },
],
gracefulRampDown: '0s',
},
},
};
export default function () {
http.get('https://test.k6.io/contacts.php');
// Injecting sleep
// Sleep time is 500ms. Total iteration time is sleep + time to finish request.
sleep(0.5);
}
🔹 동작 방식
0 → 10명까지 20초 동안 증가
10 → 0명까지 10초 동안 감소
🔹 특징
✅ 트래픽 증가/감소 테스트 가능
✅ 시스템 한계 구간 파악 가능
❌ 테스트 결과 해석이 상대적으로 복잡
📌 예제 6
- Constant arrival rate
🔹 개요
constant-arrival-rate는
초당 요청 수(TPS)를 일정하게 유지하는 방식이다.
import http from 'k6/http';
export const options = {
discardResponseBodies: true,
scenarios: {
contacts: {
executor: 'constant-arrival-rate',
// How long the test lasts
duration: '30s',
// How many iterations per timeUnit
rate: 30,
// Start `rate` iterations per second
timeUnit: '1s',
// Pre-allocate 2 VUs before starting the test
preAllocatedVUs: 2,
// Spin up a maximum of 50 VUs to sustain the defined
// constant arrival rate.
maxVUs: 50,
},
},
};
export default function () {
http.get('https://test.k6.io/contacts.php');
}
🔹 동작 방식
1초에 30개의 요청을 지속적으로 발생
부족하면 VU를 자동으로 늘려서 맞춤
👉 핵심:
VU가 아니라 “요청 속도”가 기준
🔹 특징
✅ TPS(초당 처리량) 정확하게 제어
✅ 실제 트래픽과 가장 유사
✅ VU 자동 스케일링
❌ 설정 이해 난이도 있음
📌 예제 7
- Ramping arrival rate
🔹 개요
ramping-arrival-rate는
TPS(요청 수)를 시간에 따라 증가/감소시키는 방식이다.
import http from 'k6/http';
export const options = {
discardResponseBodies: true,
scenarios: {
contacts: {
executor: 'ramping-arrival-rate',
// Start iterations per `timeUnit`
startRate: 300,
// Start `startRate` iterations per minute
timeUnit: '1m',
// Pre-allocate necessary VUs.
preAllocatedVUs: 50,
stages: [
// Start 300 iterations per `timeUnit` for the first minute.
{ target: 300, duration: '1m' },
// Linearly ramp-up to starting 600 iterations per `timeUnit` over the following two minutes.
{ target: 600, duration: '2m' },
// Continue starting 600 iterations per `timeUnit` for the following four minutes.
{ target: 600, duration: '4m' },
// Linearly ramp-down to starting 60 iterations per `timeUnit` over the last two minutes.
{ target: 60, duration: '2m' },
],
},
},
};
export default function () {
http.get('https://test.k6.io/contacts.php');
}
🔹 동작 방식
1분 동안 → 분당 300 요청 유지
2분 동안 → 300 → 600으로 증가
4분 동안 → 600 유지
2분 동안 → 600 → 60으로 감소
👉 요청 수(TPS)가 시간에 따라 변화
🔹 특징
✅ TPS 기반 + 트래픽 변화 반영
✅ 실제 서비스 패턴과 가장 유사
✅ VU 자동 스케일링
❌ 설정 난이도 높음
공식 사이트 : https://k6.io/
설치 방법 : https://grafana.com/docs/k6/latest/set-up/install-k6/
http 문서: https://grafana.com/docs/k6/latest/javascript-api/k6-http/
시나리오 문서 : https://grafana.com/docs/k6/latest/using-k6/scenarios/executors/