Skip to content

make the global and per-ip rate limits independent switches - #256

Merged
thushan merged 15 commits into
mainfrom
fix/rate-limit-independent-tiers
Oct 29, 2026
Merged

thushan merged 15 commits into
mainfrom
fix/rate-limit-independent-tiers

Conversation

@thushan

@thushan thushan commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

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_GlobalLimit that actually asserts, the first fix, and the rejection reasons as constants.ReasonRateLimitExceeded / constants.ReasonGlobalRateLimitExceeded in internal/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.Validate in internal/adapter/security/request_rate_limit.go had three faults:

  • per_ip_requests_per_minute: 0 returned early and skipped the global limiter as well, while global_requests_per_minute: 0 only disabled itself. The two limits are now independent and 0 disables only its own tier.
  • A request already over its per-IP limit still took a global token, so one noisy client could starve everyone else on the default config. The per-IP tier is now checked first, and a request rejected by either tier is charged to neither (ipCharge.refund hands the per-IP token back on a global rejection).
  • A global rejection reported the per-IP value in X-RateLimit-Limit and a fixed Retry-After: 60. It now reports global_requests_per_minute and a Retry-After from globalRetryAfter, and the "Rate limit exceeded" WARN carries reason (Global rate limit exceeded for this tier). Any 429 now reports X-RateLimit-Remaining: 0; the per-IP reject path used to report the per-minute window counter instead.

Two concurrency details: ipLimiterInfo.flow serialises one client's reserve, global decision and refund so CancelAt restores the token exactly, and the global tier uses Allow rather than Reserve/Cancel so concurrent rejections cannot leave the shared bucket in debt. A zero health limit still means health probes are not limited.

Type of change

  • Bug fix

Upgrading

per_ip_requests_per_minute: 0 (or OLLA_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. Set global_requests_per_minute: 0 as 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_TierSwitches
  • TestRateLimitValidator_Validate_PerIPRejectionDoesNotDrainGlobal
  • TestRateLimitValidator_Validate_GlobalRejectionRefundsPerIP
  • TestRateLimitValidator_CheckIPLimit_ZeroLimitDoesNotPanic
  • TestRateLimitValidator_Middleware_GlobalRejectionHeaders
  • TestRateLimitValidator_Validate_ConcurrentGlobalRejectionKeepsPerIPToken
  • TestRateLimitValidator_Validate_ConcurrentRejectionsKeepGlobalTokens
  • TestRateLimitValidator_Middleware_PerIPRejectionReportsZeroRemaining
  • TestRateLimitValidator_Middleware_LogsRejectionReason
  • TestRateLimitValidator_Middleware_ZeroBurstRetryAfterFloor
  • TestRateLimitValidator_Validate_PerIPDisabledStillEnforcesGlobal (@matthewjhunter)

And TestRateLimit_EveryProxyRouteIsLimited in handler_security_status_codes_test.go.

Tested together with the other uplift-october branches on a local integration branch at 4990a5d:

  • make ready and betteralign v0.8.2 pass at d188d2e, and go test -race passes (security, handlers, router, config). 4990a5d is a docs-only reconciliation on top.
  • /olla-validate --quick: 50 pass, 0 fail (anthropic 7/7)
  • /claude-code-e2e against real Ollama at the shipped default limits: Tier A passes on both the passthrough and translation legs, no 429s
  • Real Claude Code against per_ip_requests_per_minute: 2, burst 1: Anthropic rate_limit_error 429s, each retried after exactly Retry-After; the task completed
  • Tier checks on both engines (40 requests each): global 60 / per-IP 0 gives 10 passed and 30 429s; global 0 / per-IP 60 gives the same; both 0 gives no 429s. Every 429 has X-RateLimit-Remaining: 0. The WARN reason is Global rate limit exceeded for the global tier.
  • Fairness: a 2/s client was never starved (38/38 and 40/40) while another client hammered
  • An oversized chunked body to /olla/anthropic/v1/messages gives 413 request_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 WARN
  • OpenAI surface (chat stream and non-stream, models, embeddings) 200. Log scan: no panics, races or unexpected ERROR lines.

Checklist

  • make ready passes at 909ae33
  • Tests added or updated for the change
  • Documentation updated: docs/content/configuration/reference.md, v0.0.30 release note and upgrading checklist
  • No new dependencies added

Summary by CodeRabbit

  • Documentation
    • Clarified that each rate limit can be disabled independently, and both must be set to zero to disable rate limiting entirely.
    • Documented that per-IP checks run first, rejected requests consume neither bucket’s token, and rejection responses report the applicable limit and retry timing.
  • Bug Fixes
    • Corrected rate-limit handling so per-IP and global limits operate independently, rejected requests do not consume tokens, and global limits remain active when the per-IP limit is disabled.

thushan and others added 14 commits October 28, 2026 10:07
…n assertion, mention env var in upgrade note
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.
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Walkthrough

The 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.

Changes

Independent rate-limit tiers

Layer / File(s) Summary
Per-IP-first limiter accounting
internal/core/constants/security.go, internal/adapter/security/request_rate_limit.go, docs/content/configuration/reference.md, docs/content/about/release-notes.md
The validator checks the per-IP tier before the global tier and refunds the per-IP reservation if the global tier rejects. The code defines rejection reason constants and reports tier-specific rejection details. The configuration reference and release notes describe the independent limit settings and rejection headers.
Limiter regression and route coverage
internal/adapter/security/request_rate_limit_test.go, internal/adapter/security/factory_test.go, internal/app/handlers/handler_security_status_codes_test.go
Tests cover independent tier settings, token refunds, concurrent rejections, middleware responses and headers, rejection logging, and rate limiting across proxy routes.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: martinemrich

Merge Risk: Minimal · up to 5a924

No actionable merge-blocking risk remains in the supplied review scope.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: making the global and per-IP rate limits independent switches.
Docstring Coverage Passed Docstring coverage is 82.35% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 82.35% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 17 functions across 5 files. (1 skipped: 1 unsupported.)

Finishing Touches
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

# Conflicts:
#	docs/content/configuration/reference.md
@thushan
thushan merged commit 17a2fb0 into main Oct 29, 2026
8 checks passed
@thushan
thushan deleted the fix/rate-limit-independent-tiers branch October 29, 2026 21:08
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.

2 participants