Repository navigation
make the global and per-ip rate limits independent switches - #256
Conversation
…n assertion, mention env var in upgrade note
…nnot put it in debt
Fails on main. Validate() reads perIPRequestsPerMinute, returns early when it is <= 0, and only then would it consult globalLimiter, so setting the per-IP limit to 0 turns off all rate limiting rather than just the per-IP tier. The two fields are documented as independent switches with identical "0=disabled" semantics, and global_requests_per_minute: 0 does behave that way, disabling only itself while per-IP keeps working. This test pins the reciprocal case: global limit set, per-IP disabled, and the global limiter still enforced. 50 requests against a global limit of 60/min with a burst of 5. A tight loop earns no meaningful refill at 1/sec, so anything far above the burst means the global limiter was never asked. Currently all 50 are allowed. TestRateLimitValidator_Validate_Disabled sets both limits to 0 and so does not cover this case.
TestRateLimitValidator_Validate_GlobalLimit checked for a rejection Reason of "Global rate limit exceeded", which the code never emits: all three rejection paths in request_rate_limit.go set "Rate limit exceeded". So globalBlocked could not become true, and the miss was reported with t.Log rather than t.Error, leaving the test passing unconditionally. Assert on Allowed instead, and fail when the global limiter never rejects. Passes on main, since the global limiter is consulted when the per-IP limit is non-zero. This is the coverage that should have caught a zero per-IP limit disabling global limiting, and did not.
Validate() read the per-IP allowance first and returned early when it was
<= 0, so setting per_ip_requests_per_minute to 0 disabled all rate limiting
rather than just the per-IP tier. The global limiter was still constructed
whenever global_requests_per_minute was non-zero; it was simply never asked.
The reference documents the two as independent switches with identical
"0=disabled" semantics, and global_requests_per_minute: 0 already behaved that
way, disabling only itself while per-IP kept working. This makes the reciprocal
case match.
Measured before the change, bursting a proxy route with a nonexistent model so
nothing reaches a backend: with the global limit at 60/min and burst 10,
per_ip=600000 allowed 10 and rejected 1590, while per_ip=0 allowed all 1600.
Two related corrections in the same path:
- The global rejection now reports globalRequestsPerMinute as RateLimit
rather than the per-IP value, which would be 0 when that tier is disabled
and a confusing X-RateLimit-Limit to hand a client.
- It now carries its own Reason, "Global rate limit exceeded". That is the
string TestRateLimitValidator_Validate_GlobalLimit already expected, and it
lets callers tell the two tiers apart. Adjusting the chain test in factory
revealed it had been exercising the global limiter while believing it was
testing per-IP, since both burst sizes were 1 and both reasons were equal.
RetryAfter in checkIPLimit divided a per-minute allowance by the limit, safe
only because the early return guaranteed a positive value. Reordering removes
that guarantee from the call site, so the division moves behind a helper with a
zero guard and a one second floor.
The Reason strings on ports.SecurityResult are compared by callers and tests, so they belong beside ViolationRateLimit in core/constants rather than repeated as literals at each return site. A literal that drifts fails quietly: a comparison that never matches is indistinguishable from a rejection that never happened. That is not hypothetical in this package. TestRateLimitValidator_Validate_ GlobalLimit compared against "Global rate limit exceeded", which no return site emitted, and the chain test in factory asserted on "Rate limit exceeded" while actually exercising the global limiter, because both tiers used the same string. Also tightens the global limit test to assert which limiter rejected, now that the two are distinguishable. Pure rename, no behaviour change: same strings, same paths.
Validate() keeps the per-IP-first order: a global-first order lets a client over its own limit burn global tokens and starve everyone else. Reasons use the constants from internal/core/constants.
WalkthroughThe rate limiter now checks per-IP limits before global limits and treats each zero setting as disabling only its own tier. It refunds per-IP reservations after global rejection. Rejection metadata, retry headers, logging, tests, configuration guidance, and release notes reflect this behaviour. ChangesIndependent rate-limit tiers
Priority: Estimated code review effort: 3 (Moderate) | ~25 minutes Change: Bug fix Suggested reviewers: Merge Risk:
|
# Conflicts: # docs/content/configuration/reference.md
Summary
Reported by @matthewjhunter, whose four patches open this branch as his own commits: the regression test that a zero per-IP limit must not disable the global limit, a
TestRateLimitValidator_Validate_GlobalLimitthat actually asserts, the first fix, and the rejection reasons asconstants.ReasonRateLimitExceeded/constants.ReasonGlobalRateLimitExceededininternal/core/constants/security.go. Our changes are layered on top. They check the per-IP tier before the global one rather than after, which also fixes the starvation below.RateLimitValidator.Validateininternal/adapter/security/request_rate_limit.gohad three faults:per_ip_requests_per_minute: 0returned early and skipped the global limiter as well, whileglobal_requests_per_minute: 0only disabled itself. The two limits are now independent and0disables only its own tier.ipCharge.refundhands the per-IP token back on a global rejection).X-RateLimit-Limitand a fixedRetry-After: 60. It now reportsglobal_requests_per_minuteand aRetry-AfterfromglobalRetryAfter, and the "Rate limit exceeded" WARN carriesreason(Global rate limit exceededfor this tier). Any 429 now reportsX-RateLimit-Remaining: 0; the per-IP reject path used to report the per-minute window counter instead.Two concurrency details:
ipLimiterInfo.flowserialises one client's reserve, global decision and refund soCancelAtrestores the token exactly, and the global tier usesAllowrather thanReserve/Cancelso concurrent rejections cannot leave the shared bucket in debt. A zero health limit still means health probes are not limited.Type of change
Upgrading
per_ip_requests_per_minute: 0(orOLLA_SERVER_PER_IP_RATE_LIMIT=0) no longer turns rate limiting off. If you used it for that, the global limit (default 1000/min, burst 50) now applies. Setglobal_requests_per_minute: 0as well to disable both. This is in the v0.0.30 upgrading checklist and has its own release note entry.How was this tested?
New tests in
internal/adapter/security/request_rate_limit_test.go:TestRateLimitValidator_Validate_TierSwitchesTestRateLimitValidator_Validate_PerIPRejectionDoesNotDrainGlobalTestRateLimitValidator_Validate_GlobalRejectionRefundsPerIPTestRateLimitValidator_CheckIPLimit_ZeroLimitDoesNotPanicTestRateLimitValidator_Middleware_GlobalRejectionHeadersTestRateLimitValidator_Validate_ConcurrentGlobalRejectionKeepsPerIPTokenTestRateLimitValidator_Validate_ConcurrentRejectionsKeepGlobalTokensTestRateLimitValidator_Middleware_PerIPRejectionReportsZeroRemainingTestRateLimitValidator_Middleware_LogsRejectionReasonTestRateLimitValidator_Middleware_ZeroBurstRetryAfterFloorTestRateLimitValidator_Validate_PerIPDisabledStillEnforcesGlobal(@matthewjhunter)And
TestRateLimit_EveryProxyRouteIsLimitedinhandler_security_status_codes_test.go.Tested together with the other uplift-october branches on a local integration branch at
4990a5d:make readyand betteralign v0.8.2 pass atd188d2e, andgo test -racepasses (security, handlers, router, config).4990a5dis a docs-only reconciliation on top./olla-validate --quick: 50 pass, 0 fail (anthropic 7/7)/claude-code-e2eagainst real Ollama at the shipped default limits: Tier A passes on both the passthrough and translation legs, no 429sper_ip_requests_per_minute: 2, burst 1: Anthropicrate_limit_error429s, each retried after exactlyRetry-After; the task completedX-RateLimit-Remaining: 0. The WARNreasonisGlobal rate limit exceededfor the global tier./olla/anthropic/v1/messagesgives 413request_too_large, with no ERROR line--validate-config: the shipped config passes with no ignored keys; a config with typos lists them with lines and exits 0; one startup WARNChecklist
make readypasses at909ae33docs/content/configuration/reference.md, v0.0.30 release note and upgrading checklistSummary by CodeRabbit