Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
e6f894d
fix(proxy): add prisma reconnect primitive and db watchdog
ishaan-jaff Feb 20, 2026
d1b2805
fix(proxy): start and stop prisma watchdog in lifecycle
ishaan-jaff Feb 20, 2026
ffe8637
fix(auth): retry key lookup once after prisma reconnect
ishaan-jaff Feb 20, 2026
4dee7dc
test(proxy): add prisma self-heal watchdog coverage
ishaan-jaff Feb 20, 2026
b560164
test(auth): cover reconnect-once behavior for key lookup
ishaan-jaff Feb 20, 2026
cb19ec1
refactor(auth): extract db reconnect helper and remove inline import
ishaan-jaff Feb 20, 2026
e89c5b7
fix(proxy): apply reconnect cooldown after attempt and add auth timeo…
ishaan-jaff Feb 20, 2026
14f529a
fix(auth): bound reconnect latency on key lookup path
ishaan-jaff Feb 20, 2026
5e0fbf0
test(auth): assert reconnect timeout argument in key lookup
ishaan-jaff Feb 20, 2026
67809b8
test(proxy): verify reconnect cooldown timestamp set after attempt
ishaan-jaff Feb 20, 2026
edcb6bd
fix(proxy): harden prisma reconnect cycle semantics
ishaan-jaff Feb 21, 2026
1144b7f
test(proxy): cover watchdog reconnect + timeout budget
ishaan-jaff Feb 21, 2026
1921bad
fix(proxy): bound watchdog probe and reconnect paths
ishaan-jaff Feb 21, 2026
2083f39
test(proxy): cover watchdog timeout and probe behavior
ishaan-jaff Feb 21, 2026
2c02d1e
fix(proxy): narrow prisma db connection error classification
ishaan-jaff Feb 21, 2026
c0a395a
fix(proxy): add auth reconnect lock timeout budget
ishaan-jaff Feb 21, 2026
4844f76
fix(auth): pass lock timeout for db reconnect retries
ishaan-jaff Feb 21, 2026
3bb2423
test(proxy): cover narrow prisma connection error detection
ishaan-jaff Feb 21, 2026
f288319
test(proxy): add reconnect lock-timeout behavior coverage
ishaan-jaff Feb 21, 2026
b53c342
test(auth): assert reconnect lock timeout argument
ishaan-jaff Feb 21, 2026
aa71695
fix(proxy): avoid lock leak race in reconnect lock timeout path
ishaan-jaff Feb 21, 2026
8b8c58a
test(proxy): cover reconnect lock-timeout race cleanup
ishaan-jaff Feb 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 48 additions & 6 deletions litellm/proxy/auth/auth_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@
LiteLLM_ObjectPermissionTable,
LiteLLM_OrganizationMembershipTable,
LiteLLM_OrganizationTable,
LiteLLM_ProjectTableCachedObj,
LiteLLM_TagTable,
LiteLLM_TeamMembership,
LiteLLM_TeamTable,
LiteLLM_TeamTableCachedObj,
LiteLLM_ProjectTableCachedObj,
LiteLLM_UserTable,
LiteLLMRoutes,
LitellmUserRoles,
Expand All @@ -57,6 +57,7 @@
UserAPIKeyAuth,
)
from litellm.proxy.auth.route_checks import RouteChecks
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
from litellm.proxy.route_llm_request import route_request
from litellm.proxy.utils import PrismaClient, ProxyLogging, log_db_metrics
from litellm.router import Router
Expand Down Expand Up @@ -1982,6 +1983,45 @@ def get_key_object_from_ui_hash_key(
)


async def _fetch_key_object_from_db_with_reconnect(
hashed_token: str,
prisma_client: PrismaClient,
parent_otel_span: Optional[Span],
proxy_logging_obj: Optional[ProxyLogging],
) -> Optional[BaseModel]:
"""
Fetch key object from DB and retry once if a DB connection error can be healed.
"""
try:
return await prisma_client.get_data(
token=hashed_token,
table_name="combined_view",
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
)
except Exception as e:
if PrismaDBExceptionHandler.is_database_connection_error(e):
did_reconnect = False
if hasattr(prisma_client, "attempt_db_reconnect"):
auth_reconnect_timeout = getattr(
prisma_client, "_db_auth_reconnect_timeout_seconds", 2.0
)
if not isinstance(auth_reconnect_timeout, (int, float)):
auth_reconnect_timeout = 2.0
did_reconnect = await prisma_client.attempt_db_reconnect(
reason="auth_get_key_object_lookup_failure",
timeout_seconds=auth_reconnect_timeout,
)
if did_reconnect:
return await prisma_client.get_data(
token=hashed_token,
table_name="combined_view",
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
)
raise


