Trang chủ
QA Learning Hub
Chương 08 · Performance Testing
Chương 08 Trung Cấp

Performance Testing

Từ load testing đến bottleneck analysis — đảm bảo hệ thống hoạt động tốt dưới tải thực tế và peak traffic.

Các Loại Performance Test
  • Load TestingTest hệ thống dưới tải dự kiến. Ví dụ: 500 concurrent users trong giờ cao điểm. Mục tiêu: verify hệ thống đáp ứng SLA dưới normal load.
  • Stress TestingĐẩy hệ thống vượt ngưỡng capacity đến breaking point. Mục tiêu: tìm max capacity và xem hệ thống recover thế nào sau khi overload.
  • Spike TestingTải tăng đột ngột và giảm nhanh. Ví dụ: flash sale, live event. 100 users → 2000 users trong 30 giây → back to 100. Hệ thống auto-scale được không?
  • Volume TestingTest với lượng data lớn: 10 triệu records trong DB, 100K files trong storage. Tìm performance degradation khi data grows.
  • Soak/Endurance TestingChạy dài giờ (8-72h) ở tải bình thường. Mục tiêu: phát hiện memory leak, connection pool exhaustion, disk space issues theo thời gian.
  • Scalability TestingTest hệ thống scale horizontal/vertical. Thêm server → throughput có tăng linear không? Cloud auto-scaling hoạt động đúng không?
📏 Metrics & Thresholds Chuẩn
  • Response TimeThời gian từ request đến response đầy đủ. Web pages: <2s (P90), <4s (P95). API endpoints: <500ms (P90). Checkout: <3s.
  • Percentiles (P50, P90, P95, P99)P90 = 90% requests hoàn thành trong X ms. P99 = worst case cho 99% users. Không dùng average — bị skewed bởi outliers. Luôn báo cáo theo percentile.
  • Throughput (TPS/RPS)Transactions/Requests per second. Higher = better. Giảm khi tải tăng → bottleneck.
  • Error Rate% requests bị lỗi (4xx, 5xx). Ngưỡng: <1% under normal load, <5% under stress. Cao hơn → fail test.
  • Concurrent UsersSố users active đồng thời. Khác với total users — chỉ những ai đang gửi request trong một thời điểm.
  • CPU / MemoryServer resource usage. Normal: <70%. Under stress: <85%. Nếu CPU đạt 100% → hệ thống saturated, queue up requests.
  • Apdex ScoreApplication Performance Index. 0-1. >0.9 = Excellent, 0.7-0.9 = Good, <0.7 = Poor. Tính toán từ response time targets.
🔨 JMeter — Hướng Dẫn Từng Bước
  1. Download & Setup: Download JMeter tại jmeter.apache.org. Cần Java 8+. Chạy bin/jmeter.bat (Windows) hoặc bin/jmeter (Mac/Linux).
  2. Test Plan Structure: Thread Group (users) → HTTP Request Sampler → Listeners. Đây là cấu trúc cơ bản nhất.
  3. Thread Group: Right-click Test Plan → Add → Threads → Thread Group. Set: Number of Threads (concurrent users), Ramp-up Period (seconds), Loop Count (bao nhiêu lần mỗi user).
  4. HTTP Request: Right-click Thread Group → Add → Sampler → HTTP Request. Set: Server Name, Port, Method (GET/POST), Path. Thêm Body Data cho POST.
  5. Headers: Right-click HTTP Request → Add → Config → HTTP Header Manager. Thêm Content-Type: application/json, Authorization: Bearer token.
  6. CSV Data Set: Right-click Thread Group → Add → Config → CSV Data Set Config. Load test data từ CSV file — khác nhau cho mỗi user (usernames, products...).
  7. Listeners: View Results Tree (debug), Summary Report, Aggregate Report. Đừng dùng too many listeners trong load test — tốn resource.
  8. Assertions: Add → Assertions → Response Assertion. Check: Status code = 200, Response body contains expected text.
  9. Run Non-GUI Mode: jmeter -n -t testplan.jmx -l results.jtl -e -o report/ — Chạy headless, tiết kiệm resource. HTML report tại report/index.html.
💡 Common Mistakes với JMeter
(1) Chạy từ local machine với shared network → kết quả không accurate. Chạy từ server gần target. (2) Think Time quá thấp → unrealistic load (real users có pause). Thêm Gaussian Random Timer. (3) Dùng View Results Tree trong load test → JMeter bị chậm. Chỉ dùng khi debug.
⚙️ k6 — Modern Performance Testing

k6 là tool hiện đại, script bằng JavaScript, developer-friendly. Phù hợp cho teams có coding background.

// basic-test.js import http from 'k6/http'; import { check, sleep } from 'k6'; export const options = { stages: [ { duration: '30s', target: 50 }, // ramp up to 50 users { duration: '1m', target: 100 }, // hold at 100 users { duration: '30s', target: 0 }, // ramp down ], thresholds: { http_req_duration: ['p(90)<2000'], // P90 < 2s http_req_failed: ['rate<0.01'], // Error rate < 1% }, }; export default function() { const res = http.get('https://api.example.com/products'); check(res, { 'status is 200': (r) => r.status === 200, 'response time OK': (r) => r.timings.duration < 2000, }); sleep(1); // think time }

Chạy: k6 run basic-test.js. Output real-time metrics. Tích hợp với Grafana/InfluxDB để visualize.

🌟 Core Web Vitals — Google's Standards
  • LCP (Largest Contentful Paint)Thời gian render element lớn nhất. Good: <2.5s. Needs improvement: 2.5-4s. Poor: >4s. Thường là hero image, H1, hoặc large video.
  • INP (Interaction to Next Paint)Thay thế FID từ 2024. Đo responsiveness của tất cả interactions. Good: <200ms. Poor: >500ms.
  • CLS (Cumulative Layout Shift)Tổng layout shifts bất ngờ. Good: <0.1. Poor: >0.25. Nguyên nhân: images không có dimensions, dynamic content load pushes content down.
  • TTFB (Time to First Byte)Không phải Core Web Vital nhưng quan trọng. Good: <800ms. Cao → server-side issue (slow DB, no caching).

Tools đo Core Web Vitals:

  • Lighthouse: Chrome DevTools → Lighthouse tab → Generate report. Chạy incognito để tránh extensions ảnh hưởng.
  • PageSpeed Insights: pagespeed.web.dev — test URL online, xem real field data (CrUX data) vs lab data.
  • Web Vitals extension: Chrome extension hiển thị real-time LCP/CLS/INP khi browse.
  • Playwright: page.metrics()performance.measure trong browser context.
🔍 Tìm Bottleneck
  • High Response Time + Low CPU: Network latency, slow DB query, external API wait. Check N+1 query problem.
  • High CPU + Normal Response Time: CPU-intensive computation. Consider caching or optimizing algorithm.
  • Memory Leak: Memory tăng dần trong soak test, không được released. Java GC issues, unclosed connections.
  • DB Slow Queries: Dùng EXPLAIN ANALYZE (PostgreSQL) hoặc EXPLAIN (MySQL) để xem query plan. Missing indexes thường là nguyên nhân.
  • Connection Pool Exhaustion: Max connections reached → requests queue. Tăng pool size hoặc optimize connection reuse.
  • Thread Pool Saturation: Server thread pool full → requests rejected or timeout. Tune max-threads config.
🏆 Senior Insight: Performance Budgets

Senior QA / QE thiết lập Performance Budgets: "Homepage LCP không được vượt 2.5s, API /checkout không được vượt 500ms P95." Enforce trong CI pipeline — build fail nếu budget bị vượt. Đây là cách proactive prevention thay vì reactive debugging.

✏️ Bài Tập
📝 Bài Tập: Performance Test Planning

E-commerce platform sắp có sự kiện Black Friday (traffic peak dự báo 10x bình thường). Thông tin: bình thường 200 concurrent users, average response time 800ms.

  1. Xác định loại performance test cần chạy và thứ tự thực hiện
  2. Define thresholds cụ thể cho: response time, error rate, concurrent users mục tiêu
  3. Viết k6 script cơ bản cho Load Test scenario: ramp từ 0 → 2000 users trong 5 phút, hold 10 phút, ramp down 5 phút
  4. List 5 potential bottlenecks cần check và cách phát hiện mỗi bottleneck