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(proxy): broadcast team cache invalidation on team writes (#46113)

mrinal-berri93b29c397717
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index 6a4c8ac2c9e..9cc1afd7beb 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -40,6 +40,7 @@ import litellm
from litellm._internal_context import with_service_target
from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
+from litellm.caching.redis_batch import active_request_redis_batches
from litellm.integrations.prometheus import PrometheusLogger
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm.proxy._types import (
@@ -115,7 +116,10 @@ from litellm.proxy.auth.auth_utils import (
enforce_output_token_estimates_are_admin_only,
)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
-from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import evict_and_broadcast
+from litellm.proxy.common_utils.auth_cache_invalidation_pubsub import (
+ evict_and_broadcast,
+ publish_auth_cache_invalidation,
+)
from litellm.proxy.common_utils.callback_utils import encrypt_callback_vars
from litellm.proxy.common_utils.json_merge_patch import apply_json_merge_patch
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
@@ -473,7 +477,7 @@ async def refresh_cached_team(
proxy_logging_obj: ProxyLogging,
) -> None:
"""
- Refresh the in-memory cached team object after a DB write.
+ Refresh the cached team object after a DB write and broadcast invalidations to other instances.
Every endpoint that mutates `litellm_teamtable` must call this so the
cached `LiteLLM_TeamTableCachedObj` used by `common_checks` stays in
@@ -486,12 +490,19 @@ async def refresh_cached_team(
via `model_dump()` to match the cache shape `_cache_team_object`
expects.
"""
+ team_table: Final = LiteLLM_TeamTableCachedObj.model_validate(team_row.model_dump())
await cache_team_object(
team_id=team_row.team_id,
- team_table=LiteLLM_TeamTableCachedObj.model_validate(team_row.model_dump()),
+ team_table=team_table,
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
)
+ batches: Final = active_request_redis_batches()
+ if batches is not None:
+ await batches.flush_all()
+ await publish_auth_cache_invalidation(cache_key=f"team_id:{team_row.team_id}")
+ if team_table.team_alias is not None:
+ await publish_auth_cache_invalidation(cache_key=f"team_alias:{team_table.team_alias}")
_refresh_cached_team: Final = refresh_cached_team
diff --git a/tests/integration/management/test_team_blocking_multi_instance.py b/tests/integration/management/test_team_blocking_multi_instance.py
index 1173fccaeaa..2d66d614d35 100644
--- a/tests/integration/management/test_team_blocking_multi_instance.py
+++ b/tests/integration/management/test_team_blocking_multi_instance.py
@@ -12,7 +12,7 @@ def _chat(proxy: Gateway, model: str, key: str) -> httpx.Response:
def _rejected(proxy: Gateway, model: str, key: str) -> httpx.Response:
- return eventually(lambda: _chat(proxy, model, key), lambda response: response.status_code == 401, seconds=70)
+ return eventually(lambda: _chat(proxy, model, key), lambda response: response.status_code == 401, seconds=10)
def _blocked_flag(proxy: Gateway, team_id: str) -> object:
@@ -27,6 +27,8 @@ def test_a_team_blocked_on_one_instance_is_rejected_on_both(gateway: Gateway, pe
assert _blocked_flag(peer, team) is False
allowed: Final = _chat(gateway, model, key)
assert allowed.status_code == 200, allowed.text
+ peer_allowed: Final = _chat(peer, model, key)
+ assert peer_allowed.status_code == 200, peer_allowed.text
peer.post("/team/update", {"team_id": team, "blocked": True})
diff --git a/tests/integration/management/test_team_update_multi_instance.py b/tests/integration/management/test_team_update_multi_instance.py
new file mode 100644
index 00000000000..e5b9d31cb6c
--- /dev/null
+++ b/tests/integration/management/test_team_update_multi_instance.py
@@ -0,0 +1,216 @@
+from __future__ import annotations
+
+import json
+from collections.abc import Mapping
+from typing import Final
+from uuid import uuid4
+
+import httpx
+import pytest
+from pydantic import JsonValue
+
+from tests.integration._support.client import JSON_OBJECT, Gateway, Scenario, eventually, object_value, string_value
+from tests.integration._support.wire import Reply, Request, wire_server
+
+_UPSTREAM_REPLIES: Final[Mapping[str, Mapping[str, JsonValue]]] = {
+ "/v1/chat/completions": {
+ "id": "chatcmpl_team_update",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "gpt-5.6",
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ },
+ "/v1/responses": {
+ "id": "resp_team_update",
+ "object": "response",
+ "created_at": 1,
+ "status": "completed",
+ "model": "gpt-5.6",
+ "output": [
+ {
+ "type": "message",
+ "id": "msg_team_update",
+ "status": "completed",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": "hi", "annotations": []}],
+ }
+ ],
+ "parallel_tool_calls": False,
+ "tool_choice": "auto",
+ "tools": [],
+ "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2},
+ },
+}
+
+
+def _respond(request: Request) -> Reply:
+ assert request.method == "POST", request.method
+ assert request.target in _UPSTREAM_REPLIES, request.target
+ return Reply(body=json.dumps(_UPSTREAM_REPLIES[request.target]).encode())
+
+
+def _request(proxy: Gateway, route: str, model: str, key: str) -> httpx.Response:
+ marker: Final = f"team update cache {uuid4().hex}"
+ if route == "/v1/messages":
+ return proxy.request(
+ "POST",
+ route,
+ {"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": marker}]},
+ key=key,
+ headers={"anthropic-version": "2023-06-01"},
+ )
+ if route == "/v1/responses":
+ return proxy.request(
+ "POST",
+ route,
+ {"model": model, "input": marker, "max_output_tokens": 16, "store": False},
+ key=key,
+ )
+ return proxy.request(
+ "POST", route, {"model": model, "messages": [{"role": "user", "content": marker}]}, key=key
+ )
+
+
+def _chat(proxy: Gateway, model: str, key: str) -> httpx.Response:
+ return proxy.request(
+ "POST",
+ "/v1/chat/completions",
+ {"model": model, "messages": [{"role": "user", "content": f"team limit {uuid4().hex}"}]},
+ key=key,
+ )
+
+
+def _team_limit_error(response: httpx.Response) -> None:
+ assert response.status_code == 429, response.text
+ body: Final = JSON_OBJECT.validate_json(response.content)
+ error: Final = object_value(body["error"])
+ message: Final = string_value(error["message"])
+ assert "Current limit: 1" in message, response.text
+
+
+def _scenario_model(scenario: Scenario) -> str:
+ return scenario.model()
+
+
+def _wire_model(scenario: Scenario, upstream_url: str) -> str:
+ return scenario.model(
+ model="openai/gpt-5.6",
+ api_base=upstream_url + "/v1",
+ api_key="synthetic-openai-key",
+ )
+
+
+ "route",
+ (
+ pytest.param("/v1/chat/completions", id="chat-completions"),
+ pytest.param("/v1/messages", id="messages"),
+ pytest.param("/v1/responses", id="responses"),
+ ),
+)
+def test_team_update_adds_model_on_peer_for_inference_routes(gateway: Gateway, peer: Gateway, route: str) -> None:
+ with wire_server(_respond) as upstream, gateway.scenario() as scenario:
+ model_a: Final = _wire_model(scenario, upstream.url)
+ model_b: Final = _wire_model(scenario, upstream.url)
+ team: Final = scenario.team(models=[model_a])
+ key: Final = scenario.key(team_id=team)
+
+ peer_a: Final = _request(peer, route, model_a, key)
+ assert peer_a.status_code == 200, peer_a.text
+ peer_b_before: Final = _request(peer, route, model_b, key)
+ assert peer_b_before.status_code == 403, peer_b_before.text
+
+ update: Final = gateway.request("POST", "/team/update", {"team_id": team, "models": [model_a, model_b]})
+ assert update.status_code == 200, update.text
+
+ peer_b_after: Final = eventually(
+ lambda: _request(peer, route, model_b, key),
+ lambda response: response.status_code == 200,
+ seconds=10,
+ return_last_on_timeout=True,
+ )
+ requests: Final = upstream.drain()
+ assert peer_b_after.status_code == 200, peer_b_after.text
+ expected_target: Final = "/v1/chat/completions" if route == "/v1/chat/completions" else "/v1/responses"
+ assert tuple(request.target for request in requests) == (expected_target, expected_target), peer_b_after.text
+
+
+def test_team_update_raising_rpm_limit_is_enforced_by_peer(gateway: Gateway, peer: Gateway) -> None:
+ with gateway.scenario() as scenario:
+ model: Final = _scenario_model(scenario)
+ team: Final = scenario.team(models=[model], rpm_limit=1)
+ key: Final = scenario.key(team_id=team)
+
+ peer_first: Final = _chat(peer, model, key)
+ assert peer_first.status_code == 200, peer_first.text
+ peer_limited: Final = _chat(peer, model, key)
+ _team_limit_error(peer_limited)
+
+ update: Final = gateway.request("POST", "/team/update", {"team_id": team, "rpm_limit": 1000})
+ assert update.status_code == 200, update.text
+
+ peer_after: Final = eventually(
+ lambda: _chat(peer, model, key),
+ lambda response: response.status_code == 200,
+ seconds=10,
+ return_last_on_timeout=True,
+ )
+ assert peer_after.status_code == 200, peer_after.text
+
+
+def test_team_update_lowering_rpm_limit_is_enforced_by_peer(gateway: Gateway, peer: Gateway) -> None:
+ with gateway.scenario() as scenario:
+ model: Final = _scenario_model(scenario)
+ team: Final = scenario.team(models=[model], rpm_limit=1000)
+ key: Final = scenario.key(team_id=team)
+
+ peer_warm: Final = _chat(peer, model, key)
+ assert peer_warm.status_code == 200, peer_warm.text
+
+ update: Final = gateway.request("POST", "/team/update", {"team_id": team, "rpm_limit": 1})
+ assert update.status_code == 200, update.text
+
+ peer_limited: Final = eventually(
+ lambda: _chat(peer, model, key),
+ lambda response: response.status_code == 429,
+ seconds=10,
+ return_last_on_timeout=True,
+ )
+ _team_limit_error(peer_limited)
+
+
+ ("route", "initial_models", "expected_before", "expected_after"),
+ (
+ pytest.param("/team/model/add", "one", 403, 200, id="add"),
+ pytest.param("/team/model/delete", "both", 200, 403, id="delete"),
+ ),
+)
+def test_team_model_add_delete_is_enforced_by_peer(
+ gateway: Gateway,
+ peer: Gateway,
+ route: str,
+ initial_models: str,
+ expected_before: int,
+ expected_after: int,
+) -> None:
+ with gateway.scenario() as scenario:
+ model_a: Final = _scenario_model(scenario)
+ model_b: Final = _scenario_model(scenario)
+ team: Final = scenario.team(models=[model_a] if initial_models == "one" else [model_a, model_b])
+ key: Final = scenario.key(team_id=team)
+
+ peer_before: Final = _chat(peer, model_b, key)
+ assert peer_before.status_code == expected_before, peer_before.text
+
+ update: Final = gateway.request("POST", route, {"team_id": team, "models": [model_b]})
+ assert update.status_code == 200, update.text
+
+ peer_after: Final = eventually(
+ lambda: _chat(peer, model_b, key),
+ lambda response: response.status_code == expected_after,
+ seconds=10,
+ return_last_on_timeout=True,
+ )
+ assert peer_after.status_code == expected_after, peer_after.text
diff --git a/tests/unit/proxy/management_endpoints/test_team_endpoints.py b/tests/unit/proxy/management_endpoints/test_team_endpoints.py
index e921e4df5c1..bbb83ec1248 100644
--- a/tests/unit/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/test_team_endpoints.py
@@ -2384,6 +2384,152 @@ async def test_team_model_add_delete_refresh_team_cache(endpoint_name):
assert update_call_kwargs.get("include", {}).get("object_permission") is True
+ ("team_alias", "expected_keys"),
+ [
+ ("team-alias", ("team_id:team-refresh", "team_alias:team-alias")),
+ (None, ("team_id:team-refresh",)),
+ ],
+)
+async def test_refresh_cached_team_broadcasts_team_and_alias_invalidations(
+ monkeypatch, team_alias: str | None, expected_keys: tuple[str, ...]
+) -> None:
+ from litellm.proxy.management_endpoints import team_endpoints
+
+ published: Final = MagicMock()
+
+ async def record_cache_team_object(**_kwargs: object) -> None:
+ return None
+
+ async def record_publish(cache_key: str) -> None:
+ published(cache_key)
+
+ monkeypatch.setattr(team_endpoints, "cache_team_object", record_cache_team_object)
+ monkeypatch.setattr(team_endpoints, "publish_auth_cache_invalidation", record_publish)
+
+ await team_endpoints.refresh_cached_team(
+ team_row=LiteLLM_TeamTable(team_id="team-refresh", team_alias=team_alias),
+ user_api_key_cache=MagicMock(),
+ proxy_logging_obj=MagicMock(),
+ )
+
+ assert tuple(call.args[0] for call in published.call_args_list) == expected_keys
+
+
+async def test_refresh_cached_team_flushes_redis_set_before_broadcast(monkeypatch) -> None:
+ from datetime import timedelta
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock
+
+ from litellm.caching.in_memory_cache import InMemoryCache
+ from litellm.caching.redis_batch import request_redis_batch_scope
+ from litellm.caching.redis_cache import RedisCache, RedisCircuitBreaker
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+ from litellm.proxy.management_endpoints import team_endpoints
+
+ events: Final = MagicMock()
+
+ class RecordingPipeline:
+ def __init__(self, calls: MagicMock) -> None:
+ self.calls: Final = MagicMock()
+ self.events: Final = calls
+
+ async def __aenter__(self) -> "RecordingPipeline":
+ return self
+
+ async def __aexit__(self, *exc: object) -> None:
+ return None
+
+ def set(self, key: str, _value: str, ex: timedelta | None = None) -> None:
+ self.calls("SET", key)
+
+ def delete(self, *keys: str) -> None:
+ for key in keys:
+ self.calls("DEL", key)
+
+ async def execute(self, raise_on_error: bool = True) -> list[object]:
+ assert raise_on_error is False
+ for command in self.calls.call_args_list:
+ self.events(*command.args)
+ return [True for _ in self.calls.call_args_list]
+
+ class RecordingRedisClient:
+ def __init__(self, calls: MagicMock) -> None:
+ self.events: Final = calls
+
+ def pipeline(self, transaction: bool = True) -> RecordingPipeline:
+ assert transaction is False
+ return RecordingPipeline(self.events)
+
+ class RecordingRedisCache(RedisCache):
+ def __init__(self) -> None:
+ self.redis_kwargs: Final[dict[str, object]] = {}
+ self.namespace: Final[str | None] = None
+ self.client: Final = RecordingRedisClient(events)
+ self._circuit_breaker: Final = RedisCircuitBreaker(failure_threshold=5, recovery_timeout=30)
+ self.service_logger_obj: Final = SimpleNamespace(
+ async_service_success_hook=AsyncMock(), async_service_failure_hook=AsyncMock()
+ )
+ self.default_ttl: Final[int | None] = None
+
+ def init_async_client(
+ self,
+ ) -> RecordingRedisClient: # pyright: ignore[reportIncompatibleMethodOverride] # in-memory Redis client
+ return self.client
+
+ async def record_publish(cache_key: str) -> None:
+ events("PUBLISH", cache_key)
+
+ redis_cache: Final = RecordingRedisCache()
+ cache: Final = UserApiKeyCache(in_memory_cache=InMemoryCache(), redis_cache=redis_cache)
+ proxy_logging_obj: Final = MagicMock()
+ proxy_logging_obj.internal_usage_cache.dual_cache = None
+ monkeypatch.setattr(team_endpoints, "publish_auth_cache_invalidation", record_publish)
+
+ with request_redis_batch_scope():
+ await team_endpoints.refresh_cached_team(
+ team_row=LiteLLM_TeamTable(team_id="team-order", team_alias=None),
+ user_api_key_cache=cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ assert [(call.args[0], call.args[1]) for call in events.call_args_list] == [
+ ("SET", "team_id:team-order"),
+ ("PUBLISH", "team_id:team-order"),
+ ]
+
+
+async def test_get_team_object_cache_miss_does_not_broadcast_invalidation(monkeypatch) -> None:
+ from unittest.mock import AsyncMock
+
+ from litellm.caching.in_memory_cache import InMemoryCache
+ from litellm.proxy.auth import auth_checks
+ from litellm.proxy.auth.auth_checks import get_team_object
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+
+ team_id: Final = "team-read-cache-miss"
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_teamtable.find_unique = AsyncMock(
+ return_value=LiteLLM_TeamTable(team_id=team_id, models=["model-a"])
+ )
+ cache: Final = UserApiKeyCache(in_memory_cache=InMemoryCache())
+ publish: Final = AsyncMock()
+ monkeypatch.setattr(auth_checks, "publish_auth_cache_invalidation", publish)
+
+ team: Final = await get_team_object(
+ team_id=team_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=cache,
+ )
+
+ assert team.team_id == team_id
+ assert await cache.async_get_cache(key=f"team_id:{team_id}", model_type=LiteLLM_TeamTableCachedObj) is not None
+ publish.assert_not_awaited()
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("endpoint_name", ["team_model_add", "team_model_delete"])
async def test_team_model_add_delete_keep_model_aliases_in_team_cache(endpoint_name, monkeypatch):