locust-load-testing
Authors Locust load tests as Python classes - HttpUser with @task-decorated methods plus on_start hooks and between() wait_time - runs via `locust -f locustfile.py` headless mode (or distributed via `--master` / `--worker`), and exports CSV / JUnit reports for CI gating. Use when the project's primary stack is Python and the team wants load tests in the same language as the application.
Install with skills.sh (any agent)
npx skills add testland/qa --skill locust-load-testinglocust-load-testing
Locust tests are Python classes inheriting from HttpUser; each @task-decorated method is an action a virtual user can take (locust-quickstart (opens in new window)). Workflow: write locustfile.py, run locust, observe the live dashboard or run headless for CI.
When to use
If the team isn't on Python and just needs HTTP perf testing, k6-load-testing is lower-friction. For JVM, prefer gatling-load-testing.
Install
pip install locust(Per locust-quickstart (opens in new window), current stable is the 2.x series.)
For a per-project install (preferred for CI determinism):
pip install -r requirements-load.txt # contains 'locust>=2.43'Authoring
Minimal locustfile
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 3) # 1-3 seconds between tasks per user
def on_start(self):
# Runs once per virtual user when they start
self.client.post("/login", json={"user": "test", "pass": "secret"})
@task
def index_page(self):
self.client.get("/")
@task(3) # weighted - runs 3x as often as unweighted tasks
def view_item(self):
self.client.get("/items/42")(Adapted from locust-quickstart (opens in new window).)
| Construct | Purpose |
|---|---|
HttpUser | Base class; provides self.client (a Requests-style HTTP client). |
@task | Marks a method as a callable VU action. |
@task(N) | Weighted task - gets N "lottery tickets" vs. unweighted's 1. |
wait_time = between(min, max) | Random pause between tasks per VU. |
on_start(self) | Runs once per VU at startup (auth, session setup). |
on_stop(self) | Runs once per VU before exit (cleanup). |
self.client.<verb>(...) | Standard Requests-like methods that auto-track latency / errors. |
Naming requests for clean stats
The default request name is the URL path; for parameterized URLs use the name= kwarg to keep the stats grouped:
@task
def view_item(self):
item_id = random.randint(1, 1000)
# Without name=, every URL like /items/42, /items/43 is its own row
# With name=, all roll up under "/items/[id]"
self.client.get(f"/items/{item_id}", name="/items/[id]")Without name=, the stats table fragments into thousands of near-duplicate rows.
Running
Interactive (Web UI)
locust -f locustfile.pyOpen http://localhost:8089; configure VU count + spawn rate + host in the browser; observe the live charts. The default mode for authoring / tuning.
Headless (CI)
Per locust-quickstart (opens in new window):
locust --headless --users 10 --spawn-rate 1 -H http://your-server.com| Flag | Purpose |
|---|---|
--headless | Run without the web UI (CI mode). |
--users <N> | Peak concurrent users. |
--spawn-rate <N> | Users spawned per second until peak is reached. |
--host <url> | Target host (override host attribute on the user class). |
--run-time <dur> | Total run duration (e.g. 5m, 30s); auto-stops at expiry. |
--csv <prefix> | Write <prefix>_stats.csv, <prefix>_stats_history.csv, |
<prefix>_failures.csv, <prefix>_exceptions.csv. | |
--html <file> | Write a final HTML report. |
A typical CI invocation:
locust -f locustfile.py \
--headless \
--users 100 \
--spawn-rate 10 \
--run-time 5m \
--host https://staging.example.com \
--csv results \
--html report.html \
--exit-code-on-error 1--exit-code-on-error 1 tells Locust to exit non-zero if any request failed during the run - the canonical CI gate.
Distributed mode
Per locust-quickstart (opens in new window):
# On the master node
locust -f locustfile.py --master --headless --users 1000 --spawn-rate 50 --host https://staging.example.com
# On each worker node
locust -f locustfile.py --worker --master-host master.internalThe master coordinates; workers generate the actual load. Use this when a single machine can't generate enough VUs (typically beyond ~1000 VUs depending on the target's response time and the worker's CPU).
Reports
Locust outputs three CSVs on --csv <prefix>:
| File | Content |
|---|---|
<prefix>_stats.csv | Aggregate per-request stats: count, avg, p50, p90, p95, p99. |
<prefix>_stats_history.csv | Per-second time-series of the same metrics. |
<prefix>_failures.csv | Per-failure rows: name, reason, count. |
<prefix>_exceptions.csv | Python exception stacks (if any task raised). |
The HTML report (--html) renders charts from the same data - for human review.
CI integration
# .github/workflows/locust.yml
name: load-test
on:
pull_request:
paths: ['tests/load/**']
schedule:
- cron: '0 4 * * *'
jobs:
locust:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: pip install locust
- name: Run Locust headless
env:
API_TOKEN: ${{ secrets.STAGING_API_TOKEN }}
run: |
locust -f tests/load/locustfile.py \
--headless \
--users 50 \
--spawn-rate 5 \
--run-time 3m \
--host https://staging.example.com \
--csv results \
--html report.html \
--exit-code-on-error 1
- name: Custom threshold gate
run: |
# Fail if p95 > 500ms on any endpoint
python - <<'PY'
import csv, sys
with open('results_stats.csv') as f:
for row in csv.DictReader(f):
if row['Name'] == 'Aggregated':
continue
p95 = float(row['95%'])
if p95 > 500:
print(f"::error::p95 {p95}ms on {row['Name']} (>500 budget)")
sys.exit(1)
PY
- name: Upload reports
if: always()
uses: actions/upload-artifact@v4
with:
name: locust-reports
path: |
results_stats.csv
results_stats_history.csv
results_failures.csv
report.html
retention-days: 14The custom Python gate parses results_stats.csv - Locust's --exit-code-on-error only fails on errors; latency budgets need the post-run check.
Anti-patterns
| Anti-pattern | Why it fails | Fix |
|---|---|---|
| Hardcoded URLs in the locustfile | Tests bind to one environment. | Read host from os.environ or pass via -H. |
Missing name= on parameterized URLs | Stats fragment into 1000s of rows; reports unreadable. | Always specify name= for variable URL segments. |
Low wait_time to "stress more" | Hammering at full rate doesn't model real users; client CPU saturates. | Use between(1, 3) or longer; if the goal is a target RPS, use --users × wait_time to compute. |
| Running interactive (Web UI) in CI | Locust waits for the user to click "Start swarming"; CI hangs. | Always --headless with --users / --spawn-rate / --run-time. |
Skipping --exit-code-on-error | Locust exits 0 even with failures; CI sees green. | Always include the flag. |
| Single-master 1000+ VUs from one machine | CPU saturates the load generator before the target. | Distribute via --master / --worker. |
Limitations
References
Related skills
db-query-plan-analyzer
Reads `EXPLAIN` / `EXPLAIN ANALYZE` output from PostgreSQL, MySQL, or SQLite - identifies the dominant cost (sequential scan, nested loop, sort spill, missing index, type-cast preventing index use), proposes the specific index or query rewrite to fix it, and emits the candidate `CREATE INDEX` statement. Use when load testing or production telemetry shows the database as the bottleneck and the team needs targeted query-level remediation.
flame-graph-analyzer
Reads CPU flame-graph output from py-spy (Python), async-profiler (JVM), Go pprof, or Node.js `perf_hooks` / clinic.js: identifies the hot path (top sample-time frames), classifies the bottleneck (CPU-bound vs lock contention vs allocator pressure), and proposes the next investigation step. Use when a perf regression is bisected to a commit but the hot path inside it is unclear; for tail-latency percentiles use latency-percentile-analyzer, for GC pauses specifically use jvm-gc-tuning, and for a slow SQL hot path use db-query-plan-analyzer.
gatling-load-testing
Authors Gatling simulations in Java / Kotlin / Scala (or JS / TS) using the Simulation class plus http() / scenario() / exec() DSL builders, ramps virtual users via injectOpen (arrival rate) or injectClosed (concurrent count), runs via Maven / Gradle / sbt with the Gatling plugin, and gates CI on assertions defined in setUp(). Use when the project is on the JVM and the team prefers code-first load tests over JMeter's XML or k6's JavaScript-only authoring.
jmeter-load-testing
Authors Apache JMeter `.jmx` test plans (Thread Groups + HTTP samplers + assertions + listeners) in the JMeter GUI, runs them headlessly via `jmeter -n -t plan.jmx -l results.jtl`, generates an HTML dashboard with `-e -o`, and gates CI on JTL parsing. Use when the project has an existing JMeter investment, needs JVM-native load tooling, or works in domains with strong JMeter community support (banking, telecom, enterprise).
jvm-gc-tuning
Diagnoses JVM garbage-collection behaviour under load: reads and interprets unified GC logs (-Xlog:gc*), selects the right collector (G1 vs ZGC vs Parallel vs Serial), tunes heap sizing and pause-time targets, quantifies allocation rate, and traces the GC-pause-to-latency-tail link using GCViewer and Java Flight Recorder (JFR). Use when a load test reveals p99/p999 latency spikes that correlate with GC activity, or when heap sizing and collector selection need justification before a performance baseline is locked.
k6-load-testing
Authors k6 JavaScript load-test scripts (VU loops + checks + sleeps), configures the `options` block with `stages` (ramp-up patterns) and `thresholds` (p(95) latency, error rate), runs via `k6 run script.js` or `--vus / --duration` ad-hoc flags, and uses thresholds as the CI pass/fail signal. Use when the project ships HTTP / WebSocket / gRPC load tests and the team wants developer-friendly JavaScript authoring.
latency-percentile-analyzer
Interprets latency distributions from k6 load tests beyond the p95/p99 gate: reads percentile summaries and JSON exports to identify tail shape, computes the tail ratio (p99/p50) as a distribution-spread signal, detects bimodal distributions, explains coordinated omission and why naive p99 values are optimistic under sustained load, and distinguishes request-rate from concurrency models. Use when a k6 threshold passes but the system still feels slow, when p99 is suspiciously low during ramp-up, or when the team needs to explain why tail latency is high rather than just observing that it is.
lighthouse-budget-author
Drafts a `lighthouserc.js` (or `budget.json`) at design time - picks Web Vitals thresholds (LCP / INP / CLS) per route based on traffic class (cached / dynamic / API-heavy / form-heavy) and the team's NFRs, plus resource-size budgets (JS / CSS / images / total bytes). Emits the config file ready for the lighthouse-perf runner. Use when starting Lighthouse coverage on a project that has no budgets yet, or when the existing budgets need a redesign.
lighthouse-perf
Configures Lighthouse CI (`@lhci/cli`) to audit Web Vitals (LCP, INP, CLS) on every PR, asserts against canonical thresholds (LCP ≤2.5s, INP ≤200ms, CLS ≤0.1 at the 75th percentile), uploads Lighthouse reports as build artifacts, and posts deltas as PR comments. Use when the project ships a web frontend and the team needs continuous Web Vitals monitoring tied to PR gating.
load-testing-overview
Teaches load and performance testing from zero: how to choose between k6, JMeter, Gatling, Locust, and Artillery based on observable project facts (team language, tests-as-code vs GUI authoring, protocols beyond HTTP, CI gating needs); the six load profiles (smoke, average-load, stress, spike, soak, breakpoint) and the question each one answers; the difference between open workload models that hold arrival rate constant and closed models that hold concurrent users constant; why percentiles rather than averages are the unit of measurement; and how to turn a run into a pass/fail CI gate, with a first runnable k6 script. Use when a service needs performance coverage and the tool, the load profile, or the pass/fail threshold has not been decided yet.
perf-budget-gate
Builds a unified release-readiness gate that aggregates verdicts from any combination of k6 / JMeter / Gatling / Locust load runners and Lighthouse CI Web Vitals, applies severity-aware pass/fail thresholds, and emits a single go / no-go decision with per-metric deltas vs the main-branch baseline. Posts the delta as a PR comment when the team has the integration set up. Use when authoring a CI step that gates a deployment on cross-runner perf compatibility.
slo-load-test-plan
Turns a service's SLOs and endpoint traffic mix into a named scenario matrix: one scenario per SLO boundary condition, a load profile (smoke, average-load, stress, soak, spike, breakpoint) per scenario, an open or closed workload injection model, a threshold expression derived from the SLO the scenario guards, and an error-budget calculation that sets the soak run's failure allowance. Stays runner-agnostic and fixes the pass/fail line before any tool is configured. Use when an SLO document and an endpoint list both exist but nobody has decided which load runs to make, what shape of load each carries, or what number would count as a failure.