Skip to content

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]

[Feat] Dynamic Rate Limiter - allow specifying ttl for in memory cache (#17679)

Ishaan Jaff2f335ac5a65b
diff --git a/docs/my-website/docs/proxy/dynamic_rate_limit.md b/docs/my-website/docs/proxy/dynamic_rate_limit.md
index f5438b5a6f5..3c3500f8a6c 100644
--- a/docs/my-website/docs/proxy/dynamic_rate_limit.md
+++ b/docs/my-website/docs/proxy/dynamic_rate_limit.md
@@ -149,6 +149,7 @@ litellm_settings:
priority_reservation_settings:
default_priority: 0 # Weight (0%) assigned to keys without explicit priority metadata
saturation_threshold: 0.50 # A model is saturated if it has hit 50% of its RPM limit
+ saturation_check_cache_ttl: 60 # How long (seconds) saturation values are cached locally
general_settings:
master_key: sk-1234 # OR set `LITELLM_MASTER_KEY=".."` in your .env
@@ -168,6 +169,8 @@ general_settings:
- **default_priority (float)**: Weight/percentage (0.0 to 1.0) assigned to API keys that have no priority metadata set (defaults to 0.5)
- **saturation_threshold (float)**: Saturation level (0.0 to 1.0) at which strict priority enforcement begins for a model. Saturation is calculated as `max(current_rpm/max_rpm, current_tpm/max_tpm)`. Below this threshold, generous mode allows priority borrowing from unused capacity. Above this threshold, strict mode enforces normalized priority limits.
- Example: When model usage is low, keys can use more than their allocated share. When model usage is high, keys are strictly limited to their allocated share.
+- **saturation_check_cache_ttl (int)**: TTL in seconds for local cache when reading saturation values from Redis (defaults to 60). In multi-node deployments, this controls how quickly nodes converge on the same saturation state. Lower values mean faster convergence but more Redis reads.
+ - Example: Set to `5` for faster multi-node consistency, or `0` to always read directly from Redis.
**Start Proxy**
diff --git a/litellm/proxy/hooks/dynamic_rate_limiter_v3.py b/litellm/proxy/hooks/dynamic_rate_limiter_v3.py
index 53419ef6ad7..755f5fdc201 100644
--- a/litellm/proxy/hooks/dynamic_rate_limiter_v3.py
+++ b/litellm/proxy/hooks/dynamic_rate_limiter_v3.py
@@ -58,6 +58,35 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):
def update_variables(self, llm_router: Router):
self.llm_router = llm_router
+ def _get_saturation_check_cache_ttl(self) -> int:
+ """Get the configurable TTL for local cache when reading saturation values."""
+ return litellm.priority_reservation_settings.saturation_check_cache_ttl
+
+ async def _get_saturation_value_from_cache(
+ self,
+ counter_key: str,
+ ) -> Optional[str]:
+ """
+ Get saturation value with configurable local cache TTL.
+
+ Uses DualCache with configurable TTL for local cache storage.
+ TTL is configurable via litellm.priority_reservation_settings.saturation_check_cache_ttl
+
+ Args:
+ counter_key: The cache key for the saturation counter
+
+ Returns:
+ Counter value as string, or None if not found
+ """
+ local_cache_ttl = self._get_saturation_check_cache_ttl()
+
+ return await self.internal_usage_cache.async_get_cache(
+ key=counter_key,
+ litellm_parent_otel_span=None,
+ local_only=False,
+ ttl=local_cache_ttl,
+ )
+
def _get_priority_weight(
self, priority: Optional[str], model_info: Optional[ModelGroupInfo] = None
) -> float:
@@ -195,7 +224,7 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):
try:
max_saturation = 0.0
- # Query RPM saturation
+ # Query RPM saturation - always read from Redis for multi-node consistency
if model_group_info.rpm is not None and model_group_info.rpm > 0:
# Use v3 limiter's key format: {key:value}:rate_limit_type
counter_key = self.v3_limiter.create_rate_limit_keys(
@@ -204,11 +233,9 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):
rate_limit_type="requests",
)
- # Query cache for current counter value
- counter_value = await self.internal_usage_cache.async_get_cache(
- key=counter_key,
- litellm_parent_otel_span=None,
- local_only=False, # Check Redis too
+ # Query Redis directly for current counter value (skip local cache for consistency)
+ counter_value = await self._get_saturation_value_from_cache(
+ counter_key=counter_key
)
if counter_value is not None:
@@ -229,10 +256,8 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):
rate_limit_type="tokens",
)
- counter_value = await self.internal_usage_cache.async_get_cache(
- key=counter_key,
- litellm_parent_otel_span=None,
- local_only=False,
+ counter_value = await self._get_saturation_value_from_cache(
+ counter_key=counter_key
)
if counter_value is not None:
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 9824b6db6d6..2ccc14a2719 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -3310,4 +3310,9 @@ class PriorityReservationSettings(BaseModel):
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.",
)
+ saturation_check_cache_ttl: int = Field(
+ default=60,
+ description="TTL in seconds for local cache when reading saturation check values from Redis.",
+ )
+
model_config = ConfigDict(protected_namespaces=())
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.py
index d9e10e6f4b8..095d5f50dcf 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
@@ -1418,6 +1418,100 @@ async def test_async_log_success_event_increments_by_actual_tokens():
assert any("priority_model" in k and "dev" in k for k in keys), "Should increment priority_model with 'dev' priority"
+async def test_saturation_check_cache_ttl_configuration():
+ """
+ Test that saturation_check_cache_ttl controls how long saturation values are cached locally.
+
+ This validates the configurable TTL for multi-node consistency:
+ - When saturation_check_cache_ttl is set, local cache should expire after that duration
+ - After expiration, fresh values should be fetched from Redis
+ - This prevents nodes from having stale saturation data in multi-node deployments
+ """
+ os.environ["LITELLM_LICENSE"] = "test-license-key"
+
+ # Set a short TTL for testing (5 seconds)
+ original_ttl = litellm.priority_reservation_settings.saturation_check_cache_ttl
+ litellm.priority_reservation_settings.saturation_check_cache_ttl = 5
+
+ try:
+ dual_cache = DualCache()
+ handler = DynamicRateLimitHandler(internal_usage_cache=dual_cache)
+
+ model = "test-saturation-ttl"
+ llm_router = Router(
+ model_list=[
+ {
+ "model_name": model,
+ "litellm_params": {
+ "model": "gpt-3.5-turbo",
+ "api_key": "test-key",
+ "api_base": "test-base",
+ "rpm": 100,
+ "tpm": 1000,
+ },
+ }
+ ]
+ )
+ handler.update_variables(llm_router=llm_router)
+
+ # Verify the TTL getter returns configured value
+ assert handler._get_saturation_check_cache_ttl() == 5, (
+ "TTL should be configurable via priority_reservation_settings"
+ )
+
+ # Track async_get_cache calls to verify TTL is passed
+ get_cache_calls = []
+ original_get_cache = handler.internal_usage_cache.async_get_cache
+
+ async def mock_get_cache(key, litellm_parent_otel_span=None, local_only=False, **kwargs):
+ get_cache_calls.append({
+ "key": key,
+ "ttl": kwargs.get("ttl"),
+ "local_only": local_only,
+ })
+ return None # Simulate cache miss
+
+ handler.internal_usage_cache.async_get_cache = mock_get_cache
+
+ # Call _get_saturation_value_from_cache
+ counter_key = handler.v3_limiter.create_rate_limit_keys(
+ key="model_saturation_check",
+ value=model,
+ rate_limit_type="requests",
+ )
+
+ await handler._get_saturation_value_from_cache(counter_key=counter_key)
+
+ # Verify async_get_cache was called with the configured TTL
+ assert len(get_cache_calls) == 1, "Expected 1 cache call"
+ assert get_cache_calls[0]["ttl"] == 5, (
+ f"Expected TTL of 5 seconds, got {get_cache_calls[0]['ttl']}"
+ )
+ assert get_cache_calls[0]["local_only"] is False, (
+ "Should check Redis (local_only=False) for multi-node consistency"
+ )
+
+ # Test with different TTL value
+ get_cache_calls.clear()
+ litellm.priority_reservation_settings.saturation_check_cache_ttl = 30
+
+ await handler._get_saturation_value_from_cache(counter_key=counter_key)
+
+ assert get_cache_calls[0]["ttl"] == 30, (
+ f"TTL should update to 30 seconds, got {get_cache_calls[0]['ttl']}"
+ )
+
+ print("Saturation check cache TTL test passed:")
+ print(" - TTL is configurable via priority_reservation_settings.saturation_check_cache_ttl")
+ print(" - TTL is passed to async_get_cache for local cache expiration control")
+ print(" - local_only=False ensures Redis is checked for multi-node consistency")
+
+ finally:
+ # Restore original TTL
+ litellm.priority_reservation_settings.saturation_check_cache_ttl = original_ttl
+
+
@pytest.mark.asyncio
async def test_async_log_success_event_uses_team_priority_from_auth_metadata():
"""