Skip to content

test(e2e): add Locust throughput load test that runs last - #33748

Merged
yassin-berriai merged 3 commits into
litellm_internal_stagingfrom
litellm_lit4557_locust_load_test
Jul 18, 2026
Merged

yassin-berriai merged 3 commits into
litellm_internal_stagingfrom
litellm_lit4557_locust_load_test

Conversation

@yassin-berriai

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Resolves LIT-4557

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Type

✅ Test

Changes

CodSpeed benchmarks the SDK with no IO, so it can't catch regressions that only appear under real concurrent load through the full proxy stack (auth, routing, logging, spend, Postgres, Redis). Past regressions in this class, for example a Redis SSL config bug that forced a TLS handshake per request and a dependency bump that added per-request overhead, were only visible under a real load test. The original customer load setup isn't reproducible, so this adds a Locust load test to the e2e suite that runs against the berrie-litellm-stage EKS cluster instead

The new tests/e2e/load suite drives real concurrent POST /chat/completions traffic through the live proxy with Locust and asserts an aggregate throughput SLO (minimum RPS) with a failure-ratio guard so a run that mostly errors can't masquerade as passing throughput. Traffic targets a mock deployment (litellm_params.mock_response), so the number reflects proxy overhead rather than a provider's latency, cost, or rate limit, while still exercising the whole request path. Every knob (users, spawn rate, duration, RPS floor, failure ratio) is env-overridable, so the same test points at stage EKS (defaults: 750 users, 60s, 355 RPS floor) or a smaller local compose stack

Locust runs as a subprocess because it monkey-patches the stdlib with gevent at import, which deadlocks pytest's own machinery when imported in-process; the generator lives in its own interpreter (locustfile.py) and reports back through its --json summary. Locust is invoked with --exit-code-on-error 0 so that per-request failures are folded into that JSON summary and adjudicated by the test's explicit failure-ratio assertion, rather than surfacing as an opaque CalledProcessError; a nonzero exit now means only a genuine startup failure, which the wrapper raises with the captured stderr. The shared model name lives in one load_constants.py so the fixture that registers the mock deployment and the test that drives traffic to it can never drift

The test is marked load and pytest_collection_modifyitems in the parent conftest sorts load-marked items last, so on a whole-tree pytest tests/e2e run it executes after the latency-sensitive suites and never perturbs them. It covers the existing reliability.perf.throughput.under_slo registry cell. locust==2.45.0 is added to the e2e-dev dependency group with uv.lock kept in sync, and mock_response is added to the e2e LiteLLMParamsBody model so the mock deployment can be registered through /model/new

Screenshots / Proof of Fix

This test intentionally targets a mock deployment rather than a real provider (the whole point is to measure proxy overhead under concurrency, not provider latency), so the usual "real provider call costing real $" proof doesn't apply here; the proof below instead shows the full proxy path (proxy + Postgres + Redis via docker-compose) serving the mock model and Locust sustaining throughput with zero failures. Captured at commit c880df3c64

The suite itself, run through pytest against the full local stack, passes and reports its coverage cell:

$ LITELLM_PROXY_URL=http://localhost:4557 E2E_LOAD_USERS=150 E2E_LOAD_SPAWN_RATE=75 \
    E2E_LOAD_DURATION_SECONDS=15 E2E_LOAD_MIN_RPS=100 uv run pytest tests/e2e/load/ -v
load/test_chat_completions_throughput_e2e.py::TestChatCompletionsThroughput::test_sustains_throughput_slo_under_load
  E2E_RESULT package=load outcome=passed duration_ms=15278 covers=reliability.perf.throughput.under_slo
PASSED [100%]
============================== 1 passed in 16.23s ==============================

Single request through the full proxy stack to the mock deployment:

$ curl -s -X POST http://localhost:4557/chat/completions \
    -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
    -d '{"model":"load-mock","messages":[{"role":"user","content":"hi"}],"max_tokens":16}'
{
  "model": "load-mock",
  "object": "chat.completion",
  "choices": [{"finish_reason": "stop", "index": 0,
    "message": {"content": "This is a mock response for the throughput load test.", "role": "assistant"}}],
  "usage": {"completion_tokens": 20, "prompt_tokens": 10, "total_tokens": 30}
}

Locust driving concurrent load through the same proxy (150 users, 15s, local single-container compose):

$ LOAD_API_KEY=$KEY LOAD_MODEL=load-mock python -m locust -f tests/e2e/load/locustfile.py \
    --headless -u 150 -r 75 -t 15s --host http://localhost:4557 --exit-code-on-error 0
Type     Name                # reqs      # fails |    Avg     Min     Max    Med |   req/s  failures/s
         Aggregated            1217     0(0.00%) |    405      39    2912    290 |  216.00        0.00

QA runbook

  • tests/e2e/load/test_chat_completions_throughput_e2e.py::TestChatCompletionsThroughput::test_sustains_throughput_slo_under_load - the proxy sustains its throughput SLO on /chat/completions under concurrent load against a mock deployment, with a near-zero failure rate
    • Bring up the full local stack (proxy + Postgres + Redis): docker compose -f tests/e2e/docker-compose.yml up -d and wait for curl -s -o /dev/null -w '%{http_code}' http://localhost:4000/health/liveliness to return 200
    • Run the suite against a small local load: E2E_LOAD_USERS=150 E2E_LOAD_SPAWN_RATE=75 E2E_LOAD_DURATION_SECONDS=15 E2E_LOAD_MIN_RPS=100 uv run pytest tests/e2e/load/ -v and expect the test to pass with 0 request failures (defaults of 750 users / 355 RPS are meant for berrie-litellm-stage, not a laptop)
    • Confirm ordering: uv run pytest tests/e2e/router tests/e2e/load tests/e2e/access_control --collect-only -q lists the load test last regardless of the argument order
    • Sanity check: this test makes sense to add and is not hand-wavey; it asserts a real aggregate RPS floor plus a failure-ratio ceiling (so an all-error run can't pass), and the mock deployment is deliberate so the measurement isolates proxy overhead rather than a provider's latency

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@yassin-berriai
yassin-berriai requested a review from a team July 17, 2026 18:37
@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codecov

codecov Bot commented Jul 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a Locust-based throughput load test to the tests/e2e/load/ suite that drives real concurrent POST /chat/completions traffic through the live proxy stack against a mock_response deployment, then asserts a minimum RPS floor and a maximum failure-ratio ceiling so an error-saturated run can't masquerade as passing throughput.

  • Locust runs as a subprocess (avoiding gevent/pytest deadlock), emits --json stats, and the wrapper aggregates them into a LoadResult; non-zero exit codes now map to descriptive RuntimeErrors, and a zero-exit with unparseable output does too.
  • A session-scoped autouse fixture registers the mock model idempotently (with a post-failure re-check to handle concurrent sessions) and cleans it up on exit; all five load knobs (users, spawn rate, duration, RPS floor, failure ratio) are env-overridable so the same test points at stage EKS or a local compose stack.
  • The load marker and a pytest_collection_modifyitems sort ensure the load test always runs last in a whole-tree pytest tests/e2e invocation, preventing it from perturbing latency-sensitive suites.

Confidence Score: 5/5

Safe to merge — adds new test infrastructure only, touches no production code paths.

All changed files are under tests/e2e/ (plus pyproject.toml adding locust to the e2e-dev group). The load runner, fixtures, and assertions are well-implemented: the subprocess pattern correctly isolates gevent, the RPS/failure-ratio assertions guard against false passes, the model-registration fixture handles races idempotently, and the JSON parse error path wraps failures descriptively. No production or SDK code is modified.

No files require special attention.

Important Files Changed

Filename Overview
tests/e2e/load/locust_load.py Core load runner: spawns Locust as a subprocess with --json output, wraps parse errors descriptively, aggregates RPS from per-entry timestamps correctly
tests/e2e/load/conftest.py Session-scoped fixture registers the mock deployment (with idempotent check + race-condition guard) and provides a per-test scoped key; lifecycle cleanup is correct
tests/e2e/load/locustfile.py Locust user class: reads API key and model from env at import time (correct since it runs in a subprocess), drives POST /chat/completions at maximum rate with zero wait time
tests/e2e/load/test_chat_completions_throughput_e2e.py Three-assertion test: zero-traffic guard, failure-ratio ceiling, and RPS floor; all env-overridable; marked e2e+load; clear failure messages
tests/e2e/conftest.py Adds load marker registration and a stable sort that places load-marked items last; sort key is correct (False < True puts non-load items first)
tests/e2e/e2e_config.py Adds five env-overridable load parameters with sensible stage-EKS defaults; consistent with existing config pattern
tests/e2e/models.py Adds optional mock_response field to LiteLLMParamsBody so the load suite can register a mock deployment via /model/new without touching prod models
pyproject.toml Pins locust==2.45.0 to the e2e-dev dependency group; isolated from prod and SDK deps

Reviews (2): Last reviewed commit: "test(e2e): add Locust throughput load te..." | Re-trigger Greptile

Comment thread tests/e2e/load/locust_load.py Resolved
Comment thread tests/e2e/load/locust_load.py Resolved
CodSpeed benchmarks the SDK with no IO, so it can't catch regressions that
only appear under real concurrent load through the full proxy stack (auth,
routing, logging, spend, Postgres, Redis). This adds a Locust load test under
tests/e2e/load that drives concurrent POST /chat/completions traffic against a
mock deployment (litellm_params.mock_response), so the measured throughput
reflects proxy overhead rather than a provider's latency, and asserts an
aggregate RPS SLO with a failure-ratio guard. The test is marked load and the
parent conftest sorts load-marked items last so it never perturbs
latency-sensitive suites. Covers reliability.perf.throughput.under_slo.
@yassin-berriai
yassin-berriai force-pushed the litellm_lit4557_locust_load_test branch from c880df3 to abf2af1 Compare July 17, 2026 18:49
@yassin-berriai

Copy link
Copy Markdown
Contributor Author

@greptileai please review the current head abf2af1.

Two items from the last review:

  • P1 (double-count in _aggregate): this is a false alarm. Locust's --json output comes from RequestStats.serialize_stats(), which iterates only self.entries.values() and excludes self.total (the Aggregated StatsEntry). The Aggregated row is printed by the console table, not by --json. Verified empirically on locust 2.45.0: a headless --json run with the single /chat/completions task prints exactly one stdout entry, and run_chat_load reports single-count RPS (14806 requests over ~5s -> 3022.9 RPS, not ~6000). No code change; the suggested name-filter would drop the only real entry.

  • P2 (opaque parse error): fixed in abf2af1. The --json parse is now wrapped and raises a descriptive RuntimeError with stdout/stderr if locust exits 0 without parseable stats.

@codspeed

codspeed Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit4557_locust_load_test (9feed39) with litellm_internal_staging (010b200)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (08fa250) during the generation of this report, so 010b200 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

…itellm_lit4557_locust_load_test

# Conflicts:
#	uv.lock
@yassin-berriai
yassin-berriai enabled auto-merge (squash) July 18, 2026 18:34
… merge

The staging merge left two pytest_collection_modifyitems hooks in
tests/e2e/conftest.py (one attaching JUnit result properties, one sorting
load-marked items last), so basedpyright flagged the first as obscured by
the second (reportRedeclaration) and pytest would only run the last. Fold
both into a single hook.
@yassin-berriai
yassin-berriai merged commit a2614b1 into litellm_internal_staging Jul 18, 2026
78 checks passed
@yassin-berriai
yassin-berriai deleted the litellm_lit4557_locust_load_test branch July 18, 2026 18:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants