k6 vs Locust: Flaky Load Tests Are Different for AI Too

A unit test that flips between pass and fail on one commit is a flake. A load test that does the same may be reporting something real: a P95 that spikes on one run and not the next can come from a noisy CI runner, a cold connection pool, or a code path that only misbehaves at high concurrency. Treating it like a flaky UI selector sends you in the wrong direction.

k6 and Locust report results in different shapes, and most teams squeeze both into a JUnit XML pipeline built for pass/fail assertions. That throws away the distribution, which is where load-test instability shows up. Agentic quality engineering adds two more reasons to keep it: coding agents now write and tune load scripts and thresholds, and more endpoints under load call a model, whose latency varies with output length and provider queueing.

This article covers why load-test flakiness is structurally different, a triage pipeline for each tool that preserves the distribution, when to choose k6 or Locust, and how to report load tests of model-backed endpoints without mixing their variance into everything else.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Why Load-Test Flakiness Is Structurally Different

A flaky unit test has a binary output and a narrow blast radius — one assertion, one thread, one process. Load tests are distributed by design: k6 runs hundreds of concurrent VUs, Locust spawns greenlets across workers, and both are sensitive to the test environment in ways a unit test never is. Shared CI runners, throttled egress, cold-start database connections, and GC pauses in the target service can all produce a "failure" that has nothing to do with the code under test. The standard approaches to identifying flaky tests — rerun on the same commit, compare pass rates over time — are necessary but not sufficient here, because the variance source is often infrastructural, not stochastic at the test level.

The second structural difference is that load tests produce metric streams, not assertions. k6 emits time-series data (http_req_duration, http_req_failed, vus) that you threshold into pass/fail via thresholds blocks. Locust emits an HTML report and a CSV. Neither maps cleanly onto JUnit XML semantics. When you force them to, you lose the distribution — and the distribution is exactly where flakiness lives in a load test. A test that passes at P50 but fails at P99 on 30% of runs is telling you something; a red/green badge is not.

Building a Triage Pipeline That Preserves Distribution Signal

Start with k6's built-in InfluxDB or Prometheus remote-write output instead of JUnit XML. Every threshold breach is still surfaced in CI, but you retain the full histogram for post-run analysis. A minimal GitHub Actions step looks like this:

# .github/workflows/load-test.yml
- name: Run k6 load test
  run: |
    k6 run \
      --tag run_id=${{ github.run_id }} \
      --tag branch=${{ github.ref_name }} \
      --out influxdb=http://influx:8086/k6 \
      --out json=results/k6-run-${{ github.run_id }}.json \
      scripts/checkout-flow.js

The JSON output gives you per-request timing at full fidelity. The --tag flags attach run_id and branch to every metric sample, so you can diff two runs directly in Grafana without joining on timestamps. (k6's built-in influxdb output targets InfluxDB 1.x; InfluxDB 2.x needs the xk6 output extension.) Once you have three or more runs stored, a Grafana panel of P95 per run makes spread visible much faster than reading CI logs, and correlating it with target-service logs in Loki by timestamp shortens the search for a cause.

For Locust, the CSV output is more tractable than the HTML report for automation. Run Locust with --csv=locust --csv-full-history so the history file has per-endpoint rows (without the second flag it only records the aggregate). A lightweight Python analyzer that flags endpoints whose P95 varies by more than 15% over the run:

import pandas as pd, sys

df = pd.read_csv("locust_stats_history.csv")
df = df[df["Name"] != "Aggregated"]
df["95%"] = pd.to_numeric(df["95%"], errors="coerce")  # early rows can be "N/A"
grouped = df.groupby("Name")["95%"].agg(["mean", "std"])
flagged = grouped[grouped["std"] / grouped["mean"] > 0.15]
if not flagged.empty:
    print("High-variance endpoints (CV > 15%):")
    print(flagged.to_string())
    sys.exit(1)

A coefficient of variation above 15% on a single endpoint is a useful heuristic for environment noise or a genuinely unstable code path rather than a threshold misconfiguration. Exclude the ramp-up period before computing it, and compare the same figure across runs before you call an endpoint unstable. Wire this script as a post-step in your CI job and you get a structured failure reason instead of "load test failed." For teams tracking this over time, a quarterly reliability scorecard that includes load-test CV alongside unit-test flake rates gives engineering leaders a single view of where variance is actually costing sprint time.

k6 vs Locust: Which Tool Exposes Flakiness Better

Use k6 when you need deterministic VU scheduling, scripted think-times, and first-class Prometheus/Grafana integration. k6's thresholds block makes pass/fail explicit and auditable; the JSON output retains full histogram data. Use Locust when your load shape is dynamic, you need Python-native test logic (e.g., stateful sessions, custom auth flows), or your team already owns a Python observability stack. Locust's distributed mode is easier to scale horizontally in Kubernetes without a k6 operator. The trade-off: Locust's built-in reporting is weaker — you'll spend more time on the analyzer layer described above.

Pitfalls That Senior Engineers Still Hit

The most common mistake is setting absolute latency thresholds without accounting for baseline drift. A threshold of p(95) < 500 written six months ago against a lightly loaded staging environment will produce false failures after a schema migration or a dependency upgrade — not because the code regressed, but because the baseline moved. The fix is relative thresholds: compare P95 against the rolling 7-run average, not a hardcoded number. Both k6 (via custom summary scripts) and Locust (via the CSV analyzer) support this; almost nobody implements it until they've wasted a week chasing phantom regressions. This is also where CI observability metrics beyond raw pass/fail pay off — tracking threshold breach rate as a separate signal from raw latency tells you when your thresholds are miscalibrated, not just when the service is slow.

The second pitfall is running load tests on shared CI runners and attributing variance to the application. Noisy-neighbor CPU contention on a small shared runner generating hundreds of VUs can inflate P99 unpredictably, because the load generator itself becomes the bottleneck. The org-level cause is cost pressure on CI infrastructure; the fix is dedicated runner pools or a reserved cloud instance for load tests, tagged in your cost allocation. If dedicated runners aren't feasible, at minimum tag every run with the runner's CPU idle percentage at test start and filter outlier runs before computing variance baselines.

Load-testing model-backed endpoints and agent-written scripts

An endpoint that calls a model has a wider and lumpier latency distribution than a database-backed one, and the spread has causes your own code does not control: the length of the generated output, provider-side queueing and rate limiting. If you threshold it like any other endpoint, it will look flaky on every run.

  • Tag the model and prompt version on every request. In k6, pass them as request tags or with --tag; in Locust, use a distinct request name per variant. A P95 shift that lines up with a model change is a regression, not noise.
  • Measure what the user waits for. For streaming responses, time to first token and total time answer different questions. Record both if your client can, and set thresholds on each.
  • Count 429s separately. Provider rate-limit responses depend on request rate and quota. Keep them out of the error rate you use to judge your service, and report them as their own line.
  • Report output validity as a rate. A k6 check or a Locust response validator that verifies the response schema should feed a valid-output rate per run, compared with a threshold, rather than failing the run on one bad answer.

When a coding agent writes or edits a load script, check the thresholds it chose as carefully as the script. The easy way for an agent to make a red load test green is to loosen p(95)<500 to a number the current build already meets. Require threshold changes to be reviewed by a person, and show the old and new values in the job summary. Before a new script's results join the trend data, run it a few times at a fixed, low VU count: high spread there points at the script or the environment, not the service.

What Most Teams Get Wrong About Load-Test Reliability

The dominant myth is that a passing load test means the service is reliable. A load test that consistently passes at 200 VUs with P95 < 400ms tells you the service is reliable under that specific synthetic load shape. It says nothing about burst traffic, cache cold-starts, or the latency distribution at the 99.9th percentile. Failure rate looks healthy when slow tests stop running — the same dynamic applies here: if your load test ramp-up is too gentle to trigger connection pool exhaustion, you'll never see the failure mode that takes down production at 3 AM. Complement load tests with synthetic tests as production observability to catch what the CI load test misses.

The second misunderstanding is treating load-test flakiness as unfixable noise. Teams will quarantine a flaky unit test immediately but leave a load test that fails on 1 in 4 runs because "load tests are inherently variable." They're variable, but not arbitrarily so. A CV above 15% on a specific endpoint is a tractable signal. Instrument it, correlate it with target-service GC logs or database connection wait times, and you'll find a root cause within two or three runs. The variability is the signal — not a reason to ignore the test.

Load-test flakiness is an observability problem before it's a tooling problem. k6 gives you better out-of-the-box metric fidelity; Locust gives you more flexibility in the analysis layer — pick based on your stack, not hype. Either way, stop collapsing histograms into booleans. Wire run IDs into your time-series store, build a CV-based variance detector, and treat a high-variance endpoint as a first-class bug. For a structured way to track progress, the quarterly reliability scorecard pattern applies directly to load-test stability metrics.

Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.

Understanding how systems actually work is the first step toward navigating them effectively.

Browse all articles