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]

avoid stale local spend counters after redis misses

user15d845c3211c
diff --git a/litellm/proxy/db/spend_counter_reseed.py b/litellm/proxy/db/spend_counter_reseed.py
index d4acb39062c..b3c9f4e7c35 100644
--- a/litellm/proxy/db/spend_counter_reseed.py
+++ b/litellm/proxy/db/spend_counter_reseed.py
@@ -183,7 +183,7 @@ class SpendCounterReseed:
return None
# Warm even when 0 so subsequent reads hit cache, not DB.
try:
- if require_cache_warm and spend_counter_cache.redis_cache is not None:
+ if spend_counter_cache.redis_cache is not None:
current_value = (
await spend_counter_cache.redis_cache.async_increment(
key=counter_key,
@@ -273,6 +273,7 @@ class SpendCounterReseed:
) -> Optional[float]:
lock = await SpendCounterReseed._get_lock(counter_key)
async with lock:
+ redis_clean_miss = False
if spend_counter_cache.redis_cache is not None:
try:
val = await spend_counter_cache.redis_cache.async_get_cache(
@@ -280,11 +281,13 @@ class SpendCounterReseed:
)
if val is not None:
return float(val)
+ redis_clean_miss = True
except Exception:
pass
- val = spend_counter_cache.in_memory_cache.get_cache(key=counter_key)
- if val is not None:
- return float(val)
+ if not redis_clean_miss:
+ val = spend_counter_cache.in_memory_cache.get_cache(key=counter_key)
+ if val is not None:
+ return float(val)
window_spend = await SpendCounterReseed.window_from_spend_logs(
prisma_client=prisma_client,
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 889f85c40af..e67702a7976 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -2102,8 +2102,8 @@ async def _ensure_spend_counter_initialized(
counter_key: str,
source_cache_key: str,
):
- current = await spend_counter_cache.async_get_cache(key=counter_key)
- if current is None:
+ is_warm = await _is_spend_counter_cache_warm(counter_key=counter_key)
+ if is_warm is False:
# Shares the per-counter lock with get_current_spend.
db_spend = await SpendCounterReseed.coalesced(
prisma_client=prisma_client,
@@ -2132,8 +2132,8 @@ async def _ensure_window_spend_counter_initialized(
entity_id: str,
window_start: datetime,
):
- current = await spend_counter_cache.async_get_cache(key=counter_key)
- if current is None:
+ is_warm = await _is_spend_counter_cache_warm(counter_key=counter_key)
+ if is_warm is False:
window_spend = await SpendCounterReseed.coalesced_window(
prisma_client=prisma_client,
spend_counter_cache=spend_counter_cache,
@@ -2146,6 +2146,29 @@ async def _ensure_window_spend_counter_initialized(
await _increment_spend_counter_cache(counter_key=counter_key, increment=0.0)
+async def _is_spend_counter_cache_warm(counter_key: str) -> bool:
+ if spend_counter_cache.redis_cache is not None:
+ try:
+ current_value = await spend_counter_cache.redis_cache.async_get_cache(
+ key=counter_key,
+ )
+ if current_value is None:
+ return False
+ spend_counter_cache.in_memory_cache.set_cache(
+ key=counter_key,
+ value=current_value,
+ )
+ return True
+ except Exception as e:
+ verbose_proxy_logger.debug(
+ "Unable to read Redis spend counter %s before initialization, falling back to in-memory: %s",
+ counter_key,
+ e,
+ )
+
+ return spend_counter_cache.in_memory_cache.get_cache(key=counter_key) is not None
+
+
async def _increment_spend_counter_cache(counter_key: str, increment: float):
if spend_counter_cache.redis_cache is not None:
try:
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index 36a5895dbe7..9dfa6bc1936 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -5212,6 +5212,118 @@ async def test_window_spend_counter_reseeds_from_spend_logs_on_counter_miss():
ps.prisma_client = orig_prisma
+async def test_init_spend_counter_redis_clean_miss_skips_stale_in_memory():
+ from litellm.caching.dual_cache import DualCache
+ from litellm.proxy.proxy_server import _init_and_increment_spend_counter
+
+ counter_cache = DualCache()
+ counter_key = "spend:team:team-stale-local"
+ counter_cache.in_memory_cache.set_cache(key=counter_key, value=10.0)
+
+ redis_store: dict = {}
+
+ async def redis_increment(key, value, **_):
+ redis_store[key] = (redis_store.get(key) or 0.0) + value
+ return redis_store[key]
+
+ fake_redis = AsyncMock()
+ fake_redis.async_get_cache = AsyncMock(return_value=None)
+ fake_redis.async_increment = AsyncMock(side_effect=redis_increment)
+ counter_cache.redis_cache = fake_redis
+
+ db_row = MagicMock()
+ db_row.spend = 42.0
+ fake_prisma = MagicMock()
+ fake_prisma.db.litellm_teamtable.find_unique = AsyncMock(return_value=db_row)
+
+ import litellm.proxy.proxy_server as ps
+
+ orig_counter, orig_prisma, orig_user = (
+ ps.spend_counter_cache,
+ ps.prisma_client,
+ ps.user_api_key_cache,
+ )
+ ps.spend_counter_cache = counter_cache
+ ps.prisma_client = fake_prisma
+ ps.user_api_key_cache = DualCache()
+ try:
+ await _init_and_increment_spend_counter(
+ counter_key=counter_key,
+ source_cache_key="team_id:team-stale-local",
+ increment=1.5,
+ )
+
+ fake_prisma.db.litellm_teamtable.find_unique.assert_awaited_once_with(
+ where={"team_id": "team-stale-local"}
+ )
+ assert redis_store[counter_key] == pytest.approx(43.5)
+ assert counter_cache.in_memory_cache.get_cache(
+ key=counter_key
+ ) == pytest.approx(43.5)
+ finally:
+ ps.spend_counter_cache = orig_counter
+ ps.prisma_client = orig_prisma
+ ps.user_api_key_cache = orig_user
+
+
+async def test_window_spend_counter_redis_clean_miss_skips_stale_in_memory():
+ from litellm.caching.dual_cache import DualCache
+ from litellm.proxy.proxy_server import _init_and_increment_window_spend_counter
+
+ counter_cache = DualCache()
+ counter_key = "spend:key:key-window-stale-local:window:1h"
+ counter_cache.in_memory_cache.set_cache(key=counter_key, value=100.0)
+ window_start = datetime.now(timezone.utc) - timedelta(hours=1)
+
+ redis_store: dict = {}
+
+ async def redis_increment(key, value, **_):
+ redis_store[key] = (redis_store.get(key) or 0.0) + value
+ return redis_store[key]
+
+ fake_redis = AsyncMock()
+ fake_redis.async_get_cache = AsyncMock(return_value=None)
+ fake_redis.async_increment = AsyncMock(side_effect=redis_increment)
+ counter_cache.redis_cache = fake_redis
+
+ fake_prisma = MagicMock()
+ fake_prisma.db.litellm_spendlogs.group_by = AsyncMock(
+ return_value=[{"api_key": "key-window-stale-local", "_sum": {"spend": 2.25}}]
+ )
+
+ import litellm.proxy.proxy_server as ps
+
+ orig_counter, orig_prisma = ps.spend_counter_cache, ps.prisma_client
+ ps.spend_counter_cache = counter_cache
+ ps.prisma_client = fake_prisma
+ try:
+ await _init_and_increment_window_spend_counter(
+ counter_key=counter_key,
+ entity_type="Key",
+ entity_id="key-window-stale-local",
+ window_start=window_start,
+ increment=0.5,
+ )
+
+ fake_prisma.db.litellm_spendlogs.group_by.assert_awaited_once_with(
+ by=["api_key"],
+ where={
+ "api_key": "key-window-stale-local",
+ "startTime": {"gte": window_start},
+ },
+ sum={"spend": True},
+ )
+ assert redis_store[counter_key] == pytest.approx(2.75)
+ assert counter_cache.in_memory_cache.get_cache(
+ key=counter_key
+ ) == pytest.approx(2.75)
+ finally:
+ ps.spend_counter_cache = orig_counter
+ ps.prisma_client = orig_prisma
+
+
@pytest.mark.asyncio
async def test_increment_spend_counter_invalidates_stale_cache_on_redis_failure():
from litellm.caching.dual_cache import DualCache
@@ -5293,6 +5405,9 @@ async def test_get_current_spend_reseeds_from_db_when_counter_missing():
assert ("spend:team_member:user-1:team-1", 362.0) in [
(w["key"], w["value"]) for w in recorded_warms
]
+ assert counter_cache.in_memory_cache.get_cache(
+ key="spend:team_member:user-1:team-1"
+ ) == pytest.approx(362.0)
finally:
ps.spend_counter_cache = orig_counter
ps.prisma_client = orig_prisma