Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test(e2e): cover key rpm/tpm rate limiting, window reset, and pacing headers

mateo-berrib9aef1b8106d
diff --git a/tests/e2e/CLAUDE.md b/tests/e2e/CLAUDE.md
index 88992038cb7..6b1b9950656 100644
--- a/tests/e2e/CLAUDE.md
+++ b/tests/e2e/CLAUDE.md
@@ -11,7 +11,7 @@ Each subdirectory under `tests/e2e/` is one suite, scoped to an endpoint family
- `embeddings/` - the `/embeddings` endpoint across providers
- `batches/` - the `/batches` endpoint (placeholder until the first test lands)
- `realtime/` - realtime websocket sessions, including the pipecat audio path
-- `quota_management/` - quota enforcement and accounting, one subfolder per behavior: `budgets/` (budget definition, enforcement, and reset windows: key, team, tag, soft, multi-window) and `spend_tracking/` (spend logging and cost attribution on `/spend/*`)
+- `quota_management/` - quota enforcement and accounting, one subfolder per behavior: `ratelimit/` (rpm/tpm blocks, window reset, pacing headers on live traffic), `budgets/` (budget definition, enforcement, and reset windows: key, team, tag, soft, multi-window), and `spend_tracking/` (spend logging and cost attribution on `/spend/*`)
- `management/` - key/team/user/organization management routes: create/update/delete persistence via the info routes, team membership, and llm-only-key route denials; also the dashboard UI behavior on top of them, driven through the proxy-served UI at /ui with playwright (optional dep behind importorskip)
- `logging/` - logging-integration delivery (datadog and friends)
- `security/` - secret handling and log-leak protection
diff --git a/tests/e2e/e2e_http.py b/tests/e2e/e2e_http.py
index 32005faed4b..ad53b2b4aa2 100644
--- a/tests/e2e/e2e_http.py
+++ b/tests/e2e/e2e_http.py
@@ -109,14 +109,16 @@ class StreamingResponse(BaseModel):
"""Raw outcome for calls whose body is provider-native or streamed: status, the
x-litellm-call-id header, the x-litellm-response-cost header (StandardLogging
response_cost), the content-type (which tells streaming `text/event-stream` from
- non-streaming `application/json`), and the body. SpendLogs.request_id is the
- completion body id, not call_id. Used by passthrough and streaming, where one
- validated JSON model does not fit."""
+ non-streaming `application/json`), the response headers (lowercased names, e.g.
+ the x-ratelimit-* pacing headers and retry-after on a 429), and the body.
+ SpendLogs.request_id is the completion body id, not call_id. Used by passthrough
+ and streaming, where one validated JSON model does not fit."""
status_code: int
call_id: str | None = None # x-litellm-call-id header
response_cost: float | None = None # x-litellm-response-cost header
content_type: str | None = None
+ headers: dict[str, str] = {}
body: str
chunks: int = 0 # streamed events (0 for non-streaming)
@@ -276,12 +278,14 @@ def _streaming_outcome(resp: requests.Response, stream: bool) -> StreamingRespon
call_id = _hdr(resp, "x-litellm-call-id")
response_cost = _parse_response_cost(resp)
content_type = _hdr(resp, "content-type")
+ headers = {name.lower(): value for name, value in resp.headers.items()}
if not stream or not (200 <= resp.status_code < 300):
return StreamingResponse(
status_code=resp.status_code,
call_id=call_id,
response_cost=response_cost,
content_type=content_type,
+ headers=headers,
body=resp.text,
)
lines = cast("Iterator[bytes]", resp.iter_lines())
@@ -291,6 +295,7 @@ def _streaming_outcome(resp: requests.Response, stream: bool) -> StreamingRespon
call_id=call_id,
response_cost=response_cost,
content_type=content_type,
+ headers=headers,
body="<streamed>",
chunks=chunks,
)
diff --git a/tests/e2e/management/test_management_e2e.py b/tests/e2e/management/test_management_e2e.py
index cbd5db0d59f..7a05a5c520f 100644
--- a/tests/e2e/management/test_management_e2e.py
+++ b/tests/e2e/management/test_management_e2e.py
@@ -111,7 +111,7 @@ class TestKeyRoutes:
key = _generate_key(
client,
resources,
- KeyGenerateBody(models=["gemini-2.5-flash"], key_alias=alias, tpm_limit=424242),
+ KeyGenerateBody(models=["gemini-2.5-flash"], key_alias=alias, tpm_limit=424242, rpm_limit=424243),
)
info = client.gateway.key_info(key)
@@ -122,6 +122,9 @@ class TestKeyRoutes:
assert info.tpm_limit == 424242, (
f"/key/info reports tpm_limit {info.tpm_limit}, configured 424242"
)
+ assert info.rpm_limit == 424243, (
+ f"/key/info reports rpm_limit {info.rpm_limit}, configured 424243"
+ )
_poll_chat_ok(client, key, "gemini-2.5-flash")
_assert_model_denied(
diff --git a/tests/e2e/models.py b/tests/e2e/models.py
index e32f2709181..ebd082161e0 100644
--- a/tests/e2e/models.py
+++ b/tests/e2e/models.py
@@ -82,6 +82,7 @@ class KeyInfo(BaseModel):
key_alias: str | None = None
models: list[str] = []
tpm_limit: int | None = None
+ rpm_limit: int | None = None
team_id: str | None = None
spend: float | None = None
max_budget: float | None = None
diff --git a/tests/e2e/quota_management/ratelimit/conftest.py b/tests/e2e/quota_management/ratelimit/conftest.py
new file mode 100644
index 00000000000..4a5a73bb5e4
--- /dev/null
+++ b/tests/e2e/quota_management/ratelimit/conftest.py
@@ -0,0 +1,15 @@
+"""Quota-management suite's `client` fixture.
+
+The shared lifecycle (resources/scoped_key), proxy liveness skip, and e2e marker
+live in the parent tests/e2e/conftest.py. QuotaClient holds the shared Gateway,
+so the `resources` fixture cleans up keys through it.
+"""
+
+import pytest
+
+from quota_client import QuotaClient, build_client
+
+
[email protected](scope="session")
+def client() -> QuotaClient:
+ return build_client()
diff --git a/tests/e2e/quota_management/ratelimit/quota_client.py b/tests/e2e/quota_management/ratelimit/quota_client.py
new file mode 100644
index 00000000000..806ab1d1557
--- /dev/null
+++ b/tests/e2e/quota_management/ratelimit/quota_client.py
@@ -0,0 +1,32 @@
+"""Client for the quota-management suite: the shared Gateway plus raw chat
+calls judged by HTTP status, body, and headers (a rate-limit block is a 429
+whose body and retry-after header carry the contract, not a typed success
+model)."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from e2e_gateway import Gateway, build_gateway
+from e2e_http import StreamingResponse
+from models import ChatBody, ChatMessage
+
+
+@dataclass(frozen=True, slots=True)
+class QuotaClient:
+ gateway: Gateway
+
+ def chat(self, key: str, model: str, content: str, *, max_tokens: int = 16) -> StreamingResponse:
+ return self.gateway.transport.send(
+ "/chat/completions",
+ headers=self.gateway.transport.bearer(key),
+ json=ChatBody(
+ model=model,
+ messages=[ChatMessage(role="user", content=content)],
+ max_tokens=max_tokens,
+ ),
+ )
+
+
+def build_client() -> QuotaClient:
+ return QuotaClient(gateway=build_gateway())
diff --git a/tests/e2e/quota_management/ratelimit/test_rate_limit_e2e.py b/tests/e2e/quota_management/ratelimit/test_rate_limit_e2e.py
new file mode 100644
index 00000000000..a66d7974fc5
--- /dev/null
+++ b/tests/e2e/quota_management/ratelimit/test_rate_limit_e2e.py
@@ -0,0 +1,149 @@
+"""Live e2e: key-level rpm/tpm rate limits on the gateway.
+
+Covers quota_management.ratelimit.*: a key generated with rpm_limit/tpm_limit gets a
+429 once the limit is crossed inside one window (blocks_over_limit), serves
+again once the window rolls (resets_after_window), and successful responses
+report x-ratelimit-* limit/remaining headers so clients can pace
+(headers_report_remaining). Each test asserts both halves of the contract: the
+recorded state (/key/info echoes the configured limit) and the enforced
+behavior (the 429, the recovery, or the headers on live traffic).
+
+The v3 limiter counts a request against the rpm budget at the pre-call hook,
+before model routing, so every call that clears auth consumes budget whether or
+not it ultimately succeeds. All calls of one test must land inside a single
+window (LITELLM_RATE_LIMIT_WINDOW_SIZE, 60s default), which real chat latency
+comfortably allows.
+"""
+
+from __future__ import annotations
+
+import time
+
+import pytest
+
+from e2e_config import unique_marker
+from e2e_http import StreamingResponse, require_successful_call
+from lifecycle import ResourceManager
+from models import KeyGenerateBody
+from quota_client import QuotaClient
+
+pytestmark = pytest.mark.e2e
+
+MODEL = "claude-haiku-4-5"
+
+
+def _limited_key(
+ client: QuotaClient,
+ resources: ResourceManager,
+ *,
+ rpm_limit: int | None = None,
+ tpm_limit: int | None = None,
+) -> str:
+ key = client.gateway.generate_key(KeyGenerateBody(models=[MODEL], rpm_limit=rpm_limit, tpm_limit=tpm_limit))
+ resources.defer(lambda: client.gateway.delete_key(key))
+ return key
+
+
+def _chat(client: QuotaClient, key: str) -> StreamingResponse:
+ return client.chat(key, MODEL, f"reply with one word {unique_marker()}")
+
+
+def _first_ok(client: QuotaClient, key: str) -> StreamingResponse:
+ """First successful call on a fresh key, which opens the rate-limit window.
+ A fresh key may briefly 401 until the data plane's auth cache picks it up, so
+ retry on 401 to a deadline; a 401 never reaches the rate limiter, so only the
+ successful call consumes budget. Any other failure is behavior under test and
+ fails hard."""
+ deadline = time.monotonic() + client.gateway.poll_timeout
+ while True:
+ outcome = _chat(client, key)
+ if outcome.ok:
+ return outcome
+ if outcome.status_code != 401 or time.monotonic() >= deadline:
+ require_successful_call(outcome)
+ time.sleep(client.gateway.poll_interval)
+
+
+def _assert_rate_limited(outcome: StreamingResponse, limit_type: str) -> None:
+ assert outcome.status_code == 429, (
+ f"expected a 429 {limit_type} rate-limit block, got {outcome.status_code}: {outcome.body[:300]}"
+ )
+ assert "Rate limit exceeded for api_key" in outcome.body, (
+ f"429 body must name the api_key scope, got: {outcome.body[:300]}"
+ )
+ assert f"Limit type: {limit_type}" in outcome.body, (
+ f"429 body must carry 'Limit type: {limit_type}', got: {outcome.body[:300]}"
+ )
+ retry_after = outcome.headers.get("retry-after")
+ assert retry_after is not None and retry_after.isdigit() and int(retry_after) > 0, (
+ f"429 must carry a positive integer retry-after header, got {retry_after!r}"
+ )
+
+
+class TestKeyRateLimits:
+ @pytest.mark.covers("quota_management.ratelimit.rpm.blocks_over_limit")
+ def test_rpm_limit_blocks_over_limit(self, client: QuotaClient, resources: ResourceManager) -> None:
+ key = _limited_key(client, resources, rpm_limit=3)
+ info = client.gateway.key_info(key)
+ assert info.rpm_limit == 3, f"/key/info reports rpm_limit {info.rpm_limit}, configured 3"
+
+ _ = _first_ok(client, key)
+ for _ in range(2):
+ require_successful_call(_chat(client, key))
+
+ _assert_rate_limited(_chat(client, key), "requests")
+
+ @pytest.mark.covers("quota_management.ratelimit.tpm.blocks_over_limit")
+ def test_tpm_limit_blocks_over_limit(self, client: QuotaClient, resources: ResourceManager) -> None:
+ key = _limited_key(client, resources, tpm_limit=60)
+ info = client.gateway.key_info(key)
+ assert info.tpm_limit == 60, f"/key/info reports tpm_limit {info.tpm_limit}, configured 60"
+
+ _ = _first_ok(client, key)
+ for _ in range(8):
+ outcome = _chat(client, key)
+ if outcome.status_code == 429:
+ _assert_rate_limited(outcome, "tokens")
+ return
+ require_successful_call(outcome)
+ pytest.fail("tpm_limit=60 was never enforced with a 429 within 8 calls of ~25 tokens each")
+
+ @pytest.mark.covers("quota_management.ratelimit.rpm.resets_after_window")
+ def test_rpm_limit_resets_after_window(self, client: QuotaClient, resources: ResourceManager) -> None:
+ key = _limited_key(client, resources, rpm_limit=1)
+
+ _ = _first_ok(client, key)
+ _assert_rate_limited(_chat(client, key), "requests")
+
+ deadline = time.monotonic() + client.gateway.poll_timeout
+ while time.monotonic() < deadline:
+ outcome = _chat(client, key)
+ if outcome.ok:
+ return
+ assert outcome.status_code == 429, (
+ f"while the window drains only 429s are acceptable, got {outcome.status_code}: {outcome.body[:300]}"
+ )
+ time.sleep(client.gateway.poll_interval)
+ pytest.fail("a blocked key never recovered after the rate-limit window elapsed")
+
+ @pytest.mark.covers("quota_management.ratelimit.rpm.headers_report_remaining")
+ def test_headers_report_limit_and_remaining(self, client: QuotaClient, resources: ResourceManager) -> None:
+ key = _limited_key(client, resources, rpm_limit=5, tpm_limit=100000)
+
+ first = _first_ok(client, key)
+ assert first.headers.get("x-ratelimit-api_key-limit-requests") == "5", (
+ f"success response must report the key's request limit, headers: "
+ f"{ {k: v for k, v in first.headers.items() if 'ratelimit' in k} }"
+ )
+ assert first.headers.get("x-ratelimit-api_key-remaining-requests") == "4", (
+ f"first call against rpm_limit=5 must leave 4 remaining, got "
+ f"{first.headers.get('x-ratelimit-api_key-remaining-requests')!r}"
+ )
+ assert first.headers.get("x-ratelimit-api_key-limit-tokens") == "100000", (
+ f"success response must report the key's token limit, got "
+ f"{first.headers.get('x-ratelimit-api_key-limit-tokens')!r}"
+ )
+ remaining_tokens = first.headers.get("x-ratelimit-api_key-remaining-tokens")
+ assert remaining_tokens is not None and remaining_tokens.isdigit() and int(remaining_tokens) < 100000, (
+ f"one call must leave remaining tokens reported and below the limit, got {remaining_tokens!r}"
+ )