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]

refactor(proxy): replace DualCache with UserApiKeyCache for user API key management

harish-berri3c2c61e1e4c1
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 3cce911cd0c..8bd8eb794e0 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -68,6 +68,7 @@ from litellm.proxy.guardrails.tool_name_extraction import (
extract_request_tool_names,
)
from litellm.proxy.common_utils.cache_pydantic_utils import CacheCodec
+from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.proxy.route_llm_request import route_request
from litellm.proxy.utils import PrismaClient, ProxyLogging, log_db_metrics
from litellm.router import Router
@@ -854,7 +855,7 @@ def get_actual_routes(allowed_routes: list) -> list:
async def get_default_end_user_budget(
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
) -> Optional[LiteLLM_BudgetTable]:
"""
@@ -877,11 +878,12 @@ async def get_default_end_user_budget(
cache_key = f"default_end_user_budget:{litellm.max_end_user_budget_id}"
# Check cache first
- cached_budget = await user_api_key_cache.async_get_cache(key=cache_key)
+ cached_budget = await user_api_key_cache.async_get_cache(
+ key=cache_key,
+ model_type=LiteLLM_BudgetTable,
+ )
if cached_budget is not None:
- deserialized = CacheCodec.deserialize(cached_budget, LiteLLM_BudgetTable)
- if deserialized is not None:
- return deserialized
+ return cached_budget
# Fetch from database
try:
@@ -899,7 +901,8 @@ async def get_default_end_user_budget(
# Cache the budget for 60 seconds
await user_api_key_cache.async_set_cache(
key=cache_key,
- value=CacheCodec.serialize(_budget_obj, model_type=LiteLLM_BudgetTable),
+ value=_budget_obj,
+ model_type=LiteLLM_BudgetTable,
ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,
)
@@ -914,7 +917,7 @@ async def get_default_end_user_budget(
async def get_team_member_default_budget(
budget_id: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
) -> Optional[LiteLLM_BudgetTable]:
"""
Fetches the team-level default per-member budget referenced by team.metadata["team_member_budget_id"].
@@ -970,7 +973,7 @@ async def get_team_member_default_budget(
async def _apply_default_budget_to_end_user(
end_user_obj: LiteLLM_EndUserTable,
prisma_client: PrismaClient,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
) -> LiteLLM_EndUserTable:
"""
@@ -1043,7 +1046,7 @@ def _check_end_user_budget(
async def get_end_user_object(
end_user_id: Optional[str],
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
route: str,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
@@ -1074,22 +1077,24 @@ async def get_end_user_object(
_key = "end_user_id:{}".format(end_user_id)
# Check cache first
- cached_user_obj = await user_api_key_cache.async_get_cache(key=_key)
+ cached_user_obj = await user_api_key_cache.async_get_cache(
+ key=_key,
+ model_type=LiteLLM_EndUserTable,
+ )
if cached_user_obj is not None:
- return_obj = CacheCodec.deserialize(cached_user_obj, LiteLLM_EndUserTable)
- if return_obj is not None:
- # Apply default budget if needed
- return_obj = await _apply_default_budget_to_end_user(
- end_user_obj=return_obj,
- prisma_client=prisma_client,
- user_api_key_cache=user_api_key_cache,
- parent_otel_span=parent_otel_span,
- )
+ return_obj = cached_user_obj
+ # Apply default budget if needed
+ return_obj = await _apply_default_budget_to_end_user(
+ end_user_obj=return_obj,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=parent_otel_span,
+ )
- # Check budget limits
- _check_end_user_budget(end_user_obj=return_obj, route=route)
+ # Check budget limits
+ _check_end_user_budget(end_user_obj=return_obj, route=route)
- return return_obj
+ return return_obj
# Fetch from database
try:
@@ -1115,7 +1120,8 @@ async def get_end_user_object(
# Save to cache
await user_api_key_cache.async_set_cache(
key="end_user_id:{}".format(end_user_id),
- value=CacheCodec.serialize(_response, model_type=LiteLLM_EndUserTable),
+ value=_response,
+ model_type=LiteLLM_EndUserTable,
)
# Check budget limits
@@ -1133,7 +1139,7 @@ async def get_end_user_object(
async def get_tag_objects_batch(
tag_names: List[str],
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> Dict[str, LiteLLM_TagTable]:
@@ -1166,13 +1172,12 @@ async def get_tag_objects_batch(
# Try to get all tags from cache first
for tag_name in tag_names:
cache_key = f"tag:{tag_name}"
- cached_tag = await user_api_key_cache.async_get_cache(key=cache_key)
+ cached_tag = await user_api_key_cache.async_get_cache(
+ key=cache_key,
+ model_type=LiteLLM_TagTable,
+ )
if cached_tag is not None:
- deserialized_tag = CacheCodec.deserialize(cached_tag, LiteLLM_TagTable)
- if deserialized_tag is not None:
- tag_objects[tag_name] = deserialized_tag
- else:
- uncached_tags.append(tag_name)
+ tag_objects[tag_name] = cached_tag
else:
uncached_tags.append(tag_name)
@@ -1191,7 +1196,8 @@ async def get_tag_objects_batch(
_tag_obj = LiteLLM_TagTable(**db_tag.dict())
await user_api_key_cache.async_set_cache(
key=cache_key,
- value=CacheCodec.serialize(_tag_obj, model_type=LiteLLM_TagTable),
+ value=_tag_obj,
+ model_type=LiteLLM_TagTable,
)
tag_objects[tag_name] = _tag_obj
except Exception as e:
@@ -1204,7 +1210,7 @@ async def get_tag_objects_batch(
async def get_tag_object(
tag_name: Optional[str],
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> Optional[LiteLLM_TagTable]:
@@ -1243,7 +1249,7 @@ async def get_team_membership(
user_id: str,
team_id: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> Optional["LiteLLM_TeamMembership"]:
@@ -1263,13 +1269,12 @@ async def get_team_membership(
_key = "team_membership:{}:{}".format(user_id, team_id)
# check if in cache
- cached_membership_obj = await user_api_key_cache.async_get_cache(key=_key)
+ cached_membership_obj = await user_api_key_cache.async_get_cache(
+ key=_key,
+ model_type=LiteLLM_TeamMembership,
+ )
if cached_membership_obj is not None:
- deserialized_membership = CacheCodec.deserialize(
- cached_membership_obj, LiteLLM_TeamMembership
- )
- if deserialized_membership is not None:
- return deserialized_membership
+ return cached_membership_obj
# else, check db
try:
@@ -1284,7 +1289,8 @@ async def get_team_membership(
_response = LiteLLM_TeamMembership(**response.dict())
await user_api_key_cache.async_set_cache(
key=_key,
- value=CacheCodec.serialize(_response, model_type=LiteLLM_TeamMembership),
+ value=_response,
+ model_type=LiteLLM_TeamMembership,
)
return _response
@@ -1453,7 +1459,7 @@ async def _get_fuzzy_user_object(
async def get_user_object(
user_id: Optional[str],
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
user_id_upsert: bool,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
@@ -1472,13 +1478,12 @@ async def get_user_object(
# check if in cache
if not check_db_only:
- cached_user_obj = await user_api_key_cache.async_get_cache(key=user_id)
+ cached_user_obj = await user_api_key_cache.async_get_cache(
+ key=user_id,
+ model_type=LiteLLM_UserTable,
+ )
if cached_user_obj is not None:
- deserialized_user = CacheCodec.deserialize(
- cached_user_obj, LiteLLM_UserTable
- )
- if deserialized_user is not None:
- return deserialized_user
+ return cached_user_obj
# else, check db
if prisma_client is None:
raise Exception("No db connected")
@@ -1540,7 +1545,8 @@ async def get_user_object(
# save the user object to cache
await user_api_key_cache.async_set_cache(
key=user_id,
- value=CacheCodec.serialize(_response, model_type=LiteLLM_UserTable),
+ value=_response,
+ model_type=LiteLLM_UserTable,
ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,
)
@@ -1562,22 +1568,20 @@ async def get_user_object(
async def _cache_management_object(
key: str,
value: Union[BaseModel, Dict[str, Any]],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: Optional[ProxyLogging],
*,
model_type: Type[BaseModel],
):
"""
- Persist management objects to DualCache (in-memory + optional Redis).
+ Persist management objects via ``UserApiKeyCache`` (in-memory + optional Redis).
- Values must be JSON-serializable for the Redis path (``json.dumps``). Payloads are
- encoded with ``CacheCodec.serialize(..., model_type=...)`` so writes match reads
- via ``CacheCodec.deserialize(..., model_type)``.
+ ``UserApiKeyCache`` serializes with ``model_type`` so Redis and in-memory stay aligned.
"""
- cache_payload = CacheCodec.serialize(value, model_type=model_type)
await user_api_key_cache.async_set_cache(
key=key,
- value=cache_payload,
+ value=value,
+ model_type=model_type,
ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,
)
@@ -1585,7 +1589,7 @@ async def _cache_management_object(
async def _cache_team_object(
team_id: str,
team_table: LiteLLM_TeamTableCachedObj,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: Optional[ProxyLogging],
):
key = "team_id:{}".format(team_id)
@@ -1605,7 +1609,7 @@ async def _cache_team_object(
async def _cache_key_object(
hashed_token: str,
user_api_key_obj: UserAPIKeyAuth,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: Optional[ProxyLogging],
):
key = hashed_token
@@ -1624,7 +1628,7 @@ async def _cache_key_object(
async def _delete_cache_key_object(
hashed_token: str,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: Optional[ProxyLogging],
):
key = hashed_token
@@ -1672,7 +1676,7 @@ async def _get_team_object_from_db(team_id: str, prisma_client: PrismaClient):
async def _get_team_object_from_user_api_key_cache(
team_id: str,
prisma_client: PrismaClient,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
last_db_access_time: LimitedSizeOrderedDict,
db_cache_expiry: int,
proxy_logging_obj: Optional[ProxyLogging],
@@ -1733,35 +1737,38 @@ async def _get_team_object_from_user_api_key_cache(
async def _get_team_object_from_cache(
key: str,
proxy_logging_obj: Optional[ProxyLogging],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span],
) -> Optional[LiteLLM_TeamTableCachedObj]:
- cached_team_obj: Optional[LiteLLM_TeamTableCachedObj] = None
-
- ## CHECK REDIS CACHE ##
+ ## INTERNAL USAGE CACHE (plain DualCache) — checked before UserApiKeyCache stores ##
if (
proxy_logging_obj is not None
and proxy_logging_obj.internal_usage_cache.dual_cache
):
- cached_team_obj = (
+ cached_raw = (
await proxy_logging_obj.internal_usage_cache.dual_cache.async_get_cache(
key=key, parent_otel_span=parent_otel_span
)
)
+ if cached_raw is not None:
+ from_internal = CacheCodec.deserialize(
+ cached_raw, LiteLLM_TeamTableCachedObj
+ )
+ if from_internal is not None:
+ return from_internal
- if cached_team_obj is None:
- cached_team_obj = await user_api_key_cache.async_get_cache(key=key)
-
- if cached_team_obj is None:
- return None
-
- return CacheCodec.deserialize(cached_team_obj, LiteLLM_TeamTableCachedObj)
+ decoded = await user_api_key_cache.async_get_cache(
+ key=key,
+ parent_otel_span=parent_otel_span,
+ model_type=LiteLLM_TeamTableCachedObj,
+ )
+ return decoded
async def get_team_object(
team_id: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
check_cache_only: Optional[bool] = None,
@@ -1827,23 +1834,21 @@ async def get_team_object(
async def _cache_access_object(
access_group_id: str,
access_group_table: LiteLLM_AccessGroupTable,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: Optional[ProxyLogging] = None,
):
key = "access_group_id:{}".format(access_group_id)
- cache_payload = CacheCodec.serialize(
- access_group_table, model_type=LiteLLM_AccessGroupTable
- )
await user_api_key_cache.async_set_cache(
key=key,
- value=cache_payload,
+ value=access_group_table,
+ model_type=LiteLLM_AccessGroupTable,
ttl=DEFAULT_ACCESS_GROUP_CACHE_TTL,
)
async def _delete_cache_access_object(
access_group_id: str,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: Optional[ProxyLogging] = None,
):
key = "access_group_id:{}".format(access_group_id)
@@ -1861,7 +1866,7 @@ async def _delete_cache_access_object(
async def get_access_object(
access_group_id: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> LiteLLM_AccessGroupTable:
"""
@@ -1883,10 +1888,12 @@ async def get_access_object(
key = "access_group_id:{}".format(access_group_id)
- cached_access_obj = await user_api_key_cache.async_get_cache(key=key)
- deserialized = CacheCodec.deserialize(cached_access_obj, LiteLLM_AccessGroupTable)
- if deserialized is not None:
- return deserialized
+ cached_access_obj = await user_api_key_cache.async_get_cache(
+ key=key,
+ model_type=LiteLLM_AccessGroupTable,
+ )
+ if cached_access_obj is not None:
+ return cached_access_obj
# Not in cache - fetch from DB
try:
@@ -1932,7 +1939,7 @@ async def get_access_object(
async def get_team_object_by_alias(
team_alias: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional["Span"] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> LiteLLM_TeamTableCachedObj:
@@ -2011,19 +2018,18 @@ async def get_team_object_by_alias(
)
# Cache the result by both alias and team_id
- _serialized_team = CacheCodec.serialize(
- team_obj, model_type=LiteLLM_TeamTableCachedObj
- )
await user_api_key_cache.async_set_cache(
key=cache_key,
- value=_serialized_team,
+ value=team_obj,
+ model_type=LiteLLM_TeamTableCachedObj,
ttl=DEFAULT_IN_MEMORY_TTL,
)
# Also cache by team_id for consistency
team_id_cache_key = "team_id:{}".format(team_obj.team_id)
await user_api_key_cache.async_set_cache(
key=team_id_cache_key,
- value=_serialized_team,
+ value=team_obj,
+ model_type=LiteLLM_TeamTableCachedObj,
ttl=DEFAULT_IN_MEMORY_TTL,
)
@@ -2045,7 +2051,7 @@ async def get_team_object_by_alias(
async def get_org_object_by_alias(
org_alias: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional["Span"] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> Optional[LiteLLM_OrganizationTable]:
@@ -2072,13 +2078,12 @@ async def get_org_object_by_alias(
# Check cache first (keyed by alias)
cache_key = "org_alias:{}".format(org_alias)
- cached_org_obj = await user_api_key_cache.async_get_cache(key=cache_key)
+ cached_org_obj = await user_api_key_cache.async_get_cache(
+ key=cache_key,
+ model_type=LiteLLM_OrganizationTable,
+ )
if cached_org_obj is not None:
- deserialized_org = CacheCodec.deserialize(
- cached_org_obj, LiteLLM_OrganizationTable
- )
- if deserialized_org is not None:
- return deserialized_org
+ return cached_org_obj
# Query database by organization_alias
try:
@@ -2105,19 +2110,18 @@ async def get_org_object_by_alias(
org = orgs[0]
org_obj = LiteLLM_OrganizationTable(**org.model_dump())
- _serialized_org = CacheCodec.serialize(
- org_obj, model_type=LiteLLM_OrganizationTable
- )
# Cache the result
await user_api_key_cache.async_set_cache(
key=cache_key,
- value=_serialized_org,
+ value=org_obj,
+ model_type=LiteLLM_OrganizationTable,
ttl=DEFAULT_IN_MEMORY_TTL,
)
# Also cache by org_id for consistency
await user_api_key_cache.async_set_cache(
key="org_id:{}".format(org_obj.organization_id),
- value=_serialized_org,
+ value=org_obj,
+ model_type=LiteLLM_OrganizationTable,
ttl=DEFAULT_IN_MEMORY_TTL,
)
@@ -2321,7 +2325,7 @@ async def get_jwt_key_mapping_object(
async def get_key_object(
hashed_token: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
check_cache_only: Optional[bool] = None,
@@ -2341,11 +2345,12 @@ async def get_key_object(
# Same flow as before: use cache only when we have a hit we can turn into UserAPIKeyAuth
# (dict from Redis / model_dump, or UserAPIKeyAuth from in-memory). Otherwise fall through to DB.
- cached_key_obj = await user_api_key_cache.async_get_cache(key=key)
- if cached_key_obj is not None:
- user_api_key_auth = CacheCodec.deserialize(cached_key_obj, UserAPIKeyAuth)
- if user_api_key_auth is not None:
- return user_api_key_auth
+ user_api_key_auth = await user_api_key_cache.async_get_cache(
+ key=key,
+ model_type=UserAPIKeyAuth,
+ )
+ if user_api_key_auth is not None:
+ return user_api_key_auth
if check_cache_only:
raise Exception(
@@ -2402,7 +2407,7 @@ async def get_key_object(
async def get_object_permission(
object_permission_id: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> Optional[LiteLLM_ObjectPermissionTable]:
@@ -2418,13 +2423,12 @@ async def get_object_permission(
# check if in cache
key = "object_permission_id:{}".format(object_permission_id)
- cached_obj_permission = await user_api_key_cache.async_get_cache(key=key)
- if cached_obj_permission is not None:
- deserialized_perm = CacheCodec.deserialize(
- cached_obj_permission, LiteLLM_ObjectPermissionTable
- )
- if deserialized_perm is not None:
- return deserialized_perm
+ deserialized_perm = await user_api_key_cache.async_get_cache(
+ key=key,
+ model_type=LiteLLM_ObjectPermissionTable,
+ )
+ if deserialized_perm is not None:
+ return deserialized_perm
# else, check db
try:
@@ -2438,9 +2442,8 @@ async def get_object_permission(
_perm_obj = LiteLLM_ObjectPermissionTable(**response.dict())
await user_api_key_cache.async_set_cache(
key=key,
- value=CacheCodec.serialize(
- _perm_obj, model_type=LiteLLM_ObjectPermissionTable
- ),
+ value=_perm_obj,
+ model_type=LiteLLM_ObjectPermissionTable,
ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,
)
@@ -2453,7 +2456,7 @@ async def get_object_permission(
async def get_managed_vector_store_rows_by_uuids(
uuids: List[str],
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> List[LiteLLM_ManagedVectorStoresTable]:
@@ -2473,15 +2476,12 @@ async def get_managed_vector_store_rows_by_uuids(
for uuid in uuids:
key = "managed_vector_store_id:{}".format(uuid)
- cached = await user_api_key_cache.async_get_cache(key=key)
- if cached is not None:
- deserialized_vs = CacheCodec.deserialize(
- cached, LiteLLM_ManagedVectorStoresTable
- )
- if deserialized_vs is not None:
- result.append(deserialized_vs)
- else:
- cache_misses.append(uuid)
+ deserialized_vs = await user_api_key_cache.async_get_cache(
+ key=key,
+ model_type=LiteLLM_ManagedVectorStoresTable,
+ )
+ if deserialized_vs is not None:
+ result.append(deserialized_vs)
else:
cache_misses.append(uuid)
@@ -2507,9 +2507,8 @@ async def get_managed_vector_store_rows_by_uuids(
key = "managed_vector_store_id:{}".format(cached_obj.vector_store_id)
await user_api_key_cache.async_set_cache(
key=key,
- value=CacheCodec.serialize(
- cached_obj, model_type=LiteLLM_ManagedVectorStoresTable
- ),
+ value=cached_obj,
+ model_type=LiteLLM_ManagedVectorStoresTable,
ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,
)
result.append(cached_obj)
@@ -2521,7 +2520,7 @@ async def get_managed_vector_store_rows_by_uuids(
async def get_org_object(
org_id: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
include_budget_table: bool = False,
@@ -2552,13 +2551,12 @@ async def get_org_object(
cache_key = "org_id:{}:with_budget".format(org_id)
# check if in cache
- cached_org_obj = await user_api_key_cache.async_get_cache(key=cache_key)
- if cached_org_obj is not None:
- deserialized_org = CacheCodec.deserialize(
- cached_org_obj, LiteLLM_OrganizationTable
- )
- if deserialized_org is not None:
- return deserialized_org
+ deserialized_org = await user_api_key_cache.async_get_cache(
+ key=cache_key,
+ model_type=LiteLLM_OrganizationTable,
+ )
+ if deserialized_org is not None:
+ return deserialized_org
# else, check db
try:
query_kwargs: Dict[str, Any] = {"where": {"organization_id": org_id}}
@@ -2576,7 +2574,8 @@ async def get_org_object(
# Cache the result
await user_api_key_cache.async_set_cache(
key=cache_key,
- value=CacheCodec.serialize(_org_obj, model_type=LiteLLM_OrganizationTable),
+ value=_org_obj,
+ model_type=LiteLLM_OrganizationTable,
ttl=DEFAULT_IN_MEMORY_TTL,
)
@@ -2593,7 +2592,7 @@ async def _get_resources_from_access_groups(
"access_model_names", "access_mcp_server_ids", "access_agent_ids"
],
prisma_client: Optional[PrismaClient] = None,
- user_api_key_cache: Optional[DualCache] = None,
+ user_api_key_cache: Optional[UserApiKeyCache] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> List[str]:
"""
@@ -2651,7 +2650,7 @@ async def _get_resources_from_access_groups(
async def _get_models_from_access_groups(
access_group_ids: List[str],
prisma_client: Optional[PrismaClient] = None,
- user_api_key_cache: Optional[DualCache] = None,
+ user_api_key_cache: Optional[UserApiKeyCache] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> List[str]:
"""
@@ -2670,7 +2669,7 @@ async def _get_models_from_access_groups(
async def _get_mcp_server_ids_from_access_groups(
access_group_ids: List[str],
prisma_client: Optional[PrismaClient] = None,
- user_api_key_cache: Optional[DualCache] = None,
+ user_api_key_cache: Optional[UserApiKeyCache] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> List[str]:
"""
@@ -2689,7 +2688,7 @@ async def _get_mcp_server_ids_from_access_groups(
async def _get_agent_ids_from_access_groups(
access_group_ids: List[str],
prisma_client: Optional[PrismaClient] = None,
- user_api_key_cache: Optional[DualCache] = None,
+ user_api_key_cache: Optional[UserApiKeyCache] = None,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> List[str]:
"""
@@ -3303,7 +3302,7 @@ async def _check_team_member_budget(
user_object: Optional[LiteLLM_UserTable],
valid_token: Optional[UserAPIKeyAuth],
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging,
):
"""Check if team member is over their max budget within the team."""
@@ -3370,7 +3369,7 @@ async def _check_team_member_model_access(
valid_token: UserAPIKeyAuth,
llm_router: Optional[Router],
prisma_client: Optional["PrismaClient"],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging,
) -> None:
"""
@@ -3677,7 +3676,7 @@ async def _project_soft_budget_check(
async def get_project_object(
project_id: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: Optional[ProxyLogging] = None,
) -> Optional[LiteLLM_ProjectTableCachedObj]:
"""
@@ -3692,13 +3691,12 @@ async def get_project_object(
# Check cache first
cache_key = "project_id:{}".format(project_id)
- cached_obj = await user_api_key_cache.async_get_cache(key=cache_key)
- if cached_obj is not None:
- deserialized_project = CacheCodec.deserialize(
- cached_obj, LiteLLM_ProjectTableCachedObj
- )
- if deserialized_project is not None:
- return deserialized_project
+ deserialized_project = await user_api_key_cache.async_get_cache(
+ key=cache_key,
+ model_type=LiteLLM_ProjectTableCachedObj,
+ )
+ if deserialized_project is not None:
+ return deserialized_project
# Fetch from DB
project_row = await prisma_client.db.litellm_projecttable.find_unique(
@@ -3727,7 +3725,7 @@ async def _organization_max_budget_check(
valid_token: Optional[UserAPIKeyAuth],
team_object: Optional[LiteLLM_TeamTable],
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging,
):
"""
@@ -3821,7 +3819,7 @@ async def _organization_max_budget_check(
async def _tag_max_budget_check(
request_body: dict,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging,
valid_token: Optional[UserAPIKeyAuth],
):
diff --git a/litellm/proxy/auth/handle_jwt.py b/litellm/proxy/auth/handle_jwt.py
index fb86485ffad..9e7c0abd983 100644
--- a/litellm/proxy/auth/handle_jwt.py
+++ b/litellm/proxy/auth/handle_jwt.py
@@ -20,7 +20,6 @@ import jwt
from jwt.api_jwk import PyJWK
from litellm._logging import verbose_proxy_logger
-from litellm.caching.caching import DualCache
from litellm.constants import DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL
from litellm.litellm_core_utils.dot_notation_indexing import get_nested_value
from litellm.llms.custom_httpx.httpx_handler import HTTPHandler
@@ -46,7 +45,7 @@ from litellm.proxy._types import (
)
from litellm.proxy.auth.auth_checks import can_team_access_model
from litellm.proxy.auth.route_checks import RouteChecks
-from litellm.proxy.common_utils.cache_pydantic_utils import CacheCodec
+from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.proxy.utils import PrismaClient, ProxyLogging
from .auth_checks import (
@@ -74,7 +73,7 @@ class JWTHandler:
"""
prisma_client: Optional[PrismaClient]
- user_api_key_cache: DualCache
+ user_api_key_cache: UserApiKeyCache
# Supported algos: https://pyjwt.readthedocs.io/en/stable/algorithms.html
# "Warning: Make sure not to mix symmetric and asymmetric algorithms that interpret
# the key in different ways (e.g. HS* and RS*)."
@@ -100,7 +99,7 @@ class JWTHandler:
def update_environment(
self,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
litellm_jwtauth: LiteLLM_JWTAuth,
leeway: int = 0,
) -> None:
@@ -953,7 +952,7 @@ class JWTAuthManager:
jwt_handler: JWTHandler,
jwt_valid_token: dict,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
) -> Tuple[Optional[str], Optional[LiteLLM_TeamTable]]:
@@ -1046,7 +1045,7 @@ class JWTAuthManager:
route: str,
jwt_handler: JWTHandler,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
) -> Tuple[Optional[str], Optional[LiteLLM_TeamTable]]:
@@ -1134,7 +1133,7 @@ class JWTAuthManager:
valid_user_email: Optional[bool],
jwt_handler: JWTHandler,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
route: str,
@@ -1350,7 +1349,7 @@ class JWTAuthManager:
jwt_valid_token: dict,
user_object: Optional[LiteLLM_UserTable],
prisma_client: Optional[PrismaClient],
- user_api_key_cache: Optional[DualCache] = None,
+ user_api_key_cache: Optional[UserApiKeyCache] = None,
) -> None:
"""
Sync user role and team memberships with JWT claims
@@ -1378,9 +1377,8 @@ class JWTAuthManager:
if user_api_key_cache is not None:
await user_api_key_cache.async_set_cache(
key=user_object.user_id,
- value=CacheCodec.serialize(
- user_object, model_type=LiteLLM_UserTable
- ),
+ value=user_object,
+ model_type=LiteLLM_UserTable,
ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,
)
@@ -1403,9 +1401,8 @@ class JWTAuthManager:
if user_api_key_cache is not None:
await user_api_key_cache.async_set_cache(
key=user_object.user_id,
- value=CacheCodec.serialize(
- user_object, model_type=LiteLLM_UserTable
- ),
+ value=user_object,
+ model_type=LiteLLM_UserTable,
ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,
)
return None
@@ -1417,7 +1414,7 @@ class JWTAuthManager:
request_headers: Optional[dict],
jwt_handler: JWTHandler,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
) -> None:
@@ -1464,7 +1461,7 @@ class JWTAuthManager:
general_settings: dict,
route: str,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
request_headers: Optional[dict] = None,
diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py
index f77fdc47398..30f78a50813 100644
--- a/litellm/proxy/auth/user_api_key_auth.py
+++ b/litellm/proxy/auth/user_api_key_auth.py
@@ -20,7 +20,6 @@ from fastapi.security.api_key import APIKeyHeader
import litellm
from litellm._logging import verbose_logger, verbose_proxy_logger
from litellm._service_logger import ServiceLogging
-from litellm.caching import DualCache
from litellm.litellm_core_utils.dd_tracing import tracer
from litellm.litellm_core_utils.dot_notation_indexing import get_nested_value
from litellm.proxy._types import *
@@ -58,7 +57,7 @@ from litellm.proxy.auth.oauth2_check import Oauth2Handler
from litellm.proxy.auth.oauth2_proxy_hook import handle_oauth2_proxy_request
from litellm.proxy.auth.route_checks import RouteChecks
from litellm.proxy.common_utils.cache_coordinator import EventDrivenCacheCoordinator
-from litellm.proxy.common_utils.cache_pydantic_utils import CacheCodec
+from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.proxy.common_utils.http_parsing_utils import (
_read_request_body,
_safe_get_request_headers,
@@ -328,7 +327,7 @@ _global_spend_coordinator = EventDrivenCacheCoordinator(log_prefix="[GLOBAL SPEN
async def _fetch_global_spend_with_event_coordination(
cache_key: str,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
prisma_client: PrismaClient,
) -> Optional[float]:
"""
@@ -351,7 +350,7 @@ async def _fetch_global_spend_with_event_coordination(
async def get_global_proxy_spend(
litellm_proxy_admin_name: str,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
prisma_client: Optional[PrismaClient],
token: str,
proxy_logging_obj: ProxyLogging,
@@ -504,7 +503,7 @@ async def _resolve_jwt_to_virtual_key(
jwt_claims: dict,
jwt_handler: JWTHandler,
prisma_client: Optional[PrismaClient],
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
) -> Optional[UserAPIKeyAuth]:
@@ -1315,13 +1314,9 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
if prisma_client is not None:
_cache_key = f"{valid_token.team_id}_{valid_token.user_id}"
- _cached_member = await user_api_key_cache.async_get_cache(
- key=_cache_key
- )
- team_member_info: Optional[LiteLLM_TeamMembership] = (
- CacheCodec.deserialize(_cached_member, LiteLLM_TeamMembership)
- if _cached_member is not None
- else None
+ team_member_info = await user_api_key_cache.async_get_cache(
+ key=_cache_key,
+ model_type=LiteLLM_TeamMembership,
)
if team_member_info is None:
# read from DB
@@ -1342,10 +1337,8 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
)
await user_api_key_cache.async_set_cache(
key=_cache_key,
- value=CacheCodec.serialize(
- team_member_info,
- model_type=LiteLLM_TeamMembership,
- ),
+ value=team_member_info,
+ model_type=LiteLLM_TeamMembership,
ttl=5,
)
@@ -1497,9 +1490,8 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
team_cache_key = f"team_id:{valid_token.team_id}"
await user_api_key_cache.async_set_cache(
key=team_cache_key,
- value=CacheCodec.serialize(
- _team_obj, model_type=LiteLLM_TeamTableCachedObj
- ),
+ value=_team_obj,
+ model_type=LiteLLM_TeamTableCachedObj,
) # save team table in cache - used for tpm/rpm limiting - tpm_rpm_limiter.py
# Fetch project object if key belongs to a project
diff --git a/litellm/proxy/common_utils/user_api_key_cache.py b/litellm/proxy/common_utils/user_api_key_cache.py
new file mode 100644
index 00000000000..2eebc291bb0
--- /dev/null
+++ b/litellm/proxy/common_utils/user_api_key_cache.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from typing import Any, Optional, Type, TypeVar, Union, cast, overload
+
+from pydantic import BaseModel
+
+from litellm._logging import verbose_proxy_logger
+from litellm.caching.dual_cache import DualCache
+from litellm.proxy.common_utils.cache_pydantic_utils import CacheCodec
+
+T = TypeVar("T", bound=BaseModel)
+
+
+class UserApiKeyCache(DualCache):
+ """
+ DualCache wrapper for UserAPIKeyAuth-like payloads.
+
+ Stores a Redis-safe JSON payload in BOTH in-memory and Redis to avoid
+ "memory returns BaseModel, Redis returns dict" format drift.
+
+ When ``model_type`` is provided:
+ - writes are serialized via ``CacheCodec.serialize(..., model_type=...)``
+ - reads are deserialized via ``CacheCodec.deserialize(..., model_type)``
+ and return ``Optional[T]``: the model on success, ``None`` on cache miss
+ **or** if the cached payload fails validation (schema drift). On
+ validation failure after a cache hit, an error line is emitted via
+ ``verbose_proxy_logger``.
+
+ When ``model_type`` is omitted, the interface behaves like ``DualCache``:
+ raw cached payload is returned (dict/str/etc.).
+
+ ``async_set_cache_pipeline`` applies the same untyped Codec pass as omitting
+ ``model_type`` on ``async_set_cache`` (so ``BaseModel`` rows are dumped before Redis).
+ """
+
+ # Overloads: `model_type` must be a real parameter (not only via **kwargs) so
+ # the untyped branch cannot match calls that pass `model_type=...`.
+
+ @overload
+ def get_cache(
+ self,
+ key,
+ parent_otel_span=None,
+ local_only: bool = False,
+ ) -> Any: ...
+
+ @overload
+ def get_cache(
+ self,
+ key,
+ parent_otel_span=None,
+ local_only: bool = False,
+ *,
+ model_type: Type[T],
+ ) -> Optional[T]: ...
+
+ def set_cache(self, key, value, local_only: bool = False, **kwargs): # type: ignore[override]
+ model_type = cast(Optional[Type[BaseModel]], kwargs.pop("model_type", None))
+ payload = CacheCodec.serialize(value, model_type=model_type)
+ return super().set_cache(key=key, value=payload, local_only=local_only, **kwargs)
+
+ async def async_set_cache(self, key, value, local_only: bool = False, **kwargs): # type: ignore[override]
+ model_type = cast(Optional[Type[BaseModel]], kwargs.pop("model_type", None))
+ payload = CacheCodec.serialize(value, model_type=model_type)
+ return await super().async_set_cache(
+ key=key, value=payload, local_only=local_only, **kwargs
+ )
+
+ async def async_set_cache_pipeline( # type: ignore[override]
+ self, cache_list: list, local_only: bool = False, **kwargs
+ ) -> None:
+ """
+ Batch writes with the same Codec boundary as ``async_set_cache`` without
+ ``model_type``: ``BaseModel`` values become JSON-safe dicts; dicts/scalars unchanged.
+ """
+ normalized = [
+ (key, CacheCodec.serialize(value, model_type=None))
+ for key, value in cache_list
+ ]
+ return await super().async_set_cache_pipeline(
+ cache_list=normalized, local_only=local_only, **kwargs
+ )
+
+ @overload
+ async def async_get_cache(
+ self,
+ key,
+ parent_otel_span=None,
+ local_only: bool = False,
+ ) -> Any: ...
+
+ @overload
+ async def async_get_cache(
+ self,
+ key,
+ parent_otel_span=None,
+ local_only: bool = False,
+ *,
+ model_type: Type[T],
+ ) -> Optional[T]: ...
+
+ def get_cache( # type: ignore[override]
+ self,
+ key,
+ parent_otel_span=None,
+ local_only: bool = False,
+ model_type: Optional[Type[BaseModel]] = None,
+ **kwargs,
+ ) -> Union[Any, Optional[BaseModel]]:
+ if model_type is None and "model_type" in kwargs:
+ model_type = cast(Optional[Type[BaseModel]], kwargs.pop("model_type", None))
+ cached = super().get_cache(
+ key=key, parent_otel_span=parent_otel_span, local_only=local_only, **kwargs
+ )
+ if model_type is None:
+ return cached
+ if cached is None:
+ return None
+ decoded = CacheCodec.deserialize(cached, model_type=model_type)
+ if decoded is None:
+ verbose_proxy_logger.error(
+ "UserApiKeyCache.get_cache failed to deserialize cached value for "
+ "key=%r model_type=%s",
+ key,
+ getattr(model_type, "__name__", str(model_type)),
+ )
+ return None
+ return decoded
+
+ async def async_get_cache( # type: ignore[override]
+ self,
+ key,
+ parent_otel_span=None,
+ local_only: bool = False,
+ model_type: Optional[Type[BaseModel]] = None,
+ **kwargs,
+ ) -> Union[Any, Optional[BaseModel]]:
+ if model_type is None and "model_type" in kwargs:
+ model_type = cast(Optional[Type[BaseModel]], kwargs.pop("model_type", None))
+ cached = await super().async_get_cache(
+ key=key, parent_otel_span=parent_otel_span, local_only=local_only, **kwargs
+ )
+ if model_type is None:
+ return cached
+ if cached is None:
+ return None
+ decoded = CacheCodec.deserialize(cached, model_type=model_type)
+ if decoded is None:
+ verbose_proxy_logger.error(
+ "UserApiKeyCache.async_get_cache failed to deserialize cached value for "
+ "key=%r model_type=%s",
+ key,
+ getattr(model_type, "__name__", str(model_type)),
+ )
+ return None
+ return decoded
diff --git a/litellm/proxy/management_endpoints/access_group_endpoints.py b/litellm/proxy/management_endpoints/access_group_endpoints.py
index 30fed096232..ceaef20a8d0 100644
--- a/litellm/proxy/management_endpoints/access_group_endpoints.py
+++ b/litellm/proxy/management_endpoints/access_group_endpoints.py
@@ -9,7 +9,6 @@ from litellm.proxy._types import (
LitellmUserRoles,
UserAPIKeyAuth,
)
-from litellm.proxy.common_utils.cache_pydantic_utils import CacheCodec
from litellm.proxy.auth.auth_checks import (
_cache_access_object,
_cache_key_object,
@@ -237,10 +236,10 @@ async def _patch_key_caches_add_access_group(
) -> None:
"""Patch cached key objects to include access_group_id."""
for token in key_tokens:
- raw = await user_api_key_cache.async_get_cache(key=token)
- if raw is None:
- continue
- cached_key = CacheCodec.deserialize(raw, UserAPIKeyAuth)
+ cached_key = await user_api_key_cache.async_get_cache(
+ key=token,
+ model_type=UserAPIKeyAuth,
+ )
if cached_key is None:
continue
if cached_key.access_group_ids is None:
@@ -267,10 +266,10 @@ async def _patch_key_caches_remove_access_group(
) -> None:
"""Patch cached key objects to remove access_group_id."""
for token in key_tokens:
- raw = await user_api_key_cache.async_get_cache(key=token)
- if raw is None:
- continue
- cached_key = CacheCodec.deserialize(raw, UserAPIKeyAuth)
+ cached_key = await user_api_key_cache.async_get_cache(
+ key=token,
+ model_type=UserAPIKeyAuth,
+ )
if cached_key is not None and cached_key.access_group_ids:
cached_key.access_group_ids = [
ag for ag in cached_key.access_group_ids if ag != access_group_id
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 0362c3ff6b2..c00f7269bbd 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -39,7 +39,6 @@ from fastapi.responses import RedirectResponse
import litellm
from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
-from litellm.caching import DualCache
from litellm.constants import (
LITELLM_UI_SESSION_DURATION,
MAX_SPENDLOG_ROWS_TO_QUERY,
@@ -70,7 +69,7 @@ from litellm.proxy._types import (
UserAPIKeyAuth,
)
from litellm.proxy.auth.auth_checks import ExperimentalUIJWTToken, get_user_object
-from litellm.proxy.common_utils.cache_pydantic_utils import CacheCodec
+from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.proxy.auth.auth_utils import _has_user_setup_sso
from litellm.proxy.auth.handle_jwt import JWTHandler
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
@@ -1051,7 +1050,7 @@ async def get_existing_user_info_from_db(
user_id: Optional[str],
user_email: Optional[str],
prisma_client: PrismaClient,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging,
) -> Optional[LiteLLM_UserTable]:
try:
@@ -1075,7 +1074,7 @@ async def get_existing_user_info_from_db(
async def get_user_info_from_db(
result: Union[CustomOpenID, OpenID, dict],
prisma_client: PrismaClient,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging,
user_email: Optional[str],
user_defined_values: Optional[SSOUserDefinedValues],
@@ -1195,7 +1194,7 @@ async def _sync_user_role_from_jwt_role_map(
received_response: Optional[dict],
user_info: Optional[Union[LiteLLM_UserTable, NewUserResponse]],
prisma_client: PrismaClient,
- user_api_key_cache: DualCache,
+ user_api_key_cache: UserApiKeyCache,
user_defined_values: Optional[SSOUserDefinedValues],
) -> None:
"""
@@ -1234,7 +1233,8 @@ async def _sync_user_role_from_jwt_role_map(
user_info.user_role = mapped_role.value
await user_api_key_cache.async_set_cache(
key=user_info.user_id,
- value=CacheCodec.serialize(user_info, model_type=LiteLLM_UserTable),
+ value=user_info,
+ model_type=LiteLLM_UserTable,
)
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 8d199d2c092..865a46a5478 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -209,6 +209,7 @@ from litellm import Router
from litellm._logging import verbose_proxy_logger, verbose_router_logger
from litellm.caching.caching import DualCache, RedisCache
from litellm.caching.redis_cluster_cache import RedisClusterCache
+from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.constants import (
_REALTIME_BODY_CACHE_SIZE,
APSCHEDULER_COALESCE,
@@ -1598,7 +1599,7 @@ prisma_client: Optional[PrismaClient] = None
shared_aiohttp_session: Optional["ClientSession"] = (
None # Global shared session for connection reuse
)
-user_api_key_cache = DualCache(
+user_api_key_cache = UserApiKeyCache(
default_in_memory_ttl=UserAPIKeyCacheTTLEnum.in_memory_cache_ttl.value
)
spend_counter_cache = DualCache(
@@ -2041,19 +2042,13 @@ async def update_cache( # noqa: PLR0915
else:
hashed_token = token
verbose_proxy_logger.debug("_update_key_cache: hashed_token=%s", hashed_token)
- cached_key = await user_api_key_cache.async_get_cache(key=hashed_token)
+ existing_spend_obj = await user_api_key_cache.async_get_cache(
+ key=hashed_token, model_type=UserAPIKeyAuth
+ )
verbose_proxy_logger.debug(
- f"_update_key_cache: existing_spend_obj={cached_key}"
+ f"_update_key_cache: existing_spend_obj={existing_spend_obj}"
)
- if cached_key is None:
- return
- existing_spend_obj = CacheCodec.deserialize(cached_key, UserAPIKeyAuth)
if existing_spend_obj is None:
- verbose_proxy_logger.warning(
- "_update_key_cache: unexpected cached key type %s for hashed_token=%s; skipping spend update",
- type(cached_key).__name__,
- hashed_token,
- )
return
existing_spend = existing_spend_obj.spend or 0.0
@@ -2114,14 +2109,10 @@ async def update_cache( # noqa: PLR0915
existing_team_member_spend + response_cost
)
- # Update the cost column for the given token (dict for Redis pipeline json.dumps)
+ # Existing spend_obj is mutated; UserApiKeyCache.async_set_cache_pipeline turns
+ # BaseModel values into dicts for Redis (same Codec path as async_set_cache).
existing_spend_obj.spend = new_spend
- values_to_update_in_cache.append(
- (
- hashed_token,
- CacheCodec.serialize(existing_spend_obj, model_type=UserAPIKeyAuth),
- )
- )
+ values_to_update_in_cache.append((hashed_token, existing_spend_obj))
### UPDATE USER SPEND ###
async def _update_user_cache():
diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.py
index 8612d243c41..37646373a03 100644
--- a/tests/test_litellm/proxy/auth/test_auth_checks.py
+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py
@@ -922,19 +922,21 @@ async def test_get_tag_objects_batch():
# Simulate 5 tags: 2 cached, 3 uncached
tag_names = ["cached-1", "uncached-1", "cached-2", "uncached-2", "uncached-3"]
- # Mock cached tags
- cached_tag_1 = {
- "tag_name": "cached-1",
- "spend": 10.0,
- "models": [],
- "litellm_budget_table": None,
- }
- cached_tag_2 = {
- "tag_name": "cached-2",
- "spend": 20.0,
- "models": [],
- "litellm_budget_table": None,
- }
+ # Mock cached tags — must be LiteLLM_TagTable instances: the mocked async_get_cache
+ # bypasses UserApiKeyCache deserialization, so returning plain dicts would flow through
+ # as dict (production returns models after Codec.deserialize inside the cache).
+ cached_tag_1 = LiteLLM_TagTable(
+ tag_name="cached-1",
+ spend=10.0,
+ models=[],
+ litellm_budget_table=None,
+ )
+ cached_tag_2 = LiteLLM_TagTable(
+ tag_name="cached-2",
+ spend=20.0,
+ models=[],
+ litellm_budget_table=None,
+ )
# Mock DB response for uncached tags
uncached_tag_1 = MagicMock()
@@ -980,13 +982,13 @@ async def test_get_tag_objects_batch():
)
# Mock cache behavior - return cached tags, None for uncached
- async def mock_get_cache(key):
+ async def mock_get_cache(*args, **kwargs):
+ key = kwargs.get("key")
if key == "tag:cached-1":
return cached_tag_1
- elif key == "tag:cached-2":
+ if key == "tag:cached-2":
return cached_tag_2
- else:
- return None
+ return None
mock_cache.async_get_cache = AsyncMock(side_effect=mock_get_cache)
mock_cache.async_set_cache = AsyncMock()
diff --git a/tests/test_litellm/proxy/common_utils/test_user_api_key_cache.py b/tests/test_litellm/proxy/common_utils/test_user_api_key_cache.py
new file mode 100644
index 00000000000..cff331d9b19
--- /dev/null
+++ b/tests/test_litellm/proxy/common_utils/test_user_api_key_cache.py
@@ -0,0 +1,113 @@
+import json
+from typing import Any
+
+import pytest
+
+from litellm.caching.redis_cache import RedisCache
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+
+class FakeRedisCache(RedisCache):
+ """
+ In-memory fake that enforces the UserApiKeyCache Redis payload contract.
+
+ For user_api_key_cache entries we expect Redis to store a JSON object (dict)
+ produced by `CacheCodec.serialize(..., model_type=...)`.
+
+ This fake:
+ - raises TypeError if the value is not a dict
+ - raises TypeError if the dict is not JSON-serializable
+ """
+
+ def __init__(self): # noqa: super().__init__ skipped intentionally
+ self._store: dict[str, str] = {}
+
+ def set_cache(self, key: str, value: Any, **kwargs): # type: ignore[override]
+ if not isinstance(value, dict):
+ raise TypeError("FakeRedisCache only accepts dict payloads")
+ self._store[key] = json.dumps(value)
+ return True
+
+ def get_cache(self, key: str, **kwargs): # type: ignore[override]
+ raw = self._store.get(key)
+ if raw is None:
+ return None
+ return json.loads(raw)
+
+ async def async_set_cache(self, key: str, value: Any, **kwargs): # type: ignore[override]
+ if not isinstance(value, dict):
+ raise TypeError("FakeRedisCache only accepts dict payloads")
+ self._store[key] = json.dumps(value)
+ return True
+
+ async def async_get_cache(self, key: str, **kwargs): # type: ignore[override]
+ raw = self._store.get(key)
+ if raw is None:
+ return None
+ return json.loads(raw)
+
+ def delete_cache(self, key: str): # type: ignore[override]
+ self._store.pop(key, None)
+
+ async def async_delete_cache(self, key: str): # type: ignore[override]
+ self._store.pop(key, None)
+
+
+def _make_key_obj(token: str = "tok") -> UserAPIKeyAuth:
+ # Minimal object (UserAPIKeyAuth inherits token from base view).
+ return UserAPIKeyAuth(token=token)
+
+
+class TestUserApiKeyCache:
+ @pytest.mark.asyncio
+ async def test_async_set_typed_stores_serialized_payload_in_memory_and_redis(self):
+ cache = UserApiKeyCache(redis_cache=FakeRedisCache())
+ obj = _make_key_obj("abc")
+
+ await cache.async_set_cache("k", obj, model_type=UserAPIKeyAuth)
+
+ # In-memory hit should still be raw dict (not BaseModel) because wrapper
+ # stores the serialized payload into both layers.
+ raw = await cache.in_memory_cache.async_get_cache("k") # type: ignore[union-attr]
+ assert isinstance(raw, dict)
+ assert raw["token"] == "abc"
+
+ # Redis should also hold the same serialized dict
+ redis_raw = await cache.redis_cache.async_get_cache("k") # type: ignore[union-attr]
+ assert redis_raw == raw
+
+ @pytest.mark.asyncio
+ async def test_async_get_typed_returns_model_on_valid_hit(self):
+ cache = UserApiKeyCache(redis_cache=FakeRedisCache())
+ await cache.async_set_cache("k", {"token": "abc"}, model_type=UserAPIKeyAuth)
+
+ value = await cache.async_get_cache("k", model_type=UserAPIKeyAuth)
+ assert value is not None
+ assert isinstance(value, UserAPIKeyAuth)
+ assert value.token == "abc"
+
+ @pytest.mark.asyncio
+ async def test_async_get_typed_returns_none_on_validation_failure_after_hit(self):
+ cache = UserApiKeyCache(redis_cache=FakeRedisCache())
+
+ # Bypass UserApiKeyCache.serialize: CacheCodec rejects non-dict cached values
+ # for dict-based models (deserialize returns None).
+ await cache.in_memory_cache.async_set_cache(
+ key="k", value="invalid-payload-not-a-dict"
+ )
+
+ value = await cache.async_get_cache("k", model_type=UserAPIKeyAuth)
+ assert value is None
+
+ def test_fake_redis_cache_rejects_non_json_serializable_values(self):
+ fake = FakeRedisCache()
+
+ class NotSerializable:
+ pass
+
+ with pytest.raises(TypeError):
+ fake.set_cache("k", NotSerializable())
+
+ with pytest.raises(TypeError):
+ fake.set_cache("k2", {"ok": NotSerializable()})
diff --git a/tests/test_litellm/proxy/test_redis_auth_cache_flag.py b/tests/test_litellm/proxy/test_redis_auth_cache_flag.py
index 261222be9a2..d0cb5ec5465 100644
--- a/tests/test_litellm/proxy/test_redis_auth_cache_flag.py
+++ b/tests/test_litellm/proxy/test_redis_auth_cache_flag.py
@@ -6,6 +6,7 @@ the flag is explicitly set to True, and leaves it in-memory-only otherwise.
"""
from contextlib import contextmanager
+import json
from unittest.mock import MagicMock, patch
import pytest
@@ -29,7 +30,18 @@ class _FakeRedisCache(RedisCache):
"""
def __init__(self): # noqa: super().__init__ skipped intentionally
- pass
+ self._store = {}
+
+ def set_cache(self, key, value, **kwargs): # type: ignore[override]
+ # Enforce Redis JSON-serializable payload contract.
+ self._store[key] = json.dumps(value)
+ return True
+
+ def get_cache(self, key, **kwargs): # type: ignore[override]
+ raw = self._store.get(key)
+ if raw is None:
+ return None
+ return json.loads(raw)
@contextmanager