-
Notifications
You must be signed in to change notification settings - Fork 0
feat: k6 부하테스트 스크립트 및 Grafana 대시보드 추가 #93
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
1,247 changes: 1,247 additions & 0 deletions
1,247
grafana/provisioning/dashboards/catcheat-backend-dashboard.json
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| /** | ||
| * 매장 조회 부하테스트 | ||
| * 실행: k6 run k6/01-store-browse.js | ||
| * | ||
| * 테스트 항목: | ||
| * - GET /stores (목록 + 필터) | ||
| * - GET /stores/popular (인기 매장) | ||
| * - GET /stores/nearby (PostGIS 거리 계산) | ||
| * - GET /stores/in-bounds (지도 영역 조회) | ||
| * - GET /stores/{id} (상세) | ||
| * - GET /remains (시간대별 좌석) | ||
| */ | ||
| import http from 'k6/http'; | ||
| import { sleep, check, group } from 'k6'; | ||
| import { Trend } from 'k6/metrics'; | ||
| import { BASE_URL, HEADERS_JSON, THRESHOLDS } from './config.js'; | ||
|
|
||
| const nearbyDuration = new Trend('nearby_duration', true); | ||
| const inBoundsDuration = new Trend('in_bounds_duration', true); | ||
|
|
||
| export const options = { | ||
| scenarios: { | ||
| // 단계적으로 부하 증가 → 유지 → 감소 | ||
| ramp_up: { | ||
| executor: 'ramping-vus', | ||
| startVUs: 0, | ||
| stages: [ | ||
| { duration: '30s', target: 10 }, // 워밍업 | ||
| { duration: '30s', target: 30 }, // 1단계 | ||
| { duration: '1m', target: 50 }, // 2단계 | ||
| { duration: '1m', target: 50 }, // 50명 유지 | ||
| { duration: '30s', target: 0 }, // 종료 | ||
| ], | ||
| }, | ||
| }, | ||
| thresholds: { | ||
| ...THRESHOLDS, | ||
| nearby_duration: ['p(95)<2000'], // PostGIS 쿼리는 2초 기준 | ||
| in_bounds_duration: ['p(95)<2000'], | ||
| }, | ||
| }; | ||
|
|
||
| // 서울 중심 좌표 | ||
| const SEOUL = { lat: 37.5665, lng: 126.9780 }; | ||
|
|
||
| // 테스트할 매장 ID 목록 (실제 DB에 있는 ID로 교체) | ||
| const STORE_IDS = [1, 2, 3, 4, 5]; | ||
|
|
||
| export default function () { | ||
| const storeId = STORE_IDS[Math.floor(Math.random() * STORE_IDS.length)]; | ||
| const today = new Date(Date.now() + 9 * 60 * 60 * 1000).toISOString().split('T')[0]; | ||
|
|
||
| group('매장 목록 조회', () => { | ||
| const res = http.get(`${BASE_URL}/api/v1/stores?page=0&size=10`, { headers: HEADERS_JSON }); | ||
| check(res, { '목록 200': (r) => r.status === 200 }); | ||
| }); | ||
|
|
||
| group('인기 매장 조회', () => { | ||
| const res = http.get(`${BASE_URL}/api/v1/stores/popular?limit=10`, { headers: HEADERS_JSON }); | ||
| check(res, { '인기 200': (r) => r.status === 200 }); | ||
| }); | ||
|
|
||
| group('근처 매장 조회 (PostGIS)', () => { | ||
| const res = http.get( | ||
| `${BASE_URL}/api/v1/stores/nearby?latitude=${SEOUL.lat}&longitude=${SEOUL.lng}&page=0&size=10`, | ||
| { headers: HEADERS_JSON }, | ||
| ); | ||
| check(res, { '근처 200': (r) => r.status === 200 }); | ||
| nearbyDuration.add(res.timings.duration); | ||
| }); | ||
|
|
||
| group('지도 영역 매장 조회 (in-bounds)', () => { | ||
| // 서울 강남 일대 bounding box | ||
| const res = http.get( | ||
| `${BASE_URL}/api/v1/stores/in-bounds` + | ||
| `?minLat=37.49&maxLat=37.54&minLng=127.01&maxLng=127.07` + | ||
| `¢erLat=${SEOUL.lat}¢erLng=${SEOUL.lng}&limit=100`, | ||
| { headers: HEADERS_JSON }, | ||
| ); | ||
| check(res, { 'in-bounds 200': (r) => r.status === 200 }); | ||
| inBoundsDuration.add(res.timings.duration); | ||
| }); | ||
|
|
||
| group('매장 상세 조회', () => { | ||
| const res = http.get(`${BASE_URL}/api/v1/stores/${storeId}`, { headers: HEADERS_JSON }); | ||
| check(res, { '상세 200': (r) => r.status === 200 }); | ||
| }); | ||
|
|
||
| group('시간대별 좌석 조회', () => { | ||
| const res = http.get( | ||
| `${BASE_URL}/api/v1/remains?storeId=${storeId}&date=${today}`, | ||
| { headers: HEADERS_JSON }, | ||
| ); | ||
| check(res, { '좌석 200': (r) => r.status === 200 }); | ||
| }); | ||
|
|
||
| sleep(1); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| /** | ||
| * 예약 동시성 부하테스트 (핵심 시나리오) | ||
| * 실행: k6 run -e AUTH_TOKEN=<JWT> -e REMAIN_ID=<ID> k6/02-reservation-concurrency.js | ||
| * | ||
| * 목적: 같은 remainId에 100명이 동시에 예약 요청 → 분산락/Optimistic Lock 검증 | ||
| * 기대 결과: | ||
| * - 좌석 수만큼만 성공 (201) | ||
| * - 나머지는 REMAIN_EXHAUSTED (400/409) | ||
| * - 데이터 정합성 깨지면 안 됨 (중복 예약 X) | ||
| */ | ||
| import http from 'k6/http'; | ||
| import { sleep, check, group } from 'k6'; | ||
| import { Counter, Rate, Trend } from 'k6/metrics'; | ||
| import { BASE_URL, HEADERS_AUTH, REMAIN_ID, THRESHOLDS } from './config.js'; | ||
|
|
||
| const successCount = new Counter('reservation_success'); | ||
| const exhaustedCount = new Counter('reservation_exhausted'); | ||
| const conflictCount = new Counter('reservation_conflict'); | ||
| const errorRate = new Rate('reservation_error_rate'); | ||
| const reserveDuration = new Trend('reservation_duration', true); | ||
|
|
||
| export const options = { | ||
| scenarios: { | ||
| // 100명이 동시에 한꺼번에 예약 요청 — 스파이크 시나리오 | ||
| spike: { | ||
| executor: 'ramping-arrival-rate', | ||
| startRate: 0, | ||
| timeUnit: '1s', | ||
| preAllocatedVUs: 150, | ||
| maxVUs: 200, | ||
| stages: [ | ||
| { duration: '5s', target: 100 }, // 5초 만에 초당 100 요청 | ||
| { duration: '30s', target: 100 }, // 30초 유지 | ||
| { duration: '5s', target: 0 }, | ||
| ], | ||
| }, | ||
| }, | ||
| thresholds: { | ||
| ...THRESHOLDS, | ||
| reservation_duration: ['p(95)<3000'], | ||
| // 동시성 테스트이므로 에러율 기준 완화 (좌석 부족 에러는 정상) | ||
| http_req_failed: ['rate<0.01'], // 5xx 에러만 실패로 간주 | ||
| }, | ||
| }; | ||
|
|
||
| export default function () { | ||
| group('예약 생성 (동시성)', () => { | ||
| const payload = JSON.stringify({ | ||
| remainId: parseInt(REMAIN_ID), | ||
| member: 2, | ||
| }); | ||
|
|
||
| const res = http.post(`${BASE_URL}/api/v1/reservations`, payload, { | ||
| headers: HEADERS_AUTH, | ||
| }); | ||
|
|
||
| reserveDuration.add(res.timings.duration); | ||
|
|
||
| if (res.status === 201) { | ||
| successCount.add(1); | ||
| errorRate.add(false); | ||
| check(res, { '예약 성공 (201)': (r) => r.status === 201 }); | ||
| } else if (res.status === 400 || res.status === 409) { | ||
| const body = (() => { try { return res.json(); } catch { return {}; } })(); | ||
| const code = body?.code || ''; | ||
|
|
||
| if (code === 'REMAIN_EXHAUSTED') { | ||
| exhaustedCount.add(1); | ||
| } else if (code === 'OPTIMISTIC_LOCK_CONFLICT') { | ||
| conflictCount.add(1); | ||
| } | ||
|
|
||
| errorRate.add(false); // 좌석 부족/락 충돌은 정상 동작 | ||
| check(res, { '좌석 부족/락 충돌 (정상)': () => true }); | ||
| } else { | ||
| errorRate.add(true); | ||
| check(res, { '예상치 못한 에러': (r) => r.status < 500 }); | ||
| console.error(`예상치 못한 응답: ${res.status} - ${res.body}`); | ||
| } | ||
| }); | ||
|
|
||
| sleep(0.1); | ||
| } | ||
|
|
||
| export function handleSummary(data) { | ||
| const success = data.metrics.reservation_success?.values?.count || 0; | ||
| const exhausted = data.metrics.reservation_exhausted?.values?.count || 0; | ||
| const conflict = data.metrics.reservation_conflict?.values?.count || 0; | ||
| const total = success + exhausted + conflict; | ||
| const p99 = data.metrics.reservation_duration?.values?.['p(99)'] || 0; | ||
| const p95 = data.metrics.reservation_duration?.values?.['p(95)'] || 0; | ||
|
|
||
| return { | ||
| stdout: ` | ||
| ===== 예약 동시성 테스트 결과 ===== | ||
| 총 요청수 : ${total} | ||
| 예약 성공 : ${success} | ||
| 좌석 소진 (정상) : ${exhausted} | ||
| 락 충돌 (정상) : ${conflict} | ||
| p95 응답시간 : ${p95.toFixed(0)}ms | ||
| p99 응답시간 : ${p99.toFixed(0)}ms | ||
|
|
||
| [검증] 예약 성공 수가 실제 좌석 수와 일치하는지 DB에서 확인하세요. | ||
| SELECT COUNT(*) FROM reservations WHERE remain_id = ${REMAIN_ID} AND status != 'PAYMENT_FAILED'; | ||
| =================================== | ||
| `, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| /** | ||
| * 실제 사용자 플로우 부하테스트 | ||
| * 실행: k6 run -e AUTH_TOKEN=<JWT> k6/03-full-flow.js | ||
| * | ||
| * 시나리오: 홈 진입 → 매장 검색 → 상세 조회 → 좌석 확인 | ||
| * (결제가 필요한 예약 확정은 외부 API 의존이라 포함하지 않음) | ||
| */ | ||
| import http from 'k6/http'; | ||
| import { sleep, check, group } from 'k6'; | ||
| import { Trend } from 'k6/metrics'; | ||
| import { BASE_URL, HEADERS_JSON, HEADERS_AUTH, THRESHOLDS } from './config.js'; | ||
|
|
||
| const flowDuration = new Trend('full_flow_duration', true); | ||
|
|
||
| export const options = { | ||
| scenarios: { | ||
| // 일반 트래픽 — 점진적 증가 | ||
| normal_traffic: { | ||
| executor: 'ramping-vus', | ||
| startVUs: 0, | ||
| stages: [ | ||
| { duration: '30s', target: 10 }, | ||
| { duration: '1m', target: 30 }, | ||
| { duration: '1m', target: 50 }, | ||
| { duration: '30s', target: 0 }, | ||
| ], | ||
| }, | ||
| }, | ||
| thresholds: { | ||
| ...THRESHOLDS, | ||
| full_flow_duration: ['p(95)<5000'], // 전체 플로우 5초 이내 | ||
| }, | ||
| }; | ||
|
|
||
| const SEOUL = { lat: 37.5665, lng: 126.9780 }; | ||
| const STORE_IDS = [1, 2, 3, 4, 5]; | ||
|
|
||
| export default function () { | ||
| const start = Date.now(); | ||
| const storeId = STORE_IDS[Math.floor(Math.random() * STORE_IDS.length)]; | ||
| const today = new Date(Date.now() + 9 * 60 * 60 * 1000).toISOString().split('T')[0]; | ||
|
|
||
| group('1. 홈 - 인기 매장 조회', () => { | ||
| const res = http.get(`${BASE_URL}/api/v1/stores/popular?limit=10`, { | ||
| headers: HEADERS_JSON, | ||
| }); | ||
| check(res, { '인기 매장 200': (r) => r.status === 200 }); | ||
| sleep(0.5); | ||
| }); | ||
|
|
||
| group('2. 카테고리/지역 필터 검색', () => { | ||
| const categories = ['KOREAN', 'JAPANESE', 'CHINESE', 'WESTERN']; | ||
| const category = categories[Math.floor(Math.random() * categories.length)]; | ||
| const res = http.get( | ||
| `${BASE_URL}/api/v1/stores?category=${encodeURIComponent(category)}&page=0&size=10`, | ||
| { headers: HEADERS_JSON }, | ||
| ); | ||
| check(res, { '필터 검색 200': (r) => r.status === 200 }); | ||
| sleep(0.5); | ||
| }); | ||
|
|
||
| group('3. 지도 화면 - 영역 내 매장 조회', () => { | ||
| const res = http.get( | ||
| `${BASE_URL}/api/v1/stores/in-bounds` + | ||
| `?minLat=37.49&maxLat=37.54&minLng=127.01&maxLng=127.07` + | ||
| `¢erLat=${SEOUL.lat}¢erLng=${SEOUL.lng}&limit=100`, | ||
| { headers: HEADERS_JSON }, | ||
| ); | ||
| check(res, { '지도 200': (r) => r.status === 200 }); | ||
| sleep(0.3); | ||
| }); | ||
|
|
||
| group('4. 매장 상세 조회', () => { | ||
| const res = http.get(`${BASE_URL}/api/v1/stores/${storeId}`, { | ||
| headers: HEADERS_JSON, | ||
| }); | ||
| check(res, { '상세 200': (r) => r.status === 200 }); | ||
| sleep(1); | ||
| }); | ||
|
|
||
| group('5. 메뉴 + 리뷰 조회 (동시)', () => { | ||
| const responses = http.batch([ | ||
| ['GET', `${BASE_URL}/api/v1/stores/${storeId}/menu`, null, { headers: HEADERS_JSON }], | ||
| ['GET', `${BASE_URL}/api/v1/reviews/store/${storeId}`, null, { headers: HEADERS_JSON }], | ||
| ]); | ||
| check(responses[0], { '메뉴 200': (r) => r.status === 200 }); | ||
| check(responses[1], { '리뷰 200': (r) => r.status === 200 }); | ||
| sleep(0.5); | ||
| }); | ||
|
|
||
| group('6. 예약 가능 시간 조회', () => { | ||
| const res = http.get( | ||
| `${BASE_URL}/api/v1/remains?storeId=${storeId}&date=${today}`, | ||
| { headers: HEADERS_JSON }, | ||
| ); | ||
| check(res, { '좌석 200': (r) => r.status === 200 }); | ||
| sleep(0.5); | ||
| }); | ||
|
|
||
| // 로그인 유저만: 북마크 폴더 조회 | ||
| if (HEADERS_AUTH.Authorization !== 'Bearer ') { | ||
| group('7. 북마크 폴더 조회 (로그인)', () => { | ||
| const res = http.get(`${BASE_URL}/api/v1/bookmark-folders`, { | ||
| headers: HEADERS_AUTH, | ||
| }); | ||
| check(res, { '북마크 200': (r) => r.status === 200 }); | ||
| }); | ||
| } | ||
|
|
||
| flowDuration.add(Date.now() - start); | ||
| sleep(1); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
고부하 상황에서 서버가 502, 503, 504 등 비정상 응답(HTML 에러 페이지 등)을 반환할 경우,
res.json()호출 시 예외가 발생하여 k6 VU(가상 사용자) 실행이 중단될 수 있습니다.08-coupon-issue.js에서 적용하신 것처럼 안전하게try-catch로 감싸서 예외를 방지하는 것이 좋습니다.