Skip to content

Apply rate limits per caller in the Cloud Run gateway - #1715

Open
anth-volk wants to merge 2 commits into
mainfrom
fix/gateway-per-caller-rate-limits
Open

anth-volk wants to merge 2 commits into
mainfrom
fix/gateway-per-caller-rate-limits

Conversation

@anth-volk

Copy link
Copy Markdown
Collaborator

Fixes #1714

Modal Version Release

No Modal release configuration: this PR does not change Modal release behavior.

Summary

Workers replay every request into the household app through Flask's test client, so the app's Flask-Limiter limits counted every caller as 127.0.0.1 and each limit was shared by all callers on a worker container. This PR moves per-caller counting into the public Cloud Run gateway, which sees both the validated Auth0 client ID and the client's address.

Gateway limits (projects/cloud-run-failover-api/policyengine_household_failover/rate_limits.py), checked before a request is forwarded to Modal or a Cloud Run worker:

Route Limit Counted by
POST /<country_id>/calculate 60 per minute Auth0 client ID; client IP without a valid token
GET/HEAD /analytics/calculate/requests 60 per minute Auth0 client ID; client IP without a valid token
POST /<country_id>/calculate_demo 1 per 10 seconds client IP
  • Over-limit requests get a JSON 429 with code rate_limited, Retry-After, and CORS headers when the request has an Origin header. Limited routes return X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset.
  • The client ID reuses the gateway's existing bearer-token validation for request logs.
  • The client IP is the X-Forwarded-For entry at position HOUSEHOLD_FAILOVER_TRUSTED_PROXY_COUNT from the end (default 1); earlier entries are set by the caller and ignored.
  • Counts use the limits package's in-process memory storage, so a caller's effective allowance is the limit times the number of gateway processes receiving its requests (1–20 instances × 2 Gunicorn workers by default). Shared storage such as Redis was considered and left for later.

Worker side: the gateway sets gateway_rate_limited on every request it forwards (carried through the Cloud Run dispatch codec), and the household app's request_filter skips its own limits only for those requests. Requests without the marker keep the app's limits, so workers deployed by the Modal job before the gateway deploy stay limited until the new gateway is live. Direct deployments of the app, such as the Docker image, are unchanged.

Configuration and deploy wiring (both variables are non-secret and optional):

Variable Provider Wiring
HOUSEHOLD_FAILOVER_RATE_LIMIT_ENABLED GitHub Actions variable (staging/production environments); not set yet, so limits are on deploy-staged.yml deploy step env: → cloud-run-deploy-failover.sh append_env_if_set → gateway --env-vars-file; not written to worker env files
HOUSEHOLD_FAILOVER_TRUSTED_PROXY_COUNT GitHub Actions variable (staging/production environments); not set yet, so the default 1 applies same as above
AUTH0_ADDRESS_NO_DOMAIN, AUTH0_AUDIENCE_NO_DOMAIN (existing) GitHub Actions secrets, present in both environments already passed to the gateway env file

cloud-run-testing-deploy-and-load-test.sh exports HOUSEHOLD_FAILOVER_RATE_LIMIT_ENABLED=false, because its load test sends 100 calculate requests with one client's token and allows no errors.

Open production configuration

household.api.policyengine.org resolves to a Google Cloud address that appears to be an external load balancer, which appends its own address to X-Forwarded-For. With the default trusted proxy count of 1, the gateway reads that load balancer address as the client IP in production:

  • authenticated /calculate and analytics requests are counted per Auth0 client, as intended;
  • /calculate_demo and requests without a valid token share one count per gateway process, which matches today's behavior.

Setting the count to 2 alone is not safe, because the gateway's run.app URL is publicly reachable and a direct caller controls every X-Forwarded-For entry except the last. Per-IP counting in production needs, together:

  1. HOUSEHOLD_CLOUD_RUN_GATEWAY_INGRESS set so only the load balancer can reach the gateway;
  2. HOUSEHOLD_CLOUD_RUN_GATEWAY_PUBLIC_URL set so the deploy health check calls the public hostname instead of run.app;
  3. HOUSEHOLD_FAILOVER_TRUSTED_PROXY_COUNT=2.

The load balancer setup was not confirmed with gcloud. These are left for a separate decision.

Testing

Added or changed tests, each run individually and passing (33):

  • tests/unit/failover/test_gateway_rate_limits.py (new)
  • tests/unit/failover/test_dispatch_codec.py::test_dispatch_request_round_trips_gateway_rate_limit_marker
  • tests/unit/failover/test_dispatch_codec.py::test_dispatch_request_decode_ignores_non_boolean_rate_limit_marker
  • tests/unit/test_api_limits.py::test_requests_the_gateway_rate_limited_skip_app_limits
  • tests/unit/test_api_limits.py::test_dispatched_requests_without_gateway_marker_keep_app_limits
  • tests/unit/test_api_limits.py::test_direct_requests_with_gateway_dispatch_header_are_rate_limited
  • .github/scripts/test_cloud_run_deploy_failover.py::test_cloud_run_deploy_failover_deploys_workers_manifest_and_gateway
  • .github/scripts/test_cloud_run_testing_deploy_and_load_test.py::test_testing_deploy_script_deploys_smokes_and_load_tests
  • .github/scripts/test_deploy_staged_workflow.py::test_cloud_run_deploy_jobs_pass_gateway_rate_limit_environment

make format-check passes. make test and make test-with-auth were not run locally; PR CI runs them. The first commit adds the failing tests; the second makes them pass. One round of independent review found four problems (HEAD requests bypassing the analytics limit, no CORS headers on the gateway's 429, a deploy-order period with no limits, and load-test guidance that conflicted with the limits), all fixed in the second commit with tests.

🤖 Generated with Claude Code

anth-volk and others added 2 commits November 26, 2026 19:05
Workers replay every request into the household app through Flask's test
client, so the app's Flask-Limiter limits count every caller as 127.0.0.1.
These tests describe per-caller limits in the public Cloud Run gateway:

- /calculate and /analytics/calculate/requests: 60 per minute per Auth0
  client ID, or per client IP without a valid token
- /calculate_demo: 1 per 10 seconds per client IP, read from the
  X-Forwarded-For entry added by the trusted proxies
- a JSON 429 with Retry-After and CORS headers, and X-RateLimit-* headers
- workers skip the app's limits only for requests the gateway marks
- deploy wiring for HOUSEHOLD_FAILOVER_RATE_LIMIT_ENABLED and
  HOUSEHOLD_FAILOVER_TRUSTED_PROXY_COUNT

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The gateway now counts requests per Auth0 client ID or client IP before
forwarding them to Modal or Cloud Run workers, using in-process memory
storage from the limits package. It marks forwarded requests, and the
household app skips its own limits for marked requests. Unmarked requests,
for example from a gateway deployed before this change, keep the app's
limits, so the Modal deploy that runs before the gateway deploy does not
leave requests unlimited.

HOUSEHOLD_FAILOVER_RATE_LIMIT_ENABLED and
HOUSEHOLD_FAILOVER_TRUSTED_PROXY_COUNT come from GitHub Actions variables
and reach the gateway through the deploy workflow, the deploy script and
its env-vars file. The disposable testing deploy disables limits for its
single-client load test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@anth-volk
anth-volk requested a review from hua7450 November 26, 2026 15:16
@anth-volk
anth-volk marked this pull request as ready for review November 26, 2026 15:16

This branch has not been deployed

No deployments
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.

Rate limits count every caller as 127.0.0.1 behind the Cloud Run gateway

1 participant