feat: add opt-in per-caller request rate limiting #458
All Vouch review confidence checks passed
Residual risk 0.30 = Change Risk (0.52) × (1 − Review Confidence (0.43)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #458"
general
weight: 0.35
franciscojavierarceo
Summary
Closes #457
The gateway had only global concurrency bounds, so one caller could use up the upstream's capacity and shared web-search or code-interpreter quotas for everyone. This PR adds an opt-in, per-caller request rate limit. It is off by default: no middleware is installed and no headers change.
Configuration (CLI > environment >
[server]file setting, followingmax_request_body_size_bytes):| CLI | Environment | File (
[server]) || --- | --- | --- |
|
--rate-limit-requests-per-minute|AGENTIC_RATE_LIMIT_REQUESTS_PER_MINUTE|rate_limit_requests_per_minute||
--rate-limit-burst|AGENTIC_RATE_LIMIT_BURST|rate_limit_burst(default: the per-minute rate) |Caller key (first match):
1. OIDC issuer and subject;
2. a keyed hash of the bearer token;
3. a keyed hash of
x-api-key;4. one shared anonymous bucket.
Raw credentials are never stored. A WebSocket is keyed by its upgrade request's own credentials, never by the server's
OPENAI_API_KEYfallback.Algorithm: GCRA (equivalent to a token bucket). Each caller holds one theoretical arrival time in a
std::sync::Mutex<HashMap>, usingtokio::time::Instantso tests can pause time. No lock is held across an await. Memory is bounded at 100,000 callers: idle callers are pruned first, and new callers share an overflow bucket while every tracked caller is active, with awarnat most once a minute. No new dependencies.HTTP:
route_layeron the protected routes, layered before OIDC so that it runs after authentication and sees the principal./health,/readyand Swagger are exempt.429in OpenAI format (rate_limit_error/rate_limit_exceeded), or in Anthropic format withrequest-idon/v1/messagesandcount_tokens.retry-after,retry-after-ms,x-ratelimit-limit-requests,x-ratelimit-remaining-requests: 0, andx-ratelimit-reset-requests. The last is the time until the full burst returns, formatted like1.5sor2m3s.WebSocket:
response.createis charged before any lane or byte capacity is reserved. A limited create gets anerrorframe withstatus: 429, and the connection stays open.response.steer,response.injectand gateway-started continuations are not charged. The check sits where client messages arrive, not inWsMultiplexer::schedule, which also runs automatic continuations.Structure:
rate_limit.rsholds the limiter, middleware,429builder and retry formatting.server_settings.rsresolves the[server]table. Its first commit is a pure move of the existing body-size resolution out ofmain.rs, which was at its 644-line exception (now 616).ServerConfiggainsrate_limit, soAppStateand its 16 test literals are unchanged.auth.rsis at its line baseline. Its only change is visibility (AuthErrorFormatandfor_path, reused for the 429 format), andbearer_tokeninauth/api_key.rsis also now crate-visible.Scope:
- distributed or token-based quotas (#107, #315);
- per-IP keying, which needs trusted-proxy configuration;
-
agenticlauncher flags. The launcher's child process inherits the environment variables, and the configuration file is shared.Conflicts: a trial merge with #436, #440 and #420 is clean.
Test Plan
Unit tests:
rate_limit::tests(paused time):- burst, then one request per interval, including exact
retry_afterandreset;- steady state;
- independent callers;
- pruning before overflow;
- credentials kept only as a hash (no token text in
Debug; bearer andx-api-keyshare a key;Basicis anonymous);- retry rounding and
x-ratelimit-reset-requestsformatting;- the burst bound.
server_settings::tests:- off by default;
- file, then environment, then CLI, including a CLI value over a malformed environment value;
- the burst defaulting to the rate;
- five invalid inputs, each named in its error;
- flag parsing;
- the generated
[server]table.config_filetests: the new keys parse,0is rejected, and an unset burst is not written.tests/rate_limit_test.rs(one request per minute, so the outcomes are deterministic):a_caller_over_its_limit_gets_an_openai_429_with_retry_headers: exact body and all five headers; the limited request never reaches the upstream; another bearer is unaffected.callers_without_credentials_share_one_buckethealth_endpoints_are_never_limitedmessages_routes_answer_in_the_anthropic_format_and_key_by_api_key: exact body; therequest-idheader matches the body.rate_limiting_is_off_by_default: 10 requests and no rate-limit headers.websocket_creates_are_charged_and_a_limited_create_keeps_the_connection: the upgrade and two creates use a burst of 3; the next create gets the exact429frame; thenresponse.steeris answered on the same connection.http_and_websocket_share_a_bucket_and_the_upgrade_is_charged: a limited upgrade gets HTTP429before switching protocols.a_websocket_without_credentials_is_not_charged_to_the_server_keyoidc_auth_test::rate_limits_key_oidc_callers_by_subject_not_token: two tokens for one subject share a bucket, and another subject has its own.Negative controls (each applied to the finished code):
| Change | Result |
| --- | --- |
| Never install the HTTP layer | 6 of the 8 integration tests fail; health and off-by-default pass |
| Drop the WebSocket charge | Both WebSocket charging tests fail |
| Layer the limiter outside OIDC | The OIDC subject test fails |
| Off-by-one in the GCRA comparison | 4 unit tests fail |
| Disable pruning | The pruning test fails |
Binary smoke test at 1 request per minute:
--helplists both flags.AGENTIC_RATE_LIMIT_BURSTwithout a rate fails at startup:AGENTIC_RATE_LIMIT_BURST requires AGENTIC_RATE_LIMIT_REQUESTS_PER_MINUTE./v1/modelsrequest reaches the upstream; the second gets429with all headers;/healthstill returns200.Gate:
cargo fmt -- --checkcargo clippy --workspace --all-targets -- -D warnings--features embedded-code-interpreter) for both cratespre-commit run --all-filesmkdocs build --strictcargo test --workspace --no-fail-fast: 2530 passed, 1 failed. The failure istool::web_fetch::http::tests::the_deadline_bounds_a_slow_origin, which also fails on unmodifiedmainwhen the whole lib suite runs in parallel.