Performance Testing
Overview
Performance testing validates that your application meets speed, stability, and scalability requirements under expected and extreme conditions. It answers questions like "How many concurrent users can we handle?", "What's the 99th percentile response time?", and "Where does the system break?".
Performance Test Types
| Type |
Goal |
Pattern |
When to Use |
| Load |
Validate expected traffic |
Ramp to target VUs, sustain, ramp down |
Before release, capacity planning |
| Stress |
Find the breaking point |
Ramp beyond expected capacity |
Pre-launch, architecture validation |
| Spike |
Handle sudden traffic bursts |
Jump to high VUs instantly |
Flash sales, event-driven traffic |
| Soak |
Detect memory leaks / degradation |
Moderate load over hours |
After major changes, long-running services |
| Breakpoint |
Determine absolute maximum |
Continuously increase until failure |
Capacity planning, SLA definition |
Key Metrics
| Metric |
Description |
Typical Thresholds |
| Response Time (p50) |
Median latency |
< 200ms for APIs, < 1s for pages |
| Response Time (p95) |
95th percentile latency |
< 500ms for APIs, < 3s for pages |
| Response Time (p99) |
99th percentile latency |
< 1s for APIs, < 5s for pages |
| Throughput (RPS) |
Requests per second |
Application-specific |
| Error Rate |
% of failed requests |
< 1% under normal load |
| VU Concurrency |
Active virtual users |
Application-specific |
| TTFB |
Time to first byte |
< 200ms |
| Core Web Vitals (LCP) |
Largest Contentful Paint |
< 2.5s |
| Core Web Vitals (INP) |
Interaction to Next Paint |
< 200ms |
| Core Web Vitals (CLS) |
Cumulative Layout Shift |
< 0.1 |
Cross-Platform Tools
| Tool |
Language |
Strengths |
| k6 (Grafana) |
JavaScript |
Developer-friendly, CLI-native, thresholds, scenarios, k6 cloud, k6 browser |
| JMeter |
Java (GUI + CLI) |
Mature, GUI test plan builder, extensive protocol support, plugins |
| Gatling |
Scala / Java |
High performance, code-based DSL, detailed HTML reports |
| Artillery |
YAML + JS |
Simple YAML config, plugin ecosystem, serverless mode |
| Lighthouse |
CLI / Chrome |
Web performance audits, Core Web Vitals, accessibility, SEO |
k6 (Grafana)
Load Test with Stages, Thresholds, and Checks
// tests/performance/load-test.k6.js
import http from "k6/http";
import { check, sleep, group } from "k6";
export const options = {
stages: [
{ duration: "2m", target: 50 }, // Ramp up to 50 VUs
{ duration: "5m", target: 50 }, // Sustain 50 VUs
{ duration: "2m", target: 100 }, // Ramp up to 100 VUs
{ duration: "5m", target: 100 }, // Sustain 100 VUs
{ duration: "2m", target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: [
"p(50)<200", // 50th percentile under 200ms
"p(95)<500", // 95th percentile under 500ms
"p(99)<1000", // 99th percentile under 1s
],
http_req_failed: ["rate<0.01"], // Less than 1% errors
checks: ["rate>0.99"], // 99%+ checks pass
},
};
const BASE_URL = __ENV.BASE_URL || "http://localhost:3000";
export default function () {
group("Homepage flow", () => {
const homeRes = http.get(`${BASE_URL}/`);
check(homeRes, {
"homepage returns 200": (r) => r.status === 200,
"homepage loads under 500ms": (r) => r.timings.duration < 500,
});
const apiRes = http.get(`${BASE_URL}/api/products?limit=20`);
check(apiRes, {
"products API returns 200": (r) => r.status === 200,
"products returns array": (r) => Array.isArray(r.json()),
});
});
sleep(1); // Think time between iterations
}
k6 Scenarios (Advanced)
// tests/performance/scenarios.k6.js
import http from "k6/http";
import { check } from "k6";
export const options = {
scenarios: {
// Constant arrival rate — fixed RPS regardless of response time
constant_load: {
executor: "constant-arrival-rate",
rate: 100, // 100 RPS
timeUnit: "1s",
duration: "5m",
preAllocatedVUs: 50,
maxVUs: 200,
},
// Ramping VUs — gradual increase
ramping_users: {
executor: "ramping-vus",
startVUs: 0,
stages: [
{ duration: "2m", target: 50 },
{ duration: "3m", target: 50 },
{ duration: "1m", target: 0 },
],
},
// Spike test — sudden burst
spike: {
executor: "ramping-arrival-rate",
startRate: 10,
timeUnit: "1s",
stages: [
{ duration: "10s", target: 10 },
{ duration: "1m", target: 500 }, // Spike
{ duration: "10s", target: 10 }, // Recover
],
preAllocatedVUs: 200,
maxVUs: 500,
},
},
thresholds: {
http_req_duration: ["p(95)<500"],
http_req_failed: ["rate<0.01"],
},
};
export default function () {
const res = http.get(`${__ENV.BASE_URL}/api/health`);
check(res, { "status 200": (r) => r.status === 200 });
}
Running k6
# Basic run
k6 run tests/performance/load-test.k6.js
# With environment variables
k6 run tests/performance/load-test.k6.js --env BASE_URL=https://staging.example.com
# Output to multiple destinations
k6 run tests/performance/load-test.k6.js \
--out json=results.json \
--out influxdb=http://localhost:8086/k6
# k6 cloud (Grafana Cloud k6)
k6 cloud tests/performance/load-test.k6.js
Artillery
YAML Configuration Example
# tests/performance/artillery-config.yml
config:
target: "https://staging-api.example.com"
phases:
- name: "Warm up"
duration: 60 # seconds
arrivalRate: 5 # new virtual users per second
- name: "Ramp up"
duration: 120
arrivalRate: 5
rampTo: 50
- name: "Sustained load"
duration: 300
arrivalRate: 50
defaults:
headers:
Authorization: "Bearer {{ $processEnvironment.AUTH_TOKEN }}"
Content-Type: "application/json"
ensure:
thresholds:
- http.response_time.p95: 500
- http.response_time.p99: 1000
- http.codes.200: 95 # 95% of responses must be 200
plugins:
expect: {}
scenarios:
- name: "Browse and purchase flow"
flow:
- get:
url: "/api/products"
expect:
- statusCode: 200
- hasProperty: "body.length"
capture:
- json: "$[0].id"
as: "productId"
- think: 2
- get:
url: "/api/products/{{ productId }}"
expect:
- statusCode: 200
- think: 1
- post:
url: "/api/cart"
json:
productId: "{{ productId }}"
quantity: 1
expect:
- statusCode: 201
Running Artillery
# Install Artillery
npm install -g artillery
# Run test
artillery run tests/performance/artillery-config.yml
# Run with environment overrides
artillery run tests/performance/artillery-config.yml --target https://staging.example.com
# Generate HTML report
artillery run tests/performance/artillery-config.yml --output results.json
artillery report results.json --output report.html
# Quick one-liner smoke test
artillery quick --count 10 --num 5 https://staging-api.example.com/api/health
JMeter
Overview
Apache JMeter is a mature load testing tool with a GUI for building test plans and a CLI mode for CI execution.
Key Concepts
| Concept |
Description |
| Test Plan |
Root container for all test elements |
| Thread Group |
Defines VUs (threads), ramp-up time, loop count |
| Samplers |
HTTP Request, JDBC Request, FTP, etc. |
| Assertions |
Response assertions (status, body, duration) |
| Listeners |
Results viewers (Summary Report, Graph, JTL files) |
| Config Elements |
CSV Data Set, HTTP Header Manager, User Variables |
| Timers |
Think time between requests |
CLI Mode for CI
# Run test plan in non-GUI mode
jmeter -n -t test-plan.jmx -l results.jtl -e -o report/
# With properties
jmeter -n -t test-plan.jmx \
-Jthreads=100 \
-Jrampup=60 \
-Jduration=300 \
-Jhost=staging-api.example.com \
-l results.jtl
# Generate HTML report from results
jmeter -g results.jtl -o report/
GitHub Actions Integration
# .github/workflows/jmeter.yml
jobs:
performance-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run JMeter Tests
uses: rbhadti94/apache-jmeter-action@v0.5.0
with:
testFilePath: tests/performance/test-plan.jmx
outputReportsFolder: reports/
args: >
-Jthreads=50 -Jrampup=30 -Jduration=120
-Jhost=${{ secrets.STAGING_HOST }}
- uses: actions/upload-artifact@v4
if: always()
with:
name: jmeter-report
path: reports/
Gatling
Overview
Gatling uses a code-based DSL (Scala or Java) for defining simulations, producing detailed HTML reports automatically.
Scala DSL Example
// src/test/scala/simulations/BasicSimulation.scala
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
class BasicSimulation extends Simulation {
val httpProtocol = http
.baseUrl("https://staging-api.example.com")
.acceptHeader("application/json")
.authorizationHeader("Bearer ${authToken}")
val feeder = csv("test-data/users.csv").random
val browseScenario = scenario("Browse Products")
.feed(feeder)
.exec(
http("List Products")
.get("/api/products")
.check(status.is(200))
.check(jsonPath("$[0].id").saveAs("productId"))
)
.pause(1, 3)
.exec(
http("Get Product Detail")
.get("/api/products/${productId}")
.check(status.is(200))
)
setUp(
browseScenario.inject(
rampUsers(50).during(2.minutes),
constantUsersPerSec(10).during(5.minutes),
rampUsers(0).during(1.minute)
)
).protocols(httpProtocol)
.assertions(
global.responseTime.percentile(95).lt(500),
global.successfulRequests.percent.gt(99.0)
)
}
Running Gatling
# Run with Maven
mvn gatling:test
# Run with Gradle
gradle gatlingRun
# Run specific simulation
mvn gatling:test -Dgatling.simulationClass=simulations.BasicSimulation
Lighthouse
Overview
Lighthouse audits web performance, accessibility, best practices, and SEO. It measures Core Web Vitals and provides actionable improvement suggestions.
CLI Usage
# Install Lighthouse CLI
npm install -g lighthouse
# Run performance audit
lighthouse https://example.com \
--output json,html \
--output-path ./results/lighthouse \
--chrome-flags="--headless --no-sandbox"
# Performance-only audit
lighthouse https://example.com \
--only-categories=performance \
--output json \
--output-path ./results/perf.json
# Run with budget
lighthouse https://example.com \
--budget-path=budgets.json \
--output html
Performance Budget File
// budgets.json
[
{
"path": "/*",
"timings": [
{ "metric": "interactive", "budget": 3000 },
{ "metric": "first-contentful-paint", "budget": 1500 },
{ "metric": "largest-contentful-paint", "budget": 2500 }
],
"resourceSizes": [
{ "resourceType": "script", "budget": 300 },
{ "resourceType": "total", "budget": 1000 }
]
}
]
CI Integration with Lighthouse CI
# .github/workflows/lighthouse.yml
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm install -g @lhci/cli
- run: |
lhci autorun \
--collect.url=https://staging.example.com \
--collect.numberOfRuns=3 \
--assert.preset=lighthouse:recommended \
--assert.assertions.largest-contentful-paint=warn:2500 \
--assert.assertions.interactive=error:5000
CI Integration Patterns
When to Run Each Test Type
| Test Type |
Trigger |
Duration |
Gate |
| Smoke (minimal load) |
Every PR |
1-2 min |
Fail PR if errors |
| Load (expected traffic) |
Nightly or pre-release |
10-20 min |
Alert on threshold breach |
| Stress (beyond capacity) |
Pre-release |
20-30 min |
Report, don't gate |
| Soak (extended duration) |
Weekly or pre-release |
2-8 hours |
Alert on degradation |
| Lighthouse |
Every PR |
1-2 min |
Warn on budget violation |
k6 CI Pipeline Example
# .github/workflows/performance.yml
name: Performance Tests
on:
pull_request:
branches: [main]
schedule:
- cron: "0 2 * * *" # Nightly at 2 AM
jobs:
smoke-test:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: grafana/k6-action@v0.3.1
with:
filename: tests/performance/smoke.k6.js
env:
BASE_URL: ${{ secrets.STAGING_URL }}
load-test:
if: github.event_name == 'schedule'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: grafana/k6-action@v0.3.1
with:
filename: tests/performance/load-test.k6.js
env:
BASE_URL: ${{ secrets.STAGING_URL }}
- uses: actions/upload-artifact@v4
if: always()
with:
name: k6-results
path: results/
Best Practices
Test Design
- Start with a smoke test (minimal load) to validate the test script works before scaling up.
- Use realistic think times (
sleep() / pause()) to simulate actual user behavior.
- Use data-driven tests with CSV feeders or dynamic data generation to avoid caching skew.
- Test the same scenario at different load levels: smoke, load, stress, spike.
Metrics and Thresholds
- Always define thresholds — tests without pass/fail criteria are just logs.
- Focus on percentiles (p95, p99), not averages — averages hide tail latency.
- Track error rate alongside response time — fast errors are still failures.
- Baseline before optimizing — run tests against a known-good build first.
CI Integration
- Run smoke tests on every PR (fast, catches regressions early).
- Run full load tests nightly or pre-release (comprehensive, takes time).
- Store results as artifacts for trend analysis over time.
- Set thresholds as CI gates: fail the pipeline if p95 exceeds the budget.
Infrastructure
- Run performance tests against a dedicated staging environment, not shared dev.
- Ensure the load generator has sufficient resources (CPU, network) to avoid bottlenecking the test tool itself.
- Use distributed load generation (k6 cloud, JMeter distributed mode) for large-scale tests.
- Monitor the system under test (CPU, memory, DB connections) alongside the k6/Artillery metrics.
Reporting
- Generate HTML reports for human review (Gatling, JMeter, Artillery all support this).
- Export machine-readable results (JSON, JTL) for trend tracking and dashboards.
- Compare results against previous runs to catch performance regressions.
- Document performance baselines and SLAs in the repository alongside the test scripts.
1---2name: performance-testing3description: Use for load, stress, and scalability testing of applications and APIs. Covers k6 (Grafana), JMeter, Gatling, Artillery, and Lighthouse for web performance audits. Includes test type definitions, key metrics, thresholds, CI integration patterns, and performance budgets. USE FOR: k6, JMeter, Gatling, Artillery, Lighthouse, load testing, stress testing, performance benchmarks, Core Web Vitals, throughput testing, spike testing, soak testing, capacity planning, performance budgets DO NOT USE FOR: functional API testing (use api-testing), browser E2E tests (use e2e-testing), visual regression (use visual-testing)4license: MIT5---6# Performance Testing78## Overview9Performance testing validates that your application meets speed, stability, and scalability requirements under expected and extreme conditions. It answers questions like "How many concurrent users can we handle?", "What's the 99th percentile response time?", and "Where does the system break?".1011## Performance Test Types1213| Type | Goal | Pattern | When to Use |14|------|------|---------|-------------|15| **Load** | Validate expected traffic | Ramp to target VUs, sustain, ramp down | Before release, capacity planning |16| **Stress** | Find the breaking point | Ramp beyond expected capacity | Pre-launch, architecture validation |17| **Spike** | Handle sudden traffic bursts | Jump to high VUs instantly | Flash sales, event-driven traffic |18| **Soak** | Detect memory leaks / degradation | Moderate load over hours | After major changes, long-running services |19| **Breakpoint** | Determine absolute maximum | Continuously increase until failure | Capacity planning, SLA definition |2021## Key Metrics2223| Metric | Description | Typical Thresholds |24|--------|-------------|-------------------|25| **Response Time (p50)** | Median latency | < 200ms for APIs, < 1s for pages |26| **Response Time (p95)** | 95th percentile latency | < 500ms for APIs, < 3s for pages |27| **Response Time (p99)** | 99th percentile latency | < 1s for APIs, < 5s for pages |28| **Throughput (RPS)** | Requests per second | Application-specific |29| **Error Rate** | % of failed requests | < 1% under normal load |30| **VU Concurrency** | Active virtual users | Application-specific |31| **TTFB** | Time to first byte | < 200ms |32| **Core Web Vitals (LCP)** | Largest Contentful Paint | < 2.5s |33| **Core Web Vitals (INP)** | Interaction to Next Paint | < 200ms |34| **Core Web Vitals (CLS)** | Cumulative Layout Shift | < 0.1 |3536---3738## Cross-Platform Tools3940| Tool | Language | Strengths |41|------|----------|-----------|42| **k6 (Grafana)** | JavaScript | Developer-friendly, CLI-native, thresholds, scenarios, k6 cloud, k6 browser |43| **JMeter** | Java (GUI + CLI) | Mature, GUI test plan builder, extensive protocol support, plugins |44| **Gatling** | Scala / Java | High performance, code-based DSL, detailed HTML reports |45| **Artillery** | YAML + JS | Simple YAML config, plugin ecosystem, serverless mode |46| **Lighthouse** | CLI / Chrome | Web performance audits, Core Web Vitals, accessibility, SEO |4748---4950## k6 (Grafana)5152### Load Test with Stages, Thresholds, and Checks5354```javascript55// tests/performance/load-test.k6.js56import http from "k6/http";57import { check, sleep, group } from "k6";5859export const options = {60 stages: [61 { duration: "2m", target: 50 }, // Ramp up to 50 VUs62 { duration: "5m", target: 50 }, // Sustain 50 VUs63 { duration: "2m", target: 100 }, // Ramp up to 100 VUs64 { duration: "5m", target: 100 }, // Sustain 100 VUs65 { duration: "2m", target: 0 }, // Ramp down66 ],67 thresholds: {68 http_req_duration: [69 "p(50)<200", // 50th percentile under 200ms70 "p(95)<500", // 95th percentile under 500ms71 "p(99)<1000", // 99th percentile under 1s72 ],73 http_req_failed: ["rate<0.01"], // Less than 1% errors74 checks: ["rate>0.99"], // 99%+ checks pass75 },76};7778const BASE_URL = __ENV.BASE_URL || "http://localhost:3000";7980export default function () {81 group("Homepage flow", () => {82 const homeRes = http.get(`${BASE_URL}/`);83 check(homeRes, {84 "homepage returns 200": (r) => r.status === 200,85 "homepage loads under 500ms": (r) => r.timings.duration < 500,86 });8788 const apiRes = http.get(`${BASE_URL}/api/products?limit=20`);89 check(apiRes, {90 "products API returns 200": (r) => r.status === 200,91 "products returns array": (r) => Array.isArray(r.json()),92 });93 });9495 sleep(1); // Think time between iterations96}97```9899### k6 Scenarios (Advanced)100101```javascript102// tests/performance/scenarios.k6.js103import http from "k6/http";104import { check } from "k6";105106export const options = {107 scenarios: {108 // Constant arrival rate — fixed RPS regardless of response time109 constant_load: {110 executor: "constant-arrival-rate",111 rate: 100, // 100 RPS112 timeUnit: "1s",113 duration: "5m",114 preAllocatedVUs: 50,115 maxVUs: 200,116 },117 // Ramping VUs — gradual increase118 ramping_users: {119 executor: "ramping-vus",120 startVUs: 0,121 stages: [122 { duration: "2m", target: 50 },123 { duration: "3m", target: 50 },124 { duration: "1m", target: 0 },125 ],126 },127 // Spike test — sudden burst128 spike: {129 executor: "ramping-arrival-rate",130 startRate: 10,131 timeUnit: "1s",132 stages: [133 { duration: "10s", target: 10 },134 { duration: "1m", target: 500 }, // Spike135 { duration: "10s", target: 10 }, // Recover136 ],137 preAllocatedVUs: 200,138 maxVUs: 500,139 },140 },141 thresholds: {142 http_req_duration: ["p(95)<500"],143 http_req_failed: ["rate<0.01"],144 },145};146147export default function () {148 const res = http.get(`${__ENV.BASE_URL}/api/health`);149 check(res, { "status 200": (r) => r.status === 200 });150}151```152153### Running k6154155```bash156# Basic run157k6 run tests/performance/load-test.k6.js158159# With environment variables160k6 run tests/performance/load-test.k6.js --env BASE_URL=https://staging.example.com161162# Output to multiple destinations163k6 run tests/performance/load-test.k6.js \164 --out json=results.json \165 --out influxdb=http://localhost:8086/k6166167# k6 cloud (Grafana Cloud k6)168k6 cloud tests/performance/load-test.k6.js169```170171---172173## Artillery174175### YAML Configuration Example176177```yaml178# tests/performance/artillery-config.yml179config:180 target: "https://staging-api.example.com"181 phases:182 - name: "Warm up"183 duration: 60 # seconds184 arrivalRate: 5 # new virtual users per second185 - name: "Ramp up"186 duration: 120187 arrivalRate: 5188 rampTo: 50189 - name: "Sustained load"190 duration: 300191 arrivalRate: 50192 defaults:193 headers:194 Authorization: "Bearer {{ $processEnvironment.AUTH_TOKEN }}"195 Content-Type: "application/json"196 ensure:197 thresholds:198 - http.response_time.p95: 500199 - http.response_time.p99: 1000200 - http.codes.200: 95 # 95% of responses must be 200201 plugins:202 expect: {}203204scenarios:205 - name: "Browse and purchase flow"206 flow:207 - get:208 url: "/api/products"209 expect:210 - statusCode: 200211 - hasProperty: "body.length"212 capture:213 - json: "$[0].id"214 as: "productId"215 - think: 2216 - get:217 url: "/api/products/{{ productId }}"218 expect:219 - statusCode: 200220 - think: 1221 - post:222 url: "/api/cart"223 json:224 productId: "{{ productId }}"225 quantity: 1226 expect:227 - statusCode: 201228```229230### Running Artillery231232```bash233# Install Artillery234npm install -g artillery235236# Run test237artillery run tests/performance/artillery-config.yml238239# Run with environment overrides240artillery run tests/performance/artillery-config.yml --target https://staging.example.com241242# Generate HTML report243artillery run tests/performance/artillery-config.yml --output results.json244artillery report results.json --output report.html245246# Quick one-liner smoke test247artillery quick --count 10 --num 5 https://staging-api.example.com/api/health248```249250---251252## JMeter253254### Overview255Apache JMeter is a mature load testing tool with a GUI for building test plans and a CLI mode for CI execution.256257### Key Concepts258259| Concept | Description |260|---------|-------------|261| **Test Plan** | Root container for all test elements |262| **Thread Group** | Defines VUs (threads), ramp-up time, loop count |263| **Samplers** | HTTP Request, JDBC Request, FTP, etc. |264| **Assertions** | Response assertions (status, body, duration) |265| **Listeners** | Results viewers (Summary Report, Graph, JTL files) |266| **Config Elements** | CSV Data Set, HTTP Header Manager, User Variables |267| **Timers** | Think time between requests |268269### CLI Mode for CI270271```bash272# Run test plan in non-GUI mode273jmeter -n -t test-plan.jmx -l results.jtl -e -o report/274275# With properties276jmeter -n -t test-plan.jmx \277 -Jthreads=100 \278 -Jrampup=60 \279 -Jduration=300 \280 -Jhost=staging-api.example.com \281 -l results.jtl282283# Generate HTML report from results284jmeter -g results.jtl -o report/285```286287### GitHub Actions Integration288289```yaml290# .github/workflows/jmeter.yml291jobs:292 performance-test:293 runs-on: ubuntu-latest294 steps:295 - uses: actions/checkout@v4296 - name: Run JMeter Tests297 uses: rbhadti94/apache-jmeter-action@v0.5.0298 with:299 testFilePath: tests/performance/test-plan.jmx300 outputReportsFolder: reports/301 args: >302 -Jthreads=50 -Jrampup=30 -Jduration=120303 -Jhost=${{ secrets.STAGING_HOST }}304 - uses: actions/upload-artifact@v4305 if: always()306 with:307 name: jmeter-report308 path: reports/309```310311---312313## Gatling314315### Overview316Gatling uses a code-based DSL (Scala or Java) for defining simulations, producing detailed HTML reports automatically.317318### Scala DSL Example319320```scala321// src/test/scala/simulations/BasicSimulation.scala322import io.gatling.core.Predef._323import io.gatling.http.Predef._324import scala.concurrent.duration._325326class BasicSimulation extends Simulation {327328 val httpProtocol = http329 .baseUrl("https://staging-api.example.com")330 .acceptHeader("application/json")331 .authorizationHeader("Bearer ${authToken}")332333 val feeder = csv("test-data/users.csv").random334335 val browseScenario = scenario("Browse Products")336 .feed(feeder)337 .exec(338 http("List Products")339 .get("/api/products")340 .check(status.is(200))341 .check(jsonPath("$[0].id").saveAs("productId"))342 )343 .pause(1, 3)344 .exec(345 http("Get Product Detail")346 .get("/api/products/${productId}")347 .check(status.is(200))348 )349350 setUp(351 browseScenario.inject(352 rampUsers(50).during(2.minutes),353 constantUsersPerSec(10).during(5.minutes),354 rampUsers(0).during(1.minute)355 )356 ).protocols(httpProtocol)357 .assertions(358 global.responseTime.percentile(95).lt(500),359 global.successfulRequests.percent.gt(99.0)360 )361}362```363364### Running Gatling365366```bash367# Run with Maven368mvn gatling:test369370# Run with Gradle371gradle gatlingRun372373# Run specific simulation374mvn gatling:test -Dgatling.simulationClass=simulations.BasicSimulation375```376377---378379## Lighthouse380381### Overview382Lighthouse audits web performance, accessibility, best practices, and SEO. It measures Core Web Vitals and provides actionable improvement suggestions.383384### CLI Usage385386```bash387# Install Lighthouse CLI388npm install -g lighthouse389390# Run performance audit391lighthouse https://example.com \392 --output json,html \393 --output-path ./results/lighthouse \394 --chrome-flags="--headless --no-sandbox"395396# Performance-only audit397lighthouse https://example.com \398 --only-categories=performance \399 --output json \400 --output-path ./results/perf.json401402# Run with budget403lighthouse https://example.com \404 --budget-path=budgets.json \405 --output html406```407408### Performance Budget File409410```json411// budgets.json412[413 {414 "path": "/*",415 "timings": [416 { "metric": "interactive", "budget": 3000 },417 { "metric": "first-contentful-paint", "budget": 1500 },418 { "metric": "largest-contentful-paint", "budget": 2500 }419 ],420 "resourceSizes": [421 { "resourceType": "script", "budget": 300 },422 { "resourceType": "total", "budget": 1000 }423 ]424 }425]426```427428### CI Integration with Lighthouse CI429430```yaml431# .github/workflows/lighthouse.yml432jobs:433 lighthouse:434 runs-on: ubuntu-latest435 steps:436 - uses: actions/checkout@v4437 - uses: actions/setup-node@v4438 with:439 node-version: 20440 - run: npm install -g @lhci/cli441 - run: |442 lhci autorun \443 --collect.url=https://staging.example.com \444 --collect.numberOfRuns=3 \445 --assert.preset=lighthouse:recommended \446 --assert.assertions.largest-contentful-paint=warn:2500 \447 --assert.assertions.interactive=error:5000448```449450---451452## CI Integration Patterns453454### When to Run Each Test Type455456| Test Type | Trigger | Duration | Gate |457|-----------|---------|----------|------|458| **Smoke** (minimal load) | Every PR | 1-2 min | Fail PR if errors |459| **Load** (expected traffic) | Nightly or pre-release | 10-20 min | Alert on threshold breach |460| **Stress** (beyond capacity) | Pre-release | 20-30 min | Report, don't gate |461| **Soak** (extended duration) | Weekly or pre-release | 2-8 hours | Alert on degradation |462| **Lighthouse** | Every PR | 1-2 min | Warn on budget violation |463464### k6 CI Pipeline Example465466```yaml467# .github/workflows/performance.yml468name: Performance Tests469on:470 pull_request:471 branches: [main]472 schedule:473 - cron: "0 2 * * *" # Nightly at 2 AM474475jobs:476 smoke-test:477 if: github.event_name == 'pull_request'478 runs-on: ubuntu-latest479 steps:480 - uses: actions/checkout@v4481 - uses: grafana/k6-action@v0.3.1482 with:483 filename: tests/performance/smoke.k6.js484 env:485 BASE_URL: ${{ secrets.STAGING_URL }}486487 load-test:488 if: github.event_name == 'schedule'489 runs-on: ubuntu-latest490 steps:491 - uses: actions/checkout@v4492 - uses: grafana/k6-action@v0.3.1493 with:494 filename: tests/performance/load-test.k6.js495 env:496 BASE_URL: ${{ secrets.STAGING_URL }}497 - uses: actions/upload-artifact@v4498 if: always()499 with:500 name: k6-results501 path: results/502```503504---505506## Best Practices507508### Test Design509- Start with a smoke test (minimal load) to validate the test script works before scaling up.510- Use realistic think times (`sleep()` / `pause()`) to simulate actual user behavior.511- Use data-driven tests with CSV feeders or dynamic data generation to avoid caching skew.512- Test the same scenario at different load levels: smoke, load, stress, spike.513514### Metrics and Thresholds515- Always define thresholds — tests without pass/fail criteria are just logs.516- Focus on percentiles (p95, p99), not averages — averages hide tail latency.517- Track error rate alongside response time — fast errors are still failures.518- Baseline before optimizing — run tests against a known-good build first.519520### CI Integration521- Run smoke tests on every PR (fast, catches regressions early).522- Run full load tests nightly or pre-release (comprehensive, takes time).523- Store results as artifacts for trend analysis over time.524- Set thresholds as CI gates: fail the pipeline if p95 exceeds the budget.525526### Infrastructure527- Run performance tests against a dedicated staging environment, not shared dev.528- Ensure the load generator has sufficient resources (CPU, network) to avoid bottlenecking the test tool itself.529- Use distributed load generation (k6 cloud, JMeter distributed mode) for large-scale tests.530- Monitor the system under test (CPU, memory, DB connections) alongside the k6/Artillery metrics.531532### Reporting533- Generate HTML reports for human review (Gatling, JMeter, Artillery all support this).534- Export machine-readable results (JSON, JTL) for trend tracking and dashboards.535- Compare results against previous runs to catch performance regressions.536- Document performance baselines and SLAs in the repository alongside the test scripts.