Skip to content

Add project request rate limits - #35

Merged
mitchins merged 3 commits into
mainfrom
feature/project-rate-limits
Jul 21, 2026
Merged

mitchins merged 3 commits into
mainfrom
feature/project-rate-limits

Conversation

@mitchins

@mitchins mitchins commented Jul 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add atomic Redis-backed two-window admission limits for anonymous and facade-key project traffic
  • default to 1 request/second and 3 requests/10 seconds, with isolated project buckets and complete per-project overrides
  • fail closed on limiter outages, fail startup on malformed limiter policy, and return stable 429/503 responses before body parsing or upstream work
  • expose effective project policies in the Projects UI/API and document the five proxy-backed routes in scope

Safety and behavior

  • anonymous callers share one global Redis bucket across workers and instances
  • project buckets use digests of logical identity; raw facade keys and bearer tokens never enter Redis keys, logs, headers, or error bodies
  • one atomic Lua operation enforces both sliding windows using Redis server time and exact millisecond TTL
  • invalid/mismatched local keys reject before admission; legacy anonymous routing honors configured limits and opt-out

Validation

  • full suite: 961 passed, 9 skipped
  • real Redis 7 semantic suite: concurrency, exclusive boundaries, denied-no-charge, lowered-policy retry rank, TTL/cardinality
  • Ruff: clean
  • vulture: clean
  • package build: succeeded
  • independent adversarial design and final ready/done gates: PASS

Summary by CodeRabbit

  • New Features

    • Added two-window Redis-backed request rate limiting for supported inference routes, with separate anonymous vs project policies and optional per-project overrides.
    • Added facade-key–scoped rate-limit propagation and surfaced effective request limits in the Projects UI/API (policy-based, not live counters).
  • Documentation

    • Documented configuration (request_rate_limits), route coverage/exclusions, and rate-limit response semantics; updated the example routes config.
  • Bug Fixes

    • Enforced rate limits early (before request body parsing); added consistent 429/503 responses, Retry-After handling, and fail-closed startup validation.
  • Tests

    • Expanded coverage for parsing/validation, limiter admission/denial behavior, UI/API expectations, and lifespan startup verification.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7d0c2ab8-cbd3-42ae-9746-bec0884a6de1

📥 Commits

Reviewing files that changed from the base of the PR and between 92bf706 and d321b23.

📒 Files selected for processing (6)
  • README.md
  • smolrouter/app.py
  • smolrouter/request_rate_limits.py
  • smolrouter/templates/projects.html
  • tests/unit/test_app.py
  • tests/unit/test_request_rate_limits.py
🚧 Files skipped from review as they are similar to previous changes (6)
  • README.md
  • smolrouter/templates/projects.html
  • tests/unit/test_request_rate_limits.py
  • smolrouter/request_rate_limits.py
  • smolrouter/app.py
  • tests/unit/test_app.py

📝 Walkthrough

Walkthrough

Adds configurable, Redis-backed two-window request rate limiting for selected inference routes, including project-specific policies, startup verification, structured rejection responses, dashboard policy visibility, documentation, and extensive unit/integration coverage.

Changes

Request rate limiting

