4.15.0 — 2026-07-13¶
← 4.16.0 | 4.14.0 → | ↑ 4.x series
Added¶
Configs¶
- FastAPI Rate Limit Settings - Added
FastAPIRateLimitConfigand theBaseConfig.FASTAPI_RATE_LIMITattribute, centralizing trusted-proxy resolution, Redis key layout, fail-open/closed behavior,X-RateLimit-*headers, and JWT-based identity forFastAPIRestRateLimitHandler.- New
.envvariables:FASTAPI_RATE_LIMIT__TRUSTED_PROXY_IPS,ALLOW_PRIVATE_IPS,KEY_PREFIX,FAIL_CLOSED,SKIP_METHODS,HASH_QUERY_PARAM_VALUES,REQUIRE_IDENTIFIER_FOR_QUERY_PARAMS,REJECT_UNKNOWN_CLIENT,RATE_LIMIT_HEADERS,IDENTITY_FROM_ACCESS_TOKEN.
- New
- gRPC Rate Limit Settings - Added
GrpcRateLimitConfigand theBaseConfig.GRPC_RATE_LIMITattribute, controlling Redis key layout, fail-open/closed behavior, skipped health-check methods, and JWT-based identity for the new gRPC rate-limit interceptors.- New
.envvariables:GRPC_RATE_LIMIT__IS_ENABLED,FAIL_CLOSED,IDENTITY_FROM_ACCESS_TOKEN. - When
IS_ENABLEDisTrue,AppUtils.create_grpc_appandAppUtils.create_async_grpc_appregister the matching interceptor automatically.
- New
Models - DTOs¶
- Rate Limit Window DTO - Added
RateLimitWindowDTO(calls_count,window_ms) with akey_suffixproperty producing a stable Redis key segment per tier. Shared by the FastAPI handler and both gRPC interceptors.
Helpers - Decorators¶
- gRPC Rate Limit Decorator - Added
grpc_rate_limit_decorator, attaching one or more rate-limit windows to a servicer method without wrapping it. Stacking the decorator declares independent burst and sustained tiers, all enforced in declaration order byGrpcServerRateLimitInterceptor.
Helpers - Utils¶
- Rate Limit Utils - Added
RateLimitUtilswithcompute_rate_limit_window(validatescalls_count >= 1and a positive combined window) andget_rate_limit_windows_from_callable(reads stacked windows off a function or bound method). - gRPC Interceptor Auto-Registration - Added
GrpcAPIUtils.setup_rate_limit_interceptorandAsyncGrpcAPIUtils.setup_rate_limit_interceptor, wired intoAppUtils.create_grpc_app/create_async_grpc_appto append the sync or async rate-limit interceptor whenGRPC_RATE_LIMIT.IS_ENABLEDisTrue.
Helpers - Interceptors¶
- gRPC Rate Limit Interceptors - Added
GrpcServerRateLimitInterceptorandAsyncGrpcServerRateLimitInterceptor, enforcing decorator-declared Redis-backed windows per RPC.- Uses atomic
INCREX(saturate=True,enx=True, millisecondpxexpiry) to avoid check-then-act races. - Identity resolution: custom
identifier_fn, JWTsubclaim from a Bearer token in invocation metadata (IDENTITY_FROM_ACCESS_TOKEN), falling back to parsed peer host (ipv4:/ipv6:/unix:prefixes handled). - Breached windows abort with
RESOURCE_EXHAUSTED(viaRateLimitExceededError) including a computedretry_after; Redis/identity failures abort withUNAVAILABLE(viaUnavailableError) whenFAIL_CLOSEDisTrue. SKIP_METHODSexcludes full gRPC method names (health checks by default) from rate limiting.
- Uses atomic
- gRPC Identity Helpers - Added
archipy.helpers.interceptors.grpc.rate_limit.identifierswithinvocation_metadata_to_dict,extract_bearer_token_from_metadata, andresolve_jwt_access_token_sub_from_metadata, verifying Bearer tokens viaJWTUtilsand returning thesubclaim. - FastAPI Identity Helpers - Added
archipy.helpers.interceptors.fastapi.rate_limit.identifierswithextract_bearer_tokenandresolve_jwt_access_token_sub, used byFastAPIRestRateLimitHandlerto bucket authenticated requests by user instead of IP.
Changed¶
Helpers - FastAPI Rate Limit¶
- Handler Rewrite -
FastAPIRestRateLimitHandlergained config-driven behavior sourced fromFastAPIRateLimitConfig, with per-instance overrides for every setting.- Trusted Proxy Chain Resolution - Client IP is only taken from forwarded headers (
Forwarded,X-Forwarded-For,X-Real-IP,CF-Connecting-IP,True-Client-IP) when the immediate peer is a configured trusted proxy (TRUSTED_PROXY_IPS, CIDR or exact match, or*to trust all peers).X-Forwarded-Foris walked right-to-left with nginxreal_ip_recursivesemantics, skipping trusted hops and stripping port suffixes. - JWT-Based Identity -
identity_from_access_token(defaultTrue) verifies a Bearer token viaJWTUtilsand buckets bysub, falling back to client IP when the token is missing or invalid. - Stacked Windows - New
additional_windowsparameter enforces extraRateLimitWindowDTOtiers alongside the primary window; all tiers must pass, and the most constrained remaining quota is reported in headers. - Rate Limit Headers -
rate_limit_headers(defaultTrue) attachesX-RateLimit-Limit/X-RateLimit-Remainingon allowed responses and addsRetry-Afteron429s. - Unknown Client Handling -
reject_unknown_client(defaultTrue) returns503when no client identity can be resolved instead of silently allowing the request. - Query Param Safety -
require_identifier_for_query_params(defaultTrue) raisesInvalidArgumentErrorat construction whenquery_paramsis set withoutidentifier_fnoridentity_from_access_token, preventing client-controlled per-user quota targeting. - Redis Failure Handling -
fail_closed(defaultTrue) returns503on Redis connection errors instead of allowing requests through.
- Trusted Proxy Chain Resolution - Client IP is only taken from forwarded headers (
Tests¶
Tests - gRPC Rate Limit¶
- New Feature Suite - Added
features/grpc_rate_limit.featureandfeatures/steps/grpc_rate_limit_steps.pycovering sync and async interceptor modes: within-limit success, over-limitRESOURCE_EXHAUSTEDrejection, undecorated methods bypassing limits, stacked burst/sustained windows, per-JWT-user isolation,UNAVAILABLEabort when Redis is down and fail-closed, andInvalidArgumentErroron invalid window construction.
Tests - FastAPI Rate Limit¶
- Expanded Scenario Coverage - Extended
features/fastapi_rate_limit.featureandfeatures/steps/fastapi_rate_limit_steps.py.X-RateLimit-Limit/X-RateLimit-Remainingheader assertions on allowed and rejected responses.- Spoofed
X-Real-IPis ignored without a configured trusted proxy; distinct clients are isolated only behind trusted proxies. - Multi-hop
X-Forwarded-Forchains, injected entries ahead of the real client, port-suffix stripping, and multipleX-Forwarded-Forheader fields combined per RFC 9110. X-Real-IPprecedence rules whenX-Forwarded-Foris also present.503on Redis unavailability withfail_closed;InvalidArgumentErrorwhenquery_paramsis set without an identifier.- JWT-based user isolation, fallback to client IP when a JWT is missing or invalid/expired.
Documentation¶
Tutorials - Decorators¶
- gRPC Rate Limit Decorator - Added usage guide for
grpc_rate_limit_decorator, including stacked burst/sustained window examples and interceptor registration.
Tutorials - Interceptors¶
- gRPC Rate Limiting - Added a
GrpcServerRateLimitInterceptor/AsyncGrpcServerRateLimitInterceptorguide coveringGRPC_RATE_LIMITconfig, automatic registration viaAppUtils, JWT-based identity, and health-check exclusions. - FastAPI Rate Limiting - Expanded the
FastAPIRestRateLimitHandlerguide with trusted-proxy configuration, JWT identity, stackedadditional_windows, and rate-limit header reference.
Getting Started¶
- Complete User Example / Project Structure - Updated to reference the new rate-limiting configuration and helper modules.
API Reference¶
- Added mkdocstrings entries for
FastAPIRateLimitConfig,GrpcRateLimitConfig,grpc_rate_limitdecorator,grpc.rate_limitinterceptors and identifiers,RateLimitUtils, andRateLimitWindowDTO.