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]

feat(proxy): auto-suppress the no-Redis banner for confirmed single-worker deployments

mateo-berried33687422c5
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260814000000_add_proxy_worker_heartbeat/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260814000000_add_proxy_worker_heartbeat/migration.sql
new file mode 100644
index 00000000000..0a5d9df8aaf
--- /dev/null
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260814000000_add_proxy_worker_heartbeat/migration.sql
@@ -0,0 +1,9 @@
+-- CreateTable
+CREATE TABLE "LiteLLM_ProxyWorkerHeartbeat" (
+ "worker_id" TEXT NOT NULL,
+ "hostname" TEXT NOT NULL,
+ "started_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "last_heartbeat_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "LiteLLM_ProxyWorkerHeartbeat_pkey" PRIMARY KEY ("worker_id")
+);
diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
index 79d778fb464..09efef813a7 100644
--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma
@@ -945,6 +945,17 @@ model LiteLLM_DailyTagSpend {
}
+// One row per live proxy worker process. Workers upsert their row on a fixed
+// heartbeat; counting rows with a recent heartbeat tells how many workers share
+// this database, which lets the Admin UI hide its "no Redis" warning for
+// deployments that are provably a single worker.
+model LiteLLM_ProxyWorkerHeartbeat {
+ worker_id String @id
+ hostname String
+ started_at DateTime @default(now())
+ last_heartbeat_at DateTime @default(now())
+}
+
// Track the status of cron jobs running. Only allow one pod to run the job at a time
model LiteLLM_CronJob {
cronjob_id String @id @default(cuid()) // Unique ID for the record
diff --git a/litellm/proxy/db/proxy_worker_heartbeat.py b/litellm/proxy/db/proxy_worker_heartbeat.py
new file mode 100644
index 00000000000..6a2a4572e43
--- /dev/null
+++ b/litellm/proxy/db/proxy_worker_heartbeat.py
@@ -0,0 +1,89 @@
+"""
+Live proxy worker census, one row per worker process.
+
+Every uvicorn worker upserts its own row on a fixed heartbeat, so counting
+rows with a recent heartbeat answers "how many workers share this database?"
+without any coordination. The Admin UI's "no Redis" banner uses that count to
+hide itself for deployments that are provably a single worker, where per-worker
+rate limits, budgets, and router state are already global. All timestamps are
+written and compared with the database's own clock, so pods with skewed clocks
+still agree.
+"""
+
+from __future__ import annotations
+
+import socket
+from typing import TYPE_CHECKING, Final
+
+from pydantic import TypeAdapter
+from typing_extensions import ReadOnly, TypedDict
+
+from litellm._logging import verbose_proxy_logger
+from litellm._uuid import uuid
+
+if TYPE_CHECKING:
+ from litellm.proxy.utils import PrismaClient
+
+PROXY_WORKER_HEARTBEAT_INTERVAL_SECONDS: Final = 60
+PROXY_WORKER_LIVENESS_WINDOW_SECONDS: Final = 3 * PROXY_WORKER_HEARTBEAT_INTERVAL_SECONDS
+STALE_ROW_RETENTION_SECONDS: Final = 3600
+
+BEAT_SQL: Final = """
+INSERT INTO "LiteLLM_ProxyWorkerHeartbeat" (worker_id, hostname, last_heartbeat_at)
+VALUES ($1, $2, NOW())
+ON CONFLICT (worker_id) DO UPDATE SET last_heartbeat_at = NOW()
+"""
+
+PRUNE_SQL: Final = """
+DELETE FROM "LiteLLM_ProxyWorkerHeartbeat"
+WHERE last_heartbeat_at < NOW() - make_interval(secs => $1)
+"""
+
+COUNT_SQL: Final = """
+SELECT COUNT(*)::int AS live_workers FROM "LiteLLM_ProxyWorkerHeartbeat"
+WHERE last_heartbeat_at > NOW() - make_interval(secs => $1)
+"""
+
+DEREGISTER_SQL: Final = """
+DELETE FROM "LiteLLM_ProxyWorkerHeartbeat" WHERE worker_id = $1
+"""
+
+
+class _LiveWorkerCountRow(TypedDict):
+ live_workers: ReadOnly[int]
+
+
+_COUNT_ROWS_ADAPTER: Final = TypeAdapter(tuple[_LiveWorkerCountRow, ...])
+
+
+class ProxyWorkerHeartbeat:
+ def __init__(self, prisma_client: PrismaClient, worker_id: str | None = None) -> None:
+ self.prisma_client: Final = prisma_client
+ self.worker_id: Final[str] = worker_id or str(uuid.uuid4())
+ self.hostname: Final = socket.gethostname()
+
+ async def beat(self) -> None:
+ try:
+ await self.prisma_client.db.execute_raw(BEAT_SQL, self.worker_id, self.hostname)
+ await self.prisma_client.db.execute_raw(PRUNE_SQL, STALE_ROW_RETENTION_SECONDS)
+ except Exception as beat_err: # noqa: BLE001 # a missed heartbeat must never take down the worker
+ verbose_proxy_logger.debug("Proxy worker heartbeat write failed: %s", beat_err)
+
+ async def deregister(self) -> None:
+ try:
+ await self.prisma_client.db.execute_raw(DEREGISTER_SQL, self.worker_id)
+ except Exception as deregister_err: # noqa: BLE001 # best-effort cleanup; the liveness window ages the row out anyway
+ verbose_proxy_logger.debug("Proxy worker heartbeat deregister failed: %s", deregister_err)
+
+
+async def count_live_proxy_workers(prisma_client: PrismaClient) -> int | None:
+ """
+ The number of workers with a recent heartbeat, or None when the database
+ cannot answer. Callers must treat None as "unknown", not as zero.
+ """
+ try:
+ rows: Final = await prisma_client.db.query_raw(COUNT_SQL, PROXY_WORKER_LIVENESS_WINDOW_SECONDS)
+ return _COUNT_ROWS_ADAPTER.validate_python(rows)[0]["live_workers"]
+ except Exception as count_err: # noqa: BLE001 # an unknown count must degrade to "warn", never to a 503
+ verbose_proxy_logger.debug("Live proxy worker count unavailable: %s", count_err)
+ return None
diff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.py
index e814ec42d26..33894777bc3 100644
--- a/litellm/proxy/health_endpoints/_health_endpoints.py
+++ b/litellm/proxy/health_endpoints/_health_endpoints.py
@@ -34,6 +34,7 @@ from litellm.proxy.auth.auth_utils import (
)
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
+from litellm.proxy.db.proxy_worker_heartbeat import count_live_proxy_workers
from litellm.proxy.health_check import (
ADMIN_ONLY_HEALTH_DISPLAY_PARAMS,
_clean_endpoint_data,
@@ -1451,7 +1452,7 @@ def callback_name(callback):
DISABLE_NO_REDIS_WARNING_ENV_VAR: Final = "LITELLM_DISABLE_NO_REDIS_WARNING"
-def _show_no_redis_warning() -> bool:
+async def _show_no_redis_warning() -> bool:
"""
Whether the UI should warn that no Redis is configured.
@@ -1461,16 +1462,22 @@ def _show_no_redis_warning() -> bool:
coordination cache (from a Redis response cache, general_settings.
coordination_redis, or the REDIS_* env fallback) and the router's own
Redis (router_settings.redis_host), which backs cooldowns and usage-based
- routing on its own. Operators who know they run one worker can silence the
- warning with LITELLM_DISABLE_NO_REDIS_WARNING=true.
+ routing on its own. A deployment whose worker-heartbeat census proves it
+ is exactly one worker needs no cross-worker coordination, so it never
+ warns; when the census is unavailable or shows more than one worker, the
+ warning stands unless LITELLM_DISABLE_NO_REDIS_WARNING=true silences it.
"""
- from litellm.proxy.proxy_server import llm_router, redis_usage_cache
+ from litellm.proxy.proxy_server import llm_router, prisma_client, redis_usage_cache
if redis_usage_cache is not None:
return False
if llm_router is not None and llm_router.cache.redis_cache is not None:
return False
- return get_secret_bool(DISABLE_NO_REDIS_WARNING_ENV_VAR, False) is not True
+ if get_secret_bool(DISABLE_NO_REDIS_WARNING_ENV_VAR, False) is True:
+ return False
+ if prisma_client is None:
+ return True
+ return await count_live_proxy_workers(prisma_client) != 1
async def _get_health_readiness_details(
@@ -1513,7 +1520,7 @@ async def _get_health_readiness_details(
# check log level
log_level_name: Final = logging.getLevelName(verbose_logger.getEffectiveLevel())
is_detailed_debug: Final = verbose_logger.isEnabledFor(logging.DEBUG)
- show_no_redis_warning: Final = _show_no_redis_warning()
+ show_no_redis_warning: Final = await _show_no_redis_warning()
# check DB
if prisma_client is not None: # if db passed in, check if it's connected
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 359187f81cb..6ee08a732f2 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -379,6 +379,10 @@ from litellm.proxy.db.gateway_request_tracking import (
GatewayRequestAccumulator,
flush_gateway_requests,
)
+from litellm.proxy.db.proxy_worker_heartbeat import (
+ PROXY_WORKER_HEARTBEAT_INTERVAL_SECONDS,
+ ProxyWorkerHeartbeat,
+)
from litellm.proxy.db.spend_counter_reseed import SpendCounterReseed
from litellm.proxy.discovery_endpoints import ui_discovery_endpoints_router
from litellm.proxy.fine_tuning_endpoints.endpoints import router as fine_tuning_router
@@ -864,9 +868,11 @@ async def _flush_spend_logs_queue_on_shutdown() -> None:
verbose_proxy_logger.exception("Error flushing spend logs queue on shutdown: %s", e)
-async def proxy_shutdown_event():
+async def proxy_shutdown_event(worker_heartbeat: ProxyWorkerHeartbeat | None = None):
global prisma_client, master_key, user_custom_auth, user_custom_key_generate, user_custom_key_update
verbose_proxy_logger.info("Shutting down LiteLLM Proxy Server")
+ if worker_heartbeat is not None and prisma_client:
+ await worker_heartbeat.deregister()
if prisma_client:
# Drain the SGR fold first: it lives in memory, so an un-drained interval
# is lost, and a write attempted after disconnect raises
@@ -1200,7 +1206,7 @@ async def proxy_startup_event(app: FastAPI):
)
### START BATCH WRITING DB + CHECKING NEW MODELS###
- if prisma_client is not None:
+ worker_heartbeat: Final = (
await ProxyStartupEvent.initialize_scheduled_background_jobs(
general_settings=general_settings,
prisma_client=prisma_client,
@@ -1209,7 +1215,10 @@ async def proxy_startup_event(app: FastAPI):
proxy_batch_write_at=proxy_batch_write_at,
proxy_logging_obj=proxy_logging_obj,
)
-
+ if prisma_client is not None
+ else None
+ )
+ if prisma_client is not None:
await ProxyStartupEvent._update_default_team_member_budget()
## SYNC UI SETTINGS ##
@@ -1280,7 +1289,7 @@ async def proxy_startup_event(app: FastAPI):
await proxy_config.stop_auth_cache_invalidation_subscriber()
- await proxy_shutdown_event()
+ await proxy_shutdown_event(worker_heartbeat=worker_heartbeat)
def _generate_stable_operation_id(route: "APIRoute") -> str:
@@ -8665,7 +8674,7 @@ class ProxyStartupEvent:
proxy_budget_rescheduler_max_time: int,
proxy_batch_write_at: int,
proxy_logging_obj: ProxyLogging,
- ):
+ ) -> ProxyWorkerHeartbeat:
"""Initializes scheduled background jobs"""
global store_model_in_db, scheduler
@@ -8710,6 +8719,18 @@ class ProxyStartupEvent:
# Ensure minimum interval of 30 seconds for batch writing to prevent memory issues
batch_writing_interval: Final = proxy_batch_write_at + random.randint(0, 5)
+ ### PROXY WORKER HEARTBEAT ###
+ worker_heartbeat: Final = ProxyWorkerHeartbeat(prisma_client=prisma_client)
+ await worker_heartbeat.beat()
+ scheduler.add_job(
+ worker_heartbeat.beat,
+ "interval",
+ seconds=PROXY_WORKER_HEARTBEAT_INTERVAL_SECONDS,
+ id="proxy_worker_heartbeat_job",
+ replace_existing=True,
+ misfire_grace_time=APSCHEDULER_MISFIRE_GRACE_TIME,
+ )
+
### RESET BUDGET ###
if general_settings.get("disable_reset_budget", False) is False:
budget_reset_job: Final = ResetBudgetJob(
@@ -9048,6 +9069,7 @@ class ProxyStartupEvent:
"APScheduler started with memory leak prevention settings: removed jitter, increased intervals, misfire_grace_time=%s",
APSCHEDULER_MISFIRE_GRACE_TIME,
)
+ return worker_heartbeat
@classmethod
async def _initialize_spend_tracking_background_jobs(cls, scheduler: AsyncIOScheduler):
diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prisma
index 79d778fb464..09efef813a7 100644
--- a/litellm/proxy/schema.prisma
+++ b/litellm/proxy/schema.prisma
@@ -945,6 +945,17 @@ model LiteLLM_DailyTagSpend {
}
+// One row per live proxy worker process. Workers upsert their row on a fixed
+// heartbeat; counting rows with a recent heartbeat tells how many workers share
+// this database, which lets the Admin UI hide its "no Redis" warning for
+// deployments that are provably a single worker.
+model LiteLLM_ProxyWorkerHeartbeat {
+ worker_id String @id
+ hostname String
+ started_at DateTime @default(now())
+ last_heartbeat_at DateTime @default(now())
+}
+
// Track the status of cron jobs running. Only allow one pod to run the job at a time
model LiteLLM_CronJob {
cronjob_id String @id @default(cuid()) // Unique ID for the record
diff --git a/schema.prisma b/schema.prisma
index 79d778fb464..09efef813a7 100644
--- a/schema.prisma
+++ b/schema.prisma
@@ -945,6 +945,17 @@ model LiteLLM_DailyTagSpend {
}
+// One row per live proxy worker process. Workers upsert their row on a fixed
+// heartbeat; counting rows with a recent heartbeat tells how many workers share
+// this database, which lets the Admin UI hide its "no Redis" warning for
+// deployments that are provably a single worker.
+model LiteLLM_ProxyWorkerHeartbeat {
+ worker_id String @id
+ hostname String
+ started_at DateTime @default(now())
+ last_heartbeat_at DateTime @default(now())
+}
+
// Track the status of cron jobs running. Only allow one pod to run the job at a time
model LiteLLM_CronJob {
cronjob_id String @id @default(cuid()) // Unique ID for the record
diff --git a/tests/test_litellm/proxy/db/test_proxy_worker_heartbeat.py b/tests/test_litellm/proxy/db/test_proxy_worker_heartbeat.py
new file mode 100644
index 00000000000..2209be0dc2e
--- /dev/null
+++ b/tests/test_litellm/proxy/db/test_proxy_worker_heartbeat.py
@@ -0,0 +1,81 @@
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from litellm.proxy.db.proxy_worker_heartbeat import (
+ BEAT_SQL,
+ COUNT_SQL,
+ DEREGISTER_SQL,
+ PROXY_WORKER_LIVENESS_WINDOW_SECONDS,
+ PRUNE_SQL,
+ STALE_ROW_RETENTION_SECONDS,
+ ProxyWorkerHeartbeat,
+ count_live_proxy_workers,
+)
+
+
+def _prisma():
+ prisma = MagicMock()
+ prisma.db.execute_raw = AsyncMock()
+ prisma.db.query_raw = AsyncMock()
+ return prisma
+
+
+async def test_beat_upserts_own_row_then_prunes_stale_rows():
+ prisma = _prisma()
+ heartbeat = ProxyWorkerHeartbeat(prisma_client=prisma, worker_id="worker-1")
+ await heartbeat.beat()
+ calls = prisma.db.execute_raw.call_args_list
+ assert calls[0].args == (BEAT_SQL, "worker-1", heartbeat.hostname)
+ assert calls[1].args == (PRUNE_SQL, STALE_ROW_RETENTION_SECONDS)
+
+
+async def test_beat_survives_a_database_error():
+ prisma = _prisma()
+ prisma.db.execute_raw = AsyncMock(side_effect=RuntimeError("db down"))
+ await ProxyWorkerHeartbeat(prisma_client=prisma).beat()
+
+
+def test_each_worker_process_gets_its_own_id():
+ prisma = _prisma()
+ first = ProxyWorkerHeartbeat(prisma_client=prisma)
+ second = ProxyWorkerHeartbeat(prisma_client=prisma)
+ assert first.worker_id != second.worker_id
+
+
+async def test_deregister_deletes_only_its_own_row():
+ prisma = _prisma()
+ await ProxyWorkerHeartbeat(prisma_client=prisma, worker_id="worker-1").deregister()
+ assert prisma.db.execute_raw.call_args.args == (DEREGISTER_SQL, "worker-1")
+
+
+async def test_deregister_survives_a_database_error():
+ prisma = _prisma()
+ prisma.db.execute_raw = AsyncMock(side_effect=RuntimeError("db down"))
+ await ProxyWorkerHeartbeat(prisma_client=prisma, worker_id="worker-1").deregister()
+
+
+async def test_count_reads_workers_within_the_liveness_window():
+ prisma = _prisma()
+ prisma.db.query_raw.return_value = [{"live_workers": 3}]
+ assert await count_live_proxy_workers(prisma) == 3
+ assert prisma.db.query_raw.call_args.args == (COUNT_SQL, PROXY_WORKER_LIVENESS_WINDOW_SECONDS)
+
+
+async def test_count_returns_unknown_when_the_query_fails():
+ prisma = _prisma()
+ prisma.db.query_raw.side_effect = RuntimeError("db down")
+ assert await count_live_proxy_workers(prisma) is None
+
+
+async def test_count_returns_unknown_for_a_malformed_row():
+ prisma = _prisma()
+ prisma.db.query_raw.return_value = [{"unexpected": "shape"}]
+ assert await count_live_proxy_workers(prisma) is None
diff --git a/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py b/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py
index e2705bd5fec..831f659051c 100644
--- a/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py
+++ b/tests/test_litellm/proxy/health_endpoints/test_health_endpoints.py
@@ -2467,61 +2467,140 @@ class TestNoRedisWarning:
def _router(redis_cache):
return SimpleNamespace(cache=SimpleNamespace(redis_cache=redis_cache))
- def test_warns_when_no_redis_is_configured(self, monkeypatch):
+ @staticmethod
+ def _prisma_with_workers(live_workers=None, error=None):
+ prisma = MagicMock()
+ if error is not None:
+ prisma.db.query_raw = AsyncMock(side_effect=error)
+ else:
+ prisma.db.query_raw = AsyncMock(return_value=[{"live_workers": live_workers}])
+ return prisma
+
+ @pytest.mark.asyncio
+ async def test_warns_when_no_redis_and_no_db_to_count_workers(self, monkeypatch):
monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
with (
patch("litellm.proxy.proxy_server.redis_usage_cache", None),
patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch("litellm.proxy.proxy_server.prisma_client", None),
):
- assert _show_no_redis_warning() is True
+ assert await _show_no_redis_warning() is True
- def test_warns_when_there_is_no_router_at_all(self, monkeypatch):
+ @pytest.mark.asyncio
+ async def test_warns_when_there_is_no_router_at_all(self, monkeypatch):
monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
with (
patch("litellm.proxy.proxy_server.redis_usage_cache", None),
patch("litellm.proxy.proxy_server.llm_router", None),
+ patch("litellm.proxy.proxy_server.prisma_client", None),
):
- assert _show_no_redis_warning() is True
+ assert await _show_no_redis_warning() is True
- def test_stays_quiet_when_a_coordination_redis_is_configured(self, monkeypatch):
+ @pytest.mark.asyncio
+ async def test_stays_quiet_for_a_confirmed_single_worker(self, monkeypatch):
+ """One live worker needs no cross-worker coordination, so no env var is needed."""
monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
+ with (
+ patch("litellm.proxy.proxy_server.redis_usage_cache", None),
+ patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch("litellm.proxy.proxy_server.prisma_client", self._prisma_with_workers(1)),
+ ):
+ assert await _show_no_redis_warning() is False
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("live_workers", [2, 5])
+ async def test_warns_when_multiple_workers_share_the_db(self, monkeypatch, live_workers):
+ monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
+ with (
+ patch("litellm.proxy.proxy_server.redis_usage_cache", None),
+ patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch("litellm.proxy.proxy_server.prisma_client", self._prisma_with_workers(live_workers)),
+ ):
+ assert await _show_no_redis_warning() is True
+
+ @pytest.mark.asyncio
+ async def test_warns_when_the_worker_census_is_empty(self, monkeypatch):
+ """Zero rows means the census cannot CONFIRM a single worker, so warn."""
+ monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
+ with (
+ patch("litellm.proxy.proxy_server.redis_usage_cache", None),
+ patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch("litellm.proxy.proxy_server.prisma_client", self._prisma_with_workers(0)),
+ ):
+ assert await _show_no_redis_warning() is True
+
+ @pytest.mark.asyncio
+ async def test_warns_when_the_worker_census_query_fails(self, monkeypatch):
+ monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
+ with (
+ patch("litellm.proxy.proxy_server.redis_usage_cache", None),
+ patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch(
+ "litellm.proxy.proxy_server.prisma_client",
+ self._prisma_with_workers(error=RuntimeError("db down")),
+ ),
+ ):
+ assert await _show_no_redis_warning() is True
+
+ @pytest.mark.asyncio
+ async def test_stays_quiet_when_a_coordination_redis_is_configured(self, monkeypatch):
+ monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
+ prisma = self._prisma_with_workers(5)
with (
patch("litellm.proxy.proxy_server.redis_usage_cache", MagicMock()),
patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch("litellm.proxy.proxy_server.prisma_client", prisma),
):
- assert _show_no_redis_warning() is False
+ assert await _show_no_redis_warning() is False
+ prisma.db.query_raw.assert_not_called()
- def test_stays_quiet_when_only_the_router_has_redis(self, monkeypatch):
+ @pytest.mark.asyncio
+ async def test_stays_quiet_when_only_the_router_has_redis(self, monkeypatch):
"""router_settings.redis_host alone backs cooldowns and usage-based routing."""
monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
with (
patch("litellm.proxy.proxy_server.redis_usage_cache", None),
patch("litellm.proxy.proxy_server.llm_router", self._router(MagicMock())),
+ patch("litellm.proxy.proxy_server.prisma_client", self._prisma_with_workers(5)),
):
- assert _show_no_redis_warning() is False
+ assert await _show_no_redis_warning() is False
+ @pytest.mark.asyncio
@pytest.mark.parametrize("value", ["true", "True"])
- def test_env_var_suppresses_the_warning(self, monkeypatch, value):
+ async def test_env_var_suppresses_the_warning_despite_multiple_workers(self, monkeypatch, value):
monkeypatch.setenv("LITELLM_DISABLE_NO_REDIS_WARNING", value)
with (
patch("litellm.proxy.proxy_server.redis_usage_cache", None),
patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch("litellm.proxy.proxy_server.prisma_client", self._prisma_with_workers(5)),
):
- assert _show_no_redis_warning() is False
+ assert await _show_no_redis_warning() is False
- def test_env_var_set_false_keeps_the_warning(self, monkeypatch):
+ @pytest.mark.asyncio
+ async def test_env_var_set_false_keeps_the_warning_for_multiple_workers(self, monkeypatch):
+ monkeypatch.setenv("LITELLM_DISABLE_NO_REDIS_WARNING", "false")
+ with (
+ patch("litellm.proxy.proxy_server.redis_usage_cache", None),
+ patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch("litellm.proxy.proxy_server.prisma_client", self._prisma_with_workers(2)),
+ ):
+ assert await _show_no_redis_warning() is True
+
+ @pytest.mark.asyncio
+ async def test_env_var_set_false_does_not_force_the_warning_for_a_single_worker(self, monkeypatch):
monkeypatch.setenv("LITELLM_DISABLE_NO_REDIS_WARNING", "false")
with (
patch("litellm.proxy.proxy_server.redis_usage_cache", None),
patch("litellm.proxy.proxy_server.llm_router", self._router(None)),
+ patch("litellm.proxy.proxy_server.prisma_client", self._prisma_with_workers(1)),
):
- assert _show_no_redis_warning() is True
+ assert await _show_no_redis_warning() is False
@pytest.mark.asyncio
@pytest.mark.parametrize("has_prisma_client", [True, False])
async def test_readiness_details_carries_the_flag(self, monkeypatch, has_prisma_client):
monkeypatch.delenv("LITELLM_DISABLE_NO_REDIS_WARNING", raising=False)
- prisma_client = MagicMock() if has_prisma_client else None
+ prisma_client = self._prisma_with_workers(2) if has_prisma_client else None
with (
patch("litellm.proxy.proxy_server.prisma_client", prisma_client),
patch("litellm.proxy.proxy_server.redis_usage_cache", None),
diff --git a/ui/litellm-dashboard/src/components/NoRedisWarningBanner.test.tsx b/ui/litellm-dashboard/src/components/NoRedisWarningBanner.test.tsx
index 8afde8eec94..600315e789e 100644
--- a/ui/litellm-dashboard/src/components/NoRedisWarningBanner.test.tsx
+++ b/ui/litellm-dashboard/src/components/NoRedisWarningBanner.test.tsx
@@ -20,6 +20,7 @@ describe("NoRedisWarningBanner", () => {
renderWithProviders(<NoRedisWarningBanner accessToken="token" />);
expect(screen.getByRole("alert")).toBeInTheDocument();
expect(screen.getByText(/No Redis configured\. Redis is highly recommended/i)).toBeInTheDocument();
+ expect(screen.getByText(/more than one worker/i)).toBeInTheDocument();
});
it("should link to the docs page listing what breaks without Redis", () => {
diff --git a/ui/litellm-dashboard/src/components/NoRedisWarningBanner.tsx b/ui/litellm-dashboard/src/components/NoRedisWarningBanner.tsx
index 93c0f55486d..02433fad521 100644
--- a/ui/litellm-dashboard/src/components/NoRedisWarningBanner.tsx
+++ b/ui/litellm-dashboard/src/components/NoRedisWarningBanner.tsx
@@ -26,13 +26,13 @@ export const NoRedisWarningBanner: React.FC<NoRedisWarningBannerProps> = ({ acce
<div>
<p className="font-semibold">No Redis configured. Redis is highly recommended</p>
<p>
- Rate limits, budgets, router state, and cache invalidation are per worker without Redis, so limits are
- enforced once per worker and spend can overshoot.{" "}
+ This proxy is running more than one worker (or the worker count could not be verified). Without Redis, rate
+ limits, budgets, router state, and cache invalidation are per worker, so limits are enforced once per worker
+ and spend can overshoot.{" "}
<a className="underline" href={REDIS_DOCS_URL} target="_blank" rel="noreferrer">
See everything that does not work without Redis
</a>
- . If you run a single worker and this is intentional, set{" "}
- <code className="font-mono">LITELLM_DISABLE_NO_REDIS_WARNING=true</code> to hide this banner.
+ . Set <code className="font-mono">LITELLM_DISABLE_NO_REDIS_WARNING=true</code> to hide this banner anyway.
</p>
</div>
</div>