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]

perf(auth): negative-cache missing user/key lookups on the request hot path (#32368)

Yassin Kortam6f6bd4568118
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index e374068ca35..60fc021a6a8 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -3619,6 +3619,7 @@ class PrometheusLogger(CustomLogger):
hashed_token=user_api_key_dict.token,
prisma_client=prisma_client,
user_api_key_cache=user_api_key_cache,
+ check_cache_only=True,
)
if key_object:
user_api_key_dict.budget_reset_at = key_object.budget_reset_at
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index ee548ba0a43..e7fee8d6eb2 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -1474,7 +1474,7 @@ def _should_check_db(key: str, last_db_access_time: LimitedSizeOrderedDict, db_c
elif last_db_access_time[key][0] is not None: # check db for non-null values (for refresh operations)
return True
elif last_db_access_time[key][0] is None:
- if current_time - last_db_access_time[key] >= db_cache_expiry:
+ if current_time - last_db_access_time[key][1] >= db_cache_expiry:
return True
return False
@@ -1649,6 +1649,12 @@ async def get_user_object(
include={"organization_memberships": True},
)
else:
+ if should_check_db:
+ _update_last_db_access_time(
+ key=db_access_time_key,
+ value=None,
+ last_db_access_time=last_db_access_time,
+ )
raise Exception
if response.organization_memberships is not None and len(response.organization_memberships) > 0:
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 89c1a925eeb..dbf514d2298 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -2134,12 +2134,16 @@ async def cli_poll_key(
models=session_data.get("models", []),
)
- user_db_obj = await get_user_object(
- user_id=user_id,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- user_id_upsert=False,
- )
+ try:
+ user_db_obj = await get_user_object(
+ user_id=user_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ user_id_upsert=False,
+ )
+ except ValueError as e:
+ verbose_proxy_logger.debug(f"CLI poll: user lookup failed, proceeding without user budget: {e}")
+ user_db_obj = None
user_budget = user_db_obj.max_budget if user_db_obj is not None else None
team_budget: Optional[float] = None
diff --git a/tests/test_litellm/integrations/test_prometheus_budget_metrics_db_lookups.py b/tests/test_litellm/integrations/test_prometheus_budget_metrics_db_lookups.py
new file mode 100644
index 00000000000..ce446ae3a19
--- /dev/null
+++ b/tests/test_litellm/integrations/test_prometheus_budget_metrics_db_lookups.py
@@ -0,0 +1,93 @@
+"""
+Unit tests for PrometheusLogger._assemble_key_object DB access.
+
+The post-request budget metrics run for every LLM API request. Auth has
+already cached the key object for any real key in the same request, so the
+metrics path must read the cache only. Falling through to the DB turns every
+request whose token has no DB row (e.g. master-key requests, whose token is
+an alias hash that never matches a stored key) into per-request
+LiteLLM_VerificationToken and LiteLLM_DeprecatedVerificationToken queries.
+"""
+
+import datetime
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from prometheus_client import REGISTRY
+
+from litellm.caching.dual_cache import DualCache
+from litellm.caching.in_memory_cache import InMemoryCache
+from litellm.integrations.prometheus import PrometheusLogger
+from litellm.proxy._types import UserAPIKeyAuth
+
+
[email protected](autouse=True)
+def cleanup_prometheus_registry():
+ collectors = list(REGISTRY._collector_to_names.keys())
+ for collector in collectors:
+ try:
+ REGISTRY.unregister(collector)
+ except Exception:
+ pass
+ yield
+ collectors = list(REGISTRY._collector_to_names.keys())
+ for collector in collectors:
+ try:
+ REGISTRY.unregister(collector)
+ except Exception:
+ pass
+
+
+def prometheus_logger():
+ return PrometheusLogger()
+
+
+async def test_assemble_key_object_does_not_query_db_on_cache_miss(prometheus_logger):
+ mock_prisma = MagicMock()
+ mock_prisma.get_data = AsyncMock()
+ cache = DualCache(in_memory_cache=InMemoryCache())
+
+ with (
+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", cache),
+ ):
+ result = await prometheus_logger._assemble_key_object(
+ user_api_key="hashed-token-not-in-cache",
+ user_api_key_alias="",
+ key_max_budget=None,
+ key_spend=1.0,
+ response_cost=0.5,
+ )
+
+ mock_prisma.get_data.assert_not_called()
+ assert result.spend == 1.5
+ assert result.budget_reset_at is None
+
+
+async def test_assemble_key_object_reads_budget_reset_at_from_cache(prometheus_logger):
+ hashed_token = "hashed-token-in-cache"
+ reset_at = datetime.datetime(2026, 8, 1, tzinfo=datetime.timezone.utc)
+ cached_key = UserAPIKeyAuth(token=hashed_token, budget_reset_at=reset_at)
+
+ mock_prisma = MagicMock()
+ mock_prisma.get_data = AsyncMock()
+ cache = DualCache(in_memory_cache=InMemoryCache())
+ await cache.async_set_cache(key=hashed_token, value=cached_key)
+
+ with (
+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", cache),
+ ):
+ result = await prometheus_logger._assemble_key_object(
+ user_api_key=hashed_token,
+ user_api_key_alias="alias",
+ key_max_budget=10.0,
+ key_spend=1.0,
+ response_cost=0.5,
+ )
+
+ mock_prisma.get_data.assert_not_called()
+ assert result.budget_reset_at == reset_at
diff --git a/tests/test_litellm/proxy/auth/test_auth_hot_path_network_requests.py b/tests/test_litellm/proxy/auth/test_auth_hot_path_network_requests.py
index f1ff001777c..22752f767ce 100644
--- a/tests/test_litellm/proxy/auth/test_auth_hot_path_network_requests.py
+++ b/tests/test_litellm/proxy/auth/test_auth_hot_path_network_requests.py
@@ -516,3 +516,104 @@ async def test_full_hot_path_network_count():
assert (
summary["total_network_requests"] == 4
), f"Expected 4 total network requests on warm path, got {summary['total_network_requests']}"
+
+
+# ============================================================================
+# TEST: negative caching for entities that do not exist in the DB
+# ============================================================================
+
+
+async def test_get_user_object_missing_user_negative_cache():
+ """
+ A user_id with no DB row (e.g. the master key's default admin user_id)
+ must not trigger a DB query on every request. The first lookup hits the
+ DB; repeat lookups inside the db_cache_expiry window are throttled.
+ """
+ user_id = "user-missing-negative-cache"
+
+ cache = DualCache(in_memory_cache=InMemoryCache())
+
+ mock_prisma = MagicMock()
+ mock_prisma.db = MagicMock()
+ mock_prisma.db.litellm_usertable = MagicMock()
+ mock_prisma.db.litellm_usertable.find_unique = AsyncMock(return_value=None)
+
+ for _ in range(3):
+ with pytest.raises(ValueError):
+ await get_user_object(
+ user_id=user_id,
+ prisma_client=mock_prisma,
+ user_api_key_cache=cache,
+ parent_otel_span=None,
+ proxy_logging_obj=None,
+ user_id_upsert=False,
+ )
+
+ assert mock_prisma.db.litellm_usertable.find_unique.call_count == 1
+
+
+async def test_get_user_object_missing_user_rechecks_after_expiry():
+ """
+ The negative cache must expire: a user created after a miss becomes
+ visible once the db_cache_expiry window has passed.
+ """
+ from litellm.proxy.auth.auth_checks import db_cache_expiry, last_db_access_time
+
+ user_id = "user-missing-expiry-recheck"
+
+ cache = DualCache(in_memory_cache=InMemoryCache())
+
+ mock_prisma = MagicMock()
+ mock_prisma.db = MagicMock()
+ mock_prisma.db.litellm_usertable = MagicMock()
+ mock_prisma.db.litellm_usertable.find_unique = AsyncMock(return_value=None)
+
+ with pytest.raises(ValueError):
+ await get_user_object(
+ user_id=user_id,
+ prisma_client=mock_prisma,
+ user_api_key_cache=cache,
+ parent_otel_span=None,
+ proxy_logging_obj=None,
+ user_id_upsert=False,
+ )
+ assert mock_prisma.db.litellm_usertable.find_unique.call_count == 1
+
+ last_db_access_time[f"user_id:{user_id}"] = (
+ None,
+ time.time() - (db_cache_expiry + 1),
+ )
+
+ with pytest.raises(ValueError):
+ await get_user_object(
+ user_id=user_id,
+ prisma_client=mock_prisma,
+ user_api_key_cache=cache,
+ parent_otel_span=None,
+ proxy_logging_obj=None,
+ user_id_upsert=False,
+ )
+ assert mock_prisma.db.litellm_usertable.find_unique.call_count == 2
+
+
+def test_should_check_db_negative_entry_throttles_then_expires():
+ """
+ A recorded miss (value=None) suppresses DB checks inside the expiry
+ window and allows them again after it. Exercises the timestamp element
+ of the stored (value, time) tuple directly.
+ """
+ from litellm.caching.dual_cache import LimitedSizeOrderedDict
+ from litellm.proxy.auth.auth_checks import (
+ _should_check_db,
+ _update_last_db_access_time,
+ )
+
+ tracker: LimitedSizeOrderedDict = LimitedSizeOrderedDict(max_size=10)
+
+ _update_last_db_access_time(key="k", value=None, last_db_access_time=tracker)
+ assert _should_check_db(key="k", last_db_access_time=tracker, db_cache_expiry=5) is False
+
+ tracker["k"] = (None, time.time() - 6)
+ assert _should_check_db(key="k", last_db_access_time=tracker, db_cache_expiry=5) is True
diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
index 976048b9521..32229e3e64e 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
@@ -7131,3 +7131,54 @@ async def test_legacy_login_page_hides_credentials_hint_via_general_settings():
assert response.status_code == 200
assert "Default Credentials" not in body
assert "MASTER_KEY" not in body
+
+
+async def test_cli_poll_key_tolerates_missing_user_row():
+ """The CLI poll must still mint the JWT when the user lookup raises,
+ e.g. the user row was created moments ago and a negative-cache window
+ from the pre-creation SSO existence check is still active on this pod."""
+ from litellm.proxy.management_endpoints.ui_sso import (
+ _hash_cli_sso_secret,
+ cli_poll_key,
+ )
+
+ session_key = "cli-session-missing-user"
+ session_data = {
+ "user_id": "just-created-user",
+ "user_role": "internal_user",
+ "teams": [],
+ "models": ["gpt-4"],
+ }
+
+ mock_cache = MagicMock()
+ mock_cache.get_cache.return_value = {
+ "poll_secret_hash": _hash_cli_sso_secret("poll-secret"),
+ "sso_complete": True,
+ "user_code_verified": True,
+ "session_data": session_data,
+ }
+
+ mock_jwt_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.missing.user"
+
+ with (
+ patch("litellm.proxy.proxy_server.user_api_key_cache", mock_cache),
+ patch("litellm.proxy.proxy_server.prisma_client"),
+ patch(
+ "litellm.proxy.auth.auth_checks.ExperimentalUIJWTToken.get_cli_jwt_auth_token",
+ return_value=mock_jwt_token,
+ ),
+ patch(
+ "litellm.proxy.auth.auth_checks.get_user_object",
+ new=AsyncMock(side_effect=ValueError("User doesn't exist in db. 'user_id'=just-created-user")),
+ ),
+ ):
+ result = await cli_poll_key(
+ key_id=session_key,
+ team_id=None,
+ x_litellm_cli_poll_secret="poll-secret",
+ )
+
+ assert result["status"] == "ready"
+ assert result["key"] == mock_jwt_token
+ assert result["user_id"] == "just-created-user"