The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat] Dynamic Rate Limiter v3 - fixes for detecting saturation + fixes for post saturation behavior (#15192)
Ishaan Jafff78608082c4d
diff --git a/litellm/proxy/hooks/dynamic_rate_limiter_v3.py b/litellm/proxy/hooks/dynamic_rate_limiter_v3.pyindex 5d0157f4361..997e33d256f 100644--- a/litellm/proxy/hooks/dynamic_rate_limiter_v3.py+++ b/litellm/proxy/hooks/dynamic_rate_limiter_v3.py@@ -27,15 +27,19 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):Saturation-aware priority-based rate limiter using v3 infrastructure.Key features:- 1. Reuses v3 limiter's Redis-based tracking (works across multiple instances)- 2. Only enforces priority limits when model is saturated (>80% usage)- 3. When under capacity, allows all requests (generous behavior)- 4. When saturated, enforces strict priority-based limits (fairness)+ 1. Model capacity ALWAYS enforced at 100% (prevents over-allocation)+ 2. Priority usage tracked from first request (accurate accounting)+ 3. Priority limits only enforced when saturated >= threshold+ 4. Three-phase checking prevents partial counter increments+ 5. Reuses v3 limiter's Redis-based tracking (multi-instance safe)How it works:- - Uses v3 limiter's counter keys to check model-wide saturation- - Saturation check reads existing counters without incrementing- - Priority enforcement reuses v3 limiter's atomic Lua scripts+ - Phase 1: Read-only check of ALL limits (no increments)+ - Phase 2: Decide enforcement based on saturation+ - Phase 3: Increment counters only if request allowed+ - When under-saturated: priorities can borrow unused capacity (generous)+ - When saturated: strict priority-based limits enforced (fair)+ - Uses v3 limiter's atomic Lua scripts for race-free increments"""def __init__(self, internal_usage_cache: DualCache):self.internal_usage_cache = InternalUsageCache(dual_cache=internal_usage_cache)@@ -84,6 +88,46 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):return weights+ def _get_priority_allocation(+ self,+ model: str,+ priority: Optional[str],+ normalized_weights: Dict[str, float],+ ) -> tuple[float, str]:+ """+ Get priority weight and pool key for a given priority.++ For explicit priorities: returns specific allocation and unique pool key+ For default priority: returns default allocation and shared pool key++ Args:+ model: Model name+ priority: Priority level (None for default)+ normalized_weights: Pre-computed normalized weights++ Returns:+ tuple: (priority_weight, priority_key)+ """+ # Check if this key has an explicit priority in litellm.priority_reservation+ has_explicit_priority = (+ priority is not None+ and litellm.priority_reservation is not None+ and priority in litellm.priority_reservation+ )++ if has_explicit_priority and priority is not None:+ # Explicit priority: get its specific allocation+ priority_weight = normalized_weights.get(priority, self._get_priority_weight(priority))+ # Use unique key per priority level+ priority_key = f"{model}:{priority}"+ else:+ # No explicit priority: share the default_priority pool with ALL other default keys+ priority_weight = litellm.priority_reservation_settings.default_priority+ # Use shared key for all default-priority requests+ priority_key = f"{model}:default_pool"++ return priority_weight, priority_key+async def _check_model_saturation(self,model: str,@@ -174,7 +218,9 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):Create rate limit descriptors with normalized priority weights.Uses normalized weights to handle over-allocation scenarios.- Only called when system is saturated.++ For explicit priorities: each priority gets its own pool (e.g., prod gets 75%)+ For default priority: ALL keys without explicit priority share ONE pool (e.g., all share 25%)"""descriptors: List[RateLimitDescriptor] = []@@ -185,31 +231,24 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):if model_group_info is None:return descriptors- # Get normalized priority weight (handles over-allocation)+ # Get normalized priority weight and pool keynormalized_weights = self._normalize_priority_weights()- priority_weight = normalized_weights.get(priority, None) if priority else None- if priority_weight is None:- # Fallback to non-normalized weight- priority_weight = self._get_priority_weight(priority)--- # Create priority-specific rate limits- # Use model:priority as the key to separate different priority levels- priority_key = f"{model}:{priority or 'default'}"+ priority_weight, priority_key = self._get_priority_allocation(+ model=model,+ priority=priority,+ normalized_weights=normalized_weights,+ )rate_limit_config: RateLimitDescriptorRateLimitObject = {}- # Apply normalized priority weight to model limits+ # Apply priority weight to model limitsif model_group_info.tpm is not None:- # Reserve portion of TPM based on normalized priorityreserved_tpm = int(model_group_info.tpm * priority_weight)rate_limit_config["tokens_per_unit"] = reserved_tpmif model_group_info.rpm is not None:- # Reserve portion of RPM based on normalized priorityreserved_rpm = int(model_group_info.rpm * priority_weight)rate_limit_config["requests_per_unit"] = reserved_rpm-if rate_limit_config:rate_limit_config["window_size"] = self.v3_limiter.window_size@@ -257,58 +296,8 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):},)- async def _handle_generous_mode(- self,- model: str,- model_group_info: ModelGroupInfo,- user_api_key_dict: UserAPIKeyAuth,- key_priority: Optional[str],- ) -> None:- """- Handle rate limiting in generous mode (under saturation threshold).-- In this mode, we enforce model-wide capacity but NOT priority-specific limits.- This allows lower-priority users to borrow unused capacity from higher-priority users.-- Args:- model: Model name- model_group_info: Model configuration- user_api_key_dict: User authentication info- key_priority: User's priority level-- Raises:- HTTPException: If model capacity is reached- """- descriptor = self._create_model_tracking_descriptor(- model=model,- model_group_info=model_group_info,- high_limit_multiplier=1, # Enforce actual limits in generous mode- )-- response = await self.v3_limiter.should_rate_limit(- descriptors=[descriptor],- parent_otel_span=user_api_key_dict.parent_otel_span,- )-- if response["overall_code"] == "OVER_LIMIT":- for status in response["statuses"]:- if status["code"] == "OVER_LIMIT":- raise HTTPException(- status_code=429,- detail={- "error": f"Model capacity reached for {model}. "- f"Priority: {key_priority}, "- f"Rate limit type: {status['rate_limit_type']}, "- f"Remaining: {status['limit_remaining']}"- },- headers={- "retry-after": str(self.v3_limiter.window_size),- "rate_limit_type": str(status["rate_limit_type"]),- "x-litellm-priority": key_priority or "default",- },- )- async def _handle_strict_mode(+ async def _check_rate_limits(self,model: str,model_group_info: ModelGroupInfo,@@ -318,9 +307,23 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):data: dict,) -> None:"""- Handle rate limiting in strict mode (above saturation threshold).+ Check rate limits using THREE-PHASE approach to prevent partial increments.++ Phase 1: Read-only check of ALL limits (no increments)+ Phase 2: Decide which limits to enforce based on saturation+ Phase 3: Increment ALL counters atomically (model + priority)- In this mode, we enforce priority-specific limits using normalized weights.+ This prevents the bug where:+ - Model counter increments in stage 1+ - Priority check fails in stage 2+ - Request blocked but model counter already incremented++ Key behaviors:+ - All checks performed first (read-only)+ - Only increment counters if request will be allowed+ - Model capacity: Always enforced at 100%+ - Priority limits: Only enforced when saturated >= threshold+ - Both counters tracked from first request (accurate accounting)Args:model: Model name@@ -331,63 +334,115 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):data: Request data dictionaryRaises:- HTTPException: If priority-specific limit is exceeded+ HTTPException: If any limit is exceeded"""- # Create priority-based descriptors- descriptors = self._create_priority_based_descriptors(+ import json+ saturation_threshold = litellm.priority_reservation_settings.saturation_threshold+ should_enforce_priority = saturation >= saturation_threshold++ # Build ALL descriptors upfront+ descriptors_to_check: List[RateLimitDescriptor] = []++ # Model-wide descriptor (always enforce)+ model_wide_descriptor = self._create_model_tracking_descriptor(model=model,- user_api_key_dict=user_api_key_dict,- priority=key_priority,+ model_group_info=model_group_info,+ high_limit_multiplier=1,)-- if not descriptors:- verbose_proxy_logger.debug("No rate limit descriptors created, allowing request")- return-- # Track model-wide usage for future saturation checks- # Why tracking_multiplier: v3_limiter.should_rate_limit() both increments AND checks limits.- # We need the increment (for saturation detection) but NOT the limit check (priority limits handle enforcement).- # Setting limit to 10x capacity ensures tracking never blocks while keeping accurate counters.- tracking_multiplier = litellm.priority_reservation_settings.tracking_multiplier- tracking_descriptor = self._create_model_tracking_descriptor(+ descriptors_to_check.append(model_wide_descriptor)++ # Priority descriptors (always track, conditionally enforce)+ priority_descriptors = self._create_priority_based_descriptors(model=model,- model_group_info=model_group_info,- high_limit_multiplier=tracking_multiplier,+ user_api_key_dict=user_api_key_dict,+ priority=key_priority,)+ if priority_descriptors:+ descriptors_to_check.extend(priority_descriptors)- await self.v3_limiter.should_rate_limit(- descriptors=[tracking_descriptor],+ # PHASE 1: Read-only check of ALL limits (no increments)+ check_response = await self.v3_limiter.should_rate_limit(+ descriptors=descriptors_to_check,parent_otel_span=user_api_key_dict.parent_otel_span,+ read_only=True, # CRITICAL: Don't increment counters yet)- # Enforce priority-specific limits- response = await self.v3_limiter.should_rate_limit(- descriptors=descriptors,+ verbose_proxy_logger.debug(f"Read-only check: {json.dumps(check_response, indent=2)}")++ # PHASE 2: Decide which limits to enforce+ if check_response["overall_code"] == "OVER_LIMIT":+ for status in check_response["statuses"]:+ if status["code"] == "OVER_LIMIT":+ descriptor_key = status["descriptor_key"]++ # Model-wide limit exceeded (ALWAYS enforce)+ if descriptor_key == "model_saturation_check":+ raise HTTPException(+ status_code=429,+ detail={+ "error": f"Model capacity reached for {model}. "+ f"Priority: {key_priority}, "+ f"Rate limit type: {status['rate_limit_type']}, "+ f"Remaining: {status['limit_remaining']}"+ },+ headers={+ "retry-after": str(self.v3_limiter.window_size),+ "rate_limit_type": str(status["rate_limit_type"]),+ "x-litellm-priority": key_priority or "default",+ },+ )++ # Priority limit exceeded (ONLY enforce when saturated)+ elif descriptor_key == "priority_model" and should_enforce_priority:+ verbose_proxy_logger.debug(+ f"Enforcing priority limits for {model}, saturation: {saturation:.1%}, "+ f"priority: {key_priority}"+ )+ raise HTTPException(+ status_code=429,+ detail={+ "error": f"Priority-based rate limit exceeded. "+ f"Priority: {key_priority}, "+ f"Rate limit type: {status['rate_limit_type']}, "+ f"Remaining: {status['limit_remaining']}, "+ f"Model saturation: {saturation:.1%}"+ },+ headers={+ "retry-after": str(self.v3_limiter.window_size),+ "rate_limit_type": str(status["rate_limit_type"]),+ "x-litellm-priority": key_priority or "default",+ "x-litellm-saturation": f"{saturation:.2%}",+ },+ )++ # PHASE 3: Increment counters separately to avoid early-exit issues+ # Model counter must ALWAYS increment, but priority counter might be over limit+ # If we increment them together, v3_limiter's in-memory check will exit early+ # and skip incrementing the model counter++ # Step 3a: Increment model-wide counter (always)+ model_increment_response = await self.v3_limiter.should_rate_limit(+ descriptors=[model_wide_descriptor],parent_otel_span=user_api_key_dict.parent_otel_span,+ read_only=False,)- if response["overall_code"] == "OVER_LIMIT":- for status in response["statuses"]:- if status["code"] == "OVER_LIMIT":- raise HTTPException(- status_code=429,- detail={- "error": f"Priority-based rate limit exceeded for {status['descriptor_key']}. "- f"Priority: {key_priority}, "- f"Rate limit type: {status['rate_limit_type']}, "- f"Remaining: {status['limit_remaining']}, "- f"Model saturation: {saturation:.1%}"- },- headers={- "retry-after": str(self.v3_limiter.window_size),- "rate_limit_type": str(status["rate_limit_type"]),- "x-litellm-priority": key_priority or "default",- "x-litellm-saturation": f"{saturation:.2%}",- },- )+ # Step 3b: Increment priority counter (may be over limit, but we still track it)+ if priority_descriptors:+ priority_increment_response = await self.v3_limiter.should_rate_limit(+ descriptors=priority_descriptors,+ parent_otel_span=user_api_key_dict.parent_otel_span,+ read_only=False,+ )++ # Combine responses for post-call hook+ combined_response = {+ "overall_code": model_increment_response["overall_code"],+ "statuses": model_increment_response["statuses"] + priority_increment_response["statuses"]+ }+ data["litellm_proxy_rate_limit_response"] = combined_responseelse:- # Store response for post-call hook- data["litellm_proxy_rate_limit_response"] = response+ data["litellm_proxy_rate_limit_response"] = model_increment_responseasync def async_pre_call_hook(self,@@ -409,9 +464,27 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):"""Saturation-aware pre-call hook for priority-based rate limiting.- This hook implements a two-mode rate limiting strategy:- - Generous mode (< 80% saturation): Enforces model capacity, allows priority borrowing- - Strict mode (>= 80% saturation): Enforces normalized priority-based limits+ Flow:+ 1. Check current saturation level+ 2. THREE-PHASE rate limit check:+ - PHASE 1: Read-only check of ALL limits (no increments)+ - PHASE 2: Decide which limits to enforce based on saturation+ - PHASE 3: Increment ALL counters atomically if request allowed++ This three-phase approach ensures:+ - Model capacity is NEVER exceeded (always enforced at 100%)+ - Priority usage tracked from first request (accurate metrics)+ - Counters only increment when request will be allowed (prevents phantom usage)+ - When under-saturated: priorities can borrow unused capacity (generous)+ - When saturated: fair allocation based on normalized priority weights (strict)++ Example with 100 RPM model, 60% priority allocation, 80% threshold:+ - Saturation < 80%: Priority can use up to 100 RPM (model limit enforced only)+ - Saturation >= 80%: Priority limited to 60 RPM (both limits enforced)++ Prevents bugs where:+ - Model counter increments but priority check fails → model over-capacity+ - Priority counter increments but not enforced → inaccurate metricsArgs:user_api_key_dict: User authentication and metadata@@ -436,8 +509,8 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):verbose_proxy_logger.debug(f"No model group info for {model}, allowing request")return None- # Check current saturation leveltry:+ # STEP 1: Check current saturation levelsaturation = await self._check_model_saturation(model, model_group_info)saturation_threshold = litellm.priority_reservation_settings.saturation_threshold@@ -449,23 +522,19 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):data["litellm_model_saturation"] = saturation- # Route to appropriate mode based on saturation- if saturation < saturation_threshold:- await self._handle_generous_mode(- model=model,- model_group_info=model_group_info,- user_api_key_dict=user_api_key_dict,- key_priority=key_priority,- )- else:- await self._handle_strict_mode(- model=model,- model_group_info=model_group_info,- user_api_key_dict=user_api_key_dict,- key_priority=key_priority,- saturation=saturation,- data=data,- )+ # STEP 2: Check rate limits in THREE phases+ # Phase 1: Read-only check of ALL limits (no increments)+ # Phase 2: Decide which limits to enforce (based on saturation)+ # Phase 3: Increment ALL counters only if request will be allowed+ # This prevents partial increments and ensures accurate tracking+ await self._check_rate_limits(+ model=model,+ model_group_info=model_group_info,+ user_api_key_dict=user_api_key_dict,+ key_priority=key_priority,+ saturation=saturation,+ data=data,+ )except HTTPException:raisediff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.pyindex 2e3057cdba3..7b8ddf3ffcf 100644--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py@@ -413,6 +413,11 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):Check if any of the rate limit descriptors should be rate limited.Returns a RateLimitResponse with the overall code and status for each descriptor.Uses batch operations for Redis to improve performance.++ Args:+ descriptors: List of rate limit descriptors to check+ parent_otel_span: Optional OpenTelemetry span for tracing+ read_only: If True, only check limits without incrementing counters"""now = datetime.now().timestamp()@@ -485,8 +490,22 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):if rate_limit_response["overall_code"] == "OVER_LIMIT":return rate_limit_response- ## IF under limit, check Redis- if self.batch_rate_limiter_script is not None:+ ## IF under limit in-memory, check Redis+ if read_only:+ # READ-ONLY MODE: Just read current values without incrementing+ cache_values = await self.internal_usage_cache.async_batch_get_cache(+ keys=keys_to_fetch,+ parent_otel_span=parent_otel_span,+ local_only=False, # Check Redis too+ )++ # For keys that don't exist yet, set them to 0+ if cache_values is None:+ cache_values = []+ for _ in keys_to_fetch:+ cache_values.append(str(now_int) if _.endswith(":window") else 0)+ elif self.batch_rate_limiter_script is not None:+ # NORMAL MODE: Increment counters in Redis# Group keys by hash tag for Redis cluster compatibilitycache_values = await self._execute_redis_batch_rate_limiter_script(keys_to_fetch=keys_to_fetch,@@ -514,6 +533,7 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):local_only=True,)else:+ # NORMAL MODE: In-memory sliding window (no Redis)cache_values = await self.in_memory_cache_sliding_window(keys=keys_to_fetch,now_int=now_int,diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 4e93e167530..166706634df 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -2702,12 +2702,12 @@ class PriorityReservationSettings(BaseModel):"""default_priority: float = Field(- default=0.5,+ default=0.25,description="Priority level to assign to API keys without explicit priority metadata. Should match a key in litellm.priority_reservation.",)saturation_threshold: float = Field(- default=0.80,+ default=0.50,description="Saturation threshold (0.0-1.0) at which strict priority enforcement begins. Below this threshold, generous mode allows priority borrowing. Above this threshold, strict mode enforces normalized priority limits.")diff --git a/tests/test_litellm/proxy/hooks/test_dynamic_rate_limiter_v3.py b/tests/test_litellm/proxy/hooks/test_dynamic_rate_limiter_v3.pyindex 2b7c080e65d..138cbbef769 100644--- a/tests/test_litellm/proxy/hooks/test_dynamic_rate_limiter_v3.py+++ b/tests/test_litellm/proxy/hooks/test_dynamic_rate_limiter_v3.py@@ -1202,3 +1202,89 @@ async def test_fake_calls_case_5_default_value_priority_reservation():if total_successful > 0:key_a_share = successful_requests["key_a"] / total_successfulprint(f" - Key A got {key_a_share:.1%} of successful requests (expected ~55-62%)")+++async def test_default_priority_shared_pool():+ """+ Test that keys without explicit priority share ONE default pool, not get individual allocations.++ With default_priority=0.25:+ - Key A, B, C (no priority) should share ONE 25 RPM pool+ - NOT get 25 RPM each (which would be 75 RPM total)+ """+ os.environ["LITELLM_LICENSE"] = "test-license-key"++ litellm.priority_reservation = {"prod": 0.75}+ litellm.priority_reservation_settings.default_priority = 0.25++ dual_cache = DualCache()+ handler = DynamicRateLimitHandler(internal_usage_cache=dual_cache)++ model = "test-default-pool"+ total_rpm = 100++ llm_router = Router(+ model_list=[+ {+ "model_name": model,+ "litellm_params": {+ "model": "gpt-3.5-turbo",+ "api_key": "test-key",+ "api_base": "test-base",+ "rpm": total_rpm,+ },+ }+ ]+ )+ handler.update_variables(llm_router=llm_router)++ # Create 3 users without explicit priority+ user_a = UserAPIKeyAuth()+ user_a.metadata = {}+ user_a.user_id = "user_a"++ user_b = UserAPIKeyAuth()+ user_b.metadata = {}+ user_b.user_id = "user_b"++ user_c = UserAPIKeyAuth()+ user_c.metadata = {}+ user_c.user_id = "user_c"++ # Get descriptors for each+ desc_a = handler._create_priority_based_descriptors(+ model=model, user_api_key_dict=user_a, priority=None+ )+ desc_b = handler._create_priority_based_descriptors(+ model=model, user_api_key_dict=user_b, priority=None+ )+ desc_c = handler._create_priority_based_descriptors(+ model=model, user_api_key_dict=user_c, priority=None+ )++ # All should use the SAME shared pool key+ assert desc_a[0]["value"] == f"{model}:default_pool"+ assert desc_b[0]["value"] == f"{model}:default_pool"+ assert desc_c[0]["value"] == f"{model}:default_pool"++ # All should have same limit (25 RPM SHARED, not 25 RPM each)+ assert desc_a[0]["rate_limit"]["requests_per_unit"] == 25+ assert desc_b[0]["rate_limit"]["requests_per_unit"] == 25+ assert desc_c[0]["rate_limit"]["requests_per_unit"] == 25++ # Verify explicit priority uses different pool+ user_prod = UserAPIKeyAuth()+ user_prod.metadata = {"priority": "prod"}+ desc_prod = handler._create_priority_based_descriptors(+ model=model, user_api_key_dict=user_prod, priority="prod"+ )++ assert desc_prod[0]["value"] == f"{model}:prod"+ assert desc_prod[0]["rate_limit"]["requests_per_unit"] == 75+ assert desc_prod[0]["value"] != desc_a[0]["value"] # Different pools++ print("✅ Default priority test passed:")+ print(f" - 3 keys without priority share ONE pool: {desc_a[0]['value']}")+ print(f" - Shared pool limit: {desc_a[0]['rate_limit']['requests_per_unit']} RPM")+ print(f" - Explicit priority 'prod' uses separate pool: {desc_prod[0]['value']}")