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---67# Performance Testing89## Overview10Performance 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?".1112## Performance Test Types1314| Type | Goal | Pattern | When to Use |15|------|------|---------|-------------|16| **Load** | Validate expected traffic | Ramp to target VUs, sustain, ramp down | Before release, capacity planning |17| **Stress** | Find the breaking point | Ramp beyond expected capacity | Pre-launch, architecture validation |18| **Spike** | Handle sudden traffic bursts | Jump to high VUs instantly | Flash sales, event-driven traffic |19| **Soak** | Detect memory leaks / degradation | Moderate load over hours | After major changes, long-running services |20| **Breakpoint** | Determine absolute maximum | Continuously increase until failure | Capacity planning, SLA definition |2122## Key Metrics2324| Metric | Description | Typical Thresholds |25|--------|-------------|-------------------|26| **Response Time (p50)** | Median latency | < 200ms for APIs, < 1s for pages |27| **Response Time (p95)** | 95th percentile latency | < 500ms for APIs, < 3s for pages |28| **Response Time (p99)** | 99th percentile latency | < 1s for APIs, < 5s for pages |29| **Throughput (RPS)** | Requests per second | Application-specific |30| **Error Rate** | % of failed requests | < 1% under normal load |31| **VU Concurrency** | Active virtual users | Application-specific |32| **TTFB** | Time to first byte | < 200ms |33| **Core Web Vitals (LCP)** | Largest Contentful Paint | < 2.5s |34| **Core Web Vitals (INP)** | Interaction to Next Paint | < 200ms |35| **Core Web Vitals (CLS)** | Cumulative Layout Shift | < 0.1 |3637---3839## Cross-Platform Tools4041| Tool | Language | Strengths |42|------|----------|-----------|43| **k6 (Grafana)** | JavaScript | Developer-friendly, CLI-native, thresholds, scenarios, k6 cloud, k6 browser |44| **JMeter** | Java (GUI + CLI) | Mature, GUI test plan builder, extensive protocol support, plugins |45| **Gatling** | Scala / Java | High performance, code-based DSL, detailed HTML reports |46| **Artillery** | YAML + JS | Simple YAML config, plugin ecosystem, serverless mode |47| **Lighthouse** | CLI / Chrome | Web performance audits, Core Web Vitals, accessibility, SEO |4849---5051## k6 (Grafana)5253### Load Test with Stages, Thresholds, and Checks5455```javascript56// tests/performance/load-test.k6.js57import http from "k6/http";58import { check, sleep, group } from "k6";5960export const options = {61 stages: [62 { duration: "2m", target: 50 }, // Ramp up to 50 VUs63 { duration: "5m", target: 50 }, // Sustain 50 VUs64 { duration: "2m", target: 100 }, // Ramp up to 100 VUs65 { duration: "5m", target: 100 }, // Sustain 100 VUs66 { duration: "2m", target: 0 }, // Ramp down67 ],68 thresholds: {69 http_req_duration: [70 "p(50)<200", // 50th percentile under 200ms71 "p(95)<500", // 95th percentile under 500ms72 "p(99)<1000", // 99th percentile under 1s73 ],74 http_req_failed: ["rate<0.01"], // Less than 1% errors75 checks: ["rate>0.99"], // 99%+ checks pass76 },77};7879const BASE_URL = __ENV.BASE_URL || "http://localhost:3000";8081export default function () {82 group("Homepage flow", () => {83 const homeRes = http.get(`${BASE_URL}/`);84 check(homeRes, {85 "homepage returns 200": (r) => r.status === 200,86 "homepage loads under 500ms": (r) => r.timings.duration < 500,87 });8889 const apiRes = http.get(`${BASE_URL}/api/products?limit=20`);90 check(apiRes, {91 "products API returns 200": (r) => r.status === 200,92 "products returns array": (r) => Array.isArray(r.json()),93 });94 });9596 sleep(1); // Think time between iterations97}98```99100### k6 Scenarios (Advanced)101102```javascript103// tests/performance/scenarios.k6.js104import http from "k6/http";105import { check } from "k6";106107export const options = {108 scenarios: {109 // Constant arrival rate — fixed RPS regardless of response time110 constant_load: {111 executor: "constant-arrival-rate",112 rate: 100, // 100 RPS113 timeUnit: "1s",114 duration: "5m",115 preAllocatedVUs: 50,116 maxVUs: 200,117 },118 // Ramping VUs — gradual increase119 ramping_users: {120 executor: "ramping-vus",121 startVUs: 0,122 stages: [123 { duration: "2m", target: 50 },124 { duration: "3m", target: 50 },125 { duration: "1m", target: 0 },126 ],127 },128 // Spike test — sudden burst129 spike: {130 executor: "ramping-arrival-rate",131 startRate: 10,132 timeUnit: "1s",133 stages: [134 { duration: "10s", target: 10 },135 { duration: "1m", target: 500 }, // Spike136 { duration: "10s", target: 10 }, // Recover137 ],138 preAllocatedVUs: 200,139 maxVUs: 500,140 },141 },142 thresholds: {143 http_req_duration: ["p(95)<500"],144 http_req_failed: ["rate<0.01"],145 },146};147148export default function () {149 const res = http.get(`${__ENV.BASE_URL}/api/health`);150 check(res, { "status 200": (r) => r.status === 200 });151}152```153154### Running k6155156```bash157# Basic run158k6 run tests/performance/load-test.k6.js159160# With environment variables161k6 run tests/performance/load-test.k6.js --env BASE_URL=https://staging.example.com162163# Output to multiple destinations164k6 run tests/performance/load-test.k6.js \165 --out json=results.json \166 --out influxdb=http://localhost:8086/k6167168# k6 cloud (Grafana Cloud k6)169k6 cloud tests/performance/load-test.k6.js170```171172---173174## Artillery175176### YAML Configuration Example177178```yaml179# tests/performance/artillery-config.yml180config:181 target: "https://staging-api.example.com"182 phases:183 - name: "Warm up"184 duration: 60 # seconds185 arrivalRate: 5 # new virtual users per second186 - name: "Ramp up"187 duration: 120188 arrivalRate: 5189 rampTo: 50190 - name: "Sustained load"191 duration: 300192 arrivalRate: 50193 defaults:194 headers:195 Authorization: "Bearer {{ $processEnvironment.AUTH_TOKEN }}"196 Content-Type: "application/json"197 ensure:198 thresholds:199 - http.response_time.p95: 500200 - http.response_time.p99: 1000201 - http.codes.200: 95 # 95% of responses must be 200202 plugins:203 expect: {}204205scenarios:206 - name: "Browse and purchase flow"207 flow:208 - get:209 url: "/api/products"210 expect:211 - statusCode: 200212 - hasProperty: "body.length"213 capture:214 - json: "$[0].id"215 as: "productId"216 - think: 2217 - get:218 url: "/api/products/{{ productId }}"219 expect:220 - statusCode: 200221 - think: 1222 - post:223 url: "/api/cart"224 json:225 productId: "{{ productId }}"226 quantity: 1227 expect:228 - statusCode: 201229```230231### Running Artillery232233```bash234# Install Artillery235npm install -g artillery236237# Run test238artillery run tests/performance/artillery-config.yml239240# Run with environment overrides241artillery run tests/performance/artillery-config.yml --target https://staging.example.com242243# Generate HTML report244artillery run tests/performance/artillery-config.yml --output results.json245artillery report results.json --output report.html246247# Quick one-liner smoke test248artillery quick --count 10 --num 5 https://staging-api.example.com/api/health249```250251---252253## JMeter254255### Overview256Apache JMeter is a mature load testing tool with a GUI for building test plans and a CLI mode for CI execution.257258### Key Concepts259260| Concept | Description |261|---------|-------------|262| **Test Plan** | Root container for all test elements |263| **Thread Group** | Defines VUs (threads), ramp-up time, loop count |264| **Samplers** | HTTP Request, JDBC Request, FTP, etc. |265| **Assertions** | Response assertions (status, body, duration) |266| **Listeners** | Results viewers (Summary Report, Graph, JTL files) |267| **Config Elements** | CSV Data Set, HTTP Header Manager, User Variables |268| **Timers** | Think time between requests |269270### CLI Mode for CI271272```bash273# Run test plan in non-GUI mode274jmeter -n -t test-plan.jmx -l results.jtl -e -o report/275276# With properties277jmeter -n -t test-plan.jmx \278 -Jthreads=100 \279 -Jrampup=60 \280 -Jduration=300 \281 -Jhost=staging-api.example.com \282 -l results.jtl283284# Generate HTML report from results285jmeter -g results.jtl -o report/286```287288### GitHub Actions Integration289290```yaml291# .github/workflows/jmeter.yml292jobs:293 performance-test:294 runs-on: ubuntu-latest295 steps:296 - uses: actions/checkout@v4297 - name: Run JMeter Tests298 uses: rbhadti94/apache-jmeter-action@v0.5.0299 with:300 testFilePath: tests/performance/test-plan.jmx301 outputReportsFolder: reports/302 args: >303 -Jthreads=50 -Jrampup=30 -Jduration=120304 -Jhost=${{ secrets.STAGING_HOST }}305 - uses: actions/upload-artifact@v4306 if: always()307 with:308 name: jmeter-report309 path: reports/310```311312---313314## Gatling315316### Overview317Gatling uses a code-based DSL (Scala or Java) for defining simulations, producing detailed HTML reports automatically.318319### Scala DSL Example320321```scala322// src/test/scala/simulations/BasicSimulation.scala323import io.gatling.core.Predef._324import io.gatling.http.Predef._325import scala.concurrent.duration._326327class BasicSimulation extends Simulation {328329 val httpProtocol = http330 .baseUrl("https://staging-api.example.com")331 .acceptHeader("application/json")332 .authorizationHeader("Bearer ${authToken}")333334 val feeder = csv("test-data/users.csv").random335336 val browseScenario = scenario("Browse Products")337 .feed(feeder)338 .exec(339 http("List Products")340 .get("/api/products")341 .check(status.is(200))342 .check(jsonPath("$[0].id").saveAs("productId"))343 )344 .pause(1, 3)345 .exec(346 http("Get Product Detail")347 .get("/api/products/${productId}")348 .check(status.is(200))349 )350351 setUp(352 browseScenario.inject(353 rampUsers(50).during(2.minutes),354 constantUsersPerSec(10).during(5.minutes),355 rampUsers(0).during(1.minute)356 )357 ).protocols(httpProtocol)358 .assertions(359 global.responseTime.percentile(95).lt(500),360 global.successfulRequests.percent.gt(99.0)361 )362}363```364365### Running Gatling366367```bash368# Run with Maven369mvn gatling:test370371# Run with Gradle372gradle gatlingRun373374# Run specific simulation375mvn gatling:test -Dgatling.simulationClass=simulations.BasicSimulation376```377378---379380## Lighthouse381382### Overview383Lighthouse audits web performance, accessibility, best practices, and SEO. It measures Core Web Vitals and provides actionable improvement suggestions.384385### CLI Usage386387```bash388# Install Lighthouse CLI389npm install -g lighthouse390391# Run performance audit392lighthouse https://example.com \393 --output json,html \394 --output-path ./results/lighthouse \395 --chrome-flags="--headless --no-sandbox"396397# Performance-only audit398lighthouse https://example.com \399 --only-categories=performance \400 --output json \401 --output-path ./results/perf.json402403# Run with budget404lighthouse https://example.com \405 --budget-path=budgets.json \406 --output html407```408409### Performance Budget File410411```json412// budgets.json413[414 {415 "path": "/*",416 "timings": [417 { "metric": "interactive", "budget": 3000 },418 { "metric": "first-contentful-paint", "budget": 1500 },419 { "metric": "largest-contentful-paint", "budget": 2500 }420 ],421 "resourceSizes": [422 { "resourceType": "script", "budget": 300 },423 { "resourceType": "total", "budget": 1000 }424 ]425 }426]427```428429### CI Integration with Lighthouse CI430431```yaml432# .github/workflows/lighthouse.yml433jobs:434 lighthouse:435 runs-on: ubuntu-latest436 steps:437 - uses: actions/checkout@v4438 - uses: actions/setup-node@v4439 with:440 node-version: 20441 - run: npm install -g @lhci/cli442 - run: |443 lhci autorun \444 --collect.url=https://staging.example.com \445 --collect.numberOfRuns=3 \446 --assert.preset=lighthouse:recommended \447 --assert.assertions.largest-contentful-paint=warn:2500 \448 --assert.assertions.interactive=error:5000449```450451---452453## CI Integration Patterns454455### When to Run Each Test Type456457| Test Type | Trigger | Duration | Gate |458|-----------|---------|----------|------|459| **Smoke** (minimal load) | Every PR | 1-2 min | Fail PR if errors |460| **Load** (expected traffic) | Nightly or pre-release | 10-20 min | Alert on threshold breach |461| **Stress** (beyond capacity) | Pre-release | 20-30 min | Report, don't gate |462| **Soak** (extended duration) | Weekly or pre-release | 2-8 hours | Alert on degradation |463| **Lighthouse** | Every PR | 1-2 min | Warn on budget violation |464465### k6 CI Pipeline Example466467```yaml468# .github/workflows/performance.yml469name: Performance Tests470on:471 pull_request:472 branches: [main]473 schedule:474 - cron: "0 2 * * *" # Nightly at 2 AM475476jobs:477 smoke-test:478 if: github.event_name == 'pull_request'479 runs-on: ubuntu-latest480 steps:481 - uses: actions/checkout@v4482 - uses: grafana/k6-action@v0.3.1483 with:484 filename: tests/performance/smoke.k6.js485 env:486 BASE_URL: ${{ secrets.STAGING_URL }}487488 load-test:489 if: github.event_name == 'schedule'490 runs-on: ubuntu-latest491 steps:492 - uses: actions/checkout@v4493 - uses: grafana/k6-action@v0.3.1494 with:495 filename: tests/performance/load-test.k6.js496 env:497 BASE_URL: ${{ secrets.STAGING_URL }}498 - uses: actions/upload-artifact@v4499 if: always()500 with:501 name: k6-results502 path: results/503```504505---506507## Best Practices508509### Test Design510- Start with a smoke test (minimal load) to validate the test script works before scaling up.511- Use realistic think times (`sleep()` / `pause()`) to simulate actual user behavior.512- Use data-driven tests with CSV feeders or dynamic data generation to avoid caching skew.513- Test the same scenario at different load levels: smoke, load, stress, spike.514515### Metrics and Thresholds516- Always define thresholds — tests without pass/fail criteria are just logs.517- Focus on percentiles (p95, p99), not averages — averages hide tail latency.518- Track error rate alongside response time — fast errors are still failures.519- Baseline before optimizing — run tests against a known-good build first.520521### CI Integration522- Run smoke tests on every PR (fast, catches regressions early).523- Run full load tests nightly or pre-release (comprehensive, takes time).524- Store results as artifacts for trend analysis over time.525- Set thresholds as CI gates: fail the pipeline if p95 exceeds the budget.526527### Infrastructure528- Run performance tests against a dedicated staging environment, not shared dev.529- Ensure the load generator has sufficient resources (CPU, network) to avoid bottlenecking the test tool itself.530- Use distributed load generation (k6 cloud, JMeter distributed mode) for large-scale tests.531- Monitor the system under test (CPU, memory, DB connections) alongside the k6/Artillery metrics.532533### Reporting534- Generate HTML reports for human review (Gatling, JMeter, Artillery all support this).535- Export machine-readable results (JSON, JTL) for trend tracking and dashboards.536- Compare results against previous runs to catch performance regressions.537- Document performance baselines and SLAs in the repository alongside the test scripts.