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]

fix(router): stop queueing budget increments for Redis when no Redis is configured (#46831)

ryan-crabbe-berri977a58121372
diff --git a/litellm/router_strategy/budget_limiter.py b/litellm/router_strategy/budget_limiter.py
index b20f71cd51f..1622a30b95f 100644
--- a/litellm/router_strategy/budget_limiter.py
+++ b/litellm/router_strategy/budget_limiter.py
@@ -405,7 +405,8 @@ class RouterBudgetLimiting(CustomLogger):
Runs once the budget start time exists in Redis Cache (on the 2nd and subsequent requests to the same provider)
- Increments the spend in memory cache (so spend instantly updated in memory)
- - Queues the increment operation to Redis Pipeline (using batched pipeline to optimize performance. Using Redis for multi instance environment of LiteLLM)
+ - Queues the increment for the batched Redis pipeline when Redis is configured, since only a multi instance
+ deployment has anything to sync
"""
increment_op: Final = RedisPipelineIncrementOperation(
key=spend_key,
@@ -418,6 +419,8 @@ class RouterBudgetLimiting(CustomLogger):
value=response_cost,
ttl=ttl,
)
+ if self.dual_cache.redis_cache is None:
+ return
self.redis_increment_operation_queue.append(increment_op)
def _get_redis_increment_queue_lock(self) -> asyncio.Lock:
diff --git a/tests/integration/sdk/test_router_budget_limiter_wire.py b/tests/integration/sdk/test_router_budget_limiter_wire.py
index cf4fda41891..0863ee6d6cc 100644
--- a/tests/integration/sdk/test_router_budget_limiter_wire.py
+++ b/tests/integration/sdk/test_router_budget_limiter_wire.py
@@ -1,7 +1,9 @@
from __future__ import annotations
+import asyncio
import json
import os
+import time
import uuid
from collections.abc import Iterator
from typing import Final
@@ -222,3 +224,95 @@ async def test_tag_budget_blocks_exhausted_tag_but_allows_another(
assert response.choices[0].message.content == "openai"
assert len(requests) == 1
assert json.loads(requests[0].body)["model"] == _MODEL
+
+
+
+_ISOLATED_SPEND_KEY: Final = "provider_spend:hosted_vllm:1d"
+_INPUT_COST_PER_TOKEN: Final = 0.001
+_OUTPUT_COST_PER_TOKEN: Final = 0.002
+
+
+def _isolated_provider_deployment(api_base: str) -> dict[str, JsonValue]:
+ """Only these two tests route to hosted_vllm, so success callbacks still draining from earlier tests cannot land here."""
+ return {
+ "model_name": "isolated-budget",
+ "litellm_params": {
+ "model": "hosted_vllm/llama-3",
+ "api_base": api_base,
+ "api_key": _API_KEY,
+ "input_cost_per_token": _INPUT_COST_PER_TOKEN,
+ "output_cost_per_token": _OUTPUT_COST_PER_TOKEN,
+ },
+ "model_info": {"id": "vllm-deployment"},
+ }
+
+
+def _isolated_budget_router(api_base: str, redis_client: Redis | None) -> Router:
+ redis_params: Final = (
+ {}
+ if redis_client is None
+ else {"redis_host": os.environ["REDIS_HOST"], "redis_port": int(os.environ["REDIS_PORT"])}
+ )
+ return Router(
+ model_list=[_isolated_provider_deployment(api_base)],
+ provider_budget_config={"hosted_vllm": BudgetConfig(budget_duration="1d", max_budget=10.0)},
+ num_retries=0,
+ disable_cooldowns=True,
+ **redis_params,
+ )
+
+
+async def _complete_and_wait_for_spend(router: Router, previous: float) -> float:
+ response: Final = await router.acompletion(
+ model="isolated-budget",
+ messages=[{"role": "user", "content": "budget tracking"}],
+ )
+ cost: Final = (
+ response.usage.prompt_tokens * _INPUT_COST_PER_TOKEN + response.usage.completion_tokens * _OUTPUT_COST_PER_TOKEN
+ )
+ deadline: Final = time.monotonic() + 5.0
+ while time.monotonic() < deadline:
+ spend: float | None = router.cache.in_memory_cache.get_cache(_ISOLATED_SPEND_KEY)
+ if spend is not None and spend > previous:
+ assert spend == pytest.approx(previous + cost)
+ return spend
+ await asyncio.sleep(0.05)
+ raise AssertionError(f"{_ISOLATED_SPEND_KEY} never rose above {previous}")
+
+
+async def test_router_without_redis_tracks_spend_but_queues_no_redis_increments() -> None:
+ """A Router with no Redis never flushes, so anything it queues for Redis is retained for the life of the process."""
+ with wire_server(_peer) as wire:
+ router: Final = _isolated_budget_router(f"{wire.url}/openai/v1", redis_client=None)
+ first: Final = await _complete_and_wait_for_spend(router, previous=0.0)
+ second: Final = await _complete_and_wait_for_spend(router, previous=first)
+ third: Final = await _complete_and_wait_for_spend(router, previous=second)
+ wire.drain()
+
+ assert third > second > first > 0.0
+ assert router.router_budget_logger is not None
+ assert router.router_budget_logger.redis_increment_operation_queue == []
+
+
+async def _wait_for_redis_spend(redis_client: Redis, at_least: float) -> float:
+ deadline: Final = time.monotonic() + 15.0
+ while time.monotonic() < deadline:
+ raw: str | None = redis_client.get(_ISOLATED_SPEND_KEY)
+ if raw is not None and float(raw) >= at_least:
+ return float(raw)
+ await asyncio.sleep(0.1)
+ raise AssertionError(f"{_ISOLATED_SPEND_KEY} in Redis never reached {at_least}")
+
+
+async def test_router_with_redis_flushes_queued_spend_increments(redis_client: Redis) -> None:
+ redis_client.delete(_ISOLATED_SPEND_KEY)
+ with wire_server(_peer) as wire:
+ router: Final = _isolated_budget_router(f"{wire.url}/openai/v1", redis_client=redis_client)
+ first: Final = await _complete_and_wait_for_spend(router, previous=0.0)
+ second: Final = await _complete_and_wait_for_spend(router, previous=first)
+ redis_spend: Final = await _wait_for_redis_spend(redis_client, at_least=second)
+ wire.drain()
+
+ assert redis_spend == pytest.approx(second)
diff --git a/tests/unit/proxy/hooks/test_unit_test_max_model_budget_limiter.py b/tests/unit/proxy/hooks/test_unit_test_max_model_budget_limiter.py
index 33904637366..c6369a1f3d7 100644
--- a/tests/unit/proxy/hooks/test_unit_test_max_model_budget_limiter.py
+++ b/tests/unit/proxy/hooks/test_unit_test_max_model_budget_limiter.py
@@ -20,7 +20,6 @@ from litellm.proxy.hooks.model_max_budget_limiter import (
model_budget_start_time_cache_key,
resolve_model_budget,
)
-from litellm.types.caching import RedisPipelineIncrementOperation
async def _reset_at_of_open_window(
@@ -500,16 +499,15 @@ async def test_async_log_success_event_pushes_redis_increments_when_redis_config
@pytest.mark.asyncio
-async def test_model_budget_limiter_initializes_redis_increment_queue_lock():
+async def test_model_budget_limiter_without_redis_tracks_spend_locally_and_queues_nothing():
dual_cache = DualCache()
limiter = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=dual_cache)
spend_key = "virtual_key_spend:test-key:gpt-4:1d"
await limiter._increment_spend_in_current_window(spend_key=spend_key, response_cost=0.01, ttl=86400)
- assert limiter.redis_increment_operation_queue == [
- RedisPipelineIncrementOperation(key=spend_key, increment_value=0.01, ttl=86400)
- ]
+ assert await dual_cache.async_get_cache(spend_key) == 0.01
+ assert limiter.redis_increment_operation_queue == []
@pytest.mark.asyncio
diff --git a/tests/unit/router_strategy/test_budget_limiter.py b/tests/unit/router_strategy/test_budget_limiter.py
index 685ea46547e..380aa573b3c 100644
--- a/tests/unit/router_strategy/test_budget_limiter.py
+++ b/tests/unit/router_strategy/test_budget_limiter.py
@@ -14,6 +14,7 @@ import pytest
from litellm import Router
from litellm.caching.caching import DualCache
+from litellm.caching.in_memory_cache import InMemoryCache
from litellm.router_strategy.budget_limiter import RouterBudgetLimiting
from litellm.types.utils import BudgetConfig
import sys, os, asyncio, time, random
@@ -232,7 +233,11 @@ async def test_a_monthly_router_budget_ends_a_calendar_month_after_it_opens(
"""
monkeypatch.setattr(litellm, "tag_budget_config", tag_budget_config)
monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
- limiter = RouterBudgetLimiting(dual_cache=DualCache(), clock=charged_at.timestamp, **limiter_config)
+ limiter = RouterBudgetLimiting(
+ dual_cache=DualCache(in_memory_cache=InMemoryCache(clock=charged_at.timestamp)),
+ clock=charged_at.timestamp,
+ **limiter_config,
+ )
await limiter.dual_cache.async_set_cache(key=start_time_key, value=opened_at.timestamp())
await _log_success(
@@ -243,9 +248,8 @@ async def test_a_monthly_router_budget_ends_a_calendar_month_after_it_opens(
},
)
- assert limiter.redis_increment_operation_queue == [
- {"key": spend_key, "increment_value": 0.25, "ttl": int((closes_at - charged_at).total_seconds())}
- ]
+ assert await limiter.dual_cache.async_get_cache(spend_key) == 0.25
+ assert limiter.dual_cache.in_memory_cache.ttl_dict[spend_key] == closes_at.timestamp()
@pytest.mark.asyncio
@@ -362,24 +366,18 @@ async def test_new_budget_window_sets_spend_and_start_time() -> None:
@pytest.mark.asyncio
-async def test_spend_increment_updates_memory_and_queues_redis_operation() -> None:
- provider_budget: Final = RouterBudgetLimiting(dual_cache=DualCache(), provider_budget_config={})
- await provider_budget.dual_cache.async_set_cache(key="provider_spend:openai:1d", value=1.0, ttl=86400)
-
- await provider_budget._increment_spend_in_current_window(
- spend_key="provider_spend:openai:1d",
- response_cost=0.5,
- ttl=86400,
+async def test_redis_less_limiter_tracks_spend_without_queueing_redis_increments(disable_budget_sync) -> None:
+ """With no Redis there is nothing to flush to, so queued increments would be retained for the life of the process."""
+ limiter: Final = RouterBudgetLimiting(
+ dual_cache=DualCache(),
+ provider_budget_config={"openai": {"budget_limit": 10.0, "time_period": "1d"}},
)
- assert await provider_budget.dual_cache.async_get_cache("provider_spend:openai:1d") == 1.5
- assert provider_budget.redis_increment_operation_queue == [
- {
- "key": "provider_spend:openai:1d",
- "increment_value": 0.5,
- "ttl": 86400,
- }
- ]
+ for _ in range(3):
+ await _log_success(limiter, _success_kwargs(provider_in_litellm_params="openai", provider_in_payload="openai"))
+
+ assert await limiter.dual_cache.async_get_cache("provider_spend:openai:1d") == pytest.approx(0.75)
+ assert limiter.redis_increment_operation_queue == []
@pytest.mark.asyncio