"""Inbound rate-limit policy: per-category limits + the strategy. Separate from the outbound downstream catalog (`policies.py`/`policy.py`): different subsystem, different consumer (the `@rate_category` decorator), different lifecycle. This is the one policy that is genuinely environmental, so it reads `Config`. """ from enum import Enum from core.config import Config class RateCategory(Enum): """Per-endpoint rate-limit class applied via the @rate_category decorator.""" READ = 'read' WRITE = 'write' EXPENSIVE = 'expensive' # Calibrated from prod Datadog APM (per-principal, identity_id-keyed). A category may carry # MULTIPLE limits, enforced together, so a tight sustained cap can coexist with short bursts -- # the closest native equivalent to a token bucket (limits/flask-limiter ship no bucket strategy). # sliding-window-counter smooths enforcement and avoids the fixed-window edge-burst (2x at the seam). RATE_STRATEGY: str = 'sliding-window-counter' # The per-key default is environmental (ops-tunable), so it lives in one place -- # Config.RATELIMIT_DEFAULT -- and is referenced here rather than re-declared, to avoid drift. RATE_DEFAULT: str = Config.RATELIMIT_DEFAULT RATE_CATEGORIES: dict[RateCategory, list[str]] = { # Reads fan out on page load: a single principal bursts to ~100 req/s (observed peak 106/s) then # settles. Per-minute is usually 200-300 at the busiest, with a rare bulk-load spike (1342/min # seen once over 7d) -- so 1000/min is sized to pass heavy real minutes, not tightened below them. RateCategory.READ: ['150/second', '1000/minute'], # Writes are sparse (busiest mutation ~45/day, well under 1/s) so they never burst from traffic; # the /second is generous defense-in-depth that still clears a multi-field "save all" fan-out. RateCategory.WRITE: ['30/second', '200/minute'], RateCategory.EXPENSIVE: [ '25/minute' ], # snowflake/report/bulk -- rare + heavy; the real guard } RATE_EXEMPT: set[str] = {'base_api.health', 'base_api.ready'}