@log_db_metrics
async def get_key_object(
hashed_token: str,
Expand Down Expand Up @@ -2020,11 +2060,13 @@ async def get_key_object(
)

# else, check db
_valid_token: Optional[BaseModel] = await prisma_client.get_data(
token=hashed_token,
table_name="combined_view",
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
_valid_token: Optional[BaseModel] = (
await _fetch_key_object_from_db_with_reconnect(
hashed_token=hashed_token,
prisma_client=prisma_client,
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
)
)

if _valid_token is None:
Expand Down
14 changes: 13 additions & 1 deletion litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,10 +388,10 @@ def generate_feedback_box():
from litellm.proxy.management_endpoints.organization_endpoints import (
router as organization_router,
)
from litellm.proxy.management_endpoints.policy_endpoints import router as policy_router
from litellm.proxy.management_endpoints.project_endpoints import (
router as project_router,
)
from litellm.proxy.management_endpoints.policy_endpoints import router as policy_router
from litellm.proxy.management_endpoints.router_settings_endpoints import (
router as router_settings_router,
)
Expand Down Expand Up @@ -902,6 +902,15 @@ async def proxy_startup_event(app: FastAPI): # noqa: PLR0915
except Exception as e:
verbose_proxy_logger.error(f"Error stopping token refresh task: {e}")

# Shutdown event - stop Prisma DB health watchdog task
if prisma_client is not None and hasattr(
prisma_client, "stop_db_health_watchdog_task"
):
try:
await prisma_client.stop_db_health_watchdog_task()
except Exception as e:
verbose_proxy_logger.error(f"Error stopping DB health watchdog task: {e}")

await proxy_shutdown_event() # type: ignore[reportGeneralTypeIssues]


Expand Down Expand Up @@ -5829,6 +5838,9 @@ async def _setup_prisma_client(
is not True
):
await prisma_client.health_check()

if hasattr(prisma_client, "start_db_health_watchdog_task"):
await prisma_client.start_db_health_watchdog_task()
return prisma_client
except Exception as e:
PrismaDBExceptionHandler.handle_db_exception(e)
Expand Down
168 changes: 168 additions & 0 deletions litellm/proxy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
should_create_missing_views,
)
from litellm.proxy.db.db_spend_update_writer import DBSpendUpdateWriter
from litellm.proxy.db.exception_handler import PrismaDBExceptionHandler
from litellm.proxy.db.log_db_metrics import log_db_metrics
from litellm.proxy.db.prisma_client import PrismaWrapper
from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (
Expand Down Expand Up @@ -2266,6 +2267,28 @@ def __init__(
else False
),
) # Client to connect to Prisma db
self._db_reconnect_lock = asyncio.Lock()
self._db_health_watchdog_task: Optional[asyncio.Task] = None
self._db_last_reconnect_attempt_ts: float = 0.0
self._db_reconnect_cooldown_seconds: int = max(
1, int(os.getenv("PRISMA_RECONNECT_COOLDOWN_SECONDS", "15"))
)
self._db_health_watchdog_interval_seconds: int = max(
5, int(os.getenv("PRISMA_HEALTH_WATCHDOG_INTERVAL_SECONDS", "30"))
)
self._db_health_watchdog_enabled: bool = (
str_to_bool(os.getenv("PRISMA_HEALTH_WATCHDOG_ENABLED", "true")) is True
)
self._db_health_watchdog_probe_timeout_seconds: float = max(
0.5,
float(os.getenv("PRISMA_HEALTH_WATCHDOG_PROBE_TIMEOUT_SECONDS", "5.0")),
)
self._db_watchdog_reconnect_timeout_seconds: float = max(
1.0, float(os.getenv("PRISMA_WATCHDOG_RECONNECT_TIMEOUT_SECONDS", "30.0"))
)
self._db_auth_reconnect_timeout_seconds: float = max(
0.5, float(os.getenv("PRISMA_AUTH_RECONNECT_TIMEOUT_SECONDS", "2.0"))
)
verbose_proxy_logger.debug("Success - Created Prisma Client")

def get_request_status(
Expand Down Expand Up @@ -3533,6 +3556,151 @@ async def disconnect(self):
)
raise e

async def _run_reconnect_cycle(
self, timeout_seconds: Optional[float] = None
) -> None:
"""
Run a reconnect cycle with direct db operations and a single overall timeout
budget to avoid long retries on hot paths (e.g. auth).
"""
async def _do_direct_reconnect() -> None:
try:
await self.db.disconnect()
except Exception as disconnect_err:
verbose_proxy_logger.debug(
"Prisma DB disconnect before reconnect failed (ignored): %s",
disconnect_err,
)

await self.db.connect()
await self.db.query_raw("SELECT 1")

effective_timeout = (
timeout_seconds
if timeout_seconds is not None
else self._db_watchdog_reconnect_timeout_seconds
)
await asyncio.wait_for(_do_direct_reconnect(), timeout=effective_timeout)

async def attempt_db_reconnect(
self,
reason: str,
force: bool = False,
timeout_seconds: Optional[float] = None,
) -> bool:
"""
Attempt to reconnect the Prisma client in a singleflight manner.

Returns:
bool: True if reconnection succeeded, else False.
"""
now = time.time()
if (
force is False
and now - self._db_last_reconnect_attempt_ts
< self._db_reconnect_cooldown_seconds
):
verbose_proxy_logger.debug(
"Skipping DB reconnect attempt due to cooldown. reason=%s",
reason,
)
return False

async with self._db_reconnect_lock:
now = time.time()
if (
force is False
and now - self._db_last_reconnect_attempt_ts
< self._db_reconnect_cooldown_seconds
):
verbose_proxy_logger.debug(
"Skipping DB reconnect attempt inside lock due to cooldown. reason=%s",
reason,
)
return False

verbose_proxy_logger.warning(
"Attempting Prisma DB reconnect. reason=%s", reason
)

reconnect_succeeded = False
try:
await self._run_reconnect_cycle(timeout_seconds=timeout_seconds)
reconnect_succeeded = True
verbose_proxy_logger.info(
"Prisma DB reconnect succeeded. reason=%s", reason
)
except Exception as reconnect_err:
verbose_proxy_logger.error(
"Prisma DB reconnect failed. reason=%s error=%s",
reason,
reconnect_err,
)
finally:
# Start cooldown after reconnect attempt has completed.
self._db_last_reconnect_attempt_ts = time.time()

return reconnect_succeeded

async def start_db_health_watchdog_task(self) -> None:
"""
Start a background task that probes DB health and attempts reconnect on failure.
"""
if self._db_health_watchdog_enabled is not True:
verbose_proxy_logger.debug(
"Prisma DB health watchdog disabled via PRISMA_HEALTH_WATCHDOG_ENABLED"
)
return
if self._db_health_watchdog_task is not None:
return
self._db_health_watchdog_task = asyncio.create_task(
self._db_health_watchdog_loop()
)
verbose_proxy_logger.info(
"Started Prisma DB health watchdog (interval=%ss, reconnect_cooldown=%ss, probe_timeout=%ss, reconnect_timeout=%ss)",
self._db_health_watchdog_interval_seconds,
self._db_reconnect_cooldown_seconds,
self._db_health_watchdog_probe_timeout_seconds,
self._db_watchdog_reconnect_timeout_seconds,
)

async def stop_db_health_watchdog_task(self) -> None:
"""
Stop DB health watchdog task gracefully.
"""
if self._db_health_watchdog_task is None:
return
self._db_health_watchdog_task.cancel()
try:
await self._db_health_watchdog_task
except asyncio.CancelledError:
pass
self._db_health_watchdog_task = None
verbose_proxy_logger.info("Stopped Prisma DB health watchdog")

async def _db_health_watchdog_loop(self) -> None:
while True:
try:
await asyncio.sleep(self._db_health_watchdog_interval_seconds)
await asyncio.wait_for(
self.db.query_raw("SELECT 1"),
timeout=self._db_health_watchdog_probe_timeout_seconds,
)
except asyncio.CancelledError:
break
except Exception as e:
if isinstance(
e, asyncio.TimeoutError
) or PrismaDBExceptionHandler.is_database_connection_error(e):
await self.attempt_db_reconnect(
reason="db_health_watchdog_connection_error",
timeout_seconds=self._db_watchdog_reconnect_timeout_seconds,
)
else:
verbose_proxy_logger.debug(
"Prisma DB health watchdog observed non-DB error: %s", e
)
Comment on lines +3741 to +3762

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Watchdog health_check uses backoff retries before reaching reconnect

health_check() is decorated with @backoff.on_exception(max_tries=3, max_time=10), so each watchdog iteration will retry the health check with exponential backoff for up to 10 seconds before the exception propagates here. Combined with the unbounded attempt_db_reconnect call, a single watchdog cycle when the DB is down could take 10s (health_check retries) + unbounded time (reconnect with no timeout) before the loop can sleep and try again.

Consider calling self.db.query_raw("SELECT 1") directly instead of self.health_check() to avoid the backoff retries in the watchdog loop, since the watchdog already has its own retry-via-sleep cadence.


@backoff.on_exception(
backoff.expo,
Exception,
Expand Down
Loading
Loading