Layer / File(s) Summary
Limiter models and atomic admission
smolrouter/request_rate_limits.py, tests/unit/test_request_rate_limits.py, pyproject.toml, requirements.txt
Defines strict policy parsing, hashed bucket keys, atomic Redis Lua admission, retry timing, telemetry, startup verification, and backend failure behavior with comprehensive tests.
Configuration and project policy resolution
smolrouter/container.py, smolrouter/facade_keys.py, config/routes.yaml.example, tests/unit/test_container.py, tests/unit/test_facade_keys.py
Loads global policies, parses facade-key overrides, propagates policies through request identities, and serializes configured limits.
Startup and proxy enforcement
smolrouter/app.py, tests/unit/test_app.py
Verifies limiter readiness during startup and applies admission before request parsing and upstream routing, returning structured 429 or 503 responses.
Inventory, dashboard, and documentation
smolrouter/templates/*, README.md, tests/unit/test_app.py
Displays effective request policies in project views and documents route coverage, configuration, rejection behavior, and accounting semantics.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant proxy_request
  participant RedisRequestRateLimiter
  participant Redis
  Client->>proxy_request: POST inference request
  proxy_request->>RedisRequestRateLimiter: check effective policy
  RedisRequestRateLimiter->>Redis: atomic Lua admission
  Redis-->>RedisRequestRateLimiter: decision
  RedisRequestRateLimiter-->>proxy_request: allow or rate-limit response
  proxy_request-->>Client: upstream response, 429, or 503
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.89% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding request rate limits for project traffic.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/project-rate-limits

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a Redis-backed, two-window request rate limiter for SmolRouter, applying limits to inference POST routes for both anonymous and project-identified traffic. The implementation includes atomic Lua scripting for concurrency safety, configuration parsing, and UI updates to display effective policies. The review feedback highlights several improvement opportunities: expanding the production environment check to match both "prod" and "production", simplifying the policy resolution logic in _apply_request_rate_limit, preventing exception masking in the rate limiter's verification cleanup, adding traceback logging for backend failures, and safely handling potential None values in the Jinja templates to avoid rendering crashes.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread smolrouter/app.py Outdated
config = _request_rate_limit_config(container)
if not config.enabled:
return
if os.getenv("APP_ENV", "dev").lower() == "prod" and is_fake_redis():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The check for production environment only matches "prod". If the environment is configured as "production", this critical safety check (which prevents using FakeRedis in production) will be bypassed. It is safer to check for both "prod" and "production".

Suggested change
if os.getenv("APP_ENV", "dev").lower() == "prod" and is_fake_redis():
if os.getenv("APP_ENV", "dev").lower() in ("prod", "production") and is_fake_redis():

Comment thread smolrouter/app.py Outdated
Comment on lines +1919 to +1925
policy = config.anonymous
if context.active_container is not None:
effective_policy = context.active_container.get_effective_request_rate_limit_policy(context.identity)
if isinstance(effective_policy, RequestRateLimitPolicy):
policy = effective_policy
elif context.identity is not None:
policy = context.identity.rate_limit_policy or config.project_default

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If context.active_container is None (e.g., during startup/initialization failure or legacy proxy routing), policy defaults to config.anonymous even for identified project requests. Initializing policy to config.project_default for identified projects ensures correct fallback behavior. Additionally, since get_effective_request_rate_limit_policy always returns a RequestRateLimitPolicy, we can simplify the resolution logic and eliminate the dead code block.

Suggested change
policy = config.anonymous
if context.active_container is not None:
effective_policy = context.active_container.get_effective_request_rate_limit_policy(context.identity)
if isinstance(effective_policy, RequestRateLimitPolicy):
policy = effective_policy
elif context.identity is not None:
policy = context.identity.rate_limit_policy or config.project_default
policy = config.project_default if context.identity else config.anonymous
if context.active_container is not None:
policy = context.active_container.get_effective_request_rate_limit_policy(context.identity)

Comment thread smolrouter/request_rate_limits.py Outdated
Comment on lines +288 to +289
finally:
await self._client.delete(verification_key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If self._client.eval raises an exception (e.g., due to a Lua script compilation error or Redis permission issue), the finally block will attempt to delete the verification key. If Redis is down or has connection issues, delete will also raise an exception, masking the original primary exception and making troubleshooting extremely difficult. Wrapping the cleanup in a try-except block prevents masking the primary error.

        finally:
            try:
                await self._client.delete(verification_key)
            except Exception:
                pass
References
  1. When updating shared data structures in Redis under concurrent conditions, prefer using atomic Lua scripts for the primary path to ensure concurrency safety, or native atomic commands as a fallback, rather than non-atomic read-modify-write patterns.

)
except Exception:
self._backend_error_count += 1
logger.warning("Request rate-limit backend check failed")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Logging the rate-limit backend failure without the exception traceback makes diagnosing Redis connection timeouts, authentication failures, or other issues extremely difficult in production. Adding exc_info=True will include the traceback in the warning log.

Suggested change
logger.warning("Request rate-limit backend check failed")
logger.warning("Request rate-limit backend check failed", exc_info=True)

Comment thread smolrouter/templates/projects.html Outdated
{% for window in project.request_rate_limit.policy.windows %}
<div class="quota-value">{{ window.requests }} request{{ "s" if window.requests != 1 else "" }} / {{ window.seconds }}s</div>
{% endfor %}
<div class="quota-value">{{ project.request_rate_limit.source | replace('_', ' ') }}</div>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If project.request_rate_limit.source is None (which can happen if a project is unconfigured or in future edge cases), calling replace directly on it will raise a Jinja template rendering error and crash the entire dashboard page. Using a default filter or logical OR ensures it is always treated as a string before calling replace.

                                    <div class="quota-value">{{ (project.request_rate_limit.source or "") | replace('_', ' ') }}</div>

@mitchins
mitchins marked this pull request as ready for review July 21, 2026 00:56

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 92bf706a34

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread smolrouter/app.py Outdated
Comment on lines +805 to +806
if active_container is None:
return _default_request_rate_limit_config()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor disabled limiter during legacy fallback

When container initialization has fallen back to legacy mode, callers reach this helper with active_container is None both during startup verification and request handling, so a routes file that explicitly sets request_rate_limits.enabled: false is replaced with the default enabled policy. In that fallback scenario the proxy will still verify Redis and enforce the 1/s, 3/10s anonymous limit, causing unexpected 429/503 responses even though the operator disabled request limiting.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
smolrouter/app.py (1)

1939-1955: 🩺 Stability & Availability | 🔵 Trivial

Fail-closed on limiter errors makes Redis a hard dependency for all proxy traffic. Any check(...) failure returns 503, so a Redis outage rejects every proxied request, not just those that would have been throttled. This is a deliberate posture per the PR, but consider making the degradation strategy explicit/configurable (e.g. fail-open for anonymous/low-risk traffic, or a short-lived circuit breaker) so a transient backend blip doesn't translate into a full proxy outage. Ensure this behavior and its blast radius are covered by alerting.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@smolrouter/app.py` around lines 1939 - 1955, The rate-limiter exception path
currently fails closed for every proxied request, making Redis a hard
dependency. Update the handling around the limiter check and its `except
Exception` branch to make the degradation strategy explicitly configurable,
supporting an appropriate fail-open path for anonymous or low-risk traffic while
preserving strict rejection where required; also add alerting/metrics that
identify limiter failures and their affected traffic scope.
smolrouter/request_rate_limits.py (1)

359-370: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Reuse a registered Redis script here

_CHECK_RATE_LIMIT_LUA is executed on the per-request path, so register_script/EVALSHA would avoid sending and parsing the full Lua body on every admission. Reuse the same registered script in verify() too.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@smolrouter/request_rate_limits.py` around lines 359 - 370, Update the
rate-limit admission flow around the eval call in the relevant verification
method to reuse a script registered once with Redis, invoking it through the
registered-script callable rather than sending _CHECK_RATE_LIMIT_LUA on every
request. Apply the same registered script reuse in verify(), while preserving
the existing keys and arguments.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@smolrouter/app.py`:
- Around line 1828-1849: The 429 payload from _rate_limit_response_payload uses
the project-specific error code for anonymous callers. Make the code
bucket-specific (using an anonymous rate-limit code for the anonymous bucket
while preserving the project code), and update the corresponding assertion in
tests/unit/test_app.py to match.

---

Nitpick comments:
In `@smolrouter/app.py`:
- Around line 1939-1955: The rate-limiter exception path currently fails closed
for every proxied request, making Redis a hard dependency. Update the handling
around the limiter check and its `except Exception` branch to make the
degradation strategy explicitly configurable, supporting an appropriate
fail-open path for anonymous or low-risk traffic while preserving strict
rejection where required; also add alerting/metrics that identify limiter
failures and their affected traffic scope.

In `@smolrouter/request_rate_limits.py`:
- Around line 359-370: Update the rate-limit admission flow around the eval call
in the relevant verification method to reuse a script registered once with
Redis, invoking it through the registered-script callable rather than sending
_CHECK_RATE_LIMIT_LUA on every request. Apply the same registered script reuse
in verify(), while preserving the existing keys and arguments.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4361790a-abb6-46c4-8a83-bfa6f228620a

📥 Commits

Reviewing files that changed from the base of the PR and between 9bf89f0 and 92bf706.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (14)
  • README.md
  • config/routes.yaml.example
  • pyproject.toml
  • requirements.txt
  • smolrouter/app.py
  • smolrouter/container.py
  • smolrouter/facade_keys.py
  • smolrouter/request_rate_limits.py
  • smolrouter/templates/project_detail.html
  • smolrouter/templates/projects.html
  • tests/unit/test_app.py
  • tests/unit/test_container.py
  • tests/unit/test_facade_keys.py
  • tests/unit/test_request_rate_limits.py

Comment thread smolrouter/app.py Resolved
@codecov

codecov Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.05204% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.43%. Comparing base (9bf89f0) to head (d321b23).

Files with missing lines Patch % Lines
smolrouter/request_rate_limits.py 92.94% 6 Missing and 6 partials ⚠️
smolrouter/app.py 95.12% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #35      +/-   ##
==========================================
+ Coverage   74.88%   75.43%   +0.55%     
==========================================
  Files          36       37       +1     
  Lines       10008    10275     +267     
  Branches     1557     1599      +42     
==========================================
+ Hits         7494     7751     +257     
- Misses       1937     1939       +2     
- Partials      577      585       +8     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sonarqubecloud

Copy link
Copy Markdown

@mitchins
mitchins merged commit d39948a into main Jul 21, 2026
12 checks passed
@mitchins
mitchins deleted the feature/project-rate-limits branch July 21, 2026 01:26
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.

1 participant